feat: 以已安装 0.4.2 版本源码重建工作树(顶部会话标签条 / 快切面板 / 分支视图)
仓库 HEAD(942babe, package 版本仍是 0.1.0) 只有侧栏分组浏览器,缺少用户
实际运行的 0.4.2 构建中的会话标签条等模块。本次以
profiles/desktop 中已安装的 @dsh-xhl/workspace-groups@0.4.2 的
lib/client.js.map(内联 sourcesContent)为准重建完整 client 源码树,
并补齐宿主侧 host-tabs.ts 与 /workspace-groups/tabs 路由。
重建结果与安装构建逐字节对齐:
- 宿主产物 lib/index.js 与安装版 diff 行数 0
- 客户端产物 lib/client.js 仅 1 行差异(CSS 虚拟模块内联的绝对路径)
- lib/types 下 27 个 .d.ts 与安装版完全一致
相对仓库 HEAD 新增:SessionTabs / QuickPanel / FlowerBranch / open-folder /
subagent-lineage / store-hook / tab-* 模块,tsdown 平台外置模块补充
@deepseek-ai/dsh-client-store,package 版本对齐 0.4.2。
This commit is contained in:
parent
942babe9ed
commit
b30f771aeb
|
|
@ -1,12 +1,12 @@
|
|||
# dsh-workspace-groups bundle patch
|
||||
# @dsh-xhl/workspace-groups bundle patch
|
||||
#
|
||||
# This file is the `dsh.bundle.patch` layer of the package: when the plugin is
|
||||
# installed through the official CLI —
|
||||
#
|
||||
# dsh plugin --profile <name> add dsh-workspace-groups
|
||||
# dsh plugin --profile <name> add @dsh-xhl/workspace-groups
|
||||
#
|
||||
# — the command reconciles `dsh.profile.bundles` against installed packages
|
||||
# and, seeing this declaration, appends `dsh-workspace-groups` to the bundle
|
||||
# and, seeing this declaration, appends `@dsh-xhl/workspace-groups` to the bundle
|
||||
# stack. The profile boot then merges THIS patch (a single `insert` of the
|
||||
# plugin row) exactly like a manual cordis.patch.yml mount line.
|
||||
#
|
||||
|
|
@ -14,5 +14,5 @@
|
|||
# host Loader resolves as a package, and a `config` the host half consumes.
|
||||
- insert:
|
||||
- id: workspace-groups
|
||||
name: 'dsh-workspace-groups'
|
||||
name: '@dsh-xhl/workspace-groups'
|
||||
config: {}
|
||||
|
|
|
|||
2225
lib/client.js
2225
lib/client.js
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
224
lib/index.js
224
lib/index.js
|
|
@ -2462,7 +2462,7 @@ function ruleDisplayName(manual, originalName) {
|
|||
//#endregion
|
||||
//#region src/host-config.ts
|
||||
/**
|
||||
* Sidecar config reading for dsh-workspace-groups. The classification rules
|
||||
* Sidecar config reading for @dsh-xhl/workspace-groups. The classification rules
|
||||
* live in a user-editable YAML file (default `~/.dsh/workspace-groups.yaml`),
|
||||
* read and validated on the host, served to the browser half as JSON. The
|
||||
* core workspace.json and session storage are never touched.
|
||||
|
|
@ -2533,7 +2533,7 @@ async function readGroupsConfig(path) {
|
|||
//#endregion
|
||||
//#region src/host-manual.ts
|
||||
/**
|
||||
* Runtime grouping overlay for dsh-workspace-groups: manual groups created in
|
||||
* Runtime grouping overlay for @dsh-xhl/workspace-groups: manual groups created in
|
||||
* the sidebar UI and per-workspace category overrides. Stored in a plugin-
|
||||
* owned JSON sidecar (`$DSH_HOME/workspace-groups.manual.json`), separate from
|
||||
* the operator YAML — the YAML stays the rule source, this file only records
|
||||
|
|
@ -2702,9 +2702,135 @@ async function writeManualGroups(path, manual) {
|
|||
}
|
||||
}
|
||||
//#endregion
|
||||
//#region src/host-tabs.ts
|
||||
/**
|
||||
* Host-side persistence for the session-tab strip.
|
||||
*
|
||||
* Why the host and not the browser: **browser storage is scoped to the origin,
|
||||
* and the origin includes the PORT.** `dsh web` / `dsh test` / the desktop shell
|
||||
* each pick a port, and a different port is a different origin, so BOTH
|
||||
* `localStorage` and `sessionStorage` start empty on the next launch. A tab list
|
||||
* kept there survives a reload only by luck (same port) and is lost on the next
|
||||
* start.
|
||||
*
|
||||
* Host storage has no such problem: one JSON sidecar under `$DSH_HOME`, keyed by
|
||||
* nothing but the plugin, so every port and every session reads the same file.
|
||||
* That file IS the strip's memory — it is returned as-is, with no browser-session
|
||||
* marker gating it.
|
||||
*
|
||||
* (An earlier version DID gate on a `sessionKey` kept in `sessionStorage`, to
|
||||
* express "clear when the browser closes". That cannot work here: the marker is
|
||||
* itself per-origin, so a port change erased it, the host saw an unfamiliar
|
||||
* marker, and every restart silently discarded the user's tabs. Persistence the
|
||||
* user can rely on beats a tidy-up nobody asked for.)
|
||||
*
|
||||
* Writes are atomic (temp file + fsync + rename), matching the manual overlay.
|
||||
*/
|
||||
/** Default location: `$DSH_HOME/workspace-groups.tabs.json`. */
|
||||
function defaultTabsPath() {
|
||||
const home = process.env.DSH_HOME !== void 0 && process.env.DSH_HOME !== "" ? process.env.DSH_HOME : resolve(homedir(), ".dsh");
|
||||
return resolve(home, "workspace-groups.tabs.json");
|
||||
}
|
||||
/**
|
||||
* Parse + shape-validate a tabs document.
|
||||
*
|
||||
* Tolerant on purpose: this file is a display cache, so a malformed one must
|
||||
* read as "no tabs" rather than break the strip. Individual bad rows are dropped
|
||||
* and the rest kept. Unknown fields (such as the `sessionKey` an older build
|
||||
* wrote) are ignored, so an existing file keeps working across the change.
|
||||
*
|
||||
* @param raw - parsed JSON value.
|
||||
* @returns the normalized document, or null when it is unusable.
|
||||
*/
|
||||
function parseTabsDocument(raw) {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
|
||||
const source = raw;
|
||||
if (source.version !== 1) return null;
|
||||
if (typeof source.order !== "number" || !Number.isFinite(source.order)) return null;
|
||||
if (!Array.isArray(source.tabs)) return null;
|
||||
const tabs = [];
|
||||
const seen = /* @__PURE__ */ new Set();
|
||||
for (const entry of source.tabs) {
|
||||
if (typeof entry !== "object" || entry === null) continue;
|
||||
const row = entry;
|
||||
if (typeof row.sessionId !== "string" || row.sessionId === "") continue;
|
||||
if (typeof row.order !== "number" || !Number.isFinite(row.order)) continue;
|
||||
if (seen.has(row.sessionId)) continue;
|
||||
seen.add(row.sessionId);
|
||||
tabs.push({
|
||||
sessionId: row.sessionId,
|
||||
order: row.order
|
||||
});
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
order: source.order,
|
||||
tabs
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Read the tabs document.
|
||||
*
|
||||
* A missing file is not an error (first run). A corrupt one is reported as null
|
||||
* so the caller starts empty, and the next write repairs the file.
|
||||
*
|
||||
* @param path - sidecar path.
|
||||
* @returns the document, or null when absent/unusable.
|
||||
*/
|
||||
async function readTabsDocument(path) {
|
||||
let text;
|
||||
try {
|
||||
text = await readFile(path, "utf8");
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") return null;
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
return parseTabsDocument(JSON.parse(text));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Write the tabs document atomically.
|
||||
* @param path - sidecar path.
|
||||
* @param document - document to store.
|
||||
*/
|
||||
async function writeTabsDocument(path, document) {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const temp = `${path}.${process.pid}.${Date.now()}.tmp`;
|
||||
const body = `${JSON.stringify(document, null, 2)}\n`;
|
||||
const handle = await open(temp, "w");
|
||||
try {
|
||||
await handle.writeFile(body, "utf8");
|
||||
await handle.sync();
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
try {
|
||||
await rename(temp, path);
|
||||
} catch (error) {
|
||||
await unlink(temp).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Build the document to persist.
|
||||
* @param state - the client's current strip and its arrival counter.
|
||||
* @returns the document to write.
|
||||
*/
|
||||
function documentForTabs(state) {
|
||||
const highest = state.tabs.reduce((max, tab) => Math.max(max, tab.order), 0);
|
||||
return {
|
||||
version: 1,
|
||||
order: Math.max(state.order, highest),
|
||||
tabs: [...state.tabs]
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
//#region src/index.ts
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
const name = "dsh-workspace-groups";
|
||||
const name = "@dsh-xhl/workspace-groups";
|
||||
/** Services required before mounting: the webserver route. */
|
||||
const inject = ["webServer"];
|
||||
/** Cap on the PUT body: the overlay is tiny; anything bigger is a client bug. */
|
||||
|
|
@ -2717,6 +2843,41 @@ var HttpError = class extends Error {
|
|||
this.status = status;
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Shape-validate a PUT /tabs body.
|
||||
*
|
||||
* Returns null on a malformed payload rather than throwing, so the route can
|
||||
* answer 400 without a try/catch around the parse. Individual bad tab rows are
|
||||
* dropped (the strip is a display cache; one bad row must not reject a whole
|
||||
* write), and duplicate session ids are collapsed to the first.
|
||||
*
|
||||
* @param raw - parsed request body.
|
||||
* @returns the payload, or null when the envelope is unusable.
|
||||
*/
|
||||
function parseTabsPayload(raw) {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
|
||||
const source = raw;
|
||||
if (typeof source.order !== "number" || !Number.isFinite(source.order)) return null;
|
||||
if (!Array.isArray(source.tabs)) return null;
|
||||
const tabs = [];
|
||||
const seen = /* @__PURE__ */ new Set();
|
||||
for (const entry of source.tabs) {
|
||||
if (typeof entry !== "object" || entry === null) continue;
|
||||
const row = entry;
|
||||
if (typeof row.sessionId !== "string" || row.sessionId === "") continue;
|
||||
if (typeof row.order !== "number" || !Number.isFinite(row.order)) continue;
|
||||
if (seen.has(row.sessionId)) continue;
|
||||
seen.add(row.sessionId);
|
||||
tabs.push({
|
||||
sessionId: row.sessionId,
|
||||
order: row.order
|
||||
});
|
||||
}
|
||||
return {
|
||||
order: source.order,
|
||||
tabs
|
||||
};
|
||||
}
|
||||
/** Write a plain-text error response with the given status. */
|
||||
function writeError(res, status, message) {
|
||||
res.writeHead(status, { "Content-Type": "text/plain; charset=utf-8" });
|
||||
|
|
@ -2739,6 +2900,7 @@ async function readBody(req, limit) {
|
|||
function apply(ctx) {
|
||||
const configPath = defaultConfigPath();
|
||||
const manualPath = defaultManualPath();
|
||||
const tabsPath = defaultTabsPath();
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/workspace-groups/config",
|
||||
|
|
@ -2766,7 +2928,59 @@ function apply(ctx) {
|
|||
});
|
||||
res.end(req.method === "HEAD" ? void 0 : body);
|
||||
}
|
||||
}), "dsh-workspace-groups: /workspace-groups/config route");
|
||||
}), "@dsh-xhl/workspace-groups: /workspace-groups/config route");
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/workspace-groups/tabs",
|
||||
handler: async (req, res) => {
|
||||
if (req.method === "GET" || req.method === "HEAD") {
|
||||
let stored;
|
||||
try {
|
||||
stored = await readTabsDocument(tabsPath);
|
||||
} catch (error) {
|
||||
writeError(res, 500, `workspace-groups: failed to read tabs: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
const body = JSON.stringify({ tabs: stored?.tabs ?? [] });
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Length": Buffer.byteLength(body)
|
||||
});
|
||||
res.end(req.method === "HEAD" ? void 0 : body);
|
||||
return;
|
||||
}
|
||||
if (req.method !== "PUT") {
|
||||
writeError(res, 405, "method not allowed");
|
||||
return;
|
||||
}
|
||||
let raw;
|
||||
try {
|
||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES));
|
||||
} catch (error) {
|
||||
writeError(res, error instanceof HttpError ? error.status : 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
const parsed = parseTabsPayload(raw);
|
||||
if (parsed === null) {
|
||||
writeError(res, 400, "workspace-groups: malformed tabs payload");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await writeTabsDocument(tabsPath, documentForTabs(parsed));
|
||||
} catch (error) {
|
||||
writeError(res, 500, `workspace-groups: failed to write tabs: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
const body = JSON.stringify({ ok: true });
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Length": Buffer.byteLength(body)
|
||||
});
|
||||
res.end(body);
|
||||
}
|
||||
}), "@dsh-xhl/workspace-groups: /workspace-groups/tabs route");
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/workspace-groups/manual",
|
||||
|
|
@ -2805,7 +3019,7 @@ function apply(ctx) {
|
|||
});
|
||||
res.end(body);
|
||||
}
|
||||
}), "dsh-workspace-groups: /workspace-groups/manual route");
|
||||
}), "@dsh-xhl/workspace-groups: /workspace-groups/manual route");
|
||||
}
|
||||
//#endregion
|
||||
export { apply, inject, name };
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
/**
|
||||
* Attribute the tree puts on every row the branch should connect. */
|
||||
export declare const BRANCH_ROW_ATTRIBUTE = "data-wg-branch-row";
|
||||
/**
|
||||
* Attribute marking the row the stem should grow to.
|
||||
*
|
||||
* Only the DEEPEST row gets this (the session). Its ancestors — the project and
|
||||
* the category that contain it — deliberately do NOT, because a session belongs
|
||||
* to both and marking all three would make "which row is active?" ambiguous.
|
||||
* When several rows do carry it, the deepest (last in document order) wins.
|
||||
*/
|
||||
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";
|
||||
/**
|
||||
* Render the branch for the rows currently inside `scope`.
|
||||
* @param props - the element to measure, and whether the open session is working.
|
||||
* @returns the SVG overlay, or null until at least one row is measured.
|
||||
*/
|
||||
export declare function FlowerBranch({ scope, spinning }: {
|
||||
scope: HTMLElement | null;
|
||||
spinning: boolean;
|
||||
}): import("react").JSX.Element | null;
|
||||
|
|
@ -30,4 +30,4 @@ export type DragIndicator = {
|
|||
* @param props - composed slot props (shell owner share + store + injected actions).
|
||||
* @returns the region element tree.
|
||||
*/
|
||||
export declare function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useStore, actions, startSession, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, t, }: GroupsBrowserProps): import("react").JSX.Element;
|
||||
export declare function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t, }: GroupsBrowserProps): import("react").JSX.Element;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
/** Which surface of the quick panel is active. */
|
||||
export type QuickTab = 'workspaces' | 'sessions';
|
||||
/** The locale seat's translate function (same shape GroupsBrowser receives). */
|
||||
type Translate = PropsLocale<'workspaceGroups'>['t'];
|
||||
/** Quick panel props: hooks snapshots + the two injected verbs + shared CSS context. */
|
||||
export type QuickPanelProps = {
|
||||
/** Close request (Escape, mask click, action completed, or parent Ctrl+R toggle). */
|
||||
onClose: () => void;
|
||||
/** Sessions list snapshot (drives running detection). */
|
||||
list: SessionListState;
|
||||
/** Real workspaces in stable Host order. */
|
||||
workspaces: readonly WorkspaceView[];
|
||||
/** Registry-global archive set. */
|
||||
archivedSessionIds: readonly SessionId[];
|
||||
/** Category label per grouped workspace id (badge column; top-level absent). */
|
||||
categoryByWorkspace: ReadonlyMap<string, string>;
|
||||
/** The Session the Conversation currently shows (mainView retention), if any. */
|
||||
current: SessionId | undefined;
|
||||
/** Start a New Session in a workspace (injected share verb). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void;
|
||||
/** Open a real Session (injected share verb). */
|
||||
openSession: (sessionId: SessionId) => void;
|
||||
/** Render clock for relative times (parent refreshes per render). */
|
||||
now: number;
|
||||
/** Dictionary accessor (workspaceGroups namespace). */
|
||||
t: Translate;
|
||||
};
|
||||
/**
|
||||
* Render the quick switch panel (portaled overlay).
|
||||
* @param props - hooks snapshots + injected verbs.
|
||||
* @returns the panel element tree.
|
||||
*/
|
||||
export declare function QuickPanel({ onClose, list, workspaces, archivedSessionIds, categoryByWorkspace, current: currentSessionId, startSession, openSession, now, t, }: QuickPanelProps): import("react").ReactPortal;
|
||||
export {};
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { SessionsTabsProps } from './contract.ts';
|
||||
/**
|
||||
* Render the session tab strip into the conversation column's head seat.
|
||||
* @param props - tab store, catalog/status hooks, navigation, locale.
|
||||
* @returns the portal (or null until the column has mounted).
|
||||
*/
|
||||
export declare function SessionTabs({ useTabs, actions, useSessions, useSessionStatus, useWorkspaces, activate, rename, t, }: SessionsTabsProps): import("react").ReactPortal | null;
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
/**
|
||||
* The "flower branch" geometry for the sidebar tree.
|
||||
*
|
||||
* Reproduces the RewampUI *Flower Sidebar* mechanism: a single curly branch runs
|
||||
* down the left of the nav list, drawn as SVG so it can be *grown* — a faded
|
||||
* dashed ghost shows the whole route, and a solid stroke is drawn only as far as
|
||||
* the row you are on. Each row gets a dot sitting exactly on the curve, and the
|
||||
* active row's dot blooms.
|
||||
*
|
||||
* How it maps onto OUR tree (three levels: 分组 folder → 项目 folder → 会话 row):
|
||||
*
|
||||
* - The branch is **one continuous path** through every visible row, not one
|
||||
* rail per folder. That is what makes it read as a plant rather than as the
|
||||
* per-folder rail it replaces.
|
||||
* - The stem runs at `STEM_X`; at each **group boundary** it kinks outward to
|
||||
* `BULGE_X` and back — a half-pitch out plus a half-pitch back, which is
|
||||
* exactly the reference's 32px rhythm.
|
||||
* - Rows that are not group boundaries sit on a straight run, one row pitch
|
||||
* apart, each carrying a dot at its own y.
|
||||
*
|
||||
* Runtime-free on purpose (same discipline as `tabs.ts` / `store-core.ts`): the
|
||||
* component measures the DOM and hands plain numbers here, so the geometry is
|
||||
* unit-testable without a browser.
|
||||
*/
|
||||
/** Horizontal position of the stem's straight runs. */
|
||||
/**
|
||||
* Default x for a row's anchor, in SVG coordinates.
|
||||
*
|
||||
* A fallback only: rows carry their OWN measured `x`, because the tree indents
|
||||
* with per-row padding rather than one shared origin. A folder's chevron and a
|
||||
* session's text sit at different x, and no single constant lands on both.
|
||||
*/
|
||||
export declare const STEM_X = 30;
|
||||
/** Default vertical pitch between two rows. */
|
||||
export declare const ROW_PITCH = 32;
|
||||
/**
|
||||
* One row the branch must pass through.
|
||||
*
|
||||
* Both coordinates are MEASURED, not derived:
|
||||
* - `y` because the tree mixes row heights and inter-row gaps (deriving one
|
||||
* pitch from a single gap drifted the dots up to 15px off their rows);
|
||||
* - `x` because the tree indents per row via padding, so a folder's chevron and
|
||||
* a session's text are at different x.
|
||||
*/
|
||||
export interface BranchRow {
|
||||
/** Stable key, used to match a row to its dot. */
|
||||
readonly key: string;
|
||||
/** Row centre y, in the SVG's coordinate space. */
|
||||
readonly y: number;
|
||||
/**
|
||||
* Row anchor x, in the SVG's coordinate space.
|
||||
*
|
||||
* A folder row's anchor is its CHEVRON centre — the triangle the user already
|
||||
* reads as "this row opens" — so the stem visually hangs off the marker rather
|
||||
* than floating beside it. A session row's anchor is the indent its text sits
|
||||
* on.
|
||||
*/
|
||||
readonly x: number;
|
||||
/**
|
||||
* Row kind. A `'group'` row starts a new group and makes the stem kink;
|
||||
* an `'item'` row runs straight (or curves back in right after a group).
|
||||
*/
|
||||
readonly kind: 'group' | 'item';
|
||||
/** Whether this is the row the user is currently on (the bloomed dot). */
|
||||
readonly active: boolean;
|
||||
}
|
||||
/** A dot on the branch: one per row, positioned on the curve. */
|
||||
export interface BranchDot {
|
||||
/** The row this dot belongs to. */
|
||||
readonly key: string;
|
||||
readonly cx: number;
|
||||
readonly cy: number;
|
||||
readonly active: boolean;
|
||||
}
|
||||
/**
|
||||
* The bloom that flowers at the branch's endpoint.
|
||||
*
|
||||
* The endpoint is where the GROWN stroke stops — the row the user is on — not
|
||||
* the last visible row: the stem is drawn to the active row, so that is where
|
||||
* the plant has visibly reached, whether the tree is folded above it or not.
|
||||
*
|
||||
* This is deliberately the ONE row an active marker names, so the flower can
|
||||
* never disagree with the stem about where the branch ends.
|
||||
*/
|
||||
export interface BranchFlower {
|
||||
/** Row whose endpoint carries the bloom (the active row's key). */
|
||||
readonly key: string;
|
||||
/** Endpoint x: the last dot's centre, i.e. exactly where the grown path stops. */
|
||||
readonly cx: number;
|
||||
/** Endpoint y, on the measured row centre. */
|
||||
readonly cy: number;
|
||||
}
|
||||
/** The branch: one path for the ghost, its total length, and the dots. */
|
||||
export interface Branch {
|
||||
/** Full route, drawn as the faded dashed ghost. */
|
||||
readonly ghostPath: string;
|
||||
/** Path up to and including the active row (the "grown" part). */
|
||||
readonly grownPath: string;
|
||||
/** Drawn length of the full route. */
|
||||
readonly ghostLength: number;
|
||||
/** Drawn length of the grown part. */
|
||||
readonly grownLength: number;
|
||||
/** Dots, in row order. */
|
||||
readonly dots: readonly BranchDot[];
|
||||
/**
|
||||
* Bloom at the grown path's endpoint, or NULL when no row carries the active
|
||||
* marker.
|
||||
*
|
||||
* Deliberately stricter than `grownPath`: the stem has to be *some* path even
|
||||
* when nothing is active (it collapses to the bare origin, drawing nothing),
|
||||
* but a bloom with no active row has nothing to be the flower OF. Falling back
|
||||
* to the first dot — the earlier rule — put the blossom on a folder row at the
|
||||
* top of the tree as soon as the open session's folder was collapsed, because
|
||||
* folding removes the only row carrying the marker. No active row means no
|
||||
* flower.
|
||||
*/
|
||||
readonly flower: BranchFlower | null;
|
||||
/** Total vertical extent, so the SVG box can be sized. */
|
||||
readonly height: number;
|
||||
}
|
||||
/**
|
||||
* How far short of the flower's centre the stem stops, in SVG user units.
|
||||
*
|
||||
* The bloom is drawn ON the endpoint, so a stem that runs all the way to the
|
||||
* centre is visible through the petal notches and reads as a line crossing the
|
||||
* flower. Stopping the stroke at (a little over) the bloom's radius keeps the
|
||||
* stem ending cleanly at the flower's edge, where it reads as a stalk holding
|
||||
* the bloom.
|
||||
*
|
||||
* 7 units ≈ the 6.2-unit flower radius plus a hair, so the stroke's round cap
|
||||
* tucks just under the outer petals without a visible gap.
|
||||
*/
|
||||
export declare const STEM_END_CLEARANCE = 7;
|
||||
/**
|
||||
* Build the branch for a list of rows.
|
||||
*
|
||||
* @param rows - visible rows in render order, each carrying its MEASURED centre.
|
||||
* @returns the branch geometry; empty strings when there are no rows.
|
||||
*/
|
||||
export declare function buildBranch(rows: readonly BranchRow[]): Branch;
|
||||
|
|
@ -1,15 +1,33 @@
|
|||
/**
|
||||
* Registrant-private injected share for the workspace-groups browser entry.
|
||||
* Mirrors the official ui-workspace browser inject (same runtime calls), with
|
||||
* two differences: no directory-flow hole dependency (Add Workspace is
|
||||
* self-contained via `pickDirectory`), and no locale-keyed naming collision.
|
||||
* two differences: the directory-flow hole is kept occupied (`hooks.directoryFlow`)
|
||||
* because the official entry stays registered behind this one and gates its own
|
||||
* "Add workspace…" affordance on that hole — Add Workspace itself is
|
||||
* self-contained via `pickDirectory` — and no locale-keyed naming collision.
|
||||
*/
|
||||
import type { PropsHooks, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { HostDescriptionSource } from '@deepseek-ai/dsh-client-connection/client';
|
||||
import type { SessionId, SessionSearchResultItem, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client';
|
||||
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||
import type { WorkspaceId, WorkspaceSnapshot, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import type { createGroupsViewStore } from './stores.ts';
|
||||
import type { SessionTabsInstance, SessionTabsState } from './tab-store.ts';
|
||||
/** Services/slots this registrant's props depend on (documentation alias). */
|
||||
export type WorkspaceGroupsStoreHandle = ReturnType<typeof createGroupsViewStore>;
|
||||
/** Injected share (arrives via the register inject factory). */
|
||||
export type GroupsBrowserInjected = {
|
||||
/**
|
||||
* Reserved hooks compartment. `directoryFlow` reports the
|
||||
* `sidebar.workspaces.directoryFlow` hole as occupied: the official
|
||||
* ui-workspace entry stays registered behind this one and withdraws its
|
||||
* "Add workspace…" affordance when the hole is empty, so this browser keeps
|
||||
* it truthy (it drives the picker itself through `pickDirectory`).
|
||||
*/
|
||||
hooks: {
|
||||
/** True while the sidebar browsing region's directory-flow hole is occupied. */
|
||||
directoryFlow: HostObservable<boolean>;
|
||||
};
|
||||
/** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void;
|
||||
/** Open a real Session. */
|
||||
|
|
@ -41,11 +59,66 @@ export type GroupsBrowserInjected = {
|
|||
}) => Promise<WorkspaceView>;
|
||||
/** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */
|
||||
pickDirectory: () => Promise<string | null>;
|
||||
/** Browser-private injected hooks (host description; bound by the slot renderer). */
|
||||
hooks: {
|
||||
/** Current generation's Host description. */
|
||||
hostDescription: HostDescriptionSource;
|
||||
};
|
||||
/**
|
||||
* Surface the session-tab strip for a session that is in play (called with the
|
||||
* session the browser itself just opened, and again whenever its status
|
||||
* changes). Tab visibility rules live in `shouldOpenTab`; the status is passed
|
||||
* in because "it started working" is a live-status fact the store layer cannot
|
||||
* read on its own.
|
||||
* @param sessionId - the session to consider.
|
||||
* @param status - its unified UI status, when one is published.
|
||||
*/
|
||||
openTab: (sessionId: SessionId, status: SessionStatus | undefined) => void;
|
||||
/**
|
||||
* Selector hook over the shared tab store, bound by this plugin (the strip is
|
||||
* not a slot occupant, so the framework does not bind it). Built from the one
|
||||
* live instance the browser writes through.
|
||||
*/
|
||||
useTabs: <S>(selector: (state: SessionTabsState) => S, eq?: (a: S, b: S) => boolean) => S;
|
||||
/** The tab store's baked write set (the same one `apply` writes through). */
|
||||
tabActions: SessionTabsInstance['actions'];
|
||||
};
|
||||
/** Full browser props: shell owner share + viewing store + injected actions + locale seat. */
|
||||
export type GroupsBrowserProps = PropsRuntime<'sidebar.workspaces'> & PropsStore<ReturnType<typeof createGroupsViewStore>> & Omit<GroupsBrowserInjected, 'hooks'> & PropsHooks<GroupsBrowserInjected['hooks']> & PropsLocale<'workspaceGroups'>;
|
||||
export type GroupsBrowserProps = PropsRuntime<'sidebar.workspaces'> & PropsStore<ReturnType<typeof createGroupsViewStore>> & InjectFace<GroupsBrowserInjected> & PropsLocale<'workspaceGroups'>;
|
||||
/**
|
||||
* The two framework global seats the strip reads, declared structurally because
|
||||
* `GlobalStandardProps`'s own members arrive from merge declarations this repo
|
||||
* cannot resolve (its packages ship no `src`, so the merged hook types are only
|
||||
* visible to the compiling package). Both are the shipped global selector hooks
|
||||
* with the same names and shapes, and both are seated on the
|
||||
* `sidebar.workspaces` occupant that renders this strip.
|
||||
*/
|
||||
export interface SessionsTabsStandardProps {
|
||||
/** Session list and current selection (framework global seat). */
|
||||
useSessions: SnapshotSelectorHook<SessionListState>;
|
||||
/** Unified per-session UI status (framework global seat). */
|
||||
useSessionStatus: SnapshotSelectorHook<SessionStatusSnapshot>;
|
||||
/**
|
||||
* Workspace registry (framework global seat). The strip reads it to label each
|
||||
* tab with the project that owns its session — the one fact a bare strip of
|
||||
* session titles cannot convey.
|
||||
*/
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>;
|
||||
}
|
||||
/**
|
||||
* Full tab-strip props.
|
||||
*
|
||||
* The strip is NOT a slot occupant: the conversation column declares no child
|
||||
* slot, so it renders through a DOM seat (`tab-seat.ts`) and receives plain
|
||||
* React props instead of framework shares. Only the two global selector hooks
|
||||
* below are framework-provided, and they arrive because the strip is rendered
|
||||
* as a CHILD of this plugin's own `sidebar.workspaces` occupant — which seats
|
||||
* both of them in the standard kit. Everything else is passed explicitly by
|
||||
* that parent, which is what removes the strip from the slot registry entirely
|
||||
* and with it the cross-scope store conflict the slot version hit.
|
||||
*/
|
||||
export type SessionsTabsProps = SessionsTabsStandardProps & {
|
||||
/** Selector hook over the shared tab store's snapshot. */
|
||||
useTabs: SnapshotSelectorHook<SessionTabsState>;
|
||||
/** The tab store's baked write set (the same set `apply` writes through). */
|
||||
actions: SessionTabsInstance['actions'];
|
||||
/** Make a tab's session the open one (`ctx.uiWorkspace.openSession`). */
|
||||
activate: (sessionId: SessionId) => void;
|
||||
/** Ask the browser to open its rename dialog for a tab session. */
|
||||
rename: (sessionId: SessionId, currentTitle: string) => void;
|
||||
} & PropsLocale<'workspaceGroups'>;
|
||||
|
|
|
|||
|
|
@ -1,27 +1,60 @@
|
|||
/**
|
||||
* dsh-workspace-groups client half: registers the three-level grouped
|
||||
* workspace browser into the `sidebar.workspaces` slot, shadowing the
|
||||
* official ui-workspace browser.
|
||||
* @dsh-xhl/workspace-groups client half. ONE registration, plus a DOM-seated
|
||||
* view that hangs off it:
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — `ctx.workspaces.pickDirectory()` + `create()`, no hole.
|
||||
* The three-level grouped workspace browser into `sidebar.workspaces`,
|
||||
* shadowing the official ui-workspace browser.
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — the shared navigation service + `workspaces.create()`, no
|
||||
* hole.
|
||||
*
|
||||
* The session tab strip is NOT a second registration. It renders into a DOM
|
||||
* seat at the head of the conversation column (`pI_x6G_centerCol`) because that
|
||||
* column declares no child slot — its only child is the `main` slot's occupant
|
||||
* — so there is nowhere to register. See `tab-seat.ts` for the injection and
|
||||
* `SessionTabs.tsx` for the portal.
|
||||
*
|
||||
* Two consequences of that choice, both deliberate:
|
||||
* - The strip is a CHILD of this entry's component, so it inherits this
|
||||
* fiber's frame; it needs no injected seam, no cross-entry callback set,
|
||||
* and the rename dialog stays owned by one place.
|
||||
* - The tab store is seated by exactly ONE entry. Registering one handle
|
||||
* under a second, differently-scoped slot throws inside the registry
|
||||
* ("one handle, one scope") and would abort this whole `apply()` — which
|
||||
* is precisely why the strip does not occupy a slot.
|
||||
*
|
||||
* 0.1.6 适配:导航(选中会话 / New Session / fork / archive / 目录选择)从
|
||||
* `ctx.sessions` 抽到 ui-workspace 提供的 `ctx.uiWorkspace` 服务
|
||||
* (`ISessions` 现在只有目录 / retain / search 能力,选中由 `mainView` 保留位
|
||||
* 表达)。本插件不再自建 connectWorkspace/recentWorkspace 语义,全部委托给该
|
||||
* 服务,只保留改名、删除、排序、搜索等数据动作。
|
||||
*/
|
||||
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client';
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import { type WorkspaceGroupsKey } from './locales.ts';
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** The workspace-groups browsing region copy. */
|
||||
workspaceGroups: WorkspaceGroupsKey;
|
||||
}
|
||||
interface GlobalStandardProps {
|
||||
/** Selector hook over the pure Workspace Controller snapshot. */
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>;
|
||||
}
|
||||
}
|
||||
/** Required services (cordis fiber inject). */
|
||||
/**
|
||||
* Required services (cordis fiber inject; 0.1.6 service roster). `uiWorkspace`
|
||||
* is the shipped navigation face this entry delegates selection to.
|
||||
*/
|
||||
export declare const inject: string[];
|
||||
/**
|
||||
* Register the grouped browser once the sidebar slot declaration is on the
|
||||
|
|
@ -29,4 +62,4 @@ export declare const inject: string[];
|
|||
* framework's global hooks.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export declare function apply(ctx: ClientContext): void;
|
||||
export declare function apply(ctx: Context): void;
|
||||
|
|
|
|||
|
|
@ -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' | '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' | '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';
|
||||
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' | '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' | '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';
|
||||
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
|
||||
/** Simplified Chinese dictionary. */
|
||||
export declare const zh: WorkspaceGroupsDict;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,34 @@
|
|||
/**
|
||||
* Transport for the official open-in-app host routes served by
|
||||
* `@deepseek-ai/dsh-host-open-in-app`. The project row offers "open this
|
||||
* project's folder" by asking that host half for the applications it verified
|
||||
* as installed, then POSTing the launcher it already resolved — this plugin
|
||||
* never probes or spawns a launcher itself, and a host without the capability
|
||||
* (no resolved application, e.g. an SSH launch) simply yields no menu entry.
|
||||
*/
|
||||
/** GET route serving the probed application ids (host-owned constant). */
|
||||
export declare const OPEN_IN_APP_APPS_ROUTE = "/open-in-app/apps";
|
||||
/** POST route launching one resolved application on one absolute directory. */
|
||||
export declare const OPEN_IN_APP_OPEN_ROUTE = "/open-in-app/open";
|
||||
/**
|
||||
* The installed file-manager id for this host, or undefined when the host
|
||||
* resolved none (the row then offers no "open in folder" entry).
|
||||
* @param apps - installed catalog ids from the apps route.
|
||||
* @returns the preferred available id.
|
||||
*/
|
||||
export declare function folderAppId(apps: readonly string[]): string | undefined;
|
||||
/**
|
||||
* Read the host's installed-application ids. A host without the capability
|
||||
* (or one that refuses) reads as an empty list rather than an error, so the
|
||||
* caller can treat "no apps" and "no route" identically.
|
||||
* @param signal - aborts the read when the browser half unmounts.
|
||||
* @returns installed catalog ids, in host menu order.
|
||||
*/
|
||||
export declare function fetchOpenInApps(signal?: AbortSignal): Promise<readonly string[]>;
|
||||
/**
|
||||
* Launch one installed application on one absolute directory.
|
||||
* @param appId - catalog id from the apps route.
|
||||
* @param path - the project's absolute directory.
|
||||
* @returns after the host acknowledged the launch; rejects on any refusal.
|
||||
*/
|
||||
export declare function openPathInApp(appId: string, path: string): Promise<void>;
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
/**
|
||||
* Pure data shaping for the Ctrl+R quick switch panel. Runtime-free (same
|
||||
* discipline as store-core.ts): unit tests exercise the real semantics
|
||||
* without a browser module loader; the panel only binds them to the
|
||||
* framework's global hooks.
|
||||
*/
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
/**
|
||||
* Running quick-switchable sessions across the whole list, newest first.
|
||||
* @param list - sessions list snapshot.
|
||||
* @param archived - registry-global archive set (archived rows never surface).
|
||||
* @returns running summaries in recency order (id as deterministic tiebreak).
|
||||
*/
|
||||
export declare function runningSessions(list: SessionListState, archived: ReadonlySet<SessionId>): SessionSummary[];
|
||||
/**
|
||||
* Every quick-switchable session across the whole list — the sessions tab's
|
||||
* data: running rows pinned on top, everything else under them, both groups
|
||||
* newest first. Visibility mirrors the tree (subagent rows never; archived
|
||||
* never; a blank row only while it is the open session).
|
||||
* @param list - sessions list snapshot.
|
||||
* @param archived - registry-global archive set (archived rows never surface).
|
||||
* @param current - the selected session (`mainView` retention; keeps its blank row visible).
|
||||
* @returns summaries with running first, then recency (id as deterministic tiebreak).
|
||||
*/
|
||||
export declare function allSessions(list: SessionListState, archived: ReadonlySet<SessionId>, current: SessionId | undefined): SessionSummary[];
|
||||
/**
|
||||
* Session search for the quick panel: display-title or owning-workspace-title
|
||||
* substring match (trimmed, case-insensitive). Filters only — the incoming
|
||||
* running-first/recency order is preserved verbatim, so "running on top"
|
||||
* survives any query.
|
||||
* @param sessions - allSessions() output (running pinned on top, then recency).
|
||||
* @param query - raw query.
|
||||
* @param workspaceTitleOf - owning workspace title resolver (sub-line source).
|
||||
* @param limit - hard render cap.
|
||||
* @returns matching sessions in the given order.
|
||||
*/
|
||||
export declare function filterSessions(sessions: readonly SessionSummary[], query: string, workspaceTitleOf: (session: SessionSummary) => string | undefined, limit?: number): SessionSummary[];
|
||||
/**
|
||||
* Most recently updated running session inside one workspace.
|
||||
* @param list - sessions list snapshot.
|
||||
* @param workspace - target workspace (its session account order is irrelevant;
|
||||
* recency picks the row).
|
||||
* @returns the session id, or undefined when nothing in the workspace runs.
|
||||
*/
|
||||
export declare function latestRunningInWorkspace(list: SessionListState, workspace: WorkspaceView): SessionId | undefined;
|
||||
/**
|
||||
* Running-session count per workspace id (badge on the workspace tab rows).
|
||||
* @param running - runningSessions() output.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @returns counts keyed by workspace id; absent key = none running.
|
||||
*/
|
||||
export declare function runningCountByWorkspace(running: readonly SessionSummary[], workspaces: readonly WorkspaceView[]): Map<string, number>;
|
||||
/**
|
||||
* The workspace that owns the currently open session.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param currentSessionId - the selected session (`mainView` retention); may be undefined
|
||||
* (no session open, cleared selection) or an id no listed workspace holds
|
||||
* (e.g. an addressed subagent session).
|
||||
* @returns the workspace id, or undefined when there is no active workspace.
|
||||
*/
|
||||
export declare function activeWorkspaceId(workspaces: readonly WorkspaceView[], currentSessionId: SessionId | undefined): string | undefined;
|
||||
/**
|
||||
* Workspace search for the quick panel: title prefix → title substring →
|
||||
* category label substring → path substring; ties keep host order via a
|
||||
* stable title compare inside one rank.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param query - raw query (trimmed, case-insensitive).
|
||||
* @param categoryLabelOf - category label resolver (grouped workspaces only).
|
||||
* @param limit - hard render cap.
|
||||
* @returns ranked matches; an empty query returns host order.
|
||||
*/
|
||||
export declare function filterWorkspaces(workspaces: readonly WorkspaceView[], query: string, categoryLabelOf?: (workspace: WorkspaceView) => string | undefined, limit?: number): WorkspaceView[];
|
||||
|
|
@ -8,7 +8,7 @@
|
|||
* workspace rows, standing for their containing category) are drop targets.
|
||||
* The payload is a custom dataTransfer type so only in-plugin drags land.
|
||||
*/
|
||||
import { type DragEvent } from 'react';
|
||||
import { type DragEvent, type ReactNode } from 'react';
|
||||
import { type StateDotState } from '@deepseek-ai/dsh-client-ui-primitives';
|
||||
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts';
|
||||
|
|
@ -52,7 +52,7 @@ export declare function CategoryRow({ node, t, onToggle, onRename, onDelete, dro
|
|||
onDragStartCategory?: (event: DragEvent) => void;
|
||||
} & RowDropProps): import("react").JSX.Element;
|
||||
/** One workspace folder row inside a category: draggable source + drop target. */
|
||||
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut, onMoveOut, flat, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut, onMoveOut, onOpenInFolder, flat, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
node: WorkspaceGroupNode;
|
||||
t: T;
|
||||
onToggle: () => void;
|
||||
|
|
@ -62,11 +62,28 @@ export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename
|
|||
/** Project currently sits inside a group — offer "move out of group". */
|
||||
canMoveOut?: boolean;
|
||||
onMoveOut?: () => void;
|
||||
/**
|
||||
* Open the project directory in the host's file manager. Omitted when the
|
||||
* host resolved no folder application (no capability, or a remote launch),
|
||||
* which keeps the entry out of the menu entirely.
|
||||
*/
|
||||
onOpenInFolder?: () => void;
|
||||
/** Render as a top-level row (no folder indentation). */
|
||||
flat?: boolean;
|
||||
/** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */
|
||||
onDragStartExtra?: () => void;
|
||||
} & RowDropProps): import("react").JSX.Element;
|
||||
/**
|
||||
* Children container for one folder's rows.
|
||||
*
|
||||
* Keeps the tree's `role="group"` semantics and gives the rows a single
|
||||
* positioned ancestor. It used to draw a per-folder guide rail; that is now the
|
||||
* flower branch's job (one continuous stem for the whole tree, see
|
||||
* `FlowerBranch.tsx`), so this is structure only.
|
||||
*/
|
||||
export declare function TreeChildren({ children }: {
|
||||
children: ReactNode;
|
||||
}): import("react").JSX.Element;
|
||||
/** One session leaf row. */
|
||||
export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {
|
||||
node: SessionNode;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,7 @@
|
|||
import type { ActionsDecl, StoreInstance } from '@deepseek-ai/dsh-client-store';
|
||||
/**
|
||||
* Build a selector hook bound to one store instance.
|
||||
* @param instance - the live store instance (snapshot source).
|
||||
* @returns a `SnapshotSelectorHook`-compatible hook over that instance.
|
||||
*/
|
||||
export declare function createStoreHook<T, A extends ActionsDecl<T>>(instance: StoreInstance<T, A>): <S>(selector: (state: T) => S, eq?: (a: S, b: S) => boolean) => S;
|
||||
|
|
@ -10,7 +10,7 @@
|
|||
* unit tests exercise the real semantics without a browser module loader;
|
||||
* this file only binds them through defineStore.
|
||||
*/
|
||||
import { type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client';
|
||||
import { type EngineStoreHandle } from '@deepseek-ai/dsh-client-store';
|
||||
import { retainKeysImpl, setCategoryExpandedImpl, setWorkspaceExpandedImpl, type GroupsViewState } from './store-core.ts';
|
||||
/** Annotation twin of the actions literal below (structural type, satisfies `ActionsDecl`). */
|
||||
type GroupsViewActions = {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,27 @@
|
|||
/**
|
||||
* Plugin-owned projection of descendant counts from Session summaries.
|
||||
*
|
||||
* 0.1.2 移除了 `@deepseek-ai/dsh-client-runtime/client`(平台模块表不再提供
|
||||
* `indexSubagentDescendants`),官方 ui-workspace 改为各自持有本地副本
|
||||
* (packages/client/ui-workspace/src/client/subagent-lineage.ts,MIT)。这里
|
||||
* 保持同一实现,使运行中的子代理会话数在树行上继续可见。
|
||||
*/
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
interface LineageEntry {
|
||||
readonly id: SessionId;
|
||||
readonly parentId?: SessionId;
|
||||
readonly origin?: 'subagent';
|
||||
readonly running: boolean;
|
||||
}
|
||||
/** Descendant counts for one possible parent Session. */
|
||||
export interface SubagentDescendantSummary {
|
||||
readonly count: number;
|
||||
readonly runningCount: number;
|
||||
}
|
||||
/**
|
||||
* Index uninterrupted subagent descendants under each ancestor.
|
||||
* @param summaries - Session summaries keyed by id.
|
||||
* @returns descendant totals keyed by possible parent id.
|
||||
*/
|
||||
export declare function indexSubagentDescendants(summaries: Readonly<Record<SessionId, LineageEntry>>): ReadonlyMap<SessionId, SubagentDescendantSummary>;
|
||||
export {};
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
/**
|
||||
* Client side of the session-tab persistence, talking to
|
||||
* `GET|PUT /workspace-groups/tabs` on the host.
|
||||
*
|
||||
* Why not browser storage: **the origin includes the PORT**, and every `dsh web`
|
||||
* / `dsh test` / desktop launch picks a different one. `localStorage` and
|
||||
* `sessionStorage` are both scoped to the origin, so they start empty on the
|
||||
* next launch — a tab list kept there survives a reload only when the port
|
||||
* happens to match. The host's JSON sidecar has no such problem, which is why
|
||||
* the strip is stored there and read back verbatim.
|
||||
*
|
||||
* There is deliberately no per-browser-session marker. A marker has to live in
|
||||
* browser storage, which the port invalidates, so every restart looked like a
|
||||
* fresh session and silently discarded the user's tabs — the exact failure this
|
||||
* module exists to prevent.
|
||||
*
|
||||
* Every call is best-effort: a failed read means "no tabs" and a failed write is
|
||||
* swallowed, because the strip is a convenience and must never break the app.
|
||||
*/
|
||||
/** Host route holding the strip. */
|
||||
export declare const TABS_ROUTE = "/workspace-groups/tabs";
|
||||
/** One tab as it crosses the wire. */
|
||||
export interface WireTab {
|
||||
readonly sessionId: string;
|
||||
readonly order: number;
|
||||
}
|
||||
/**
|
||||
* Fetch the stored strip.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns the tabs, oldest first; empty on any failure.
|
||||
*/
|
||||
export declare function loadTabs(fetchImpl?: typeof fetch): Promise<WireTab[]>;
|
||||
/**
|
||||
* Store the strip. Failures are swallowed.
|
||||
* @param state - the client's current strip and its arrival counter.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
*/
|
||||
export declare function saveTabs(state: {
|
||||
order: number;
|
||||
tabs: readonly WireTab[];
|
||||
}, fetchImpl?: typeof fetch): Promise<void>;
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
/**
|
||||
* DOM seat for the session tab strip.
|
||||
*
|
||||
* Why this exists instead of a slot: the strip belongs at the very top of the
|
||||
* conversation column — `pI_x6G_centerCol` (ui-layout's AppFrame `.centerCol`,
|
||||
* a hashed CSS-Modules class). That column declares NO child slots: its only
|
||||
* child is the `main` slot's occupant (`renderSlot('main', …)`, the
|
||||
* Conversation or a global panel), so there is nowhere to register. The
|
||||
* shipped slot in that neighbourhood — `conversation.composer.dock` — is the
|
||||
* band UNDER the composer card, a different place entirely.
|
||||
*
|
||||
* So the strip gets a real DOM seat: this module finds the column, prepends a
|
||||
* `<div>` to it, and hands that element to a React portal. The element is
|
||||
* OURS, never React's: it is inserted outside the column's child list that
|
||||
* React reconciles, and it is re-inserted if React (or a theme/titlebar
|
||||
* re-render) ever drops it.
|
||||
*
|
||||
* Two hazards this module is built around:
|
||||
*
|
||||
* 1. `centerCol` is a hashed class name (`pI_x6G_centerCol`) that changes when
|
||||
* the package is rebuilt. Matching is therefore done on the *structural*
|
||||
* contract — a grid-item column that holds the `main` panel — plus a
|
||||
* `[class*="_centerCol"]` probe, never on the exact hash.
|
||||
* 2. The column mounts after the client plugin's `apply()` runs. Discovery is
|
||||
* therefore a MutationObserver on `document.body` plus a `requestAnimationFrame`
|
||||
* retry, and both are torn down when the owning effect disposes.
|
||||
*/
|
||||
/** A mounted seat: the host element plus the disposer that removes it. */
|
||||
export interface TabSeat {
|
||||
/**
|
||||
* The element the React portal renders into — null until the conversation
|
||||
* column mounts. The portal is simply not rendered while this is null.
|
||||
*/
|
||||
readonly host: HTMLElement | null;
|
||||
/** Remove the seat and stop watching for the column. */
|
||||
dispose: () => void;
|
||||
}
|
||||
/**
|
||||
* Ensure a seat exists as the FIRST child of the conversation column, creating
|
||||
* it if needed, and keep it there for as long as the returned handle is live.
|
||||
*
|
||||
* The seat element is created once and reused: a portal that re-mounts into a
|
||||
* fresh node on every shell re-render would drop the tab strip's React state
|
||||
* and visible focus. If React removes the node (it owns the column's child
|
||||
* list, and our node is not part of it), the observer re-inserts the SAME
|
||||
* element, so the portal's subtree moves with it.
|
||||
*
|
||||
* @param onReady - called with the host element each time it becomes attached
|
||||
* (once immediately when the column already exists). Used to seed React
|
||||
* state; may fire more than once if the column is remounted.
|
||||
* @returns the seat handle. `host` is null until the column appears, so the
|
||||
* caller renders nothing meanwhile and starts rendering when `onReady`
|
||||
* fires. Never null: a missing column must degrade to "no strip", not to a
|
||||
* thrown error that would take the whole client plugin down.
|
||||
*/
|
||||
export declare function mountTabSeat(onReady: (host: HTMLElement) => void): TabSeat;
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
/**
|
||||
* The session-tab store: the `defineStore` binding and nothing else.
|
||||
*
|
||||
* The action TRANSFORMS live in `tabs.ts` (pure, runtime-free), so unit tests
|
||||
* exercise the real semantics without pulling in the store engine — this module
|
||||
* is the only place that needs `@deepseek-ai/dsh-client-store`, and importing it
|
||||
* from a test would drag `zustand` into the test process.
|
||||
*
|
||||
* One handle, one scope: the tab store is seated by the `sidebar.workspaces`
|
||||
* entry alone. The tab strip is a CHILD of that entry (rendered through a DOM
|
||||
* portal into the conversation column), not a second slot registration, so the
|
||||
* handle is never mounted under a second, differently-scoped slot — which the
|
||||
* registry rejects outright ("one handle, one scope").
|
||||
*
|
||||
* Placement is navigation, not data: the strip derives its active chip from the
|
||||
* open session, and arrival order is the strip's only order, so nothing here
|
||||
* mirrors selection.
|
||||
*/
|
||||
import { type EngineStoreHandle, type StoreHandle } from '@deepseek-ai/dsh-client-store';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import { closeTabImpl, restoreTabsImpl, touchTabImpl, type SessionTab, type SessionTabsState } from './tabs.ts';
|
||||
export type { SessionTabsState };
|
||||
/**
|
||||
* Session-tab strip actions (bound by the framework, handed to the browser).
|
||||
*
|
||||
* There is deliberately NO "drop tabs whose session vanished" action. An open
|
||||
* tab is closed by the USER and by nothing else — a program that trims the strip
|
||||
* on its own eventually eats tabs the user wanted, and the whole point of the
|
||||
* strip is that it holds what you opened.
|
||||
*
|
||||
* This is also why the store needs no catalog at all: it never consults one.
|
||||
*/
|
||||
export interface SessionTabsActions {
|
||||
/** Add the open session, or leave its existing tab untouched in place. */
|
||||
touch: (sessionId: SessionId) => void;
|
||||
/** Close one tab; navigation is untouchable from here (the caller decides). */
|
||||
close: (sessionId: SessionId) => void;
|
||||
/**
|
||||
* Replace the strip with tabs loaded from the host.
|
||||
*
|
||||
* The host read is a `fetch`, so it cannot happen inside `init()`. This action
|
||||
* is how the async result lands, and it is a no-op once the user has already
|
||||
* opened a tab — a slow response must never discard what they just did.
|
||||
*/
|
||||
restore: (tabs: readonly SessionTab[]) => void;
|
||||
}
|
||||
/** Annotation twin of the actions literal below (structural `ActionsDecl`). */
|
||||
type SessionTabsActionsDecl = {
|
||||
touch: typeof touchTabImpl;
|
||||
close: typeof closeTabImpl;
|
||||
restore: typeof restoreTabsImpl;
|
||||
};
|
||||
/**
|
||||
* The tab store's registered handle: identity + spec + the instance factory the
|
||||
* framework resolves per entry x scope. It deliberately does NOT claim the live
|
||||
* instance's faces (`getSnapshot` / `actions`) — `defineStore`'s concrete return
|
||||
* is structurally narrower, and this alias has to stay a type that value can be
|
||||
* assigned to.
|
||||
*/
|
||||
export type SessionTabsStoreHandle = StoreHandle<SessionTabsState, SessionTabsActionsDecl>;
|
||||
/**
|
||||
* The live tab store value: the handle's `create()` product, which carries the
|
||||
* baked write set and the snapshot source. Named here so the registrations and
|
||||
* the strip's props can share one type without importing the store engine.
|
||||
*/
|
||||
export type SessionTabsInstance = ReturnType<EngineStoreHandle<SessionTabsState, SessionTabsActionsDecl>['create']>;
|
||||
/**
|
||||
* Create the session-tab store handle.
|
||||
*
|
||||
* The strip starts EMPTY and is hydrated by the caller through the `restore`
|
||||
* action: persistence lives on the host behind a `fetch`, which cannot run
|
||||
* during `init()`. Browser storage is deliberately not used — the origin
|
||||
* includes the port, and every launch picks a new one, so `localStorage` and
|
||||
* `sessionStorage` both start empty on the next start.
|
||||
*
|
||||
* @returns the store handle (spec + type + identity + factory in one).
|
||||
*/
|
||||
export declare function createSessionTabsStore(): EngineStoreHandle<SessionTabsState, SessionTabsActionsDecl>;
|
||||
export type { SessionTab };
|
||||
|
|
@ -0,0 +1,227 @@
|
|||
/**
|
||||
* Pure session-tab state: the ordered strip of sessions the user has opened,
|
||||
* the active one, and each tab's derived presentation.
|
||||
*
|
||||
* Position model: a tab's place in the strip is decided ONCE, when it is first
|
||||
* opened, and never changes afterwards. Switching to a tab, or re-opening a
|
||||
* session that already has one, leaves the strip exactly as it was — so clicking
|
||||
* a chip never moves the chip out from under the pointer. Only two events change
|
||||
* the order: a session opening for the FIRST time (append) and a tab closing
|
||||
* (remove).
|
||||
*
|
||||
* Runtime-free on purpose (same discipline as `store-core.ts` / `quick.ts`):
|
||||
* the component owns the ref + React state, this module owns every rule, and
|
||||
* unit tests exercise the real semantics without a browser module loader.
|
||||
*
|
||||
* Retention note: a tab outlives whatever it points at. The strip is a list of
|
||||
* things the USER opened, so nothing here consults the session catalog — a tab
|
||||
* whose session is gone stays visible until the user closes it, and no
|
||||
* background sweep ever trims the strip.
|
||||
*/
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import type { SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { SessionStatus } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||
/** One open tab: a session id plus its arrival key (React list identity). */
|
||||
export interface SessionTab {
|
||||
/** The session the tab shows. */
|
||||
readonly sessionId: SessionId;
|
||||
/**
|
||||
* Monotonic arrival key. It doubles as the React `key`, so it must stay
|
||||
* attached to the session for the tab's whole life — a reused key would make
|
||||
* React move an existing chip's DOM node instead of reconciling it in place.
|
||||
*/
|
||||
readonly order: number;
|
||||
}
|
||||
/** Feature switch: whether opening a session also surfaces a tab. */
|
||||
export type TabOpenMode = 'auto' | 'manual';
|
||||
/** Per-tab indicator derived from the catalog summary and the live UI status. */
|
||||
export interface SessionTabIndicator {
|
||||
/** A domain request is waiting for the user (approval / plan review / question). */
|
||||
readonly attention: boolean;
|
||||
/** The agent is producing output, or a descendant subagent is. */
|
||||
readonly running: boolean;
|
||||
/** The turn finished while the tab was in the background and was never looked at. */
|
||||
readonly unread: boolean;
|
||||
/** Idle tab whose session already has a title (a settled conversation). */
|
||||
readonly settled: boolean;
|
||||
}
|
||||
/**
|
||||
* Add a session to the strip, or leave an existing entry exactly where it is.
|
||||
*
|
||||
* Arrival order is the strip's only order, so re-opening a session that already
|
||||
* has a tab is a NO-OP: the tab keeps its position and its arrival key. Moving
|
||||
* it to the front here would fight the whole point of stable positions — a user
|
||||
* clicking through sessions would watch the strip reshuffle on every click.
|
||||
*
|
||||
* @param tabs - current strip (oldest first).
|
||||
* @param sessionId - arriving session.
|
||||
* @param nextOrder - monotonic arrival counter to spend when appending.
|
||||
* @returns the strip, unchanged (same array) when the session already has a tab.
|
||||
*/
|
||||
export declare function appendTab(tabs: readonly SessionTab[], sessionId: SessionId, nextOrder: number): SessionTab[];
|
||||
/**
|
||||
* Remove one session's tab. An absent session leaves the strip untouched.
|
||||
* @param tabs - current strip.
|
||||
* @param sessionId - session whose tab closes.
|
||||
* @returns a new strip.
|
||||
*/
|
||||
export declare function removeTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[];
|
||||
/**
|
||||
* Order the strip for display: strictly by arrival, regardless of which tab is
|
||||
* active.
|
||||
*
|
||||
* Position is a property of the TAB, not of the selection. Switching to a tab
|
||||
* must not move it — an earlier version pulled the active tab to the front,
|
||||
* which made every click reshuffle the strip and slid the chip out from under
|
||||
* the pointer that had just clicked it.
|
||||
*
|
||||
* `activeId` is therefore accepted only to document that "active" deliberately
|
||||
* does NOT participate in ordering; it is unused. The returned array is a copy
|
||||
* so callers cannot mutate the store's state through it.
|
||||
*
|
||||
* @param tabs - strip in arrival order.
|
||||
* @param activeId - the open session, if it has a tab (intentionally unused).
|
||||
* @returns a new array in arrival order.
|
||||
*/
|
||||
export declare function orderedTabs(tabs: readonly SessionTab[], activeId: SessionId | undefined): SessionTab[];
|
||||
/**
|
||||
* Whether the open session must surface a tab.
|
||||
*
|
||||
* A tab means "this conversation is in play right now", not "I once opened
|
||||
* this". Browsing history is what the sidebar is for; opening an old
|
||||
* conversation to read it should not litter the strip, which is the whole point
|
||||
* of the strip being a working set rather than a second session list.
|
||||
*
|
||||
* A session therefore earns a tab only once a conversation has actually STARTED
|
||||
* in it and is still engaged, which is any of:
|
||||
* - **running** — the agent is producing output (including subagents);
|
||||
* - **waiting on you** — an approval / plan review / question is pending;
|
||||
* - **unseen completion** — it finished while you were elsewhere, so the tab is
|
||||
* the thing that tells you to come back.
|
||||
*
|
||||
* A still-blank draft gets NO tab: the tab appears the moment the first message
|
||||
* is sent (which is when the controller flips `blank` on `turn/start`). Once the
|
||||
* turn ends and you have read the result, the session is settled history and
|
||||
* does not earn a tab — so clicking through finished conversations leaves the
|
||||
* strip alone. Tabs already opened stay open: this gate only decides whether a
|
||||
* NEW tab appears, never whether an existing one closes.
|
||||
*
|
||||
* `blank` (from `sessionListMetadata`) is exactly "no turn has started": the
|
||||
* controller flips it to false on `turn/start`. It is the right signal for
|
||||
* "has this conversation begun", and the wrong one ALONE — a conversation
|
||||
* finished a week ago is also non-blank, which is why the earlier `!blank` rule
|
||||
* surfaced every old conversation the user clicked.
|
||||
*
|
||||
* @param mode - feature switch ('auto' applies the engagement rule).
|
||||
* @param summary - the session's catalog row (absent while the catalog has not
|
||||
* caught up with a just-created session).
|
||||
* @param status - the session's unified UI status (absent → no live signal).
|
||||
* @returns true when a tab belongs in the strip.
|
||||
*/
|
||||
export declare function shouldOpenTab(mode: TabOpenMode, summary: SessionSummary | undefined, status: SessionStatus | undefined): boolean;
|
||||
/**
|
||||
* Derive one tab's indicators from the catalog row and the unified UI status.
|
||||
* @param summary - the tab session's catalog row (absent → inert indicators).
|
||||
* @param status - the tab session's unified UI status (absent → idle).
|
||||
* @returns the indicator quadruple.
|
||||
*/
|
||||
export declare function tabIndicator(summary: SessionSummary | undefined, status: SessionStatus | undefined): SessionTabIndicator;
|
||||
/**
|
||||
* Where one session lives: the project (workspace) that accounts for it.
|
||||
*
|
||||
* Tabs carry this because a strip of bare session titles is ambiguous once
|
||||
* several projects are open — two checkouts both named "api", or a session
|
||||
* titled after a file, give no hint which project it belongs to.
|
||||
*/
|
||||
export interface TabProject {
|
||||
/** Stable workspace id. */
|
||||
readonly workspaceId: string;
|
||||
/** Display label: the workspace title, falling back to its directory name. */
|
||||
readonly label: string;
|
||||
/** Canonical directory path, for the tooltip. */
|
||||
readonly path: string;
|
||||
}
|
||||
/**
|
||||
* Index sessions by the project that owns them.
|
||||
*
|
||||
* Membership comes from the workspace registry (`sessionIds`), which is the same
|
||||
* authority the sidebar tree uses — a tab and its sidebar row therefore agree on
|
||||
* the project without a second derivation.
|
||||
*
|
||||
* Built once per render pass rather than scanned per tab: a strip of N tabs over
|
||||
* M projects is O(N×M) with a naive `find` per tab.
|
||||
*
|
||||
* @param workspaces - workspace views from the controller snapshot.
|
||||
* @returns a session id → project map; sessions in no workspace are absent.
|
||||
*/
|
||||
export declare function projectIndex(workspaces: readonly WorkspaceViewLike[]): ReadonlyMap<SessionId, TabProject>;
|
||||
/** Minimal workspace shape this module needs (keeps it importable in tests). */
|
||||
export interface WorkspaceViewLike {
|
||||
readonly workspaceId: string;
|
||||
readonly path: string;
|
||||
readonly title: string;
|
||||
readonly sessionIds: readonly SessionId[];
|
||||
}
|
||||
/**
|
||||
* Display label for a project: its title, else the directory basename.
|
||||
* @param workspace - workspace view.
|
||||
* @returns a non-empty label, falling back to the raw path.
|
||||
*/
|
||||
export declare function projectLabel(workspace: Pick<WorkspaceViewLike, 'title' | 'path'>): string;
|
||||
/**
|
||||
* Whether two strips are the same sequence of sessions (arrival keys ignored).
|
||||
* @param left - previous strip.
|
||||
* @param right - next strip.
|
||||
* @returns true when no entry was added, removed, or reordered.
|
||||
*/
|
||||
export declare function sameTabs(left: readonly SessionTab[], right: readonly SessionTab[]): boolean;
|
||||
/** Session-tab strip state (the shape the store persists). */
|
||||
export interface SessionTabsState {
|
||||
/** Open tabs in arrival order — the strip's one and only order. */
|
||||
tabs: SessionTab[];
|
||||
/** Monotonic arrival counter; each FIRST-time session spends one. */
|
||||
order: number;
|
||||
}
|
||||
/**
|
||||
* Store transform: add the open session, or leave its existing tab in place.
|
||||
*
|
||||
* Live here rather than in `tab-store.ts` so unit tests can exercise the real
|
||||
* semantics without importing `@deepseek-ai/dsh-client-store` (which pulls
|
||||
* `zustand` into the test process). The store module binds these into its
|
||||
* actions table.
|
||||
*
|
||||
* The no-op guard matters: this runs on EVERY catalog change for the open
|
||||
* session, so an unguarded write would wake the strip and spend arrival keys on
|
||||
* every projection tick.
|
||||
*
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the session that just became open.
|
||||
*/
|
||||
export declare function touchTabImpl(state: SessionTabsState, sessionId: SessionId): void;
|
||||
/**
|
||||
* Store transform: close one tab. Closing a session that has no tab is not a
|
||||
* state change, so it writes nothing.
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the tab to close.
|
||||
*/
|
||||
export declare function closeTabImpl(state: SessionTabsState, sessionId: SessionId): void;
|
||||
/**
|
||||
* Store transform: adopt tabs loaded from the host, MERGING with whatever is
|
||||
* already in the strip.
|
||||
*
|
||||
* Async by nature (the host read is a `fetch`), so it can land after the browser
|
||||
* has already opened a tab for the current session. Merging — rather than
|
||||
* "ignore the read if the strip is non-empty" — is what makes a restart safe:
|
||||
* the tab opened during startup survives AND the stored tabs still come back.
|
||||
* (Bailing on a non-empty strip would silently drop every stored tab whenever
|
||||
* the startup tab won the race, which is the common case for a session that is
|
||||
* running or unread.)
|
||||
*
|
||||
* The arrival counter is lifted above every restored key so a tab opened later
|
||||
* cannot reuse one; a reused key makes React move a chip's DOM node instead of
|
||||
* reconciling it.
|
||||
*
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param tabs - tabs read from the host, oldest first.
|
||||
*/
|
||||
export declare function restoreTabsImpl(state: SessionTabsState, tabs: readonly SessionTab[]): void;
|
||||
|
|
@ -4,8 +4,25 @@
|
|||
* scans. Session visibility rules mirror the official ui-workspace tree
|
||||
* (blank rows only when current, archived excluded, subagent rows excluded).
|
||||
*/
|
||||
import { type PendingInteractionStatus, type SessionId, type SessionListState, type SessionSearchResultItem, type WorkspaceId, type WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client';
|
||||
import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import { type GroupsConfig, type ManualGroups } from '../core/types.ts';
|
||||
/** Pending interaction kinds with dedicated Workspace-row presentation. */
|
||||
export type SessionPendingInteractionStatus = 'approval' | 'plan-review' | 'question';
|
||||
/** Current unified UI status by Session (ui-session snapshot). */
|
||||
type SessionStatuses = SessionStatusSnapshot;
|
||||
/**
|
||||
* The Session the Conversation is currently showing.
|
||||
*
|
||||
* 0.1.6 removed `SessionListState.current`: selection is expressed as the
|
||||
* Session retained through the `mainView` reference source (the ui-workspace
|
||||
* navigation holds exactly one). Same read the official browser performs.
|
||||
* @param list - sessions list snapshot.
|
||||
* @returns the retained Session id, or undefined while no Session is selected.
|
||||
*/
|
||||
export declare function currentSessionId(list: SessionListState): SessionId | undefined;
|
||||
/** One top-level session row inside a workspace folder. */
|
||||
export interface SessionNode {
|
||||
id: SessionId;
|
||||
|
|
@ -13,7 +30,7 @@ export interface SessionNode {
|
|||
title: string;
|
||||
/** The provisional blank session (renderer shows the localized New Session title). */
|
||||
blank: boolean;
|
||||
pendingInteraction?: PendingInteractionStatus;
|
||||
pendingInteraction?: SessionPendingInteractionStatus;
|
||||
running: boolean;
|
||||
/** Running descendants connected through uninterrupted subagent-origin lineage. */
|
||||
runningSubagentCount: number;
|
||||
|
|
@ -72,11 +89,13 @@ export declare function workspaceLabel(cwd: string | undefined): string;
|
|||
* @param view - local expansion arrays.
|
||||
* @param manual - runtime overlay (manual groups + overrides). A workspace's
|
||||
* manual override wins over rule classification; removing it reverts to rules.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @returns category sections in render order (rule categories first, then
|
||||
* manual-only ones, uncategorized last). Manual groups render even while
|
||||
* empty; empty rule buckets stay hidden.
|
||||
*/
|
||||
export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups): CategoryNode[];
|
||||
export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses): CategoryNode[];
|
||||
/**
|
||||
* Top-level (ungrouped) workspace rows: workspaces resolving to no category
|
||||
* (no manual override and no matching rule, or a forced `null` override).
|
||||
|
|
@ -84,7 +103,7 @@ export declare function deriveGroups(list: SessionListState, workspaces: readonl
|
|||
* folder), in manual top-level order (`workspaceOrder[TOP_LEVEL_ORDER_KEY]`),
|
||||
* falling back to host registration order.
|
||||
*/
|
||||
export declare function deriveTopLevel(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups): WorkspaceGroupNode[];
|
||||
export declare function deriveTopLevel(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses): WorkspaceGroupNode[];
|
||||
/** 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). */
|
||||
|
|
@ -124,7 +143,10 @@ export interface SearchTree {
|
|||
* @param archivedSessionIds - registry-global archive set.
|
||||
* @param manual - runtime overlay (manual groups + overrides).
|
||||
* @param snippetsBySession - optional content-match snippets keyed by session id.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @returns group folders in render order plus top-level matched workspaces,
|
||||
* pruned to matched branches only.
|
||||
*/
|
||||
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap<SessionId, string>): SearchTree;
|
||||
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap<SessionId, string>, statuses?: SessionStatuses): SearchTree;
|
||||
export {};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* Shared config types for dsh-workspace-groups. Pure types (zero runtime
|
||||
* Shared config types for @dsh-xhl/workspace-groups. Pure types (zero runtime
|
||||
* deps) so both halves — the node half (sidecar YAML reading) and the
|
||||
* browser half (tree derivation) — compile against the same contract.
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -0,0 +1,54 @@
|
|||
/** One persisted tab. */
|
||||
export interface PersistedTab {
|
||||
/** Session id the tab points at. */
|
||||
readonly sessionId: string;
|
||||
/** Arrival key (React list identity). */
|
||||
readonly order: number;
|
||||
}
|
||||
/** The persisted document. */
|
||||
export interface TabsDocument {
|
||||
/** Shape version; a mismatch discards the file rather than guessing. */
|
||||
readonly version: 1;
|
||||
/** Arrival counter, kept ahead of every tab's own order. */
|
||||
readonly order: number;
|
||||
readonly tabs: readonly PersistedTab[];
|
||||
}
|
||||
/** Default location: `$DSH_HOME/workspace-groups.tabs.json`. */
|
||||
export declare function defaultTabsPath(): string;
|
||||
/**
|
||||
* Parse + shape-validate a tabs document.
|
||||
*
|
||||
* Tolerant on purpose: this file is a display cache, so a malformed one must
|
||||
* read as "no tabs" rather than break the strip. Individual bad rows are dropped
|
||||
* and the rest kept. Unknown fields (such as the `sessionKey` an older build
|
||||
* wrote) are ignored, so an existing file keeps working across the change.
|
||||
*
|
||||
* @param raw - parsed JSON value.
|
||||
* @returns the normalized document, or null when it is unusable.
|
||||
*/
|
||||
export declare function parseTabsDocument(raw: unknown): TabsDocument | null;
|
||||
/**
|
||||
* Read the tabs document.
|
||||
*
|
||||
* A missing file is not an error (first run). A corrupt one is reported as null
|
||||
* so the caller starts empty, and the next write repairs the file.
|
||||
*
|
||||
* @param path - sidecar path.
|
||||
* @returns the document, or null when absent/unusable.
|
||||
*/
|
||||
export declare function readTabsDocument(path: string): Promise<TabsDocument | null>;
|
||||
/**
|
||||
* Write the tabs document atomically.
|
||||
* @param path - sidecar path.
|
||||
* @param document - document to store.
|
||||
*/
|
||||
export declare function writeTabsDocument(path: string, document: TabsDocument): Promise<void>;
|
||||
/**
|
||||
* Build the document to persist.
|
||||
* @param state - the client's current strip and its arrival counter.
|
||||
* @returns the document to write.
|
||||
*/
|
||||
export declare function documentForTabs(state: {
|
||||
order: number;
|
||||
tabs: readonly PersistedTab[];
|
||||
}): TabsDocument;
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import type { GroupsContext } from './context-types.ts';
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
export declare const name = "dsh-workspace-groups";
|
||||
export declare const name = "@dsh-xhl/workspace-groups";
|
||||
/** Services required before mounting: the webserver route. */
|
||||
export declare const inject: string[];
|
||||
/** Plugin body: mount the config snapshot route and the overlay write route. */
|
||||
|
|
|
|||
75
package.json
75
package.json
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "dsh-workspace-groups",
|
||||
"version": "0.1.0",
|
||||
"description": "Complete workspace grouping manager for the DSH web sidebar: 分类 → 项目 → 会话 three-level tree, manual group create/rename/delete, drag-and-drop grouping & ordering with insertion indicator, rule-based auto-classification, tree search. Sidecar YAML + runtime overlay, zero core-storage intrusion.",
|
||||
"name": "@dsh-xhl/workspace-groups",
|
||||
"version": "0.4.2",
|
||||
"description": "Complete workspace grouping manager for the DSH web sidebar: 分类 → 项目 → 会话 three-level tree, manual group create/rename/delete, drag-and-drop grouping & ordering with insertion indicator, rule-based auto-classification, tree search, plus the session tab strip seated in the conversation column head. Sidecar YAML + runtime overlay, zero core-storage intrusion.",
|
||||
"keywords": [
|
||||
"dsh",
|
||||
"deepseek-harness",
|
||||
|
|
@ -15,6 +15,9 @@
|
|||
],
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/z-col/dsh-workspace-groups"
|
||||
|
|
@ -36,7 +39,10 @@
|
|||
"files": [
|
||||
"lib",
|
||||
"cordis.patch.yml",
|
||||
"README.md"
|
||||
"README.md",
|
||||
"README_ZH.md",
|
||||
"screenshot.png",
|
||||
"workspace-groups.example.yaml"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
|
|
@ -48,14 +54,21 @@
|
|||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-runtime",
|
||||
"@deepseek-ai/dsh-api-remotes",
|
||||
"@deepseek-ai/dsh-api-session-controller",
|
||||
"@deepseek-ai/dsh-api-workspace-controller",
|
||||
"@deepseek-ai/dsh-client-connection",
|
||||
"@deepseek-ai/dsh-client-locale",
|
||||
"@deepseek-ai/dsh-client-ui-slots"
|
||||
"@deepseek-ai/dsh-client-ui-conversation",
|
||||
"@deepseek-ai/dsh-client-ui-renderer",
|
||||
"@deepseek-ai/dsh-client-ui-session",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar",
|
||||
"@deepseek-ai/dsh-client-ui-workspace"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rm -rf lib && pnpm build:types && tsdown",
|
||||
"build": "node -e \"require('node:fs').rmSync('lib', { recursive: true, force: true })\" && pnpm build:types && tsdown",
|
||||
"build:types": "tsc -p tsconfig.build.json --noEmit false --declaration --emitDeclarationOnly --outDir lib/types",
|
||||
"watch": "tsdown --watch",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
|
||||
|
|
@ -63,14 +76,19 @@
|
|||
"test": "vitest run"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"@deepseek-ai/dsh-client-connection": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-locale": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-runtime": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-host-webserver": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/cordis": "^4.0.2",
|
||||
"@deepseek-ai/dsh-api-remotes": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-api-session-controller": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-api-workspace-controller": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-client-locale": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-client-store": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-client-ui-session": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-client-ui-slots": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-client-ui-workspace": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-host-webserver": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-session": ">=0.1.7-rc.2 <0.3.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
|
|
@ -83,18 +101,26 @@
|
|||
"js-yaml": "^4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"@deepseek-ai/dsh-client-connection": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-locale": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-runtime": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-host-webserver": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/cordis": "^4.0.4",
|
||||
"@deepseek-ai/dsh-api-remotes": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-api-session-controller": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-api-workspace-controller": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-client-locale": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-client-store": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-client-ui-conversation": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-client-ui-renderer": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-client-ui-session": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-client-ui-workspace": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-host-webserver": "0.2.0-rc.1",
|
||||
"@deepseek-ai/dsh-session": "0.2.0-rc.1",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/react": "~18.3.1",
|
||||
"@types/react-dom": "~18.3.0",
|
||||
"immer": "^11.1.18",
|
||||
"js-yaml": "^4.1.0",
|
||||
"jsdom": "^30.0.1",
|
||||
"lightningcss": "^1.32.0",
|
||||
|
|
@ -102,6 +128,7 @@
|
|||
"react-dom": "^18.2.0",
|
||||
"tsdown": "^0.22.2",
|
||||
"typescript": "^5.6.0",
|
||||
"vitest": "^4.1.8"
|
||||
"vitest": "4.1.8",
|
||||
"zustand": "^5.0.15"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
3424
pnpm-lock.yaml
3424
pnpm-lock.yaml
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,264 @@
|
|||
/**
|
||||
* The flower branch: an SVG overlay that draws one continuous curly stem down
|
||||
* the sidebar tree, growing to the row you are currently on.
|
||||
*
|
||||
* Ported from the RewampUI *Flower Sidebar* reference. The mechanism, verified
|
||||
* against that page's live DOM:
|
||||
*
|
||||
* - TWO paths share one `d` prefix: a **ghost** (dashed, faded) drawing the
|
||||
* whole route, and a **grown** solid stroke drawn only as far as the active
|
||||
* row. The grown one is what makes the branch look like it grew to you.
|
||||
* - A **dot per row**, sitting exactly on the curve.
|
||||
* - A **flower at the endpoint**: the stem grows into a bloom on the row you
|
||||
* are on, which is where the grown stroke stops. The bloom TURNS while that
|
||||
* session is working and rests when it is idle.
|
||||
* - The whole SVG is `pointer-events: none` and `overflow: visible`, so it is
|
||||
* pure decoration over the real rows and never intercepts a click.
|
||||
*
|
||||
* Measurement, not layout: the rows are rendered by the tree itself (they carry
|
||||
* drag handlers, menus and hover state), so this component reads each row's
|
||||
* vertical centre from the DOM and feeds plain numbers to `buildBranch`. That
|
||||
* keeps the geometry unit-tested (`branch.ts`) while the SVG stays a dumb
|
||||
* renderer of it.
|
||||
*
|
||||
* Re-measured on: row count changes (expand/collapse, new session), the active
|
||||
* row changing, and container resize. A `ResizeObserver` on the scroll body
|
||||
* covers the last one without a window listener.
|
||||
*
|
||||
* The bloom's spin is NOT re-measured here: it arrives as the `spinning` prop
|
||||
* and is applied as a class, so a status flip never re-runs the DOM measurement
|
||||
* above (the tree is the expensive part, not the class swap).
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { buildBranch, type Branch, type BranchRow } from './branch.ts'
|
||||
|
||||
/**
|
||||
* Attribute the tree puts on every row the branch should connect. */
|
||||
export const BRANCH_ROW_ATTRIBUTE = 'data-wg-branch-row'
|
||||
|
||||
/**
|
||||
* Attribute marking the row the stem should grow to.
|
||||
*
|
||||
* Only the DEEPEST row gets this (the session). Its ancestors — the project and
|
||||
* the category that contain it — deliberately do NOT, because a session belongs
|
||||
* to both and marking all three would make "which row is active?" ambiguous.
|
||||
* When several rows do carry it, the deepest (last in document order) wins.
|
||||
*/
|
||||
export const BRANCH_ACTIVE_ATTRIBUTE = 'data-wg-branch-active'
|
||||
|
||||
/** Row kind marker: a group boundary kinks the stem. */
|
||||
export const BRANCH_GROUP_ATTRIBUTE = 'data-wg-branch-group'
|
||||
|
||||
/**
|
||||
* The bloom's petal outline, in the 1024-unit box the artwork was drawn in.
|
||||
*
|
||||
* This is the user's own flower glyph verbatim: an eight-petal bloom around a
|
||||
* ringed center. Kept as a path (not a component) because it is a constant.
|
||||
*/
|
||||
const FLOWER_PATH = 'M375.3728 841.8432c92.96-12.5184 203.8784-71.264 299.5456-166.9248 22.6112-22.6112 43.1616-46.08 61.5232-69.952C712.7616 786.3936 621.2608 921.6 512 921.6c-51.1488 0-98.4-29.632-136.6272-79.7568z m-87.808-422.8096C311.2384 237.6064 402.7328 102.4 512 102.4c51.1488 0 98.4 29.632 136.6272 79.7568-92.96 12.5184-203.8784 71.264-299.5456 166.9248a719.1232 719.1232 0 0 0-61.5232 69.952z m-129.536 139.5648c57.3248 74.2464 163.6608 140.9344 294.336 175.9488a719.1232 719.1232 0 0 0 91.3472 18.304c-168.9664 70.208-331.808 58.5728-386.432-36.0512-25.5744-44.288-23.5456-100.032 0.7552-158.2016z m322.2592-287.4496c168.9664-70.208 331.808-58.5728 386.432 36.0512 25.5744 44.288 23.5456 100.032-0.7552 158.2016-57.3184-74.2464-163.648-140.9344-294.336-175.9488a719.1232 719.1232 0 0 0-91.3408-18.304zM294.656 228.7552c-35.6352 86.7648-40.224 212.1984-5.2032 342.8736a719.1232 719.1232 0 0 0 29.8176 88.256C173.9904 548.6592 102.6432 401.824 157.2736 307.2c25.5744-44.288 74.8608-70.4 137.3824-78.4448z m410.0736 135.36c145.28 111.2256 216.6272 258.0608 161.9968 352.6848-25.5744 44.288-74.8608 70.4-137.3824 78.4448 35.6352-86.7648 40.224-212.1984 5.2032-342.8736a719.1232 719.1232 0 0 0-29.8176-88.256zM512 678.4c-88.3648 0-160-71.6352-160-160s71.6352-160 160-160 160 71.6352 160 160-71.6352 160-160 160z m0-83.2c42.4128 0 76.8-34.3872 76.8-76.8s-34.3872-76.8-76.8-76.8-76.8 34.3872-76.8 76.8 34.3872 76.8 76.8 76.8z'
|
||||
|
||||
/** Petal colour: the accent the glyph was drawn in. */
|
||||
const FLOWER_PETAL = '#fa541c'
|
||||
|
||||
/**
|
||||
* Rendered size of the bloom, as a scale factor over the authored 1024 box.
|
||||
*
|
||||
* 17 / 1024 ≈ 0.0166 puts the flower at ~17px: clear of neighbouring rows (rows
|
||||
* are 28px tall) while still reading as a flower rather than a dot at the end of
|
||||
* the stem.
|
||||
*/
|
||||
const FLOWER_SCALE = 17 / 1024
|
||||
|
||||
/**
|
||||
* Centre of the artwork inside its own 1024-unit box, measured from the path.
|
||||
*
|
||||
* Both the recentring AND the rotation are expressed with this ONE pair of user
|
||||
* units, so neither depends on a percentage or on a reference box. Verified
|
||||
* against the live DOM: the path's own `getBBox()` centre is exactly (512, 512).
|
||||
*/
|
||||
const FLOWER_CENTRE = 512
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function Flower({ cx, cy, spinning }: { cx: number; cy: number; spinning: boolean }) {
|
||||
return (
|
||||
<g
|
||||
className={spinning ? 'wgFlower wgFlowerSpinning' : 'wgFlower'}
|
||||
transform={`translate(${cx} ${cy}) scale(${FLOWER_SCALE}) translate(${-FLOWER_CENTRE} ${-FLOWER_CENTRE})`}
|
||||
>
|
||||
<path className="wgFlowerArt" d={FLOWER_PATH} fill={FLOWER_PETAL} />
|
||||
</g>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the branch for the rows currently inside `scope`.
|
||||
* @param props - the element to measure, and whether the open session is working.
|
||||
* @returns the SVG overlay, or null until at least one row is measured.
|
||||
*/
|
||||
export function FlowerBranch({ scope, spinning }: { scope: HTMLElement | null; spinning: boolean }) {
|
||||
const [rows, setRows] = useState<BranchRow[]>([])
|
||||
|
||||
// A cheap change key: the caller cannot tell us when a row expanded, so we
|
||||
// watch the attribute count and the active row instead of diffing every node.
|
||||
const measureKey = useRef('')
|
||||
// The measured pixel pitch is per-list, not the module default: our rows are
|
||||
// 28/30px tall in places, and assuming 32 would drift the dots off the rows.
|
||||
const [branch, setBranch] = useState<Branch | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (scope === null) {
|
||||
setRows([])
|
||||
setBranch(null)
|
||||
return
|
||||
}
|
||||
|
||||
const measure = (): void => {
|
||||
const nodes = Array.from(scope.querySelectorAll<HTMLElement>(`[${BRANCH_ROW_ATTRIBUTE}]`))
|
||||
const first = nodes[0]
|
||||
if (first === undefined) {
|
||||
if (measureKey.current !== '') {
|
||||
measureKey.current = ''
|
||||
setRows([])
|
||||
setBranch(null)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Exactly one row carries the marker (the session); if a caller ever marks
|
||||
// several, the deepest wins so the stem still lands on a real leaf.
|
||||
const activeIndex = nodes.reduce(
|
||||
(found, node, index) => (node.hasAttribute(BRANCH_ACTIVE_ATTRIBUTE) ? index : found),
|
||||
-1,
|
||||
)
|
||||
const kinds = nodes.map(n => (n.hasAttribute(BRANCH_GROUP_ATTRIBUTE) ? 'group' : 'item')).join('')
|
||||
const key = `${nodes.length}|${activeIndex}|${kinds}|${Math.round(scope.clientWidth)}`
|
||||
if (key === measureKey.current) return
|
||||
measureKey.current = key
|
||||
|
||||
// Each row carries its OWN measured anchor: y because the tree mixes row
|
||||
// heights, x because it indents per row via padding (a folder's chevron and
|
||||
// a session's text do not share an x).
|
||||
const measured: BranchRow[] = nodes.map((node, index) => ({
|
||||
key: `${index}`,
|
||||
y: center(node),
|
||||
x: anchorX(node),
|
||||
kind: node.hasAttribute(BRANCH_GROUP_ATTRIBUTE) ? 'group' : 'item',
|
||||
active: index === activeIndex,
|
||||
}))
|
||||
|
||||
setRows(measured)
|
||||
setBranch(buildBranch(measured))
|
||||
}
|
||||
|
||||
/** Vertical centre of a node, relative to the scope box. */
|
||||
function center(node: HTMLElement): number {
|
||||
const r = node.getBoundingClientRect()
|
||||
const s = (scope as HTMLElement).getBoundingClientRect()
|
||||
return r.top - s.top + r.height / 2
|
||||
}
|
||||
|
||||
/**
|
||||
* Horizontal anchor of a row, relative to the scope box.
|
||||
*
|
||||
* A row with a chevron anchors to that triangle's CENTRE: it is the marker
|
||||
* the user already reads as "this row opens", so the stem hangs off it
|
||||
* instead of floating beside it. A chevron-less row (a session) has no
|
||||
* marker, so it anchors to where its own content starts — the status dot's
|
||||
* centre, which is the first thing in the row.
|
||||
*/
|
||||
function anchorX(node: HTMLElement): number {
|
||||
const s = (scope as HTMLElement).getBoundingClientRect()
|
||||
const marker = node.querySelector('.wgChevron')
|
||||
?? node.querySelector('[class*="wgStatusSlot"]')
|
||||
?? node.querySelector('[class*="wgCategoryIcon"]')
|
||||
?? node.querySelector('[class*="wgRowIcon"]')
|
||||
const box = (marker ?? node).getBoundingClientRect()
|
||||
return box.left - s.left + box.width / 2
|
||||
}
|
||||
|
||||
measure()
|
||||
|
||||
// Row set changes (expand/collapse/new session) arrive as childList edits.
|
||||
const observer = new MutationObserver(measure)
|
||||
observer.observe(scope, { childList: true, subtree: true, attributes: true, attributeFilter: [BRANCH_ACTIVE_ATTRIBUTE] })
|
||||
|
||||
// Width changes reflow row heights in the rail/wide layouts.
|
||||
const resizer = new ResizeObserver(measure)
|
||||
resizer.observe(scope)
|
||||
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
resizer.disconnect()
|
||||
}
|
||||
}, [scope])
|
||||
|
||||
// Dots are rendered from the measured rows; keep the memo keyed on identity so
|
||||
// a re-render with the same branch does not rebuild the element list.
|
||||
const dots = useMemo(() => branch?.dots ?? [], [branch])
|
||||
// The endpoint dot gives way to the bloom.
|
||||
const flowerKey = branch?.flower?.key
|
||||
|
||||
if (branch === null || rows.length === 0) return null
|
||||
|
||||
return (
|
||||
<svg
|
||||
className="wgBranch"
|
||||
// The box covers the measured span; `overflow: visible` lets the kink draw
|
||||
// outside it without clipping (the reference does the same).
|
||||
width={48}
|
||||
height={Math.max(1, Math.ceil(branch.height))}
|
||||
viewBox={`0 0 48 ${Math.max(1, Math.ceil(branch.height))}`}
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<path className="wgBranchGhost" d={branch.ghostPath} />
|
||||
<path className="wgBranchGrown" d={branch.grownPath} />
|
||||
{dots.map(dot => {
|
||||
// The bloom REPLACES the endpoint's dot rather than stacking on it: a
|
||||
// dot left underneath would show through the petals' notches and read
|
||||
// as a second, smaller flower.
|
||||
if (dot.key === flowerKey) return null
|
||||
return (
|
||||
<circle
|
||||
key={dot.key}
|
||||
className={dot.active ? 'wgBranchDot wgBranchDotActive' : 'wgBranchDot'}
|
||||
cx={dot.cx}
|
||||
cy={dot.cy}
|
||||
r={dot.active ? 3.2 : 2}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
{branch.flower !== null && (
|
||||
<Flower cx={branch.flower.cx} cy={branch.flower.cy} spinning={spinning} />
|
||||
)}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
|
@ -17,14 +17,19 @@
|
|||
import { useEffect, useMemo, useRef, useState, type DragEvent } from 'react'
|
||||
import {
|
||||
Button,
|
||||
IconCloseFill14,
|
||||
IconFolderOpenOutline16,
|
||||
IconProjectAddOutline16,
|
||||
IconSearchOutline16,
|
||||
IconCloseFillMedium,
|
||||
IconFolderOpenOutlineRegular,
|
||||
IconProjectAddOutlineRegular,
|
||||
IconSearchOutlineRegular,
|
||||
IconWarningOutlineRegular,
|
||||
Modal,
|
||||
Toast,
|
||||
Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SessionId, SessionListState, SessionSearchResultItem, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'
|
||||
import {
|
||||
displayCategoryKeys,
|
||||
moveAfter,
|
||||
|
|
@ -35,8 +40,12 @@ import {
|
|||
} from '../core/matcher.ts'
|
||||
import { TOP_LEVEL_ORDER_KEY, UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../core/types.ts'
|
||||
import type { GroupsBrowserProps } from './contract.ts'
|
||||
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
|
||||
import { CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, SessionRow, WorkspaceRow } from './rows.tsx'
|
||||
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
|
||||
import { CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, SessionRow, TreeChildren, WorkspaceRow } from './rows.tsx'
|
||||
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
|
||||
|
|
@ -147,6 +156,7 @@ export function GroupsBrowser({
|
|||
expandSidebar,
|
||||
useSessions,
|
||||
useWorkspaces,
|
||||
useSessionStatus,
|
||||
useStore,
|
||||
actions,
|
||||
startSession,
|
||||
|
|
@ -162,6 +172,9 @@ export function GroupsBrowser({
|
|||
pickDirectory,
|
||||
searchSessions,
|
||||
searchResultLimit,
|
||||
openTab,
|
||||
useTabs,
|
||||
tabActions,
|
||||
t,
|
||||
}: GroupsBrowserProps) {
|
||||
// Inject the stylesheet once per fiber; dispose removes it (HMR safe).
|
||||
|
|
@ -173,6 +186,21 @@ export function GroupsBrowser({
|
|||
return () => { style.remove() }
|
||||
}, [])
|
||||
|
||||
// Ctrl+R toggles the quick switch panel. Capture phase + preventDefault:
|
||||
// beats the browser's page-reload default and any shell-level handler.
|
||||
const [quickOpen, setQuickOpen] = useState(false)
|
||||
useEffect(() => {
|
||||
const onKeyDown = (e: KeyboardEvent): void => {
|
||||
if (e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey && (e.key === 'r' || e.key === 'R')) {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setQuickOpen(v => !v)
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKeyDown, true)
|
||||
return () => window.removeEventListener('keydown', onKeyDown, true)
|
||||
}, [])
|
||||
|
||||
// Grouping config from the host route + the runtime manual overlay.
|
||||
const [config, setConfig] = useState<GroupsConfig>({ categories: [] })
|
||||
const [manual, setManual] = useState<NormalizedManual>(EMPTY_MANUAL)
|
||||
|
|
@ -199,11 +227,25 @@ export function GroupsBrowser({
|
|||
const workspaceExpansion = useStore(s => s.workspaceExpansion)
|
||||
|
||||
const list = useSessions(s => s)
|
||||
const current = list.current
|
||||
const statuses = useSessionStatus(s => s)
|
||||
// 0.1.6: the selected Session is the one retained through `mainView`, not a
|
||||
// `list.current` field (the list snapshot carries catalog facts only).
|
||||
const current = currentSessionId(list)
|
||||
const currentWorkspaceKey = current === undefined
|
||||
? undefined
|
||||
: (workspaces.find(w => w.sessionIds.includes(current as SessionId))?.workspaceId as string | undefined)
|
||||
|
||||
// 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
|
||||
|
|
@ -229,6 +271,19 @@ export function GroupsBrowser({
|
|||
)
|
||||
}, [actions, config, manual, workspacePhase, workspaces])
|
||||
|
||||
// Session tabs: the strip lives in the conversation column, but its lifecycle
|
||||
// belongs here — the browser already derives the open session for its own tree,
|
||||
// so one effect covers every way a session can be opened (sidebar row,
|
||||
// workspace New Session, quick panel, conversation-header crumbs).
|
||||
//
|
||||
// `statuses` is a dependency on purpose: a session earns its tab when it
|
||||
// STARTS working, which is a status change, not a catalog change. Without it a
|
||||
// conversation that began while already open would never surface a tab.
|
||||
useEffect(() => {
|
||||
if (current === undefined) return
|
||||
openTab(current, statuses.get(current))
|
||||
}, [current, list, statuses, openTab])
|
||||
|
||||
const [query, setQuery] = useState('')
|
||||
const [searchExpanded, setSearchExpanded] = useState(false)
|
||||
const normalizedQuery = sanitizeSearchQuery(query).trim()
|
||||
|
|
@ -237,6 +292,10 @@ 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(() => {
|
||||
|
|
@ -289,17 +348,26 @@ export function GroupsBrowser({
|
|||
() => deriveGroups(list, workspaces, archivedSessionIds, config, {
|
||||
expandedCategories,
|
||||
expandedWorkspaces,
|
||||
}, manual),
|
||||
[list, workspaces, archivedSessionIds, config, manual, expandedCategories, expandedWorkspaces],
|
||||
}, manual, statuses),
|
||||
[list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces],
|
||||
)
|
||||
// Top-level (ungrouped) workspace rows, rendered after the group folders.
|
||||
const topLevel = useMemo(
|
||||
() => deriveTopLevel(list, workspaces, archivedSessionIds, config, {
|
||||
expandedCategories,
|
||||
expandedWorkspaces,
|
||||
}, manual),
|
||||
[list, workspaces, archivedSessionIds, config, manual, expandedCategories, expandedWorkspaces],
|
||||
}, manual, statuses),
|
||||
[list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces],
|
||||
)
|
||||
// Quick panel (Ctrl+R): category label per grouped workspace id (the tree
|
||||
// derivation already resolved grouping; top-level workspaces stay absent).
|
||||
const categoryByWorkspace = useMemo(() => {
|
||||
const map = new Map<string, string>()
|
||||
for (const category of groups) {
|
||||
for (const workspace of category.workspaces) map.set(workspace.workspaceId as string, category.label)
|
||||
}
|
||||
return map
|
||||
}, [groups])
|
||||
// While dragging a project, an empty top-level area must still show a landing
|
||||
// line — otherwise a project can never be dragged OUT of a group when every
|
||||
// project is currently grouped.
|
||||
|
|
@ -397,12 +465,44 @@ export function GroupsBrowser({
|
|||
setSessionRenameError(null)
|
||||
}
|
||||
|
||||
// The strip is a child of this component (rendered through a DOM portal), so
|
||||
// it shares this fiber's props directly: renames call the dialog owner here,
|
||||
// and activation goes through the same navigation verb the sidebar rows use.
|
||||
const activateTab = (sessionId: SessionId) => { open(sessionId) }
|
||||
|
||||
const onSessionArchive = (sessionId: SessionId) => {
|
||||
archiveSession(sessionId).catch((reason: unknown) => {
|
||||
console.warn('session archive rejected:', reason)
|
||||
})
|
||||
}
|
||||
|
||||
// "Open in folder": the host half of the official open-in-app plugin resolves
|
||||
// which applications it can launch; the project row then just posts the
|
||||
// project directory to that host's launch route. One availability read per
|
||||
// mount — a host without the capability (or a refused read) leaves
|
||||
// `folderApp` undefined, which drops the menu entry rather than failing.
|
||||
const [folderApp, setFolderApp] = useState<string | undefined>(undefined)
|
||||
const [folderError, setFolderError] = useState<{ id: number; text: string } | null>(null)
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
fetchOpenInApps(controller.signal).then((apps) => {
|
||||
if (controller.signal.aborted) return
|
||||
setFolderApp(folderAppId(apps))
|
||||
}).catch(() => { /* no capability: the row simply offers no folder entry */ })
|
||||
return () => { controller.abort() }
|
||||
}, [])
|
||||
|
||||
const openInFolder = folderApp === undefined
|
||||
? undefined
|
||||
: (workspaceId: WorkspaceId): void => {
|
||||
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
|
||||
if (workspace === undefined) return
|
||||
openPathInApp(folderApp, workspace.path).catch((reason: unknown) => {
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
setFolderError({ id: Date.now(), text: `${t('workspace.openInFolderError')}: ${detail}` })
|
||||
})
|
||||
}
|
||||
|
||||
// ---- Runtime group management ----------------------------------------------
|
||||
|
||||
const [groupDialog, setGroupDialog] = useState<GroupDialogState>(null)
|
||||
|
|
@ -755,6 +855,20 @@ export function GroupsBrowser({
|
|||
|
||||
return (
|
||||
<div className={`wgRoot${wide ? '' : ' wgRail'}`}>
|
||||
{/* The tab strip portals itself into the conversation column's head seat,
|
||||
so its position here is irrelevant to where it appears; rendering it
|
||||
from this component is what keeps it on this fiber (and therefore on
|
||||
this store's single scope) while still reaching the other column. */}
|
||||
<SessionTabs
|
||||
useSessions={useSessions}
|
||||
useSessionStatus={useSessionStatus}
|
||||
useWorkspaces={useWorkspaces}
|
||||
useTabs={useTabs}
|
||||
actions={tabActions}
|
||||
activate={activateTab}
|
||||
rename={onSessionRename}
|
||||
t={t}
|
||||
/>
|
||||
<div className="wgSectionHeader">
|
||||
{wide && <span className="wgSectionLabel">{t('section.workspaces')}</span>}
|
||||
{wide && (
|
||||
|
|
@ -765,7 +879,7 @@ export function GroupsBrowser({
|
|||
aria-label={t('search')}
|
||||
onClick={() => { setSearchExpanded(true) }}
|
||||
>
|
||||
<IconSearchOutline16 size={searchExpanded ? 11 : 14} />
|
||||
<IconSearchOutlineRegular size={searchExpanded ? 11 : 14} />
|
||||
</button>
|
||||
{searchExpanded && (
|
||||
<input
|
||||
|
|
@ -795,7 +909,7 @@ export function GroupsBrowser({
|
|||
setSearchExpanded(false)
|
||||
}}
|
||||
>
|
||||
<IconCloseFill14 />
|
||||
<IconCloseFillMedium />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -811,7 +925,7 @@ export function GroupsBrowser({
|
|||
setGroupDialog({ mode: 'create' })
|
||||
}}
|
||||
>
|
||||
<IconFolderOpenOutline16 size={wide ? 16 : 18} />
|
||||
<IconFolderOpenOutlineRegular size={wide ? 16 : 18} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('workspace.add')} side="bottom" delayMs={500}>
|
||||
|
|
@ -822,7 +936,7 @@ export function GroupsBrowser({
|
|||
disabled={adding}
|
||||
onClick={addWorkspace}
|
||||
>
|
||||
<IconProjectAddOutline16 size={wide ? 16 : 18} />
|
||||
<IconProjectAddOutlineRegular size={wide ? 16 : 18} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
|
@ -836,7 +950,7 @@ export function GroupsBrowser({
|
|||
aria-label={t('search')}
|
||||
onClick={() => { setSearchExpanded(true); expandSidebar() }}
|
||||
>
|
||||
<IconSearchOutline16 size={18} />
|
||||
<IconSearchOutlineRegular size={18} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
|
@ -855,6 +969,7 @@ export function GroupsBrowser({
|
|||
workspaces={workspaces}
|
||||
config={config}
|
||||
archivedSessionIds={archivedSessionIds}
|
||||
statuses={statuses}
|
||||
query={normalizedQuery}
|
||||
remote={remoteSearch}
|
||||
resultLimit={searchResultLimit}
|
||||
|
|
@ -865,7 +980,13 @@ export function GroupsBrowser({
|
|||
t={t}
|
||||
/>
|
||||
) : (
|
||||
<div className="wgList" role="tree" aria-label={t('section.workspaces')}>
|
||||
/* The branch overlay lives beside the tree, not inside it: it measures
|
||||
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="wgList" role="tree" aria-label={t('section.workspaces')}>
|
||||
{groups.length === 0 && topLevel.length === 0 && !topLevelDropActive && (
|
||||
<div className="wgEmpty">{workspacePhase === 'ready' ? t('empty.noWorkspaces') : t('empty.none')}</div>
|
||||
)}
|
||||
|
|
@ -908,6 +1029,7 @@ export function GroupsBrowser({
|
|||
setGroupDeleteError(null)
|
||||
}}
|
||||
onMoveOut={(workspaceId) => { void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY) }}
|
||||
onOpenInFolder={openInFolder}
|
||||
canMoveOut={(workspaceId) => {
|
||||
// The menu "移出分组" is offered for any project that
|
||||
// currently sits inside a group (rule-classified or manual) —
|
||||
|
|
@ -952,8 +1074,10 @@ export function GroupsBrowser({
|
|||
onSessionRename={onSessionRename}
|
||||
onSessionArchive={onSessionArchive}
|
||||
onFork={forkSession}
|
||||
onOpenInFolder={openInFolder}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -1083,6 +1207,33 @@ export function GroupsBrowser({
|
|||
>
|
||||
<div className="wgAddError" role="alert">{addError}</div>
|
||||
</Modal>
|
||||
|
||||
{/* "Open in folder" failure: transient banner, keyed per attempt so a
|
||||
repeat failure restarts the cycle. */}
|
||||
{folderError !== null && (
|
||||
<Toast
|
||||
key={folderError.id}
|
||||
text={folderError.text}
|
||||
icon={<IconWarningOutlineRegular size={16} />}
|
||||
onDone={() => { setFolderError(null) }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Ctrl+R quick switch panel (conditionally mounted: fresh query per open). */}
|
||||
{quickOpen && (
|
||||
<QuickPanel
|
||||
onClose={() => { setQuickOpen(false) }}
|
||||
list={list}
|
||||
workspaces={workspaces}
|
||||
archivedSessionIds={archivedSessionIds}
|
||||
categoryByWorkspace={categoryByWorkspace}
|
||||
current={current}
|
||||
startSession={startSession}
|
||||
openSession={open}
|
||||
now={now}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -1100,7 +1251,7 @@ function categoriesForCurrent(
|
|||
}
|
||||
|
||||
/** One category section: header row + expanded workspace folders. */
|
||||
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onMoveOut, canMoveOut }: {
|
||||
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onMoveOut, canMoveOut, onOpenInFolder }: {
|
||||
category: CategoryNode
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
|
|
@ -1125,6 +1276,8 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
|
|||
onGroupDelete: () => void
|
||||
onMoveOut: (workspaceId: WorkspaceId) => void
|
||||
canMoveOut: (workspaceId: WorkspaceId) => boolean
|
||||
/** Absent when the host resolved no folder application. */
|
||||
onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined
|
||||
}) {
|
||||
const categoryLine = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'category' && dragIndicator.row.key === category.key
|
||||
? (dragIndicator.before ? 'before' : 'after')
|
||||
|
|
@ -1158,6 +1311,9 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
|
|||
onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}
|
||||
canMoveOut={canMoveOut(workspace.workspaceId)}
|
||||
onMoveOut={() => { onMoveOut(workspace.workspaceId) }}
|
||||
{...(onOpenInFolder !== undefined
|
||||
? { onOpenInFolder: () => { onOpenInFolder(workspace.workspaceId) } }
|
||||
: {})}
|
||||
dropActive={false}
|
||||
{...(dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'workspace' && dragIndicator.row.key === workspace.workspaceId
|
||||
? { insertLine: dragIndicator.before ? 'before' : 'after' }
|
||||
|
|
@ -1167,19 +1323,23 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
|
|||
onRowDrop={onDropRow(category.key, { kind: 'workspace', key: workspace.workspaceId })}
|
||||
onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}
|
||||
/>
|
||||
{workspace.expanded && workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
/>
|
||||
))}
|
||||
{workspace.expanded && (
|
||||
<TreeChildren>
|
||||
{workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
/>
|
||||
))}
|
||||
</TreeChildren>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -1197,7 +1357,7 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
|
|||
* last row);
|
||||
* - an empty top level shows a standalone line under the last group folder.
|
||||
*/
|
||||
function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork }: {
|
||||
function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onOpenInFolder }: {
|
||||
topLevel: readonly WorkspaceGroupNode[]
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
|
|
@ -1219,6 +1379,8 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t
|
|||
onSessionRename: (sessionId: SessionId, currentTitle: string) => void
|
||||
onSessionArchive: (sessionId: SessionId) => void
|
||||
onFork: (sessionId: SessionId) => void
|
||||
/** Absent when the host resolved no folder application. */
|
||||
onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined
|
||||
}) {
|
||||
const emptyLineActive = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'topLevel' && dragIndicator.row.key === topLevelRef.key
|
||||
return (
|
||||
|
|
@ -1251,6 +1413,9 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t
|
|||
onNewSession={() => { onNewSession(workspace.workspaceId) }}
|
||||
onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}
|
||||
onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}
|
||||
{...(onOpenInFolder !== undefined
|
||||
? { onOpenInFolder: () => { onOpenInFolder(workspace.workspaceId) } }
|
||||
: {})}
|
||||
{...(dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'topLevel' && dragIndicator.row.key === workspace.workspaceId
|
||||
? { insertLine: dragIndicator.before ? 'before' : 'after' }
|
||||
: {})}
|
||||
|
|
@ -1259,19 +1424,23 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t
|
|||
onRowDrop={onDropRow(UNCATEGORIZED_KEY, { kind: 'topLevel', key: workspace.workspaceId })}
|
||||
onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}
|
||||
/>
|
||||
{workspace.expanded && workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
/>
|
||||
))}
|
||||
{workspace.expanded && (
|
||||
<TreeChildren>
|
||||
{workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
/>
|
||||
))}
|
||||
</TreeChildren>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -1283,11 +1452,12 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t
|
|||
* 分类文件夹 → 项目文件夹 → 命中会话行. 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, query, remote, resultLimit, current, now, open, manual, t }: {
|
||||
function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, query, remote, resultLimit, current, now, open, manual, t }: {
|
||||
list: SessionListState
|
||||
workspaces: readonly WorkspaceView[]
|
||||
config: GroupsConfig
|
||||
archivedSessionIds: readonly SessionId[]
|
||||
statuses: SessionStatusSnapshot
|
||||
query: string
|
||||
remote: RemoteSearchState
|
||||
resultLimit: number
|
||||
|
|
@ -1303,8 +1473,8 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, query, remot
|
|||
[list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],
|
||||
)
|
||||
const searchTree = useMemo(
|
||||
() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession),
|
||||
[list, workspaces, config, matches, archivedSessionIds, manual],
|
||||
() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses),
|
||||
[list, workspaces, config, matches, archivedSessionIds, manual, statuses],
|
||||
)
|
||||
const groups = searchTree.categories
|
||||
const searchTopLevel = searchTree.topLevel
|
||||
|
|
|
|||
|
|
@ -0,0 +1,353 @@
|
|||
/**
|
||||
* Ctrl+R quick switch panel: two tabs over the framework's global hooks.
|
||||
*
|
||||
* - Workspaces tab: search real Workspaces, select one, then either start a
|
||||
* New Session in it or jump straight to its most recently updated running
|
||||
* session (the button reads the none-running state and disables).
|
||||
* - Sessions tab: every top-level session across workspaces — running ones
|
||||
* pinned on top, everything else under them, both groups newest first; one
|
||||
* click (or Enter) opens it. The shared search input filters by session or
|
||||
* workspace title and never re-sorts, so the running-first order survives.
|
||||
*
|
||||
* Current-row marker: the open workspace (workspaces tab) and the open
|
||||
* session (sessions tab) render `.wgQuickRowCurrent`; with no current
|
||||
* session — or one no listed workspace holds — nothing is marked.
|
||||
*
|
||||
* Mount discipline: the parent conditionally mounts this component, so every
|
||||
* open starts from a fresh query/selection (quick-switcher semantics). The
|
||||
* overlay portals to document.body (sidebar ancestors clip `fixed`), sizes
|
||||
* itself like a launcher (top-anchored, 640px) instead of the host Modal's
|
||||
* 380px dialog, and handles Escape / mask click by itself. Pure data shaping
|
||||
* lives in quick.ts; this file only binds hooks + actions.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Button, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { activeWorkspaceId, allSessions, filterSessions, filterWorkspaces, latestRunningInWorkspace, runningCountByWorkspace, runningSessions } from './quick.ts'
|
||||
import { relativeTimeLabel } from './rows.tsx'
|
||||
|
||||
/** Which surface of the quick panel is active. */
|
||||
export type QuickTab = 'workspaces' | 'sessions'
|
||||
|
||||
/** The locale seat's translate function (same shape GroupsBrowser receives). */
|
||||
type Translate = PropsLocale<'workspaceGroups'>['t']
|
||||
|
||||
/** Quick panel props: hooks snapshots + the two injected verbs + shared CSS context. */
|
||||
export type QuickPanelProps = {
|
||||
/** Close request (Escape, mask click, action completed, or parent Ctrl+R toggle). */
|
||||
onClose: () => void
|
||||
/** Sessions list snapshot (drives running detection). */
|
||||
list: SessionListState
|
||||
/** Real workspaces in stable Host order. */
|
||||
workspaces: readonly WorkspaceView[]
|
||||
/** Registry-global archive set. */
|
||||
archivedSessionIds: readonly SessionId[]
|
||||
/** Category label per grouped workspace id (badge column; top-level absent). */
|
||||
categoryByWorkspace: ReadonlyMap<string, string>
|
||||
/** The Session the Conversation currently shows (mainView retention), if any. */
|
||||
current: SessionId | undefined
|
||||
/** Start a New Session in a workspace (injected share verb). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void
|
||||
/** Open a real Session (injected share verb). */
|
||||
openSession: (sessionId: SessionId) => void
|
||||
/** Render clock for relative times (parent refreshes per render). */
|
||||
now: number
|
||||
/** Dictionary accessor (workspaceGroups namespace). */
|
||||
t: Translate
|
||||
}
|
||||
|
||||
/** Basename of a host path (both separators; shortens the workspace row sub-line). */
|
||||
function pathBasename(path: string): string {
|
||||
const trimmed = path.replace(/[/\\]+$/, '')
|
||||
const base = trimmed.split(/[/\\]/).pop()
|
||||
return base !== undefined && base !== '' ? base : trimmed
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the quick switch panel (portaled overlay).
|
||||
* @param props - hooks snapshots + injected verbs.
|
||||
* @returns the panel element tree.
|
||||
*/
|
||||
export function QuickPanel({
|
||||
onClose,
|
||||
list,
|
||||
workspaces,
|
||||
archivedSessionIds,
|
||||
categoryByWorkspace,
|
||||
current: currentSessionId,
|
||||
startSession,
|
||||
openSession,
|
||||
now,
|
||||
t,
|
||||
}: QuickPanelProps) {
|
||||
const [tab, setTab] = useState<QuickTab>('workspaces')
|
||||
const [query, setQuery] = useState('')
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
const [activeIndex, setActiveIndex] = useState(0)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const activeRowRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
const archived = useMemo(() => new Set(archivedSessionIds), [archivedSessionIds])
|
||||
const running = useMemo(() => runningSessions(list, archived), [list, archived])
|
||||
const runCounts = useMemo(() => runningCountByWorkspace(running, workspaces), [running, workspaces])
|
||||
const filtered = useMemo(
|
||||
() => filterWorkspaces(workspaces, query, ws => categoryByWorkspace.get(ws.workspaceId as string)),
|
||||
[workspaces, query, categoryByWorkspace],
|
||||
)
|
||||
|
||||
// Where the user is right now: the open session and its owning workspace.
|
||||
// Both may be absent (no mainView retention, or a session no listed
|
||||
// workspace holds) — the current-row marker simply never renders then.
|
||||
const currentWorkspaceId = useMemo(
|
||||
() => activeWorkspaceId(workspaces, currentSessionId),
|
||||
[workspaces, currentSessionId],
|
||||
)
|
||||
|
||||
// Sessions tab data: every top-level session, running pinned on top then
|
||||
// recency, filtered by the shared search query (filter never re-sorts).
|
||||
const sessions = useMemo(
|
||||
() => allSessions(list, archived, currentSessionId),
|
||||
[list, archived, currentSessionId],
|
||||
)
|
||||
// Owning workspace title per session id (row sub-line + search field);
|
||||
// first workspace wins — a session lives in exactly one.
|
||||
const workspaceTitleBySession = useMemo(() => {
|
||||
const map = new Map<SessionId, string>()
|
||||
for (const workspace of workspaces) {
|
||||
for (const sessionId of workspace.sessionIds) {
|
||||
if (!map.has(sessionId)) map.set(sessionId, workspace.title)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}, [workspaces])
|
||||
const filteredSessions = useMemo(
|
||||
() => filterSessions(sessions, query, s => workspaceTitleBySession.get(s.id)),
|
||||
[sessions, query, workspaceTitleBySession],
|
||||
)
|
||||
|
||||
const selected = selectedId === null
|
||||
? undefined
|
||||
: workspaces.find(w => (w.workspaceId as string) === selectedId)
|
||||
const selectedRunningId = selected === undefined ? undefined : latestRunningInWorkspace(list, selected)
|
||||
|
||||
// Focus the search input whenever a tab becomes reachable (both tabs own it).
|
||||
useEffect(() => {
|
||||
inputRef.current?.focus()
|
||||
}, [tab])
|
||||
|
||||
// Keep the keyboard-active row visible while arrowing through the list.
|
||||
useEffect(() => {
|
||||
activeRowRef.current?.scrollIntoView({ block: 'nearest' })
|
||||
}, [activeIndex])
|
||||
|
||||
/** Select the workspace and close (New Session verb). */
|
||||
const launchNewSession = (workspace: WorkspaceView): void => {
|
||||
startSession(workspace.workspaceId)
|
||||
onClose()
|
||||
}
|
||||
|
||||
/** Open a session row and close (sessions tab click or Enter). */
|
||||
const launchSession = (sessionId: SessionId): void => {
|
||||
openSession(sessionId)
|
||||
onClose()
|
||||
}
|
||||
|
||||
/** Switch tabs; the query carries over, the per-tab selection resets. */
|
||||
const switchTab = (next: QuickTab): void => {
|
||||
setTab(next)
|
||||
setSelectedId(null)
|
||||
setActiveIndex(0)
|
||||
}
|
||||
|
||||
/** Search-input keyboard: arrows move the active row; Enter confirms it. */
|
||||
const onSearchKeyDown = (e: KeyboardEvent<HTMLInputElement>): void => {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
const max = (tab === 'workspaces' ? filtered.length : filteredSessions.length) - 1
|
||||
setActiveIndex(i => Math.min(i + 1, Math.max(max, 0)))
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
setActiveIndex(i => Math.max(i - 1, 0))
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
if (tab === 'workspaces') {
|
||||
if (selected === undefined) {
|
||||
const target = filtered[activeIndex]
|
||||
if (target !== undefined) setSelectedId(target.workspaceId as string)
|
||||
} else {
|
||||
launchNewSession(selected)
|
||||
}
|
||||
} else {
|
||||
const target = filteredSessions[activeIndex]
|
||||
if (target !== undefined) launchSession(target.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Escape closes (capture so row buttons and the input can't swallow it). */
|
||||
const onCardKeyDown = (e: KeyboardEvent<HTMLDivElement>): void => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
/** Mask click closes; clicks inside the card never reach the mask. */
|
||||
const onOverlayMouseDown = (e: MouseEvent<HTMLDivElement>): void => {
|
||||
if (e.target === e.currentTarget) onClose()
|
||||
}
|
||||
|
||||
const selectWorkspace = (id: string): void => {
|
||||
setSelectedId(id)
|
||||
inputRef.current?.focus()
|
||||
}
|
||||
|
||||
return createPortal(
|
||||
<div className="wgQuickOverlay" onMouseDown={onOverlayMouseDown}>
|
||||
<div
|
||||
className="wgQuickCard"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t('quick.title')}
|
||||
onKeyDown={onCardKeyDown}
|
||||
>
|
||||
<div className="wgQuickHeader">
|
||||
<span className="wgQuickTitle">{t('quick.title')}</span>
|
||||
<div className="wgQuickTabs" role="tablist" aria-label={t('quick.title')}>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === 'workspaces'}
|
||||
className={`wgQuickTab${tab === 'workspaces' ? ' wgQuickTabActive' : ''}`}
|
||||
onClick={() => { switchTab('workspaces') }}
|
||||
>
|
||||
{t('quick.tab.workspaces')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === 'sessions'}
|
||||
className={`wgQuickTab${tab === 'sessions' ? ' wgQuickTabActive' : ''}`}
|
||||
onClick={() => { switchTab('sessions') }}
|
||||
>
|
||||
{t('quick.tab.sessions')}
|
||||
{running.length > 0 && <span className="wgQuickTabCount">{running.length}</span>}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Shared search: workspaces on one tab, sessions on the other. */}
|
||||
<div className="wgQuickSearchWrap">
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="wgQuickSearch"
|
||||
value={query}
|
||||
placeholder={tab === 'workspaces' ? t('quick.search.placeholder') : t('quick.search.sessions')}
|
||||
aria-label={tab === 'workspaces' ? t('quick.search.placeholder') : t('quick.search.sessions')}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value)
|
||||
setSelectedId(null)
|
||||
setActiveIndex(0)
|
||||
}}
|
||||
onKeyDown={onSearchKeyDown}
|
||||
/>
|
||||
</div>
|
||||
{tab === 'workspaces' ? (
|
||||
<>
|
||||
<div className="wgQuickList" role="listbox" aria-label={t('quick.tab.workspaces')}>
|
||||
{filtered.map((workspace, i) => {
|
||||
const id = workspace.workspaceId as string
|
||||
const count = runCounts.get(id) ?? 0
|
||||
const category = categoryByWorkspace.get(id)
|
||||
const isCurrent = id === currentWorkspaceId
|
||||
return (
|
||||
<button
|
||||
key={id}
|
||||
ref={i === activeIndex ? activeRowRef : undefined}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={selectedId === id}
|
||||
aria-current={isCurrent || undefined}
|
||||
className={
|
||||
`wgQuickRow${i === activeIndex ? ' wgQuickRowActive' : ''}${selectedId === id ? ' wgQuickRowSelected' : ''}${isCurrent ? ' wgQuickRowCurrent' : ''}`
|
||||
}
|
||||
onMouseEnter={() => { setActiveIndex(i) }}
|
||||
onClick={() => { selectWorkspace(id) }}
|
||||
>
|
||||
<span className="wgQuickRowMain">
|
||||
<span className="wgQuickRowTitle">{workspace.title}</span>
|
||||
{count > 0 && <span className="wgQuickRunBadge">● {count}</span>}
|
||||
</span>
|
||||
<span className="wgQuickRowSub">
|
||||
<span className="wgQuickRowPath">
|
||||
{category !== undefined ? `${category} · ${pathBasename(workspace.path)}` : pathBasename(workspace.path)}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{filtered.length === 0 && <div className="wgQuickEmpty">{t('quick.empty.workspaces')}</div>}
|
||||
</div>
|
||||
<div className="wgQuickFooter">
|
||||
<span className="wgQuickSelected">
|
||||
{selected === undefined ? t('quick.select.hint') : selected.title}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={selected === undefined || selectedRunningId === undefined}
|
||||
onClick={() => { if (selectedRunningId !== undefined) launchSession(selectedRunningId) }}
|
||||
>
|
||||
{selectedRunningId !== undefined ? t('quick.action.running') : t('quick.action.noneRunning')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={selected === undefined}
|
||||
onClick={() => { if (selected !== undefined) launchNewSession(selected) }}
|
||||
>
|
||||
{t('quick.action.newSession')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="wgQuickList" role="listbox" aria-label={t('quick.tab.sessions')}>
|
||||
{filteredSessions.map((session, i) => {
|
||||
const workspaceTitle = workspaceTitleBySession.get(session.id) ?? ''
|
||||
const isCurrent = session.id === currentSessionId
|
||||
return (
|
||||
<button
|
||||
key={session.id}
|
||||
ref={i === activeIndex ? activeRowRef : undefined}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={i === activeIndex}
|
||||
aria-current={isCurrent || undefined}
|
||||
className={`wgQuickRow${i === activeIndex ? ' wgQuickRowActive' : ''}${isCurrent ? ' wgQuickRowCurrent' : ''}`}
|
||||
onMouseEnter={() => { setActiveIndex(i) }}
|
||||
onClick={() => { launchSession(session.id) }}
|
||||
>
|
||||
<span className="wgQuickRowMain">
|
||||
<StateDot state={session.running ? 'ongoing' : 'done'} />
|
||||
<span className="wgQuickRowTitle">{session.blank ? t('newSession') : session.displayTitle}</span>
|
||||
<span className="wgQuickTime">{relativeTimeLabel(session.updatedAt, now)}</span>
|
||||
</span>
|
||||
<span className="wgQuickRowSub">
|
||||
<span className="wgQuickRowPath">{workspaceTitle}</span>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{filteredSessions.length === 0 && <div className="wgQuickEmpty">{t('quick.empty.sessions')}</div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="wgQuickHint">{t('quick.hint')}</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,191 @@
|
|||
/**
|
||||
* The session tab strip: one chip per opened conversation, rendered into the
|
||||
* DOM seat at the head of the conversation column (see `tab-seat.ts` for why
|
||||
* this is a DOM injection rather than a slot).
|
||||
*
|
||||
* A tab is a *view* of the open session, not a second navigation model:
|
||||
* clicking a chip navigates through `ctx.uiWorkspace.openSession`, which is the
|
||||
* one path that retains a target session; the owning component derives the
|
||||
* strip from the open session plus the tab store.
|
||||
*
|
||||
* The active chip is derived, never stored: it is the chip whose session is the
|
||||
* open one, so clicking a background chip immediately shows that chip active.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { IconCloseFillMedium, StateDot, Tooltip, type StateDotState } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SessionsTabsProps } from './contract.ts'
|
||||
import { mountTabSeat } from './tab-seat.ts'
|
||||
import { orderedTabs, projectIndex, tabIndicator, type SessionTab, type SessionTabIndicator } from './tabs.ts'
|
||||
import { currentSessionId } from './tree.ts'
|
||||
|
||||
/** Dot state for one tab (the sidebar's session rows share this vocabulary). */
|
||||
function dotState(indicator: SessionTabIndicator): StateDotState {
|
||||
if (indicator.attention) return 'warning'
|
||||
if (indicator.running) return 'ongoing'
|
||||
return 'done'
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the session tab strip into the conversation column's head seat.
|
||||
* @param props - tab store, catalog/status hooks, navigation, locale.
|
||||
* @returns the portal (or null until the column has mounted).
|
||||
*/
|
||||
export function SessionTabs({
|
||||
useTabs,
|
||||
actions,
|
||||
useSessions,
|
||||
useSessionStatus,
|
||||
useWorkspaces,
|
||||
activate,
|
||||
rename,
|
||||
t,
|
||||
}: SessionsTabsProps) {
|
||||
const tabs = useTabs(s => s.tabs)
|
||||
const list = useSessions(s => s)
|
||||
const statuses = useSessionStatus(s => s)
|
||||
const currentId = useSessions(s => currentSessionId(s))
|
||||
const workspaces = useWorkspaces(s => s.items)
|
||||
|
||||
// Session → owning project, in one pass over the workspace registry. This is
|
||||
// what lets each chip name its project; without it a strip of session titles
|
||||
// is ambiguous as soon as two projects are open.
|
||||
const projects = useMemo(() => projectIndex(workspaces), [workspaces])
|
||||
|
||||
// The seat is a DOM node outside React's tree, so it cannot arrive through
|
||||
// props; it is discovered once per mount and held in state to trigger the
|
||||
// portal's first render when the column appears.
|
||||
const [seat, setSeat] = useState<HTMLElement | null>(null)
|
||||
// The scrolling row, for wheel redirection and keep-active-in-view.
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const mounted = mountTabSeat(setSeat)
|
||||
// The column may already exist, in which case onReady fired synchronously
|
||||
// during mountTabSeat and setSeat is already queued; adopt it here too so
|
||||
// the very first paint has a host instead of waiting a frame.
|
||||
if (mounted.host !== null) setSeat(mounted.host)
|
||||
return () => {
|
||||
mounted.dispose()
|
||||
// The portal must stop targeting a removed node before the next mount.
|
||||
setSeat(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// The strip renders exactly the tabs the store holds. There is deliberately NO
|
||||
// filtering against the session catalog and no "close tabs whose session
|
||||
// vanished" sweep: a tab is removed when the USER closes it, and by nothing
|
||||
// else. Trimming automatically also misfires — the catalog is briefly empty on
|
||||
// every load, which deleted restored tabs before the sessions arrived.
|
||||
//
|
||||
// Arrival order is the only order: the active tab is marked, never moved.
|
||||
const display = useMemo(() => orderedTabs(tabs, currentId), [tabs, currentId])
|
||||
|
||||
// With the row scrollable, the active chip can sit outside the viewport —
|
||||
// e.g. after clicking a session in the sidebar that has a tab far to the
|
||||
// right. Bring it into view on selection change. `block: 'nearest'` keeps
|
||||
// this a horizontal-only scroll, and `inline: 'nearest'` avoids nudging the
|
||||
// row when the chip is already fully visible.
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current
|
||||
if (el === null || currentId === undefined) return
|
||||
const chip = el.querySelector<HTMLElement>(`[data-tab-session="${CSS.escape(currentId)}"]`)
|
||||
chip?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
|
||||
}, [currentId, display.length])
|
||||
|
||||
if (seat === null || display.length === 0) return null
|
||||
|
||||
return createPortal(
|
||||
<div className="wgTabs" role="tablist" aria-label={t('tabs.aria')}>
|
||||
<div
|
||||
className="wgTabsScroll"
|
||||
ref={scrollRef}
|
||||
onWheel={(event) => {
|
||||
// A plain wheel reports only `deltaY`, and the overflow here is
|
||||
// horizontal, so without this the wheel would do nothing over the
|
||||
// strip (or scroll the transcript behind it). Redirect the dominant
|
||||
// delta to scrollLeft, and only swallow the event once there is
|
||||
// somewhere left to scroll — otherwise a wheel at either end keeps
|
||||
// propagating and the page still scrolls normally.
|
||||
const el = event.currentTarget
|
||||
if (el.scrollWidth <= el.clientWidth) return
|
||||
const delta = Math.abs(event.deltaY) > Math.abs(event.deltaX) ? event.deltaY : event.deltaX
|
||||
if (delta === 0) return
|
||||
const atStart = el.scrollLeft <= 0 && delta < 0
|
||||
const atEnd = el.scrollLeft + el.clientWidth >= el.scrollWidth - 1 && delta > 0
|
||||
if (atStart || atEnd) return
|
||||
el.scrollLeft += delta
|
||||
event.preventDefault()
|
||||
}}
|
||||
>
|
||||
{display.map((tab: SessionTab) => {
|
||||
const summary = list.byId[tab.sessionId]
|
||||
// A restored tab can render before its catalog row arrives. Show the
|
||||
// session id meanwhile rather than an empty chip — the tab is real, and
|
||||
// the title fills in as soon as the catalog catches up.
|
||||
const label = summary === undefined
|
||||
? tab.sessionId
|
||||
: summary.blank ? t('newSession') : summary.displayTitle
|
||||
const active = tab.sessionId === currentId
|
||||
const indicator = tabIndicator(summary, statuses.get(tab.sessionId))
|
||||
// The project this session belongs to. Absent for a session that is in
|
||||
// no workspace (a bare session, or one just created before the
|
||||
// registry caught up) — the chip then shows the title alone rather
|
||||
// than a placeholder.
|
||||
const project = projects.get(tab.sessionId)
|
||||
// Title attribute carries the full pair plus the directory, so the
|
||||
// truncated chip text is recoverable on hover.
|
||||
const tip = project === undefined
|
||||
? label
|
||||
: `${project.label} · ${label}\n${project.path}`
|
||||
return (
|
||||
<div
|
||||
key={tab.order}
|
||||
className={`wgTab${active ? ' wgTabActive' : ''}`}
|
||||
data-tab-session={tab.sessionId}
|
||||
{...(project !== undefined ? { 'data-tab-project': project.workspaceId } : {})}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={active}
|
||||
className="wgTabMain"
|
||||
title={tip}
|
||||
onClick={() => { activate(tab.sessionId) }}
|
||||
onDoubleClick={() => { rename(tab.sessionId, label) }}
|
||||
>
|
||||
<span className="wgTabStatus" data-tab-state={indicator.attention ? 'attention' : indicator.running ? 'running' : indicator.unread ? 'unread' : indicator.settled ? 'settled' : 'idle'}>
|
||||
<StateDot state={dotState(indicator)} />
|
||||
</span>
|
||||
{/* Two stacked lines, folder-style: the project (short, quiet)
|
||||
over the session title (long, primary). The project line is
|
||||
omitted for a session in no workspace, which lets the title
|
||||
use the full height rather than leaving a blank row. */}
|
||||
<span className="wgTabText">
|
||||
{project !== undefined && (
|
||||
<span className="wgTabProject" title={project.path}>{project.label}</span>
|
||||
)}
|
||||
<span className="wgTabLabel">{label}</span>
|
||||
</span>
|
||||
</button>
|
||||
<Tooltip label={t('tabs.close')} side="top" delayMs={600}>
|
||||
<button
|
||||
type="button"
|
||||
className="wgTabClose"
|
||||
aria-label={`${t('tabs.close')} ${label}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
actions.close(tab.sessionId)
|
||||
}}
|
||||
>
|
||||
<IconCloseFillMedium />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>,
|
||||
seat,
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,340 @@
|
|||
/**
|
||||
* The "flower branch" geometry for the sidebar tree.
|
||||
*
|
||||
* Reproduces the RewampUI *Flower Sidebar* mechanism: a single curly branch runs
|
||||
* down the left of the nav list, drawn as SVG so it can be *grown* — a faded
|
||||
* dashed ghost shows the whole route, and a solid stroke is drawn only as far as
|
||||
* the row you are on. Each row gets a dot sitting exactly on the curve, and the
|
||||
* active row's dot blooms.
|
||||
*
|
||||
* How it maps onto OUR tree (three levels: 分组 folder → 项目 folder → 会话 row):
|
||||
*
|
||||
* - The branch is **one continuous path** through every visible row, not one
|
||||
* rail per folder. That is what makes it read as a plant rather than as the
|
||||
* per-folder rail it replaces.
|
||||
* - The stem runs at `STEM_X`; at each **group boundary** it kinks outward to
|
||||
* `BULGE_X` and back — a half-pitch out plus a half-pitch back, which is
|
||||
* exactly the reference's 32px rhythm.
|
||||
* - Rows that are not group boundaries sit on a straight run, one row pitch
|
||||
* apart, each carrying a dot at its own y.
|
||||
*
|
||||
* Runtime-free on purpose (same discipline as `tabs.ts` / `store-core.ts`): the
|
||||
* component measures the DOM and hands plain numbers here, so the geometry is
|
||||
* unit-testable without a browser.
|
||||
*/
|
||||
|
||||
/** Horizontal position of the stem's straight runs. */
|
||||
/**
|
||||
* Default x for a row's anchor, in SVG coordinates.
|
||||
*
|
||||
* A fallback only: rows carry their OWN measured `x`, because the tree indents
|
||||
* with per-row padding rather than one shared origin. A folder's chevron and a
|
||||
* session's text sit at different x, and no single constant lands on both.
|
||||
*/
|
||||
export const STEM_X = 30
|
||||
|
||||
/** Default vertical pitch between two rows. */
|
||||
export const ROW_PITCH = 32
|
||||
|
||||
/**
|
||||
* One row the branch must pass through.
|
||||
*
|
||||
* Both coordinates are MEASURED, not derived:
|
||||
* - `y` because the tree mixes row heights and inter-row gaps (deriving one
|
||||
* pitch from a single gap drifted the dots up to 15px off their rows);
|
||||
* - `x` because the tree indents per row via padding, so a folder's chevron and
|
||||
* a session's text are at different x.
|
||||
*/
|
||||
export interface BranchRow {
|
||||
/** Stable key, used to match a row to its dot. */
|
||||
readonly key: string
|
||||
/** Row centre y, in the SVG's coordinate space. */
|
||||
readonly y: number
|
||||
/**
|
||||
* Row anchor x, in the SVG's coordinate space.
|
||||
*
|
||||
* A folder row's anchor is its CHEVRON centre — the triangle the user already
|
||||
* reads as "this row opens" — so the stem visually hangs off the marker rather
|
||||
* than floating beside it. A session row's anchor is the indent its text sits
|
||||
* on.
|
||||
*/
|
||||
readonly x: number
|
||||
/**
|
||||
* Row kind. A `'group'` row starts a new group and makes the stem kink;
|
||||
* an `'item'` row runs straight (or curves back in right after a group).
|
||||
*/
|
||||
readonly kind: 'group' | 'item'
|
||||
/** Whether this is the row the user is currently on (the bloomed dot). */
|
||||
readonly active: boolean
|
||||
}
|
||||
|
||||
/** A dot on the branch: one per row, positioned on the curve. */
|
||||
export interface BranchDot {
|
||||
/** The row this dot belongs to. */
|
||||
readonly key: string
|
||||
readonly cx: number
|
||||
readonly cy: number
|
||||
readonly active: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The bloom that flowers at the branch's endpoint.
|
||||
*
|
||||
* The endpoint is where the GROWN stroke stops — the row the user is on — not
|
||||
* the last visible row: the stem is drawn to the active row, so that is where
|
||||
* the plant has visibly reached, whether the tree is folded above it or not.
|
||||
*
|
||||
* This is deliberately the ONE row an active marker names, so the flower can
|
||||
* never disagree with the stem about where the branch ends.
|
||||
*/
|
||||
export interface BranchFlower {
|
||||
/** Row whose endpoint carries the bloom (the active row's key). */
|
||||
readonly key: string
|
||||
/** Endpoint x: the last dot's centre, i.e. exactly where the grown path stops. */
|
||||
readonly cx: number
|
||||
/** Endpoint y, on the measured row centre. */
|
||||
readonly cy: number
|
||||
}
|
||||
|
||||
/** The branch: one path for the ghost, its total length, and the dots. */
|
||||
export interface Branch {
|
||||
/** Full route, drawn as the faded dashed ghost. */
|
||||
readonly ghostPath: string
|
||||
/** Path up to and including the active row (the "grown" part). */
|
||||
readonly grownPath: string
|
||||
/** Drawn length of the full route. */
|
||||
readonly ghostLength: number
|
||||
/** Drawn length of the grown part. */
|
||||
readonly grownLength: number
|
||||
/** Dots, in row order. */
|
||||
readonly dots: readonly BranchDot[]
|
||||
/**
|
||||
* Bloom at the grown path's endpoint, or NULL when no row carries the active
|
||||
* marker.
|
||||
*
|
||||
* Deliberately stricter than `grownPath`: the stem has to be *some* path even
|
||||
* when nothing is active (it collapses to the bare origin, drawing nothing),
|
||||
* but a bloom with no active row has nothing to be the flower OF. Falling back
|
||||
* to the first dot — the earlier rule — put the blossom on a folder row at the
|
||||
* top of the tree as soon as the open session's folder was collapsed, because
|
||||
* folding removes the only row carrying the marker. No active row means no
|
||||
* flower.
|
||||
*/
|
||||
readonly flower: BranchFlower | null
|
||||
/** Total vertical extent, so the SVG box can be sized. */
|
||||
readonly height: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal: one move of the route, kept as STRUCTURE rather than only as a path
|
||||
* string. The endpoint trim below has to shorten the final move along its own
|
||||
* direction, which is only sound if the segment still knows where it goes.
|
||||
*/
|
||||
interface Segment {
|
||||
/** SVG path command for the full move. */
|
||||
readonly d: string
|
||||
/** Length the move contributes to the run. */
|
||||
readonly length: number
|
||||
/** Where the move starts. */
|
||||
readonly from: { readonly x: number; readonly y: number }
|
||||
/** Where the move ends. */
|
||||
readonly to: { readonly x: number; readonly y: number }
|
||||
/** Bulge x for a curved move (the curve is vertical-tangent at both ends). */
|
||||
readonly controlX?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan the route: one segment per row after the first, plus the dot positions.
|
||||
*
|
||||
* Kept separate from the string assembly so the length walk and the SVG `d`
|
||||
* always describe the same geometry — measuring one path against another is how
|
||||
* a grown/ghost pair drifts out of sync.
|
||||
*
|
||||
* The stem lands on each row's OWN anchor (x) and centre (y), so uneven row
|
||||
* heights and the tree's per-row indents both stay exact. A group row's anchor
|
||||
* is pushed out by `BULGE_OFFSET`, which is what creates the kink.
|
||||
*
|
||||
* @param rows - visible rows in render order, carrying measured anchors.
|
||||
* @returns the per-row segments and dot x positions.
|
||||
*/
|
||||
function plan(rows: readonly BranchRow[]): { segments: Segment[]; dotX: number[] } {
|
||||
const segments: Segment[] = []
|
||||
const first = rows[0] as BranchRow
|
||||
const dotX: number[] = [first.x]
|
||||
let x = first.x
|
||||
|
||||
for (let i = 1; i < rows.length; i += 1) {
|
||||
const row = rows[i] as BranchRow
|
||||
const prev = rows[i - 1] as BranchRow
|
||||
const startY = prev.y
|
||||
const endY = row.y
|
||||
const midY = startY + (endY - startY) / 2
|
||||
|
||||
// Every dot lands on its OWN anchor; the stem simply travels between them.
|
||||
// When two consecutive rows share an anchor (sessions under one project) the
|
||||
// travel is a straight run; when it changes (a folder's chevron sits left of
|
||||
// its children's dots) the stem swings out through an S-curve, which is what
|
||||
// reads as the branch stepping around the folder marker.
|
||||
const target = row.x
|
||||
|
||||
if (target === x) {
|
||||
segments.push({
|
||||
d: `L ${x} ${endY}`,
|
||||
length: Math.abs(endY - startY),
|
||||
from: { x, y: startY },
|
||||
to: { x, y: endY },
|
||||
})
|
||||
} else {
|
||||
// Two halves so the tangent is vertical at both ends, matching the
|
||||
// reference's curve rhythm.
|
||||
segments.push({
|
||||
d: `C ${x} ${midY}, ${target} ${midY}, ${target} ${endY}`,
|
||||
length: Math.hypot(target - x, endY - midY),
|
||||
from: { x, y: startY },
|
||||
to: { x: target, y: endY },
|
||||
controlX: x,
|
||||
})
|
||||
x = target
|
||||
}
|
||||
dotX.push(x)
|
||||
}
|
||||
|
||||
return { segments, dotX }
|
||||
}
|
||||
|
||||
/**
|
||||
* How far short of the flower's centre the stem stops, in SVG user units.
|
||||
*
|
||||
* The bloom is drawn ON the endpoint, so a stem that runs all the way to the
|
||||
* centre is visible through the petal notches and reads as a line crossing the
|
||||
* flower. Stopping the stroke at (a little over) the bloom's radius keeps the
|
||||
* stem ending cleanly at the flower's edge, where it reads as a stalk holding
|
||||
* the bloom.
|
||||
*
|
||||
* 7 units ≈ the 6.2-unit flower radius plus a hair, so the stroke's round cap
|
||||
* tucks just under the outer petals without a visible gap.
|
||||
*/
|
||||
export const STEM_END_CLEARANCE = 7
|
||||
|
||||
/**
|
||||
* Shorten a move so it stops `clearance` short of its end point.
|
||||
*
|
||||
* Used only on the LAST move of the grown run, which is what hides the stroke
|
||||
* behind the bloom. A straight move is trimmed along its axis; a curved move is
|
||||
* trimmed by moving its end and its control point together, which shortens the
|
||||
* curve while keeping its vertical tangents (so the kink's shape is preserved
|
||||
* rather than being flattened into a line).
|
||||
*
|
||||
* Returns the move unchanged when it is too short to trim (the stem would
|
||||
* invert), so a cramped layout degrades to "line meets flower" rather than
|
||||
* producing a backwards path.
|
||||
*
|
||||
* @param segment - the move to shorten.
|
||||
* @param clearance - distance to stop short of the end.
|
||||
* @returns the shortened move.
|
||||
*/
|
||||
function trimEnd(segment: Segment, clearance: number): Segment {
|
||||
const { from, to } = segment
|
||||
const span = Math.hypot(to.x - from.x, to.y - from.y)
|
||||
if (span <= clearance) return segment
|
||||
|
||||
if (segment.controlX === undefined) {
|
||||
// Straight: retreat along the axis by the clearance.
|
||||
const ratio = (span - clearance) / span
|
||||
const endX = from.x + (to.x - from.x) * ratio
|
||||
const endY = from.y + (to.y - from.y) * ratio
|
||||
return { ...segment, d: `L ${endX} ${endY}`, to: { x: endX, y: endY }, length: span - clearance }
|
||||
}
|
||||
|
||||
// Curved: the move is two mirrored halves, so retreating the END by half the
|
||||
// clearance and the control point by the full one shortens it symmetrically
|
||||
// while keeping both tangents vertical.
|
||||
const endY = to.y - clearance
|
||||
const controlY = from.y + (to.y - from.y) / 2 - clearance
|
||||
const endX = to.x
|
||||
return {
|
||||
...segment,
|
||||
d: `C ${segment.controlX} ${controlY}, ${endX} ${controlY}, ${endX} ${endY}`,
|
||||
to: { x: endX, y: endY },
|
||||
length: Math.max(0, segment.length - clearance),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the branch for a list of rows.
|
||||
*
|
||||
* @param rows - visible rows in render order, each carrying its MEASURED centre.
|
||||
* @returns the branch geometry; empty strings when there are no rows.
|
||||
*/
|
||||
export function buildBranch(rows: readonly BranchRow[]): Branch {
|
||||
const first = rows[0]
|
||||
if (first === undefined) {
|
||||
return { ghostPath: '', grownPath: '', ghostLength: 0, grownLength: 0, dots: [], flower: null, height: 0 }
|
||||
}
|
||||
|
||||
const { segments, dotX } = plan(rows)
|
||||
const head = `M ${first.x} ${first.y}`
|
||||
|
||||
const dots: BranchDot[] = rows.map((row, index) => ({
|
||||
key: row.key,
|
||||
cx: dotX[index] ?? row.x,
|
||||
cy: row.y,
|
||||
active: row.active,
|
||||
}))
|
||||
|
||||
// The grown stroke stops AT the active row, so its path contains every
|
||||
// segment before that row and none after. An active first row grows nothing
|
||||
// beyond the origin, which is correct (the dot sits on the stem origin).
|
||||
//
|
||||
// `activeIndex < 0` is the NO-ACTIVE-ROW case: the open session's folder was
|
||||
// collapsed, or the catalog has not resolved yet. The stem then collapses to
|
||||
// the bare origin (drawing nothing), and — crucially — `hasActive` stays false
|
||||
// so no flower is produced. Conflating this with "the first row is active" is
|
||||
// what used to sprout the blossom on a top-level folder row.
|
||||
const activeIndex = rows.findIndex(row => row.active)
|
||||
const hasActive = activeIndex >= 0
|
||||
const grownTo = hasActive ? activeIndex : 0
|
||||
|
||||
// The bloom sits on the endpoint of `grownPath`, which `join` puts at the
|
||||
// active row. It therefore uses the SAME index as the grown stroke, so the
|
||||
// flower and the stem can never disagree about where the branch ends — and it
|
||||
// exists ONLY when a row actually claimed the marker.
|
||||
const flowerAt = dots[grownTo] as BranchDot | undefined
|
||||
const flower: BranchFlower | null = hasActive && flowerAt !== undefined
|
||||
? { key: flowerAt.key, cx: flowerAt.cx, cy: flowerAt.cy }
|
||||
: null
|
||||
|
||||
const join = (list: readonly Segment[]): string =>
|
||||
list.length === 0 ? head : [head, ...list.map(s => s.d)].join(' ')
|
||||
|
||||
// The grown run: every move before the active row, plus the move INTO it —
|
||||
// which is the one trimmed so the stroke stops at the bloom's edge instead of
|
||||
// crossing the flower. The GHOST keeps its full length: it is a faint dashed
|
||||
// route at 28% opacity, and shortening it too would leave the last row's
|
||||
// guide visibly detached from that row.
|
||||
const grownSegments = segments.slice(0, grownTo)
|
||||
const lastGrown = grownSegments[grownSegments.length - 1]
|
||||
const grownStroke = lastGrown === undefined
|
||||
? grownSegments
|
||||
: [...grownSegments.slice(0, -1), trimEnd(lastGrown, STEM_END_CLEARANCE)]
|
||||
|
||||
const lengthOf = (count: number): number =>
|
||||
segments.slice(0, count).reduce((sum, s) => sum + s.length, 0)
|
||||
|
||||
const last = rows[rows.length - 1] as BranchRow
|
||||
// Half a row height of breathing room below the last dot, so the stem does not
|
||||
// stop dead on the final row.
|
||||
const tail = rows.length > 1 ? Math.abs(last.y - (rows[rows.length - 2] as BranchRow).y) / 2 : 0
|
||||
|
||||
return {
|
||||
ghostPath: join(segments),
|
||||
grownPath: join(grownStroke),
|
||||
ghostLength: lengthOf(segments.length),
|
||||
// The grown length follows the TRIMMED run, so a consumer measuring the
|
||||
// stroke (a dash animation, say) stays consistent with what is drawn.
|
||||
grownLength: Math.max(0, lengthOf(grownTo) - (lastGrown === undefined ? 0 : STEM_END_CLEARANCE)),
|
||||
dots,
|
||||
flower,
|
||||
height: last.y + tail,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,67 +1,129 @@
|
|||
/**
|
||||
* Registrant-private injected share for the workspace-groups browser entry.
|
||||
* Mirrors the official ui-workspace browser inject (same runtime calls), with
|
||||
* two differences: no directory-flow hole dependency (Add Workspace is
|
||||
* self-contained via `pickDirectory`), and no locale-keyed naming collision.
|
||||
* two differences: the directory-flow hole is kept occupied (`hooks.directoryFlow`)
|
||||
* because the official entry stays registered behind this one and gates its own
|
||||
* "Add workspace…" affordance on that hole — Add Workspace itself is
|
||||
* self-contained via `pickDirectory` — and no locale-keyed naming collision.
|
||||
*/
|
||||
import type {
|
||||
PropsHooks,
|
||||
PropsLocale,
|
||||
PropsRuntime,
|
||||
PropsStore,
|
||||
} from '@deepseek-ai/dsh-client-ui-slots'
|
||||
// Type-only: pulls the sidebar shell's SlotMap merge (sidebar.workspaces).
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'
|
||||
import type { HostDescriptionSource } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type {
|
||||
SessionId,
|
||||
SessionSearchResultItem,
|
||||
WorkspaceId,
|
||||
WorkspaceView,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { createGroupsViewStore } from './stores.ts'
|
||||
|
||||
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
// Type-only: merges the sidebar shell's SlotMap row (`sidebar.workspaces`, the
|
||||
// slot this registrant shadows) and its runtime props. Erased from both the JS
|
||||
// bundle and the emitted .d.ts, so it must stay a bare `import type {}`.
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||
import type { WorkspaceId, WorkspaceSnapshot, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import type { createGroupsViewStore } from './stores.ts';
|
||||
import type { SessionTabsInstance, SessionTabsState } from './tab-store.ts';
|
||||
/** Services/slots this registrant's props depend on (documentation alias). */
|
||||
export type WorkspaceGroupsStoreHandle = ReturnType<typeof createGroupsViewStore>;
|
||||
/** Injected share (arrives via the register inject factory). */
|
||||
export type GroupsBrowserInjected = {
|
||||
/** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void
|
||||
/** Open a real Session. */
|
||||
open: (sessionId: SessionId) => void
|
||||
/** Search current visible conversation messages. */
|
||||
searchSessions: (query: string, signal: AbortSignal) => Promise<{
|
||||
items: readonly SessionSearchResultItem[]
|
||||
hasMore: boolean
|
||||
}>
|
||||
/** Maximum number of merged rows rendered for one search. */
|
||||
searchResultLimit: number
|
||||
/** Rename a Session (resolves on host acceptance). */
|
||||
renameSession: (sessionId: SessionId, title: string) => Promise<void>
|
||||
/** Fork a Session at its last completed turn and open the child. */
|
||||
forkSession: (sessionId: SessionId) => void
|
||||
/** Rename a Host Workspace (rejects on name conflict). */
|
||||
renameWorkspace: (workspaceId: WorkspaceId, title: string) => Promise<void>
|
||||
/** Delete only a Host Workspace registration; directory and Session logs remain. */
|
||||
deleteWorkspace: (workspaceId: WorkspaceId) => Promise<void>
|
||||
/** Reorder a Workspace in the durable registry display order (omitted anchor appends). */
|
||||
insertWorkspaceBefore: (workspaceId: WorkspaceId, beforeWorkspaceId?: WorkspaceId) => Promise<void>
|
||||
/** Archive a Session into the registry-global set (hidden from grouping surfaces). */
|
||||
archiveSession: (sessionId: SessionId) => Promise<void>
|
||||
/** Reorder a session inside its Workspace account. */
|
||||
insertSessionBefore: (workspaceId: WorkspaceId, sessionId: SessionId, beforeSessionId?: SessionId) => Promise<void>
|
||||
/** Adopt a picked host directory as a real Workspace before targeting a Session. */
|
||||
createWorkspace: (input: { path: string }) => Promise<WorkspaceView>
|
||||
/** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */
|
||||
pickDirectory: () => Promise<string | null>
|
||||
/** Browser-private injected hooks (host description; bound by the slot renderer). */
|
||||
hooks: {
|
||||
/** Current generation's Host description. */
|
||||
hostDescription: HostDescriptionSource
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reserved hooks compartment. `directoryFlow` reports the
|
||||
* `sidebar.workspaces.directoryFlow` hole as occupied: the official
|
||||
* ui-workspace entry stays registered behind this one and withdraws its
|
||||
* "Add workspace…" affordance when the hole is empty, so this browser keeps
|
||||
* it truthy (it drives the picker itself through `pickDirectory`).
|
||||
*/
|
||||
hooks: {
|
||||
/** True while the sidebar browsing region's directory-flow hole is occupied. */
|
||||
directoryFlow: HostObservable<boolean>;
|
||||
};
|
||||
/** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void;
|
||||
/** Open a real Session. */
|
||||
open: (sessionId: SessionId) => void;
|
||||
/** Search current visible conversation messages. */
|
||||
searchSessions: (query: string, signal: AbortSignal) => Promise<{
|
||||
items: readonly SessionSearchResultItem[];
|
||||
hasMore: boolean;
|
||||
}>;
|
||||
/** Maximum number of merged rows rendered for one search. */
|
||||
searchResultLimit: number;
|
||||
/** Rename a Session (resolves on host acceptance). */
|
||||
renameSession: (sessionId: SessionId, title: string) => Promise<void>;
|
||||
/** Fork a Session at its last completed turn and open the child. */
|
||||
forkSession: (sessionId: SessionId) => void;
|
||||
/** Rename a Host Workspace (rejects on name conflict). */
|
||||
renameWorkspace: (workspaceId: WorkspaceId, title: string) => Promise<void>;
|
||||
/** Delete only a Host Workspace registration; directory and Session logs remain. */
|
||||
deleteWorkspace: (workspaceId: WorkspaceId) => Promise<void>;
|
||||
/** Reorder a Workspace in the durable registry display order (omitted anchor appends). */
|
||||
insertWorkspaceBefore: (workspaceId: WorkspaceId, beforeWorkspaceId?: WorkspaceId) => Promise<void>;
|
||||
/** Archive a Session into the registry-global set (hidden from grouping surfaces). */
|
||||
archiveSession: (sessionId: SessionId) => Promise<void>;
|
||||
/** Reorder a session inside its Workspace account. */
|
||||
insertSessionBefore: (workspaceId: WorkspaceId, sessionId: SessionId, beforeSessionId?: SessionId) => Promise<void>;
|
||||
/** Adopt a picked host directory as a real Workspace before targeting a Session. */
|
||||
createWorkspace: (input: {
|
||||
path: string;
|
||||
}) => Promise<WorkspaceView>;
|
||||
/** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */
|
||||
pickDirectory: () => Promise<string | null>;
|
||||
/**
|
||||
* Surface the session-tab strip for a session that is in play (called with the
|
||||
* session the browser itself just opened, and again whenever its status
|
||||
* changes). Tab visibility rules live in `shouldOpenTab`; the status is passed
|
||||
* in because "it started working" is a live-status fact the store layer cannot
|
||||
* read on its own.
|
||||
* @param sessionId - the session to consider.
|
||||
* @param status - its unified UI status, when one is published.
|
||||
*/
|
||||
openTab: (sessionId: SessionId, status: SessionStatus | undefined) => void;
|
||||
/**
|
||||
* Selector hook over the shared tab store, bound by this plugin (the strip is
|
||||
* not a slot occupant, so the framework does not bind it). Built from the one
|
||||
* live instance the browser writes through.
|
||||
*/
|
||||
useTabs: <S>(selector: (state: SessionTabsState) => S, eq?: (a: S, b: S) => boolean) => S;
|
||||
/** The tab store's baked write set (the same one `apply` writes through). */
|
||||
tabActions: SessionTabsInstance['actions'];
|
||||
};
|
||||
/** Full browser props: shell owner share + viewing store + injected actions + locale seat. */
|
||||
export type GroupsBrowserProps = PropsRuntime<'sidebar.workspaces'> &
|
||||
PropsStore<ReturnType<typeof createGroupsViewStore>> &
|
||||
Omit<GroupsBrowserInjected, 'hooks'> &
|
||||
PropsHooks<GroupsBrowserInjected['hooks']> &
|
||||
PropsLocale<'workspaceGroups'>
|
||||
export type GroupsBrowserProps = PropsRuntime<'sidebar.workspaces'> & PropsStore<ReturnType<typeof createGroupsViewStore>> & InjectFace<GroupsBrowserInjected> & PropsLocale<'workspaceGroups'>;
|
||||
/**
|
||||
* The two framework global seats the strip reads, declared structurally because
|
||||
* `GlobalStandardProps`'s own members arrive from merge declarations this repo
|
||||
* cannot resolve (its packages ship no `src`, so the merged hook types are only
|
||||
* visible to the compiling package). Both are the shipped global selector hooks
|
||||
* with the same names and shapes, and both are seated on the
|
||||
* `sidebar.workspaces` occupant that renders this strip.
|
||||
*/
|
||||
export interface SessionsTabsStandardProps {
|
||||
/** Session list and current selection (framework global seat). */
|
||||
useSessions: SnapshotSelectorHook<SessionListState>;
|
||||
/** Unified per-session UI status (framework global seat). */
|
||||
useSessionStatus: SnapshotSelectorHook<SessionStatusSnapshot>;
|
||||
/**
|
||||
* Workspace registry (framework global seat). The strip reads it to label each
|
||||
* tab with the project that owns its session — the one fact a bare strip of
|
||||
* session titles cannot convey.
|
||||
*/
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>;
|
||||
}
|
||||
/**
|
||||
* Full tab-strip props.
|
||||
*
|
||||
* The strip is NOT a slot occupant: the conversation column declares no child
|
||||
* slot, so it renders through a DOM seat (`tab-seat.ts`) and receives plain
|
||||
* React props instead of framework shares. Only the two global selector hooks
|
||||
* below are framework-provided, and they arrive because the strip is rendered
|
||||
* as a CHILD of this plugin's own `sidebar.workspaces` occupant — which seats
|
||||
* both of them in the standard kit. Everything else is passed explicitly by
|
||||
* that parent, which is what removes the strip from the slot registry entirely
|
||||
* and with it the cross-scope store conflict the slot version hit.
|
||||
*/
|
||||
export type SessionsTabsProps = SessionsTabsStandardProps & {
|
||||
/** Selector hook over the shared tab store's snapshot. */
|
||||
useTabs: SnapshotSelectorHook<SessionTabsState>;
|
||||
/** The tab store's baked write set (the same set `apply` writes through). */
|
||||
actions: SessionTabsInstance['actions'];
|
||||
/** Make a tab's session the open one (`ctx.uiWorkspace.openSession`). */
|
||||
activate: (sessionId: SessionId) => void;
|
||||
/** Ask the browser to open its rename dialog for a tab session. */
|
||||
rename: (sessionId: SessionId, currentTitle: string) => void;
|
||||
} & PropsLocale<'workspaceGroups'>;
|
||||
|
|
|
|||
|
|
@ -1,24 +1,62 @@
|
|||
/**
|
||||
* dsh-workspace-groups client half: registers the three-level grouped
|
||||
* workspace browser into the `sidebar.workspaces` slot, shadowing the
|
||||
* official ui-workspace browser.
|
||||
* @dsh-xhl/workspace-groups client half. ONE registration, plus a DOM-seated
|
||||
* view that hangs off it:
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — `ctx.workspaces.pickDirectory()` + `create()`, no hole.
|
||||
* The three-level grouped workspace browser into `sidebar.workspaces`,
|
||||
* shadowing the official ui-workspace browser.
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — the shared navigation service + `workspaces.create()`, no
|
||||
* hole.
|
||||
*
|
||||
* The session tab strip is NOT a second registration. It renders into a DOM
|
||||
* seat at the head of the conversation column (`pI_x6G_centerCol`) because that
|
||||
* column declares no child slot — its only child is the `main` slot's occupant
|
||||
* — so there is nowhere to register. See `tab-seat.ts` for the injection and
|
||||
* `SessionTabs.tsx` for the portal.
|
||||
*
|
||||
* Two consequences of that choice, both deliberate:
|
||||
* - The strip is a CHILD of this entry's component, so it inherits this
|
||||
* fiber's frame; it needs no injected seam, no cross-entry callback set,
|
||||
* and the rename dialog stays owned by one place.
|
||||
* - The tab store is seated by exactly ONE entry. Registering one handle
|
||||
* under a second, differently-scoped slot throws inside the registry
|
||||
* ("one handle, one scope") and would abort this whole `apply()` — which
|
||||
* is precisely why the strip does not occupy a slot.
|
||||
*
|
||||
* 0.1.6 适配:导航(选中会话 / New Session / fork / archive / 目录选择)从
|
||||
* `ctx.sessions` 抽到 ui-workspace 提供的 `ctx.uiWorkspace` 服务
|
||||
* (`ISessions` 现在只有目录 / retain / search 能力,选中由 `mainView` 保留位
|
||||
* 表达)。本插件不再自建 connectWorkspace/recentWorkspace 语义,全部委托给该
|
||||
* 服务,只保留改名、删除、排序、搜索等数据动作。
|
||||
*/
|
||||
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'
|
||||
// Type-only: pulls the locale plugin's Context merge (ctx.locale).
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
// Type-only service merges: sessions/workspaces controllers, the ui-workspace
|
||||
// navigation service face (ctx.uiWorkspace), locale dictionary seat, the
|
||||
// SlotRegistry, and the sidebar SlotMap.
|
||||
import type {} from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
// `useWorkspaces` is contributed by the ui-workspace browser domain (same
|
||||
// declaration as the official ui-workspace client half).
|
||||
import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { GroupsBrowserInjected } from './contract.ts'
|
||||
import { createGroupsViewStore } from './stores.ts'
|
||||
import { createSessionTabsStore } from './tab-store.ts'
|
||||
import { loadTabs, saveTabs } from './tab-persist.ts'
|
||||
import { createStoreHook } from './store-hook.ts'
|
||||
import { shouldOpenTab, type TabOpenMode } from './tabs.ts'
|
||||
import { GroupsBrowser } from './GroupsBrowser.tsx'
|
||||
import { en, zh, type WorkspaceGroupsKey } from './locales.ts'
|
||||
|
||||
|
|
@ -27,13 +65,28 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
|||
/** The workspace-groups browsing region copy. */
|
||||
workspaceGroups: WorkspaceGroupsKey
|
||||
}
|
||||
|
||||
interface GlobalStandardProps {
|
||||
/** Selector hook over the pure Workspace Controller snapshot. */
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>
|
||||
}
|
||||
}
|
||||
|
||||
/** Dictionary namespace owned by this plugin. */
|
||||
const NS = 'workspaceGroups'
|
||||
|
||||
/** Required services (cordis fiber inject). */
|
||||
export const inject = ['slots', 'sessions', 'workspaces', 'locale', 'connection']
|
||||
/**
|
||||
* Tab visibility policy. `auto` is the behaviour the feature was asked for —
|
||||
* opening a session that has no tab yet adds one at the front of the strip;
|
||||
* `manual` leaves the strip to callers that drive `openTab` themselves.
|
||||
*/
|
||||
const TAB_OPEN_MODE: TabOpenMode = 'auto'
|
||||
|
||||
/**
|
||||
* Required services (cordis fiber inject; 0.1.6 service roster). `uiWorkspace`
|
||||
* is the shipped navigation face this entry delegates selection to.
|
||||
*/
|
||||
export const inject = ['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale']
|
||||
|
||||
/**
|
||||
* Register the grouped browser once the sidebar slot declaration is on the
|
||||
|
|
@ -41,8 +94,61 @@ export const inject = ['slots', 'sessions', 'workspaces', 'locale', 'connection'
|
|||
* framework's global hooks.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export function apply(ctx: ClientContext): void {
|
||||
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-workspace-groups: dictionaries')
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.effect(() => ctx.locale.register(NS, { zh, en }), '@dsh-xhl/workspace-groups: dictionaries')
|
||||
|
||||
// ONE store, ONE scope. The tab store is seated only by the
|
||||
// `sidebar.workspaces` entry below (scope root); the strip reads it as a
|
||||
// plain prop because it renders as a CHILD of that entry through a DOM
|
||||
// portal, not as a second slot occupant. Seating the same handle under a
|
||||
// session-scoped slot as well throws inside the registry
|
||||
// (one handle, one scope) and would abort this whole apply().
|
||||
const tabsStore = createSessionTabsStore()
|
||||
const tabInstance = tabsStore.create()
|
||||
const tabWrites = tabInstance.actions
|
||||
|
||||
// Persist the strip on the HOST, not in browser storage: the origin includes
|
||||
// the port and every launch picks a new one, so localStorage/sessionStorage
|
||||
// both start empty next time.
|
||||
//
|
||||
// Writes are GATED until the initial restore has settled. The store starts
|
||||
// empty and the browser's own effects run before the host read resolves, so an
|
||||
// ungated subscriber would write that empty state over the stored tabs —
|
||||
// erasing exactly what it was supposed to restore. `hydrated` is the latch.
|
||||
let hydrated = false
|
||||
ctx.effect(() => {
|
||||
const stop = tabInstance.subscribe(() => {
|
||||
if (!hydrated) return
|
||||
void saveTabs({
|
||||
order: tabInstance.getSnapshot().order,
|
||||
tabs: tabInstance.getSnapshot().tabs,
|
||||
})
|
||||
})
|
||||
return () => { stop() }
|
||||
}, '@dsh-xhl/workspace-groups: tab persistence')
|
||||
|
||||
// Hydrate once from the host, then open the write gate.
|
||||
//
|
||||
// `restore` is a no-op if the user already opened a tab while this was in
|
||||
// flight, so a slow response cannot discard live work. The settle deliberately
|
||||
// does NOT write: writing the strip here would erase the stored tabs whenever
|
||||
// the read came back empty for a transient reason (host still booting, a
|
||||
// dropped request). Only a real state CHANGE persists, via the subscriber.
|
||||
ctx.effect(() => {
|
||||
let cancelled = false
|
||||
void loadTabs().then((tabs) => {
|
||||
if (cancelled) return
|
||||
if (tabs.length > 0) {
|
||||
tabWrites.restore(tabs.map(tab => ({ sessionId: tab.sessionId as SessionId, order: tab.order })))
|
||||
}
|
||||
hydrated = true
|
||||
}).catch(() => {
|
||||
// The read failed; leave the gate open so the user's own actions persist,
|
||||
// but never write on the strength of a failed read.
|
||||
if (!cancelled) hydrated = true
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, '@dsh-xhl/workspace-groups: tab restore')
|
||||
|
||||
const searchSessions: GroupsBrowserInjected['searchSessions'] = async (query, signal) => {
|
||||
const result = await ctx.sessions.search(query, signal)
|
||||
|
|
@ -51,40 +157,82 @@ export function apply(ctx: ClientContext): void {
|
|||
}
|
||||
|
||||
const browserInjected = (): GroupsBrowserInjected => ({
|
||||
startSession: (workspaceId) => { ctx.workspaces.startSession(workspaceId) },
|
||||
open: (sessionId) => { ctx.sessions.open(sessionId) },
|
||||
// Navigation verbs belong to the shipped ui-workspace service: it owns the
|
||||
// retained `mainView` selection, supersession and pending-navigation
|
||||
// cancellation (0.1.6 moved them out of `ctx.sessions`).
|
||||
startSession: (workspaceId) => { ctx.uiWorkspace.startSession(workspaceId) },
|
||||
open: (sessionId) => { ctx.uiWorkspace.openSession(sessionId) },
|
||||
forkSession: (sessionId) => {
|
||||
ctx.uiWorkspace.forkSession(sessionId).catch((reason: unknown) => {
|
||||
console.warn('fork session failed:', reason)
|
||||
})
|
||||
},
|
||||
archiveSession: async (sessionId) => {
|
||||
await ctx.uiWorkspace.archiveSession(sessionId)
|
||||
// The tab is deliberately LEFT ALONE. Archiving hides the session from the
|
||||
// grouped surfaces, but a tab is something the user opened, and the rule
|
||||
// for this strip is that only they close one — an automatic close here
|
||||
// would silently drop work they were keeping an eye on. The chip keeps
|
||||
// rendering (falling back to the session id when the title no longer
|
||||
// resolves).
|
||||
},
|
||||
pickDirectory: () => ctx.uiWorkspace.pickDirectory(),
|
||||
searchSessions,
|
||||
searchResultLimit: ctx.sessions.searchResultLimit,
|
||||
// Directory-flow hole occupancy. The official ui-workspace browser gates
|
||||
// its "Add workspace…" affordance on the hole being occupied (the shipped
|
||||
// picker package's client half fills it); this browser drives the picker
|
||||
// itself through `pickDirectory`, so it must keep the hole occupied or the
|
||||
// official entry (still live at priority 0) would silently withdraw the
|
||||
// affordance.
|
||||
hooks: {
|
||||
directoryFlow: {
|
||||
getSnapshot: () => true,
|
||||
subscribe: () => () => {},
|
||||
},
|
||||
},
|
||||
// Data-only verbs stay on the controllers.
|
||||
renameSession: async (sessionId, title) => {
|
||||
const session = ctx.sessions.binding(sessionId)?.session
|
||||
if (session === undefined) throw new Error(`unknown session "${sessionId}"`)
|
||||
const result = await session.rename(title)
|
||||
if (!result.ok) throw new Error(result.error.message)
|
||||
},
|
||||
forkSession: (sessionId) => {
|
||||
ctx.sessions.fork({ sessionId, increaseTitle: true })
|
||||
.then((childId) => { ctx.sessions.open(childId) })
|
||||
.catch(() => {})
|
||||
},
|
||||
renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) },
|
||||
deleteWorkspace: async (workspaceId) => { await ctx.workspaces.delete(workspaceId) },
|
||||
insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {
|
||||
await ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId)
|
||||
},
|
||||
archiveSession: async (sessionId) => { await ctx.workspaces.archiveSession(sessionId) },
|
||||
insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {
|
||||
await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId)
|
||||
},
|
||||
createWorkspace: input => ctx.workspaces.create(input),
|
||||
pickDirectory: () => ctx.workspaces.pickDirectory(),
|
||||
hooks: {
|
||||
hostDescription: (ctx.get('connection') as ConnectionHandle).hostDescription,
|
||||
// "Show a tab for what I just opened" — but only while it is actually in
|
||||
// play. The browser decides per session (see `shouldOpenTab`): a draft that
|
||||
// has not been talked to, and settled history, both stay out of the strip.
|
||||
// The status arrives from the caller because it is a live UI fact read
|
||||
// through a hook, which this (non-React) factory cannot reach.
|
||||
openTab: (sessionId, status) => {
|
||||
const summary = ctx.sessions.list.getSnapshot().byId[sessionId]
|
||||
if (shouldOpenTab(TAB_OPEN_MODE, summary, status)) tabWrites.touch(sessionId)
|
||||
},
|
||||
// The strip rides this entry's own store seat, so it needs both faces
|
||||
// explicitly: a selector hook over the one live instance, and the baked
|
||||
// writes. Both come from the same instance the browser writes through.
|
||||
useTabs: createStoreHook(tabInstance),
|
||||
tabActions: tabWrites,
|
||||
})
|
||||
|
||||
// priority: -1 — lower than the official browser's default 0, so the
|
||||
// single-slot shadow rule elects this entry. No children declaration: the
|
||||
// official entry already owns `sidebar.workspaces.directoryFlow`.
|
||||
//
|
||||
// The official WorkspaceBrowser entry is NEVER disposed — shadowing only
|
||||
// changes which entry renders (activation just bumps the store's mount
|
||||
// count). Both entries live at the same cell, so if this one ever throws
|
||||
// during render the slot core retires it for the rest of its registration's
|
||||
// life and silently falls back to the official browser. Anything that can
|
||||
// throw belongs outside the hot path.
|
||||
ctx.slots.inject('sidebar.workspaces', () => ctx.slots.register(
|
||||
{
|
||||
name: 'sidebar.workspaces',
|
||||
|
|
@ -92,7 +240,7 @@ export function apply(ctx: ClientContext): void {
|
|||
store: createGroupsViewStore(),
|
||||
inject: browserInjected,
|
||||
locale: NS,
|
||||
registrant: 'dsh-workspace-groups',
|
||||
registrant: '@dsh-xhl/workspace-groups',
|
||||
},
|
||||
GroupsBrowser,
|
||||
))
|
||||
|
|
|
|||
|
|
@ -32,6 +32,8 @@ export type WorkspaceGroupsKey =
|
|||
| 'workspace.renameConfirm'
|
||||
| 'workspace.renameCancel'
|
||||
| 'workspace.moveOutOfGroup'
|
||||
| 'workspace.openInFolder'
|
||||
| 'workspace.openInFolderError'
|
||||
| 'group.create'
|
||||
| 'group.createTitle'
|
||||
| 'group.createPlaceholder'
|
||||
|
|
@ -68,6 +70,21 @@ export type WorkspaceGroupsKey =
|
|||
| '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'
|
||||
|
||||
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>
|
||||
|
||||
|
|
@ -99,6 +116,8 @@ export const zh: WorkspaceGroupsDict = {
|
|||
'workspace.renameConfirm': '重命名',
|
||||
'workspace.renameCancel': '取消',
|
||||
'workspace.moveOutOfGroup': '移出分组',
|
||||
'workspace.openInFolder': '在文件夹中打开',
|
||||
'workspace.openInFolderError': '打开文件夹失败',
|
||||
'group.create': '新建分组',
|
||||
'group.createTitle': '新建分组',
|
||||
'group.createPlaceholder': '分组名称',
|
||||
|
|
@ -135,6 +154,21 @@ export const zh: WorkspaceGroupsDict = {
|
|||
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': 'Ctrl+R 开关 · Enter 打开/新建 · Esc 关闭',
|
||||
'tabs.aria': '已打开的会话',
|
||||
'tabs.close': '关闭标签',
|
||||
'tabs.archive': '归档',
|
||||
}
|
||||
|
||||
/** English dictionary. */
|
||||
|
|
@ -165,6 +199,8 @@ export const en: WorkspaceGroupsDict = {
|
|||
'workspace.renameConfirm': 'Rename',
|
||||
'workspace.renameCancel': 'Cancel',
|
||||
'workspace.moveOutOfGroup': 'Move out of group',
|
||||
'workspace.openInFolder': 'Open in folder',
|
||||
'workspace.openInFolderError': 'Could not open the folder',
|
||||
'group.create': 'New group',
|
||||
'group.createTitle': 'New group',
|
||||
'group.createPlaceholder': 'Group name',
|
||||
|
|
@ -201,4 +237,19 @@ export const en: WorkspaceGroupsDict = {
|
|||
collapse: 'Collapse',
|
||||
expandMore: 'Show all',
|
||||
newSession: 'New Session',
|
||||
'quick.title': 'Quick switch',
|
||||
'quick.tab.workspaces': 'Workspaces',
|
||||
'quick.tab.sessions': 'All sessions',
|
||||
'quick.search.placeholder': 'Search workspaces…',
|
||||
'quick.search.sessions': 'Search sessions…',
|
||||
'quick.empty.workspaces': 'No matching workspaces',
|
||||
'quick.action.newSession': 'New Session',
|
||||
'quick.action.running': 'Switch to running session',
|
||||
'quick.action.noneRunning': 'No running session',
|
||||
'quick.empty.sessions': 'No sessions yet',
|
||||
'quick.select.hint': 'Pick a workspace above',
|
||||
'quick.hint': 'Ctrl+R toggle · Enter open/new · Esc close',
|
||||
'tabs.aria': 'Open sessions',
|
||||
'tabs.close': 'Close tab',
|
||||
'tabs.archive': 'Archive',
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,79 @@
|
|||
/**
|
||||
* Transport for the official open-in-app host routes served by
|
||||
* `@deepseek-ai/dsh-host-open-in-app`. The project row offers "open this
|
||||
* project's folder" by asking that host half for the applications it verified
|
||||
* as installed, then POSTing the launcher it already resolved — this plugin
|
||||
* never probes or spawns a launcher itself, and a host without the capability
|
||||
* (no resolved application, e.g. an SSH launch) simply yields no menu entry.
|
||||
*/
|
||||
|
||||
/** GET route serving the probed application ids (host-owned constant). */
|
||||
export const OPEN_IN_APP_APPS_ROUTE = '/open-in-app/apps'
|
||||
|
||||
/** POST route launching one resolved application on one absolute directory. */
|
||||
export const OPEN_IN_APP_OPEN_ROUTE = '/open-in-app/open'
|
||||
|
||||
/**
|
||||
* Catalog ids that open a directory in the platform file manager, most
|
||||
* specific first (the official catalog names one per platform: `explorer` on
|
||||
* Windows, `finder` on macOS, `filemanager` on Linux).
|
||||
*/
|
||||
const FOLDER_APP_IDS = ['explorer', 'finder', 'filemanager'] as const
|
||||
|
||||
/**
|
||||
* The installed file-manager id for this host, or undefined when the host
|
||||
* resolved none (the row then offers no "open in folder" entry).
|
||||
* @param apps - installed catalog ids from the apps route.
|
||||
* @returns the preferred available id.
|
||||
*/
|
||||
export function folderAppId(apps: readonly string[]): string | undefined {
|
||||
for (const id of FOLDER_APP_IDS) {
|
||||
if (apps.includes(id)) return id
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the browser's Host base with the connection carrier's null-origin
|
||||
* fallback (same rule the official button uses): a sandboxed document reports
|
||||
* the literal origin "null", which cannot address the host.
|
||||
* @returns the absolute base URL of the current Host.
|
||||
*/
|
||||
function hostBase(): string {
|
||||
const origin = globalThis.location?.origin
|
||||
return origin !== undefined && origin !== 'null' ? origin : 'http://dsh.internal'
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the host's installed-application ids. A host without the capability
|
||||
* (or one that refuses) reads as an empty list rather than an error, so the
|
||||
* caller can treat "no apps" and "no route" identically.
|
||||
* @param signal - aborts the read when the browser half unmounts.
|
||||
* @returns installed catalog ids, in host menu order.
|
||||
*/
|
||||
export async function fetchOpenInApps(signal?: AbortSignal): Promise<readonly string[]> {
|
||||
const response = await fetch(new URL(OPEN_IN_APP_APPS_ROUTE, hostBase()), {
|
||||
headers: { accept: 'application/json' },
|
||||
cache: 'no-store',
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
})
|
||||
if (!response.ok) throw new Error(`open-in-app apps request failed: ${response.status}`)
|
||||
const payload: unknown = await response.json()
|
||||
const apps = (payload as { apps?: unknown }).apps
|
||||
return Array.isArray(apps) ? apps.filter((id): id is string => typeof id === 'string') : []
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch one installed application on one absolute directory.
|
||||
* @param appId - catalog id from the apps route.
|
||||
* @param path - the project's absolute directory.
|
||||
* @returns after the host acknowledged the launch; rejects on any refusal.
|
||||
*/
|
||||
export async function openPathInApp(appId: string, path: string): Promise<void> {
|
||||
const response = await fetch(new URL(OPEN_IN_APP_OPEN_ROUTE, hostBase()), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ app: appId, path }),
|
||||
})
|
||||
if (!response.ok) throw new Error(`open-in-app launch failed: ${response.status}`)
|
||||
}
|
||||
|
|
@ -0,0 +1,186 @@
|
|||
/**
|
||||
* Pure data shaping for the Ctrl+R quick switch panel. Runtime-free (same
|
||||
* discipline as store-core.ts): unit tests exercise the real semantics
|
||||
* without a browser module loader; the panel only binds them to the
|
||||
* framework's global hooks.
|
||||
*/
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
|
||||
/** A session row eligible for quick switching: running, top-level, real. */
|
||||
function quickEligible(summary: SessionSummary): boolean {
|
||||
return summary.running === true && summary.origin !== 'subagent' && !summary.blank
|
||||
}
|
||||
|
||||
/**
|
||||
* Running quick-switchable sessions across the whole list, newest first.
|
||||
* @param list - sessions list snapshot.
|
||||
* @param archived - registry-global archive set (archived rows never surface).
|
||||
* @returns running summaries in recency order (id as deterministic tiebreak).
|
||||
*/
|
||||
export function runningSessions(list: SessionListState, archived: ReadonlySet<SessionId>): SessionSummary[] {
|
||||
const out: SessionSummary[] = []
|
||||
for (const id of list.ids) {
|
||||
if (archived.has(id)) continue
|
||||
const summary = list.byId[id]
|
||||
if (summary !== undefined && quickEligible(summary)) out.push(summary)
|
||||
}
|
||||
out.sort((a, b) => (b.updatedAt !== a.updatedAt ? b.updatedAt - a.updatedAt : (a.id < b.id ? -1 : 1)))
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Every quick-switchable session across the whole list — the sessions tab's
|
||||
* data: running rows pinned on top, everything else under them, both groups
|
||||
* newest first. Visibility mirrors the tree (subagent rows never; archived
|
||||
* never; a blank row only while it is the open session).
|
||||
* @param list - sessions list snapshot.
|
||||
* @param archived - registry-global archive set (archived rows never surface).
|
||||
* @param current - the selected session (`mainView` retention; keeps its blank row visible).
|
||||
* @returns summaries with running first, then recency (id as deterministic tiebreak).
|
||||
*/
|
||||
export function allSessions(
|
||||
list: SessionListState,
|
||||
archived: ReadonlySet<SessionId>,
|
||||
current: SessionId | undefined,
|
||||
): SessionSummary[] {
|
||||
const out: SessionSummary[] = []
|
||||
for (const id of list.ids) {
|
||||
if (archived.has(id)) continue
|
||||
const summary = list.byId[id]
|
||||
if (summary === undefined) continue
|
||||
if (summary.origin === 'subagent') continue
|
||||
if (summary.blank && summary.id !== current) continue
|
||||
out.push(summary)
|
||||
}
|
||||
out.sort((a, b) => {
|
||||
if (a.running !== b.running) return a.running ? -1 : 1
|
||||
return b.updatedAt !== a.updatedAt ? b.updatedAt - a.updatedAt : (a.id < b.id ? -1 : 1)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Session search for the quick panel: display-title or owning-workspace-title
|
||||
* substring match (trimmed, case-insensitive). Filters only — the incoming
|
||||
* running-first/recency order is preserved verbatim, so "running on top"
|
||||
* survives any query.
|
||||
* @param sessions - allSessions() output (running pinned on top, then recency).
|
||||
* @param query - raw query.
|
||||
* @param workspaceTitleOf - owning workspace title resolver (sub-line source).
|
||||
* @param limit - hard render cap.
|
||||
* @returns matching sessions in the given order.
|
||||
*/
|
||||
export function filterSessions(
|
||||
sessions: readonly SessionSummary[],
|
||||
query: string,
|
||||
workspaceTitleOf: (session: SessionSummary) => string | undefined,
|
||||
limit = 200,
|
||||
): SessionSummary[] {
|
||||
const q = query.trim().toLowerCase()
|
||||
if (q === '') return sessions.slice(0, limit)
|
||||
const out: SessionSummary[] = []
|
||||
for (const session of sessions) {
|
||||
const workspace = workspaceTitleOf(session)?.toLowerCase() ?? ''
|
||||
if (session.displayTitle.toLowerCase().includes(q) || workspace.includes(q)) out.push(session)
|
||||
}
|
||||
return out.slice(0, limit)
|
||||
}
|
||||
|
||||
/**
|
||||
* Most recently updated running session inside one workspace.
|
||||
* @param list - sessions list snapshot.
|
||||
* @param workspace - target workspace (its session account order is irrelevant;
|
||||
* recency picks the row).
|
||||
* @returns the session id, or undefined when nothing in the workspace runs.
|
||||
*/
|
||||
export function latestRunningInWorkspace(list: SessionListState, workspace: WorkspaceView): SessionId | undefined {
|
||||
let best: SessionId | undefined
|
||||
let bestTime = Number.NEGATIVE_INFINITY
|
||||
for (const id of workspace.sessionIds) {
|
||||
const summary = list.byId[id]
|
||||
if (summary === undefined || !quickEligible(summary)) continue
|
||||
if (summary.updatedAt > bestTime) {
|
||||
best = summary.id
|
||||
bestTime = summary.updatedAt
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/**
|
||||
* Running-session count per workspace id (badge on the workspace tab rows).
|
||||
* @param running - runningSessions() output.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @returns counts keyed by workspace id; absent key = none running.
|
||||
*/
|
||||
export function runningCountByWorkspace(
|
||||
running: readonly SessionSummary[],
|
||||
workspaces: readonly WorkspaceView[],
|
||||
): Map<string, number> {
|
||||
const counts = new Map<string, number>()
|
||||
if (running.length === 0) return counts
|
||||
const runningIds = new Set(running.map(s => s.id))
|
||||
for (const workspace of workspaces) {
|
||||
let count = 0
|
||||
for (const sessionId of workspace.sessionIds) {
|
||||
if (runningIds.has(sessionId)) count += 1
|
||||
}
|
||||
if (count > 0) counts.set(workspace.workspaceId as string, count)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace that owns the currently open session.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param currentSessionId - the selected session (`mainView` retention); may be undefined
|
||||
* (no session open, cleared selection) or an id no listed workspace holds
|
||||
* (e.g. an addressed subagent session).
|
||||
* @returns the workspace id, or undefined when there is no active workspace.
|
||||
*/
|
||||
export function activeWorkspaceId(
|
||||
workspaces: readonly WorkspaceView[],
|
||||
currentSessionId: SessionId | undefined,
|
||||
): string | undefined {
|
||||
if (currentSessionId === undefined) return undefined
|
||||
const workspace = workspaces.find(w => w.sessionIds.includes(currentSessionId))
|
||||
return workspace?.workspaceId as string | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Workspace search for the quick panel: title prefix → title substring →
|
||||
* category label substring → path substring; ties keep host order via a
|
||||
* stable title compare inside one rank.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param query - raw query (trimmed, case-insensitive).
|
||||
* @param categoryLabelOf - category label resolver (grouped workspaces only).
|
||||
* @param limit - hard render cap.
|
||||
* @returns ranked matches; an empty query returns host order.
|
||||
*/
|
||||
export function filterWorkspaces(
|
||||
workspaces: readonly WorkspaceView[],
|
||||
query: string,
|
||||
categoryLabelOf?: (workspace: WorkspaceView) => string | undefined,
|
||||
limit = 50,
|
||||
): WorkspaceView[] {
|
||||
const q = query.trim().toLowerCase()
|
||||
if (q === '') return workspaces.slice(0, limit)
|
||||
const scored: { workspace: WorkspaceView; score: number }[] = []
|
||||
for (const workspace of workspaces) {
|
||||
const title = workspace.title.toLowerCase()
|
||||
const path = workspace.path.toLowerCase()
|
||||
const category = (categoryLabelOf?.(workspace) ?? '').toLowerCase()
|
||||
let score: number | undefined
|
||||
if (title.startsWith(q)) score = 0
|
||||
else if (title.includes(q)) score = 1
|
||||
else if (category !== '' && category.includes(q)) score = 2
|
||||
else if (path.includes(q)) score = 3
|
||||
if (score !== undefined) scored.push({ workspace, score })
|
||||
}
|
||||
scored.sort((a, b) => (a.score !== b.score
|
||||
? a.score - b.score
|
||||
: a.workspace.title.localeCompare(b.workspace.title)))
|
||||
return scored.slice(0, limit).map(entry => entry.workspace)
|
||||
}
|
||||
|
|
@ -8,19 +8,20 @@
|
|||
* workspace rows, standing for their containing category) are drop targets.
|
||||
* The payload is a custom dataTransfer type so only in-plugin drags land.
|
||||
*/
|
||||
import { useState, type DragEvent } from 'react'
|
||||
import { useState, type DragEvent, type ReactNode } from 'react'
|
||||
import {
|
||||
IconArchiveOutline20,
|
||||
IconBranchOutline16,
|
||||
IconEditOutline16,
|
||||
IconEllipsisOutline16,
|
||||
IconFolderClose16,
|
||||
IconFolderOpen16,
|
||||
IconFolderOpenOutline16,
|
||||
IconPlusOutline16,
|
||||
IconProjectAddOutline16,
|
||||
IconTriangleRightFill14,
|
||||
IconTrashOutline16,
|
||||
IconArchiveOutlineRegular,
|
||||
IconBranchOutlineRegular,
|
||||
IconEditOutlineRegular,
|
||||
IconEllipsisOutlineRegular,
|
||||
IconFolderCloseMedium,
|
||||
IconFolderOpenMedium,
|
||||
IconFolderOpenOutlineRegular,
|
||||
IconPlusOutlineRegular,
|
||||
IconProjectAddOutlineRegular,
|
||||
IconRightUpOutlineRegular,
|
||||
IconTriangleRightFillMedium,
|
||||
IconTrashOutlineRegular,
|
||||
Menu,
|
||||
StateDot,
|
||||
type StateDotState,
|
||||
|
|
@ -114,6 +115,12 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive
|
|||
aria-expanded={node.expanded}
|
||||
aria-label={t('section.workspaces')}
|
||||
data-wg-category={node.key}
|
||||
/* Flower-branch hooks: a category row starts a group, so the stem kinks
|
||||
here. Deliberately NOT marked active even when it contains the open
|
||||
session — the session row below it carries that marker, and only one
|
||||
row may claim it (see BRANCH_ACTIVE_ATTRIBUTE). */
|
||||
data-wg-branch-row=""
|
||||
data-wg-branch-group=""
|
||||
draggable={onDragStartCategory !== undefined}
|
||||
onClick={onToggle}
|
||||
onDragStart={onDragStartCategory}
|
||||
|
|
@ -122,10 +129,10 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive
|
|||
onDrop={onRowDrop}
|
||||
>
|
||||
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
|
||||
<IconTriangleRightFill14 />
|
||||
<IconTriangleRightFillMedium />
|
||||
</span>
|
||||
<span className="wgCategoryIcon" data-wg-row-icon="group">
|
||||
{node.expanded ? <IconFolderOpen16 /> : <IconFolderClose16 />}
|
||||
{node.expanded ? <IconFolderOpenMedium /> : <IconFolderCloseMedium />}
|
||||
</span>
|
||||
<span className="wgCategoryLabel">{node.label}</span>
|
||||
<span className="wgCategoryCount">{count}</span>
|
||||
|
|
@ -135,8 +142,8 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive
|
|||
open={menuOpen}
|
||||
onClose={() => { setMenuOpen(false) }}
|
||||
items={[
|
||||
{ id: 'rename', label: t('group.rename'), icon: <IconEditOutline16 /> },
|
||||
{ id: 'delete', label: t('group.delete'), icon: <IconTrashOutline16 />, danger: true },
|
||||
{ id: 'rename', label: t('group.rename'), icon: <IconEditOutlineRegular /> },
|
||||
{ id: 'delete', label: t('group.delete'), icon: <IconTrashOutlineRegular />, danger: true },
|
||||
]}
|
||||
onSelect={(id) => {
|
||||
setMenuOpen(false)
|
||||
|
|
@ -153,7 +160,7 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive
|
|||
aria-label={`${t('group.rename')} ${node.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
|
||||
>
|
||||
<IconEllipsisOutline16 />
|
||||
<IconEllipsisOutlineRegular />
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
|
|
@ -164,7 +171,7 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive
|
|||
}
|
||||
|
||||
/** One workspace folder row inside a category: draggable source + drop target. */
|
||||
export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, onOpenInFolder, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
node: WorkspaceGroupNode
|
||||
t: T
|
||||
onToggle: () => void
|
||||
|
|
@ -174,6 +181,12 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
/** Project currently sits inside a group — offer "move out of group". */
|
||||
canMoveOut?: boolean
|
||||
onMoveOut?: () => void
|
||||
/**
|
||||
* Open the project directory in the host's file manager. Omitted when the
|
||||
* host resolved no folder application (no capability, or a remote launch),
|
||||
* which keeps the entry out of the menu entirely.
|
||||
*/
|
||||
onOpenInFolder?: () => void
|
||||
/** Render as a top-level row (no folder indentation). */
|
||||
flat?: boolean
|
||||
/** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */
|
||||
|
|
@ -181,11 +194,14 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
} & RowDropProps) {
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const menuItems = [
|
||||
...(canMoveOut && onMoveOut !== undefined
|
||||
? [{ id: 'moveOut', label: t('workspace.moveOutOfGroup'), icon: <IconFolderOpenOutline16 size={16} /> }]
|
||||
...(onOpenInFolder !== undefined
|
||||
? [{ id: 'openInFolder', label: t('workspace.openInFolder'), icon: <IconFolderOpenOutlineRegular size={16} /> }]
|
||||
: []),
|
||||
{ id: 'rename', label: t('workspace.rename'), icon: <IconEditOutline16 /> },
|
||||
{ id: 'delete', label: t('workspace.delete'), icon: <IconTrashOutline16 />, danger: true },
|
||||
...(canMoveOut && onMoveOut !== undefined
|
||||
? [{ id: 'moveOut', label: t('workspace.moveOutOfGroup'), icon: <IconRightUpOutlineRegular size={16} /> }]
|
||||
: []),
|
||||
{ id: 'rename', label: t('workspace.rename'), icon: <IconEditOutlineRegular /> },
|
||||
{ id: 'delete', label: t('workspace.delete'), icon: <IconTrashOutlineRegular />, danger: true },
|
||||
]
|
||||
const onDragStart = (event: DragEvent): void => {
|
||||
event.dataTransfer.setData(DND_WORKSPACE_TYPE, node.workspaceId)
|
||||
|
|
@ -198,6 +214,15 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
role="treeitem"
|
||||
aria-expanded={node.expanded}
|
||||
data-wsid={node.workspaceId}
|
||||
/* Branch hooks. A project row IS a branch point: it heads its own run of
|
||||
session rows, so the stem kinks here and curves back in on the first
|
||||
session beneath it. That gives the branch one kink per project, which is
|
||||
the readable rhythm — a single top-level category would otherwise never
|
||||
produce a kink at all.
|
||||
Active is NOT set here: when this project holds the open session, the
|
||||
session row itself carries the marker. */
|
||||
data-wg-branch-row=""
|
||||
data-wg-branch-group=""
|
||||
draggable
|
||||
onClick={onToggle}
|
||||
onDragStart={onDragStart}
|
||||
|
|
@ -206,12 +231,12 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
onDrop={onRowDrop}
|
||||
>
|
||||
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
|
||||
<IconTriangleRightFill14 />
|
||||
<IconTriangleRightFillMedium />
|
||||
</span>
|
||||
<span className="wgCategoryIcon" data-wg-row-icon="project">
|
||||
{/* Project rows use the project glyph (same as the official workspace
|
||||
browser) so groups (folder glyph) and projects stay distinguishable. */}
|
||||
<IconProjectAddOutline16 />
|
||||
<IconProjectAddOutlineRegular />
|
||||
</span>
|
||||
<span className="wgProjectLabel" title={node.path}>{node.label}</span>
|
||||
<span className="wgRowActions">
|
||||
|
|
@ -221,6 +246,7 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
items={menuItems}
|
||||
onSelect={(id) => {
|
||||
setMenuOpen(false)
|
||||
if (id === 'openInFolder') onOpenInFolder?.()
|
||||
if (id === 'moveOut') onMoveOut?.()
|
||||
if (id === 'rename') onRename()
|
||||
if (id === 'delete') onDelete()
|
||||
|
|
@ -235,7 +261,7 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
aria-label={`${t('workspace.rename')} ${node.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
|
||||
>
|
||||
<IconEllipsisOutline16 />
|
||||
<IconEllipsisOutlineRegular />
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
|
|
@ -246,13 +272,29 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
aria-label={`${t('session.new')} ${node.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); onNewSession() }}
|
||||
>
|
||||
<IconPlusOutline16 />
|
||||
<IconPlusOutlineRegular />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Children container for one folder's rows.
|
||||
*
|
||||
* Keeps the tree's `role="group"` semantics and gives the rows a single
|
||||
* positioned ancestor. It used to draw a per-folder guide rail; that is now the
|
||||
* flower branch's job (one continuous stem for the whole tree, see
|
||||
* `FlowerBranch.tsx`), so this is structure only.
|
||||
*/
|
||||
export function TreeChildren({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="wgTreeChildren" role="group">
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** One session leaf row. */
|
||||
export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {
|
||||
node: SessionNode
|
||||
|
|
@ -266,17 +308,25 @@ export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork,
|
|||
}) {
|
||||
const selected = node.id === currentId
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const showStatus = true
|
||||
// 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
|
||||
const menuItems = [
|
||||
{ id: 'rename', label: t('session.rename'), icon: <IconEditOutline16 /> },
|
||||
{ id: 'fork', label: t('session.fork'), icon: <IconBranchOutline16 /> },
|
||||
{ id: 'archive', label: t('session.archive'), icon: <IconArchiveOutline20 size={16} /> },
|
||||
{ id: 'rename', label: t('session.rename'), icon: <IconEditOutlineRegular /> },
|
||||
{ id: 'fork', label: t('session.fork'), icon: <IconBranchOutlineRegular /> },
|
||||
{ id: 'archive', label: t('session.archive'), icon: <IconArchiveOutlineRegular size={16} /> },
|
||||
]
|
||||
return (
|
||||
<div
|
||||
className={`wgSessionRow${selected ? ' wgSelected' : ''}${node.matched === true ? ' wgMatched' : ''}`}
|
||||
role="treeitem"
|
||||
aria-selected={selected}
|
||||
data-wg-branch-row=""
|
||||
{...(selected ? { 'data-wg-branch-active': '' } : {})}
|
||||
onClick={() => { onOpen(node.id) }}
|
||||
>
|
||||
<span className="wgStatusSlot">
|
||||
|
|
@ -308,7 +358,7 @@ export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork,
|
|||
aria-label={`${t('session.rename')} ${node.title}`}
|
||||
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
|
||||
>
|
||||
<IconEllipsisOutline16 />
|
||||
<IconEllipsisOutlineRegular />
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,86 @@
|
|||
/**
|
||||
* A framework-shaped selector hook over a store instance.
|
||||
*
|
||||
* The renderer builds this hook for slot seats (`bindSnapshotSelector` in
|
||||
* ui-renderer, wrapping React's `useSyncExternalStoreWithSelector`), but the tab
|
||||
* strip is NOT a slot occupant: it renders through a DOM seat as a child of this
|
||||
* plugin's own `sidebar.workspaces` occupant, so it receives its store face as a
|
||||
* plain prop and needs the equivalent binding here.
|
||||
*
|
||||
* The implementation mirrors React's `useSyncExternalStoreWithSelector` without
|
||||
* depending on the `use-sync-external-store` package (it is not resolvable from
|
||||
* this plugin). The two behaviours that matter:
|
||||
*
|
||||
* - identity-stable subscribe/getSnapshot closures, so the strip never
|
||||
* resubscribes across renders;
|
||||
* - a memoized selection: the selector re-runs only when the state reference
|
||||
* changes, and an equal result (by `eq`, defaulting to `Object.is`) returns
|
||||
* the PREVIOUS reference, so a selector allocating a fresh array or object
|
||||
* does not spin the render loop.
|
||||
*
|
||||
* The hook must be called unconditionally (Rules of Hooks).
|
||||
*/
|
||||
import { useCallback, useRef, useSyncExternalStore } from 'react'
|
||||
import type { ActionsDecl, StoreInstance } from '@deepseek-ai/dsh-client-store'
|
||||
|
||||
/** One memory cell: the state it was derived from, and the value it produced. */
|
||||
interface Selection<T, S> {
|
||||
state: T
|
||||
value: S
|
||||
/** Whether `value` was produced by the selector (vs. carried over as equal). */
|
||||
hasValue: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a selector hook bound to one store instance.
|
||||
* @param instance - the live store instance (snapshot source).
|
||||
* @returns a `SnapshotSelectorHook`-compatible hook over that instance.
|
||||
*/
|
||||
export function createStoreHook<T, A extends ActionsDecl<T>>(
|
||||
instance: StoreInstance<T, A>,
|
||||
): <S>(selector: (state: T) => S, eq?: (a: S, b: S) => boolean) => S {
|
||||
// Captured once: stable closures keep uSES from resubscribing every render.
|
||||
const subscribe = (onChange: () => void): (() => void) => instance.subscribe(onChange)
|
||||
const getState = (): T => instance.getSnapshot()
|
||||
|
||||
return function useSelector<S>(
|
||||
selector: (state: T) => S,
|
||||
eq?: (a: S, b: S) => boolean,
|
||||
): S {
|
||||
// Seeded eagerly so the first render selects without an extra pass.
|
||||
const memory = useRef<Selection<T, S> | null>(null)
|
||||
|
||||
// Re-select the value for the current state. Called by uSES on every
|
||||
// notification AND on every render; the memory makes it cheap and
|
||||
// reference-stable.
|
||||
const getSelection = useCallback((): S => {
|
||||
const state = getState()
|
||||
const previous = memory.current
|
||||
|
||||
// Same state object => the previous value is still valid. This is the
|
||||
// path that lets an allocating selector stay reference-stable.
|
||||
if (previous !== null && previous.hasValue && Object.is(previous.state, state)) {
|
||||
return previous.value
|
||||
}
|
||||
|
||||
const value = selector(state)
|
||||
|
||||
// New state, but an equal value: carry the old reference forward so uSES
|
||||
// sees no change and skips the re-render.
|
||||
if (previous !== null && previous.hasValue) {
|
||||
const equal = eq !== undefined ? eq(previous.value, value) : Object.is(previous.value, value)
|
||||
if (equal) {
|
||||
memory.current = { state, value: previous.value, hasValue: true }
|
||||
return previous.value
|
||||
}
|
||||
}
|
||||
|
||||
memory.current = { state, value, hasValue: true }
|
||||
return value
|
||||
}, [selector, eq])
|
||||
|
||||
// The third argument is the server snapshot; the client plugin never
|
||||
// server-renders, so the same getter is correct for both.
|
||||
return useSyncExternalStore(subscribe, getSelection, getSelection)
|
||||
}
|
||||
}
|
||||
|
|
@ -10,7 +10,7 @@
|
|||
* unit tests exercise the real semantics without a browser module loader;
|
||||
* this file only binds them through defineStore.
|
||||
*/
|
||||
import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'
|
||||
import {
|
||||
retainKeysImpl,
|
||||
setCategoryExpandedImpl,
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,50 @@
|
|||
/**
|
||||
* Plugin-owned projection of descendant counts from Session summaries.
|
||||
*
|
||||
* 0.1.2 移除了 `@deepseek-ai/dsh-client-runtime/client`(平台模块表不再提供
|
||||
* `indexSubagentDescendants`),官方 ui-workspace 改为各自持有本地副本
|
||||
* (packages/client/ui-workspace/src/client/subagent-lineage.ts,MIT)。这里
|
||||
* 保持同一实现,使运行中的子代理会话数在树行上继续可见。
|
||||
*/
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
|
||||
interface LineageEntry {
|
||||
readonly id: SessionId
|
||||
readonly parentId?: SessionId
|
||||
readonly origin?: 'subagent'
|
||||
readonly running: boolean
|
||||
}
|
||||
|
||||
/** Descendant counts for one possible parent Session. */
|
||||
export interface SubagentDescendantSummary {
|
||||
readonly count: number
|
||||
readonly runningCount: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Index uninterrupted subagent descendants under each ancestor.
|
||||
* @param summaries - Session summaries keyed by id.
|
||||
* @returns descendant totals keyed by possible parent id.
|
||||
*/
|
||||
export function indexSubagentDescendants(
|
||||
summaries: Readonly<Record<SessionId, LineageEntry>>,
|
||||
): ReadonlyMap<SessionId, SubagentDescendantSummary> {
|
||||
const indexed = new Map<SessionId, { count: number; runningCount: number }>()
|
||||
for (const descendant of Object.values(summaries)) {
|
||||
if (descendant.origin !== 'subagent') continue
|
||||
const seen = new Set<SessionId>()
|
||||
let current: LineageEntry | undefined = descendant
|
||||
while (current?.origin === 'subagent' && current.parentId !== undefined && !seen.has(current.id)) {
|
||||
seen.add(current.id)
|
||||
const aggregate = indexed.get(current.parentId)
|
||||
if (aggregate === undefined) {
|
||||
indexed.set(current.parentId, { count: 1, runningCount: descendant.running ? 1 : 0 })
|
||||
} else {
|
||||
aggregate.count += 1
|
||||
if (descendant.running) aggregate.runningCount += 1
|
||||
}
|
||||
current = summaries[current.parentId]
|
||||
}
|
||||
}
|
||||
return indexed
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
/**
|
||||
* Client side of the session-tab persistence, talking to
|
||||
* `GET|PUT /workspace-groups/tabs` on the host.
|
||||
*
|
||||
* Why not browser storage: **the origin includes the PORT**, and every `dsh web`
|
||||
* / `dsh test` / desktop launch picks a different one. `localStorage` and
|
||||
* `sessionStorage` are both scoped to the origin, so they start empty on the
|
||||
* next launch — a tab list kept there survives a reload only when the port
|
||||
* happens to match. The host's JSON sidecar has no such problem, which is why
|
||||
* the strip is stored there and read back verbatim.
|
||||
*
|
||||
* There is deliberately no per-browser-session marker. A marker has to live in
|
||||
* browser storage, which the port invalidates, so every restart looked like a
|
||||
* fresh session and silently discarded the user's tabs — the exact failure this
|
||||
* module exists to prevent.
|
||||
*
|
||||
* Every call is best-effort: a failed read means "no tabs" and a failed write is
|
||||
* swallowed, because the strip is a convenience and must never break the app.
|
||||
*/
|
||||
|
||||
/** Host route holding the strip. */
|
||||
export const TABS_ROUTE = '/workspace-groups/tabs'
|
||||
|
||||
/** One tab as it crosses the wire. */
|
||||
export interface WireTab {
|
||||
readonly sessionId: string
|
||||
readonly order: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the stored strip.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns the tabs, oldest first; empty on any failure.
|
||||
*/
|
||||
export async function loadTabs(fetchImpl: typeof fetch = fetch): Promise<WireTab[]> {
|
||||
try {
|
||||
const response = await fetchImpl(TABS_ROUTE, {
|
||||
method: 'GET',
|
||||
// Per-session state; a cached response would restore stale tabs.
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (!response.ok) return []
|
||||
const body: unknown = await response.json()
|
||||
if (typeof body !== 'object' || body === null) return []
|
||||
const list = (body as { tabs?: unknown }).tabs
|
||||
if (!Array.isArray(list)) return []
|
||||
const tabs: WireTab[] = []
|
||||
for (const entry of list) {
|
||||
if (typeof entry !== 'object' || entry === null) continue
|
||||
const row = entry as Record<string, unknown>
|
||||
if (typeof row.sessionId !== 'string' || row.sessionId === '') continue
|
||||
if (typeof row.order !== 'number' || !Number.isFinite(row.order)) continue
|
||||
tabs.push({ sessionId: row.sessionId, order: row.order })
|
||||
}
|
||||
return tabs
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the strip. Failures are swallowed.
|
||||
* @param state - the client's current strip and its arrival counter.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
*/
|
||||
export async function saveTabs(
|
||||
state: { order: number; tabs: readonly WireTab[] },
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await fetchImpl(TABS_ROUTE, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ order: state.order, tabs: state.tabs }),
|
||||
cache: 'no-store',
|
||||
// Survive a navigation that happens while the request is in flight; the
|
||||
// write is idempotent so a re-send is harmless.
|
||||
keepalive: true,
|
||||
})
|
||||
} catch {
|
||||
// Offline or the host is restarting: the next change writes the full state
|
||||
// again, so nothing is lost beyond this tick.
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,180 @@
|
|||
/**
|
||||
* DOM seat for the session tab strip.
|
||||
*
|
||||
* Why this exists instead of a slot: the strip belongs at the very top of the
|
||||
* conversation column — `pI_x6G_centerCol` (ui-layout's AppFrame `.centerCol`,
|
||||
* a hashed CSS-Modules class). That column declares NO child slots: its only
|
||||
* child is the `main` slot's occupant (`renderSlot('main', …)`, the
|
||||
* Conversation or a global panel), so there is nowhere to register. The
|
||||
* shipped slot in that neighbourhood — `conversation.composer.dock` — is the
|
||||
* band UNDER the composer card, a different place entirely.
|
||||
*
|
||||
* So the strip gets a real DOM seat: this module finds the column, prepends a
|
||||
* `<div>` to it, and hands that element to a React portal. The element is
|
||||
* OURS, never React's: it is inserted outside the column's child list that
|
||||
* React reconciles, and it is re-inserted if React (or a theme/titlebar
|
||||
* re-render) ever drops it.
|
||||
*
|
||||
* Two hazards this module is built around:
|
||||
*
|
||||
* 1. `centerCol` is a hashed class name (`pI_x6G_centerCol`) that changes when
|
||||
* the package is rebuilt. Matching is therefore done on the *structural*
|
||||
* contract — a grid-item column that holds the `main` panel — plus a
|
||||
* `[class*="_centerCol"]` probe, never on the exact hash.
|
||||
* 2. The column mounts after the client plugin's `apply()` runs. Discovery is
|
||||
* therefore a MutationObserver on `document.body` plus a `requestAnimationFrame`
|
||||
* retry, and both are torn down when the owning effect disposes.
|
||||
*/
|
||||
|
||||
/** Persistent marker for the injected container (survives React re-renders). */
|
||||
const SEAT_ATTRIBUTE = 'data-wg-tab-seat'
|
||||
|
||||
/** Sentinel attribute on the container so discovery can skip our own node. */
|
||||
const SEAT_SELECTOR = `[${SEAT_ATTRIBUTE}]`
|
||||
|
||||
/**
|
||||
* Match the conversation column by its hashed CSS-Modules class.
|
||||
*
|
||||
* The hash prefix (`pI_x6G_`) is build-dependent, so the probe matches the
|
||||
* `_centerCol` suffix that the Modules transform always preserves. A plain
|
||||
* `class*="centerCol"` scan would risk matching unrelated utility classes, so
|
||||
* the leading underscore is required.
|
||||
* @param root - subtree to scan (normally `document`).
|
||||
* @returns the column element, or null while it has not mounted.
|
||||
*/
|
||||
function findCenterColumn(root: ParentNode): HTMLElement | null {
|
||||
// Fast path: the seat is already in place and still attached, which is the
|
||||
// steady state on every re-render (portal into an existing element).
|
||||
const existing = root.querySelector<HTMLElement>(SEAT_SELECTOR)
|
||||
if (existing?.isConnected === true) return existing.parentElement
|
||||
|
||||
// Structural probe: the column is the direct child of the app frame grid
|
||||
// that contains the `main` panel. Querying the class suffix first keeps this
|
||||
// to one selector evaluation in the common case.
|
||||
const column = root.querySelector<HTMLElement>('[class*="_centerCol"]')
|
||||
if (column !== null) return column
|
||||
|
||||
// Nothing matched: either the shell has not mounted yet, or the Modules hash
|
||||
// convention changed. Returning null keeps the caller in its wait loop
|
||||
// instead of guessing at a wrong node (which would visually corrupt the
|
||||
// shell). The strip simply appears once the frame is up.
|
||||
return null
|
||||
}
|
||||
|
||||
/** A mounted seat: the host element plus the disposer that removes it. */
|
||||
export interface TabSeat {
|
||||
/**
|
||||
* The element the React portal renders into — null until the conversation
|
||||
* column mounts. The portal is simply not rendered while this is null.
|
||||
*/
|
||||
readonly host: HTMLElement | null
|
||||
/** Remove the seat and stop watching for the column. */
|
||||
dispose: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a seat exists as the FIRST child of the conversation column, creating
|
||||
* it if needed, and keep it there for as long as the returned handle is live.
|
||||
*
|
||||
* The seat element is created once and reused: a portal that re-mounts into a
|
||||
* fresh node on every shell re-render would drop the tab strip's React state
|
||||
* and visible focus. If React removes the node (it owns the column's child
|
||||
* list, and our node is not part of it), the observer re-inserts the SAME
|
||||
* element, so the portal's subtree moves with it.
|
||||
*
|
||||
* @param onReady - called with the host element each time it becomes attached
|
||||
* (once immediately when the column already exists). Used to seed React
|
||||
* state; may fire more than once if the column is remounted.
|
||||
* @returns the seat handle. `host` is null until the column appears, so the
|
||||
* caller renders nothing meanwhile and starts rendering when `onReady`
|
||||
* fires. Never null: a missing column must degrade to "no strip", not to a
|
||||
* thrown error that would take the whole client plugin down.
|
||||
*/
|
||||
export function mountTabSeat(onReady: (host: HTMLElement) => void): TabSeat {
|
||||
let host: HTMLElement | null = null
|
||||
let column: HTMLElement | null = null
|
||||
let observer: MutationObserver | null = null
|
||||
let raf = 0
|
||||
let attempts = 0
|
||||
let disposed = false
|
||||
|
||||
// Bounded retry: ~5s at 60fps. The shell mounts well inside this; the bound
|
||||
// exists so a missing column degrades to "no strip" instead of a permanent
|
||||
// frame loop.
|
||||
const MAX_ATTEMPTS = 300
|
||||
|
||||
/**
|
||||
* Put the seat at the head of the column, creating it on first success.
|
||||
* Idempotent: a seat already first is left untouched, so repeated calls from
|
||||
* the observer cause no DOM churn (and therefore no observer feedback loop —
|
||||
* our insertion schedules one more callback, which then takes this early
|
||||
* return instead of re-inserting).
|
||||
*/
|
||||
const place = (target: HTMLElement): void => {
|
||||
if (disposed) return
|
||||
if (host === null) {
|
||||
host = document.createElement('div')
|
||||
host.setAttribute(SEAT_ATTRIBUTE, '')
|
||||
}
|
||||
if (target.firstChild === host) return
|
||||
target.insertBefore(host, target.firstChild)
|
||||
}
|
||||
|
||||
/** Locate the column and, on success, seat the host and notify the caller. */
|
||||
const tryMount = (): boolean => {
|
||||
if (disposed) return true
|
||||
// Steady state: the column we already found is still attached.
|
||||
if (column !== null && column.isConnected) {
|
||||
place(column)
|
||||
return true
|
||||
}
|
||||
const found = findCenterColumn(document)
|
||||
if (found === null) return false
|
||||
// A different column than last time (shell remount): re-seat AND re-notify,
|
||||
// because the caller may hold a stale host element from the old tree.
|
||||
const changed = found !== column
|
||||
column = found
|
||||
place(found)
|
||||
if (changed) onReady(host as HTMLElement)
|
||||
return true
|
||||
}
|
||||
|
||||
const tick = (): void => {
|
||||
if (disposed) return
|
||||
raf = 0
|
||||
if (tryMount()) return
|
||||
attempts += 1
|
||||
if (attempts >= MAX_ATTEMPTS) return
|
||||
raf = requestAnimationFrame(tick)
|
||||
}
|
||||
|
||||
// The observer covers both "column mounts later" and "React dropped our
|
||||
// node": either way the child list changes and we re-seat. `requestAnimationFrame`
|
||||
// alone would miss a removal that happens after the retry budget is spent.
|
||||
observer = new MutationObserver(() => {
|
||||
if (disposed) return
|
||||
if (tryMount()) return
|
||||
if (raf === 0 && attempts < MAX_ATTEMPTS) raf = requestAnimationFrame(tick)
|
||||
})
|
||||
observer.observe(document.body, { childList: true, subtree: true })
|
||||
|
||||
if (!tryMount() && raf === 0) raf = requestAnimationFrame(tick)
|
||||
|
||||
return {
|
||||
get host(): HTMLElement | null {
|
||||
// Null until the column mounts; the caller's `onReady` fires at the same
|
||||
// moment this becomes non-null, so the two never disagree.
|
||||
return host
|
||||
},
|
||||
dispose: () => {
|
||||
disposed = true
|
||||
if (raf !== 0) cancelAnimationFrame(raf)
|
||||
raf = 0
|
||||
observer?.disconnect()
|
||||
observer = null
|
||||
host?.remove()
|
||||
host = null
|
||||
column = null
|
||||
},
|
||||
} as TabSeat
|
||||
}
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
/**
|
||||
* The session-tab store: the `defineStore` binding and nothing else.
|
||||
*
|
||||
* The action TRANSFORMS live in `tabs.ts` (pure, runtime-free), so unit tests
|
||||
* exercise the real semantics without pulling in the store engine — this module
|
||||
* is the only place that needs `@deepseek-ai/dsh-client-store`, and importing it
|
||||
* from a test would drag `zustand` into the test process.
|
||||
*
|
||||
* One handle, one scope: the tab store is seated by the `sidebar.workspaces`
|
||||
* entry alone. The tab strip is a CHILD of that entry (rendered through a DOM
|
||||
* portal into the conversation column), not a second slot registration, so the
|
||||
* handle is never mounted under a second, differently-scoped slot — which the
|
||||
* registry rejects outright ("one handle, one scope").
|
||||
*
|
||||
* Placement is navigation, not data: the strip derives its active chip from the
|
||||
* open session, and arrival order is the strip's only order, so nothing here
|
||||
* mirrors selection.
|
||||
*/
|
||||
import { defineStore, type EngineStoreHandle, type StoreHandle } from '@deepseek-ai/dsh-client-store'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import {
|
||||
closeTabImpl,
|
||||
restoreTabsImpl,
|
||||
touchTabImpl,
|
||||
type SessionTab,
|
||||
type SessionTabsState,
|
||||
} from './tabs.ts'
|
||||
|
||||
export type { SessionTabsState }
|
||||
|
||||
/**
|
||||
* Session-tab strip actions (bound by the framework, handed to the browser).
|
||||
*
|
||||
* There is deliberately NO "drop tabs whose session vanished" action. An open
|
||||
* tab is closed by the USER and by nothing else — a program that trims the strip
|
||||
* on its own eventually eats tabs the user wanted, and the whole point of the
|
||||
* strip is that it holds what you opened.
|
||||
*
|
||||
* This is also why the store needs no catalog at all: it never consults one.
|
||||
*/
|
||||
export interface SessionTabsActions {
|
||||
/** Add the open session, or leave its existing tab untouched in place. */
|
||||
touch: (sessionId: SessionId) => void
|
||||
/** Close one tab; navigation is untouchable from here (the caller decides). */
|
||||
close: (sessionId: SessionId) => void
|
||||
/**
|
||||
* Replace the strip with tabs loaded from the host.
|
||||
*
|
||||
* The host read is a `fetch`, so it cannot happen inside `init()`. This action
|
||||
* is how the async result lands, and it is a no-op once the user has already
|
||||
* opened a tab — a slow response must never discard what they just did.
|
||||
*/
|
||||
restore: (tabs: readonly SessionTab[]) => void
|
||||
}
|
||||
|
||||
/** Annotation twin of the actions literal below (structural `ActionsDecl`). */
|
||||
type SessionTabsActionsDecl = {
|
||||
touch: typeof touchTabImpl
|
||||
close: typeof closeTabImpl
|
||||
restore: typeof restoreTabsImpl
|
||||
}
|
||||
|
||||
/**
|
||||
* The tab store's registered handle: identity + spec + the instance factory the
|
||||
* framework resolves per entry x scope. It deliberately does NOT claim the live
|
||||
* instance's faces (`getSnapshot` / `actions`) — `defineStore`'s concrete return
|
||||
* is structurally narrower, and this alias has to stay a type that value can be
|
||||
* assigned to.
|
||||
*/
|
||||
export type SessionTabsStoreHandle = StoreHandle<SessionTabsState, SessionTabsActionsDecl>
|
||||
|
||||
/**
|
||||
* The live tab store value: the handle's `create()` product, which carries the
|
||||
* baked write set and the snapshot source. Named here so the registrations and
|
||||
* the strip's props can share one type without importing the store engine.
|
||||
*/
|
||||
export type SessionTabsInstance = ReturnType<EngineStoreHandle<SessionTabsState, SessionTabsActionsDecl>['create']>
|
||||
|
||||
/**
|
||||
* Create the session-tab store handle.
|
||||
*
|
||||
* The strip starts EMPTY and is hydrated by the caller through the `restore`
|
||||
* action: persistence lives on the host behind a `fetch`, which cannot run
|
||||
* during `init()`. Browser storage is deliberately not used — the origin
|
||||
* includes the port, and every launch picks a new one, so `localStorage` and
|
||||
* `sessionStorage` both start empty on the next start.
|
||||
*
|
||||
* @returns the store handle (spec + type + identity + factory in one).
|
||||
*/
|
||||
export function createSessionTabsStore(): EngineStoreHandle<SessionTabsState, SessionTabsActionsDecl> {
|
||||
return defineStore({
|
||||
init: (): SessionTabsState => ({ tabs: [], order: 0 }),
|
||||
actions: {
|
||||
touch: touchTabImpl,
|
||||
close: closeTabImpl,
|
||||
restore: restoreTabsImpl,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export type { SessionTab }
|
||||
|
|
@ -0,0 +1,339 @@
|
|||
/**
|
||||
* Pure session-tab state: the ordered strip of sessions the user has opened,
|
||||
* the active one, and each tab's derived presentation.
|
||||
*
|
||||
* Position model: a tab's place in the strip is decided ONCE, when it is first
|
||||
* opened, and never changes afterwards. Switching to a tab, or re-opening a
|
||||
* session that already has one, leaves the strip exactly as it was — so clicking
|
||||
* a chip never moves the chip out from under the pointer. Only two events change
|
||||
* the order: a session opening for the FIRST time (append) and a tab closing
|
||||
* (remove).
|
||||
*
|
||||
* Runtime-free on purpose (same discipline as `store-core.ts` / `quick.ts`):
|
||||
* the component owns the ref + React state, this module owns every rule, and
|
||||
* unit tests exercise the real semantics without a browser module loader.
|
||||
*
|
||||
* Retention note: a tab outlives whatever it points at. The strip is a list of
|
||||
* things the USER opened, so nothing here consults the session catalog — a tab
|
||||
* whose session is gone stays visible until the user closes it, and no
|
||||
* background sweep ever trims the strip.
|
||||
*/
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { SessionStatus } from '@deepseek-ai/dsh-client-ui-session/client'
|
||||
|
||||
/** One open tab: a session id plus its arrival key (React list identity). */
|
||||
export interface SessionTab {
|
||||
/** The session the tab shows. */
|
||||
readonly sessionId: SessionId
|
||||
/**
|
||||
* Monotonic arrival key. It doubles as the React `key`, so it must stay
|
||||
* attached to the session for the tab's whole life — a reused key would make
|
||||
* React move an existing chip's DOM node instead of reconciling it in place.
|
||||
*/
|
||||
readonly order: number
|
||||
}
|
||||
|
||||
/** Feature switch: whether opening a session also surfaces a tab. */
|
||||
export type TabOpenMode = 'auto' | 'manual'
|
||||
|
||||
/** Per-tab indicator derived from the catalog summary and the live UI status. */
|
||||
export interface SessionTabIndicator {
|
||||
/** A domain request is waiting for the user (approval / plan review / question). */
|
||||
readonly attention: boolean
|
||||
/** The agent is producing output, or a descendant subagent is. */
|
||||
readonly running: boolean
|
||||
/** The turn finished while the tab was in the background and was never looked at. */
|
||||
readonly unread: boolean
|
||||
/** Idle tab whose session already has a title (a settled conversation). */
|
||||
readonly settled: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a session to the strip, or leave an existing entry exactly where it is.
|
||||
*
|
||||
* Arrival order is the strip's only order, so re-opening a session that already
|
||||
* has a tab is a NO-OP: the tab keeps its position and its arrival key. Moving
|
||||
* it to the front here would fight the whole point of stable positions — a user
|
||||
* clicking through sessions would watch the strip reshuffle on every click.
|
||||
*
|
||||
* @param tabs - current strip (oldest first).
|
||||
* @param sessionId - arriving session.
|
||||
* @param nextOrder - monotonic arrival counter to spend when appending.
|
||||
* @returns the strip, unchanged (same array) when the session already has a tab.
|
||||
*/
|
||||
export function appendTab(tabs: readonly SessionTab[], sessionId: SessionId, nextOrder: number): SessionTab[] {
|
||||
const existing = tabs.find(tab => tab.sessionId === sessionId)
|
||||
if (existing !== undefined) return tabs as SessionTab[]
|
||||
return [...tabs, { sessionId, order: nextOrder }]
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one session's tab. An absent session leaves the strip untouched.
|
||||
* @param tabs - current strip.
|
||||
* @param sessionId - session whose tab closes.
|
||||
* @returns a new strip.
|
||||
*/
|
||||
export function removeTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[] {
|
||||
return tabs.filter(tab => tab.sessionId !== sessionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Order the strip for display: strictly by arrival, regardless of which tab is
|
||||
* active.
|
||||
*
|
||||
* Position is a property of the TAB, not of the selection. Switching to a tab
|
||||
* must not move it — an earlier version pulled the active tab to the front,
|
||||
* which made every click reshuffle the strip and slid the chip out from under
|
||||
* the pointer that had just clicked it.
|
||||
*
|
||||
* `activeId` is therefore accepted only to document that "active" deliberately
|
||||
* does NOT participate in ordering; it is unused. The returned array is a copy
|
||||
* so callers cannot mutate the store's state through it.
|
||||
*
|
||||
* @param tabs - strip in arrival order.
|
||||
* @param activeId - the open session, if it has a tab (intentionally unused).
|
||||
* @returns a new array in arrival order.
|
||||
*/
|
||||
export function orderedTabs(tabs: readonly SessionTab[], activeId: SessionId | undefined): SessionTab[] {
|
||||
void activeId
|
||||
return [...tabs]
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the open session must surface a tab.
|
||||
*
|
||||
* A tab means "this conversation is in play right now", not "I once opened
|
||||
* this". Browsing history is what the sidebar is for; opening an old
|
||||
* conversation to read it should not litter the strip, which is the whole point
|
||||
* of the strip being a working set rather than a second session list.
|
||||
*
|
||||
* A session therefore earns a tab only once a conversation has actually STARTED
|
||||
* in it and is still engaged, which is any of:
|
||||
* - **running** — the agent is producing output (including subagents);
|
||||
* - **waiting on you** — an approval / plan review / question is pending;
|
||||
* - **unseen completion** — it finished while you were elsewhere, so the tab is
|
||||
* the thing that tells you to come back.
|
||||
*
|
||||
* A still-blank draft gets NO tab: the tab appears the moment the first message
|
||||
* is sent (which is when the controller flips `blank` on `turn/start`). Once the
|
||||
* turn ends and you have read the result, the session is settled history and
|
||||
* does not earn a tab — so clicking through finished conversations leaves the
|
||||
* strip alone. Tabs already opened stay open: this gate only decides whether a
|
||||
* NEW tab appears, never whether an existing one closes.
|
||||
*
|
||||
* `blank` (from `sessionListMetadata`) is exactly "no turn has started": the
|
||||
* controller flips it to false on `turn/start`. It is the right signal for
|
||||
* "has this conversation begun", and the wrong one ALONE — a conversation
|
||||
* finished a week ago is also non-blank, which is why the earlier `!blank` rule
|
||||
* surfaced every old conversation the user clicked.
|
||||
*
|
||||
* @param mode - feature switch ('auto' applies the engagement rule).
|
||||
* @param summary - the session's catalog row (absent while the catalog has not
|
||||
* caught up with a just-created session).
|
||||
* @param status - the session's unified UI status (absent → no live signal).
|
||||
* @returns true when a tab belongs in the strip.
|
||||
*/
|
||||
export function shouldOpenTab(
|
||||
mode: TabOpenMode,
|
||||
summary: SessionSummary | undefined,
|
||||
status: SessionStatus | undefined,
|
||||
): boolean {
|
||||
if (mode === 'manual') return false
|
||||
if (summary === undefined) return false
|
||||
// No turn yet: a scratch draft is not a conversation, so it holds no tab. The
|
||||
// first message flips `blank`, and the tab appears then.
|
||||
if (summary.blank) return false
|
||||
// A conversation has begun. Keep the tab only while it is still in play.
|
||||
if (summary.running) return true
|
||||
if (status?.running === true) return true
|
||||
if (status?.pendingInteraction !== undefined) return true
|
||||
if (status?.completionUnread === true) return true
|
||||
// Begun, but quiet and read: settled history, not a working tab.
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive one tab's indicators from the catalog row and the unified UI status.
|
||||
* @param summary - the tab session's catalog row (absent → inert indicators).
|
||||
* @param status - the tab session's unified UI status (absent → idle).
|
||||
* @returns the indicator quadruple.
|
||||
*/
|
||||
export function tabIndicator(
|
||||
summary: SessionSummary | undefined,
|
||||
status: SessionStatus | undefined,
|
||||
): SessionTabIndicator {
|
||||
const pending = status?.pendingInteraction !== undefined
|
||||
const running = status?.running === true || summary?.running === true
|
||||
const unread = status?.completionUnread === true
|
||||
const blank = summary?.blank !== false
|
||||
return {
|
||||
attention: pending,
|
||||
running,
|
||||
unread,
|
||||
settled: !pending && !running && !unread && summary !== undefined && !blank,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where one session lives: the project (workspace) that accounts for it.
|
||||
*
|
||||
* Tabs carry this because a strip of bare session titles is ambiguous once
|
||||
* several projects are open — two checkouts both named "api", or a session
|
||||
* titled after a file, give no hint which project it belongs to.
|
||||
*/
|
||||
export interface TabProject {
|
||||
/** Stable workspace id. */
|
||||
readonly workspaceId: string
|
||||
/** Display label: the workspace title, falling back to its directory name. */
|
||||
readonly label: string
|
||||
/** Canonical directory path, for the tooltip. */
|
||||
readonly path: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Index sessions by the project that owns them.
|
||||
*
|
||||
* Membership comes from the workspace registry (`sessionIds`), which is the same
|
||||
* authority the sidebar tree uses — a tab and its sidebar row therefore agree on
|
||||
* the project without a second derivation.
|
||||
*
|
||||
* Built once per render pass rather than scanned per tab: a strip of N tabs over
|
||||
* M projects is O(N×M) with a naive `find` per tab.
|
||||
*
|
||||
* @param workspaces - workspace views from the controller snapshot.
|
||||
* @returns a session id → project map; sessions in no workspace are absent.
|
||||
*/
|
||||
export function projectIndex(
|
||||
workspaces: readonly WorkspaceViewLike[],
|
||||
): ReadonlyMap<SessionId, TabProject> {
|
||||
const index = new Map<SessionId, TabProject>()
|
||||
for (const workspace of workspaces) {
|
||||
const label = projectLabel(workspace)
|
||||
const project: TabProject = {
|
||||
workspaceId: workspace.workspaceId,
|
||||
label,
|
||||
path: workspace.path,
|
||||
}
|
||||
for (const sessionId of workspace.sessionIds) {
|
||||
// First writer wins: a session wrongly listed by two workspaces keeps the
|
||||
// first, so the tab never flickers between labels across renders.
|
||||
if (!index.has(sessionId)) index.set(sessionId, project)
|
||||
}
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
/** Minimal workspace shape this module needs (keeps it importable in tests). */
|
||||
export interface WorkspaceViewLike {
|
||||
readonly workspaceId: string
|
||||
readonly path: string
|
||||
readonly title: string
|
||||
readonly sessionIds: readonly SessionId[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Display label for a project: its title, else the directory basename.
|
||||
* @param workspace - workspace view.
|
||||
* @returns a non-empty label, falling back to the raw path.
|
||||
*/
|
||||
export function projectLabel(workspace: Pick<WorkspaceViewLike, 'title' | 'path'>): string {
|
||||
const title = workspace.title.trim()
|
||||
if (title !== '') return title
|
||||
// Both separators: the host path may be Windows or POSIX.
|
||||
const parts = workspace.path.split(/[\\/]/).filter(part => part !== '')
|
||||
return parts[parts.length - 1] ?? workspace.path
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two strips are the same sequence of sessions (arrival keys ignored).
|
||||
* @param left - previous strip.
|
||||
* @param right - next strip.
|
||||
* @returns true when no entry was added, removed, or reordered.
|
||||
*/
|
||||
export function sameTabs(left: readonly SessionTab[], right: readonly SessionTab[]): boolean {
|
||||
return left.length === right.length
|
||||
&& left.every((tab, index) => right[index]?.sessionId === tab.sessionId)
|
||||
}
|
||||
|
||||
/** Session-tab strip state (the shape the store persists). */
|
||||
export interface SessionTabsState {
|
||||
/** Open tabs in arrival order — the strip's one and only order. */
|
||||
tabs: SessionTab[]
|
||||
/** Monotonic arrival counter; each FIRST-time session spends one. */
|
||||
order: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Store transform: add the open session, or leave its existing tab in place.
|
||||
*
|
||||
* Live here rather than in `tab-store.ts` so unit tests can exercise the real
|
||||
* semantics without importing `@deepseek-ai/dsh-client-store` (which pulls
|
||||
* `zustand` into the test process). The store module binds these into its
|
||||
* actions table.
|
||||
*
|
||||
* The no-op guard matters: this runs on EVERY catalog change for the open
|
||||
* session, so an unguarded write would wake the strip and spend arrival keys on
|
||||
* every projection tick.
|
||||
*
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the session that just became open.
|
||||
*/
|
||||
export function touchTabImpl(state: SessionTabsState, sessionId: SessionId): void {
|
||||
const next = appendTab(state.tabs, sessionId, state.order + 1)
|
||||
// Same array => the session already had a tab; nothing changed, so nothing is
|
||||
// written and no subscriber wakes.
|
||||
if (next === state.tabs) return
|
||||
state.order += 1
|
||||
state.tabs = next
|
||||
}
|
||||
|
||||
/**
|
||||
* Store transform: close one tab. Closing a session that has no tab is not a
|
||||
* state change, so it writes nothing.
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the tab to close.
|
||||
*/
|
||||
export function closeTabImpl(state: SessionTabsState, sessionId: SessionId): void {
|
||||
const next = removeTab(state.tabs, sessionId)
|
||||
if (next.length === state.tabs.length) return
|
||||
state.tabs = next
|
||||
}
|
||||
|
||||
/**
|
||||
* Store transform: adopt tabs loaded from the host, MERGING with whatever is
|
||||
* already in the strip.
|
||||
*
|
||||
* Async by nature (the host read is a `fetch`), so it can land after the browser
|
||||
* has already opened a tab for the current session. Merging — rather than
|
||||
* "ignore the read if the strip is non-empty" — is what makes a restart safe:
|
||||
* the tab opened during startup survives AND the stored tabs still come back.
|
||||
* (Bailing on a non-empty strip would silently drop every stored tab whenever
|
||||
* the startup tab won the race, which is the common case for a session that is
|
||||
* running or unread.)
|
||||
*
|
||||
* The arrival counter is lifted above every restored key so a tab opened later
|
||||
* cannot reuse one; a reused key makes React move a chip's DOM node instead of
|
||||
* reconciling it.
|
||||
*
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param tabs - tabs read from the host, oldest first.
|
||||
*/
|
||||
export function restoreTabsImpl(state: SessionTabsState, tabs: readonly SessionTab[]): void {
|
||||
if (tabs.length === 0) return
|
||||
const present = new Set(state.tabs.map(tab => tab.sessionId))
|
||||
const additions: SessionTab[] = []
|
||||
let order = state.order
|
||||
for (const tab of tabs) {
|
||||
// Never duplicate: a session already in the strip keeps its existing entry
|
||||
// and position.
|
||||
if (present.has(tab.sessionId)) continue
|
||||
present.add(tab.sessionId)
|
||||
// Re-key onto a fresh, monotonically increasing counter so a restored key
|
||||
// can never collide with one already spent.
|
||||
order += 1
|
||||
additions.push({ sessionId: tab.sessionId, order })
|
||||
}
|
||||
if (additions.length > 0) state.tabs = [...state.tabs, ...additions]
|
||||
state.order = order
|
||||
}
|
||||
|
|
@ -4,20 +4,52 @@
|
|||
* scans. Session visibility rules mirror the official ui-workspace tree
|
||||
* (blank rows only when current, archived excluded, subagent rows excluded).
|
||||
*/
|
||||
import {
|
||||
indexSubagentDescendants,
|
||||
type PendingInteractionStatus,
|
||||
type SessionId,
|
||||
type SessionListState,
|
||||
type SessionSearchResultItem,
|
||||
type SessionSummary,
|
||||
type SubagentDescendantSummary,
|
||||
type WorkspaceId,
|
||||
type WorkspaceView,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type {
|
||||
SessionListState,
|
||||
SessionSearchResultItem,
|
||||
SessionSummary,
|
||||
} from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
// Type-only: the unified UI status snapshot. 0.1.6 把 running / pendingInteraction /
|
||||
// 未读完成提示收敛为 ui-session 的 SessionStatusSnapshot;SessionSummary.completed
|
||||
// 与 SessionListState.current 同时移除,当前会话改由 `mainView` 保留位推导。
|
||||
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 { effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'
|
||||
import { TOP_LEVEL_ORDER_KEY, UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../core/types.ts'
|
||||
|
||||
/** Pending interaction kinds with dedicated Workspace-row presentation. */
|
||||
export type SessionPendingInteractionStatus = 'approval' | 'plan-review' | 'question'
|
||||
|
||||
/** Current unified UI status by Session (ui-session snapshot). */
|
||||
type SessionStatuses = SessionStatusSnapshot
|
||||
|
||||
/**
|
||||
* The Session the Conversation is currently showing.
|
||||
*
|
||||
* 0.1.6 removed `SessionListState.current`: selection is expressed as the
|
||||
* Session retained through the `mainView` reference source (the ui-workspace
|
||||
* navigation holds exactly one). Same read the official browser performs.
|
||||
* @param list - sessions list snapshot.
|
||||
* @returns the retained Session id, or undefined while no Session is selected.
|
||||
*/
|
||||
export function currentSessionId(list: SessionListState): SessionId | undefined {
|
||||
return Object.values(list.byId).find(session => (session.retainedBy?.mainView ?? 0) > 0)?.id
|
||||
}
|
||||
|
||||
/** Keep navigation presentation independent from domain-owned interaction objects. */
|
||||
function visiblePendingKind(kind: string | undefined): SessionPendingInteractionStatus | undefined {
|
||||
switch (kind) {
|
||||
case 'approval':
|
||||
case 'plan-review':
|
||||
case 'question':
|
||||
return kind
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** One top-level session row inside a workspace folder. */
|
||||
export interface SessionNode {
|
||||
id: SessionId
|
||||
|
|
@ -25,7 +57,7 @@ export interface SessionNode {
|
|||
title: string
|
||||
/** The provisional blank session (renderer shows the localized New Session title). */
|
||||
blank: boolean
|
||||
pendingInteraction?: PendingInteractionStatus
|
||||
pendingInteraction?: SessionPendingInteractionStatus
|
||||
running: boolean
|
||||
/** Running descendants connected through uninterrupted subagent-origin lineage. */
|
||||
runningSubagentCount: number
|
||||
|
|
@ -100,16 +132,24 @@ function sessionTitle(session: SessionSummary): string {
|
|||
function sessionNode(
|
||||
s: SessionSummary,
|
||||
descendants: ReadonlyMap<SessionId, SubagentDescendantSummary>,
|
||||
statuses: SessionStatuses,
|
||||
): SessionNode {
|
||||
// `SessionStatusSnapshot` is typed as ReadonlyMap, but the framework binds a
|
||||
// plain record at runtime (client.js: `statuses[sessionId]`). Read both shapes
|
||||
// so a hook backed by an object never throws "statuses.get is not a function".
|
||||
const status = typeof (statuses as { get?: unknown } | undefined)?.get === 'function'
|
||||
? statuses.get(s.id)
|
||||
: (statuses as unknown as Record<string, SessionStatus | undefined>)[s.id]
|
||||
const pending = visiblePendingKind(status?.pendingInteraction?.kind)
|
||||
return {
|
||||
id: s.id,
|
||||
title: sessionTitle(s),
|
||||
blank: s.blank,
|
||||
running: s.running,
|
||||
running: status?.running ?? s.running,
|
||||
runningSubagentCount: descendants.get(s.id)?.runningCount ?? 0,
|
||||
completed: s.completed === true,
|
||||
completed: status?.completionUnread === true,
|
||||
updatedAt: s.updatedAt,
|
||||
...(s.pendingInteraction === undefined ? {} : { pendingInteraction: s.pendingInteraction }),
|
||||
...(pending === undefined ? {} : { pendingInteraction: pending }),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -119,13 +159,15 @@ function workspaceSessions(
|
|||
workspace: WorkspaceView,
|
||||
archived: ReadonlySet<SessionId>,
|
||||
descendants: ReadonlyMap<SessionId, SubagentDescendantSummary>,
|
||||
statuses: SessionStatuses,
|
||||
current: SessionId | undefined,
|
||||
): SessionNode[] {
|
||||
const nodes: SessionNode[] = []
|
||||
for (const id of workspace.sessionIds) {
|
||||
const summary = list.byId[id]
|
||||
if (summary === undefined) continue // account may lead the list pull; appears when the summary lands
|
||||
if (!sessionVisible(summary, list.current, archived)) continue
|
||||
nodes.push(sessionNode(summary, descendants))
|
||||
if (!sessionVisible(summary, current, archived)) continue
|
||||
nodes.push(sessionNode(summary, descendants, statuses))
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
|
@ -139,6 +181,8 @@ function workspaceSessions(
|
|||
* @param view - local expansion arrays.
|
||||
* @param manual - runtime overlay (manual groups + overrides). A workspace's
|
||||
* manual override wins over rule classification; removing it reverts to rules.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @returns category sections in render order (rule categories first, then
|
||||
* manual-only ones, uncategorized last). Manual groups render even while
|
||||
* empty; empty rule buckets stay hidden.
|
||||
|
|
@ -150,11 +194,13 @@ export function deriveGroups(
|
|||
config: GroupsConfig,
|
||||
view: GroupsTreeView,
|
||||
manual: ManualGroups,
|
||||
statuses: SessionStatuses = new Map(),
|
||||
): CategoryNode[] {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const expandedCategories = new Set(view.expandedCategories)
|
||||
const expandedWorkspaces = new Set(view.expandedWorkspaces)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
const current = currentSessionId(list)
|
||||
|
||||
// Bucket workspaces by display key. Seed with every effective category so
|
||||
// manual groups render while empty. Top-level (ungrouped) workspaces are
|
||||
|
|
@ -171,9 +217,9 @@ export function deriveGroups(
|
|||
}
|
||||
|
||||
const manualCategories = new Set(manual.categories)
|
||||
const currentWorkspaceId = list.current === undefined
|
||||
const currentWorkspaceId = current === undefined
|
||||
? undefined
|
||||
: workspaces.find(w => w.sessionIds.includes(list.current as SessionId))?.workspaceId
|
||||
: workspaces.find(w => w.sessionIds.includes(current))?.workspaceId
|
||||
|
||||
const nodes: CategoryNode[] = []
|
||||
// Effective categories in display order (categoryOrder applied).
|
||||
|
|
@ -188,7 +234,7 @@ export function deriveGroups(
|
|||
for (const workspaceId of ordered) {
|
||||
const workspace = bucket.find(w => w.workspaceId === workspaceId)
|
||||
if (workspace === undefined) continue
|
||||
const sessions = workspaceSessions(list, workspace, archived, descendants)
|
||||
const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)
|
||||
const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)
|
||||
const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId
|
||||
if (wsContainsCurrent) containsCurrent = true
|
||||
|
|
@ -228,13 +274,15 @@ export function deriveTopLevel(
|
|||
config: GroupsConfig,
|
||||
view: GroupsTreeView,
|
||||
manual: ManualGroups,
|
||||
statuses: SessionStatuses = new Map(),
|
||||
): WorkspaceGroupNode[] {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const expandedWorkspaces = new Set(view.expandedWorkspaces)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
const currentWorkspaceId = list.current === undefined
|
||||
const current = currentSessionId(list)
|
||||
const currentWorkspaceId = current === undefined
|
||||
? undefined
|
||||
: workspaces.find(w => w.sessionIds.includes(list.current as SessionId))?.workspaceId
|
||||
: workspaces.find(w => w.sessionIds.includes(current))?.workspaceId
|
||||
|
||||
const topLevelIds = workspaces
|
||||
.filter(w => resolveCategory(config, manual, w.workspaceId, w.path, w.title) === undefined)
|
||||
|
|
@ -245,7 +293,7 @@ export function deriveTopLevel(
|
|||
for (const workspaceId of ordered) {
|
||||
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
|
||||
if (workspace === undefined) continue
|
||||
const sessions = workspaceSessions(list, workspace, archived, descendants)
|
||||
const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)
|
||||
const wsExpanded = expandedWorkspaces.has(workspaceId)
|
||||
nodes.push({
|
||||
workspaceId: workspace.workspaceId,
|
||||
|
|
@ -294,6 +342,7 @@ export function deriveSearchMatches(
|
|||
if (q === '') return { matchedIds: new Set(), snippetsBySession: new Map(), hasMore: false }
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
const current = currentSessionId(list)
|
||||
|
||||
const workspaceBySession = new Map<SessionId, WorkspaceView>()
|
||||
for (const workspace of workspaces) {
|
||||
|
|
@ -307,7 +356,7 @@ export function deriveSearchMatches(
|
|||
const local: SessionSummary[] = []
|
||||
for (const id of list.ids) {
|
||||
const summary = list.byId[id]
|
||||
if (summary === undefined || summary.blank || !sessionVisible(summary, list.current, archived)) continue
|
||||
if (summary === undefined || summary.blank || !sessionVisible(summary, current, archived)) continue
|
||||
if (
|
||||
sessionTitle(summary).toLowerCase().includes(q)
|
||||
|| labelOf(summary).toLowerCase().includes(q)
|
||||
|
|
@ -327,7 +376,7 @@ export function deriveSearchMatches(
|
|||
for (const summary of local) include(summary)
|
||||
for (const item of content.items) {
|
||||
const summary = list.byId[item.sessionId]
|
||||
if (summary !== undefined && !summary.blank && sessionVisible(summary, list.current, archived)) include(summary)
|
||||
if (summary !== undefined && !summary.blank && sessionVisible(summary, current, archived)) include(summary)
|
||||
}
|
||||
|
||||
const snippets = new Map<SessionId, string>()
|
||||
|
|
@ -365,6 +414,8 @@ export interface SearchTree {
|
|||
* @param archivedSessionIds - registry-global archive set.
|
||||
* @param manual - runtime overlay (manual groups + overrides).
|
||||
* @param snippetsBySession - optional content-match snippets keyed by session id.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @returns group folders in render order plus top-level matched workspaces,
|
||||
* pruned to matched branches only.
|
||||
*/
|
||||
|
|
@ -376,9 +427,11 @@ export function deriveSearchGroups(
|
|||
archivedSessionIds: readonly SessionId[],
|
||||
manual: ManualGroups,
|
||||
snippetsBySession?: ReadonlyMap<SessionId, string>,
|
||||
statuses: SessionStatuses = new Map(),
|
||||
): SearchTree {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
const current = currentSessionId(list)
|
||||
|
||||
const byCategory = new Map<string, WorkspaceGroupNode[]>()
|
||||
for (const key of effectiveCategories(config, manual).map(e => e.key)) byCategory.set(key, [])
|
||||
|
|
@ -390,8 +443,8 @@ export function deriveSearchGroups(
|
|||
for (const id of workspace.sessionIds) {
|
||||
const summary = list.byId[id]
|
||||
if (summary === undefined || !matchedIds.has(id)) continue
|
||||
if (!sessionVisible(summary, list.current, archived)) continue
|
||||
const node = sessionNode(summary, descendants)
|
||||
if (!sessionVisible(summary, current, archived)) continue
|
||||
const node = sessionNode(summary, descendants, statuses)
|
||||
const snippet = snippetsBySession?.get(id)
|
||||
nodes.push({
|
||||
...node,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* Shared config types for dsh-workspace-groups. Pure types (zero runtime
|
||||
* Shared config types for @dsh-xhl/workspace-groups. Pure types (zero runtime
|
||||
* deps) so both halves — the node half (sidecar YAML reading) and the
|
||||
* browser half (tree derivation) — compile against the same contract.
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* Sidecar config reading for dsh-workspace-groups. The classification rules
|
||||
* Sidecar config reading for @dsh-xhl/workspace-groups. The classification rules
|
||||
* live in a user-editable YAML file (default `~/.dsh/workspace-groups.yaml`),
|
||||
* read and validated on the host, served to the browser half as JSON. The
|
||||
* core workspace.json and session storage are never touched.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* Runtime grouping overlay for dsh-workspace-groups: manual groups created in
|
||||
* Runtime grouping overlay for @dsh-xhl/workspace-groups: manual groups created in
|
||||
* the sidebar UI and per-workspace category overrides. Stored in a plugin-
|
||||
* owned JSON sidecar (`$DSH_HOME/workspace-groups.manual.json`), separate from
|
||||
* the operator YAML — the YAML stays the rule source, this file only records
|
||||
|
|
|
|||
|
|
@ -0,0 +1,148 @@
|
|||
/**
|
||||
* Host-side persistence for the session-tab strip.
|
||||
*
|
||||
* Why the host and not the browser: **browser storage is scoped to the origin,
|
||||
* and the origin includes the PORT.** `dsh web` / `dsh test` / the desktop shell
|
||||
* each pick a port, and a different port is a different origin, so BOTH
|
||||
* `localStorage` and `sessionStorage` start empty on the next launch. A tab list
|
||||
* kept there survives a reload only by luck (same port) and is lost on the next
|
||||
* start.
|
||||
*
|
||||
* Host storage has no such problem: one JSON sidecar under `$DSH_HOME`, keyed by
|
||||
* nothing but the plugin, so every port and every session reads the same file.
|
||||
* That file IS the strip's memory — it is returned as-is, with no browser-session
|
||||
* marker gating it.
|
||||
*
|
||||
* (An earlier version DID gate on a `sessionKey` kept in `sessionStorage`, to
|
||||
* express "clear when the browser closes". That cannot work here: the marker is
|
||||
* itself per-origin, so a port change erased it, the host saw an unfamiliar
|
||||
* marker, and every restart silently discarded the user's tabs. Persistence the
|
||||
* user can rely on beats a tidy-up nobody asked for.)
|
||||
*
|
||||
* Writes are atomic (temp file + fsync + rename), matching the manual overlay.
|
||||
*/
|
||||
import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { homedir } from 'node:os'
|
||||
|
||||
/** One persisted tab. */
|
||||
export interface PersistedTab {
|
||||
/** Session id the tab points at. */
|
||||
readonly sessionId: string
|
||||
/** Arrival key (React list identity). */
|
||||
readonly order: number
|
||||
}
|
||||
|
||||
/** The persisted document. */
|
||||
export interface TabsDocument {
|
||||
/** Shape version; a mismatch discards the file rather than guessing. */
|
||||
readonly version: 1
|
||||
/** Arrival counter, kept ahead of every tab's own order. */
|
||||
readonly order: number
|
||||
readonly tabs: readonly PersistedTab[]
|
||||
}
|
||||
|
||||
/** Default location: `$DSH_HOME/workspace-groups.tabs.json`. */
|
||||
export function defaultTabsPath(): string {
|
||||
const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== ''
|
||||
? process.env.DSH_HOME
|
||||
: resolve(homedir(), '.dsh')
|
||||
return resolve(home, 'workspace-groups.tabs.json')
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse + shape-validate a tabs document.
|
||||
*
|
||||
* Tolerant on purpose: this file is a display cache, so a malformed one must
|
||||
* read as "no tabs" rather than break the strip. Individual bad rows are dropped
|
||||
* and the rest kept. Unknown fields (such as the `sessionKey` an older build
|
||||
* wrote) are ignored, so an existing file keeps working across the change.
|
||||
*
|
||||
* @param raw - parsed JSON value.
|
||||
* @returns the normalized document, or null when it is unusable.
|
||||
*/
|
||||
export function parseTabsDocument(raw: unknown): TabsDocument | null {
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null
|
||||
const source = raw as Record<string, unknown>
|
||||
if (source.version !== 1) return null
|
||||
if (typeof source.order !== 'number' || !Number.isFinite(source.order)) return null
|
||||
if (!Array.isArray(source.tabs)) return null
|
||||
const tabs: PersistedTab[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const entry of source.tabs) {
|
||||
if (typeof entry !== 'object' || entry === null) continue
|
||||
const row = entry as Record<string, unknown>
|
||||
if (typeof row.sessionId !== 'string' || row.sessionId === '') continue
|
||||
if (typeof row.order !== 'number' || !Number.isFinite(row.order)) continue
|
||||
if (seen.has(row.sessionId)) continue
|
||||
seen.add(row.sessionId)
|
||||
tabs.push({ sessionId: row.sessionId, order: row.order })
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
order: source.order,
|
||||
tabs,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the tabs document.
|
||||
*
|
||||
* A missing file is not an error (first run). A corrupt one is reported as null
|
||||
* so the caller starts empty, and the next write repairs the file.
|
||||
*
|
||||
* @param path - sidecar path.
|
||||
* @returns the document, or null when absent/unusable.
|
||||
*/
|
||||
export async function readTabsDocument(path: string): Promise<TabsDocument | null> {
|
||||
let text: string
|
||||
try {
|
||||
text = await readFile(path, 'utf8')
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
|
||||
throw error
|
||||
}
|
||||
try {
|
||||
return parseTabsDocument(JSON.parse(text))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the tabs document atomically.
|
||||
* @param path - sidecar path.
|
||||
* @param document - document to store.
|
||||
*/
|
||||
export async function writeTabsDocument(path: string, document: TabsDocument): Promise<void> {
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
const temp = `${path}.${process.pid}.${Date.now()}.tmp`
|
||||
const body = `${JSON.stringify(document, null, 2)}\n`
|
||||
const handle = await open(temp, 'w')
|
||||
try {
|
||||
await handle.writeFile(body, 'utf8')
|
||||
await handle.sync()
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
try {
|
||||
await rename(temp, path)
|
||||
} catch (error) {
|
||||
await unlink(temp).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the document to persist.
|
||||
* @param state - the client's current strip and its arrival counter.
|
||||
* @returns the document to write.
|
||||
*/
|
||||
export function documentForTabs(state: { order: number; tabs: readonly PersistedTab[] }): TabsDocument {
|
||||
const highest = state.tabs.reduce((max, tab) => Math.max(max, tab.order), 0)
|
||||
return {
|
||||
version: 1,
|
||||
order: Math.max(state.order, highest),
|
||||
tabs: [...state.tabs],
|
||||
}
|
||||
}
|
||||
102
src/index.ts
102
src/index.ts
|
|
@ -6,6 +6,9 @@
|
|||
* - `GET /workspace-groups/config` — snapshot of the YAML rule categories
|
||||
* merged with the runtime manual overlay (groups + assignments). Read-only
|
||||
* for the rules; the overlay is attached so one fetch boots the browser.
|
||||
* - `GET /workspace-groups/tabs` — the persisted session-tab strip (host-side
|
||||
* sidecar; see host-tabs.ts for why it cannot live in the browser).
|
||||
* - `PUT /workspace-groups/tabs` — replace the stored strip whole.
|
||||
* - `PUT /workspace-groups/manual` — replace the whole manual overlay
|
||||
* (manual groups + per-workspace overrides). Validated against the current
|
||||
* rule categories, written atomically to the plugin-owned JSON sidecar.
|
||||
|
|
@ -22,9 +25,17 @@ import {
|
|||
validateManualGroups,
|
||||
writeManualGroups,
|
||||
} from './host-manual.ts'
|
||||
import {
|
||||
defaultTabsPath,
|
||||
documentForTabs,
|
||||
readTabsDocument,
|
||||
writeTabsDocument,
|
||||
type PersistedTab,
|
||||
type TabsDocument,
|
||||
} from './host-tabs.ts'
|
||||
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
export const name = 'dsh-workspace-groups'
|
||||
export const name = '@dsh-xhl/workspace-groups'
|
||||
|
||||
/** Services required before mounting: the webserver route. */
|
||||
export const inject = ['webServer']
|
||||
|
|
@ -39,6 +50,36 @@ class HttpError extends Error {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape-validate a PUT /tabs body.
|
||||
*
|
||||
* Returns null on a malformed payload rather than throwing, so the route can
|
||||
* answer 400 without a try/catch around the parse. Individual bad tab rows are
|
||||
* dropped (the strip is a display cache; one bad row must not reject a whole
|
||||
* write), and duplicate session ids are collapsed to the first.
|
||||
*
|
||||
* @param raw - parsed request body.
|
||||
* @returns the payload, or null when the envelope is unusable.
|
||||
*/
|
||||
function parseTabsPayload(raw: unknown): { order: number; tabs: PersistedTab[] } | null {
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null
|
||||
const source = raw as Record<string, unknown>
|
||||
if (typeof source.order !== 'number' || !Number.isFinite(source.order)) return null
|
||||
if (!Array.isArray(source.tabs)) return null
|
||||
const tabs: PersistedTab[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const entry of source.tabs) {
|
||||
if (typeof entry !== 'object' || entry === null) continue
|
||||
const row = entry as Record<string, unknown>
|
||||
if (typeof row.sessionId !== 'string' || row.sessionId === '') continue
|
||||
if (typeof row.order !== 'number' || !Number.isFinite(row.order)) continue
|
||||
if (seen.has(row.sessionId)) continue
|
||||
seen.add(row.sessionId)
|
||||
tabs.push({ sessionId: row.sessionId, order: row.order })
|
||||
}
|
||||
return { order: source.order, tabs }
|
||||
}
|
||||
|
||||
/** Write a plain-text error response with the given status. */
|
||||
function writeError(res: ServerResponse, status: number, message: string): void {
|
||||
res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8' })
|
||||
|
|
@ -63,6 +104,7 @@ async function readBody(req: IncomingMessage, limit: number): Promise<string> {
|
|||
export function apply(ctx: GroupsContext): void {
|
||||
const configPath = defaultConfigPath()
|
||||
const manualPath = defaultManualPath()
|
||||
const tabsPath = defaultTabsPath()
|
||||
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
|
|
@ -91,7 +133,61 @@ export function apply(ctx: GroupsContext): void {
|
|||
})
|
||||
res.end(req.method === 'HEAD' ? undefined : body)
|
||||
},
|
||||
}), 'dsh-workspace-groups: /workspace-groups/config route')
|
||||
}), '@dsh-xhl/workspace-groups: /workspace-groups/config route')
|
||||
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
path: '/workspace-groups/tabs',
|
||||
handler: async (req, res) => {
|
||||
if (req.method === 'GET' || req.method === 'HEAD') {
|
||||
let stored: TabsDocument | null
|
||||
try {
|
||||
stored = await readTabsDocument(tabsPath)
|
||||
} catch (error) {
|
||||
writeError(res, 500, `workspace-groups: failed to read tabs: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
const body = JSON.stringify({ tabs: stored?.tabs ?? [] })
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(req.method === 'HEAD' ? undefined : body)
|
||||
return
|
||||
}
|
||||
if (req.method !== 'PUT') {
|
||||
writeError(res, 405, 'method not allowed')
|
||||
return
|
||||
}
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES))
|
||||
} catch (error) {
|
||||
const status = error instanceof HttpError ? error.status : 400
|
||||
writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
const parsed = parseTabsPayload(raw)
|
||||
if (parsed === null) {
|
||||
writeError(res, 400, 'workspace-groups: malformed tabs payload')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await writeTabsDocument(tabsPath, documentForTabs(parsed))
|
||||
} catch (error) {
|
||||
writeError(res, 500, `workspace-groups: failed to write tabs: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
const body = JSON.stringify({ ok: true })
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(body)
|
||||
},
|
||||
}), '@dsh-xhl/workspace-groups: /workspace-groups/tabs route')
|
||||
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
|
|
@ -134,5 +230,5 @@ export function apply(ctx: GroupsContext): void {
|
|||
})
|
||||
res.end(body)
|
||||
},
|
||||
}), 'dsh-workspace-groups: /workspace-groups/manual route')
|
||||
}), '@dsh-xhl/workspace-groups: /workspace-groups/manual route')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,6 +40,13 @@ const CLIENT_EXTERNALS = [
|
|||
'@deepseek-ai/cordis',
|
||||
'@deepseek-ai/dsh-client-ui-slots',
|
||||
'@deepseek-ai/dsh-client-ui-primitives',
|
||||
// `defineStore` / store handle types. In the current shell the store runtime is
|
||||
// the module-table row `@deepseek-ai/dsh-client-store`: official plugins load it
|
||||
// exactly this way (e.g. `@deepseek-ai/dsh-api-job-controller/lib/client.js`
|
||||
// does `require("@deepseek-ai/dsh-client-store")`). The older
|
||||
// `@deepseek-ai/dsh-client-runtime/client` row is kept for compatibility with
|
||||
// plugins built before the rename.
|
||||
'@deepseek-ai/dsh-client-store',
|
||||
'@deepseek-ai/dsh-client-runtime/client',
|
||||
] as const
|
||||
|
||||
|
|
@ -140,7 +147,7 @@ function clientConfig(): UserConfig {
|
|||
],
|
||||
outputOptions: {
|
||||
entryFileNames: 'client.js',
|
||||
banner: `window.__ModuleLoader__.load({ id: "dsh-workspace-groups", factory: (require) => {`,
|
||||
banner: `window.__ModuleLoader__.load({ id: "@dsh-xhl/workspace-groups", factory: (require) => {`,
|
||||
footer: 'return module.exports; } });',
|
||||
intro: 'var module = { exports: {} }; var exports = module.exports;',
|
||||
},
|
||||
|
|
|
|||
Loading…
Reference in New Issue