dsh-sidebar-sessions 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sss-1012
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # dsh-sidebar-sessions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DeepSeek Harness 的会话侧边栏增强插件:**最近优先 + 自定义分组 + 工作区树 + 归档 + 状态点 + 拖动排序**。
4
+
5
+ 它接管 Web 端 `sidebar.workspaces` 插槽,把原本按工作区平铺的会话列表换成一条以「最近使用」为先的清单。
6
+
7
+ > **建议使用暗黑模式(深色主题)以获得最佳体验**:配色全部取自 DSH 主题变量(`--dsw-alias-*`),暗色下状态点、hover 行背景与拖动落点线的对比最清楚;浅色主题同样能用,只是侧栏与主区域的明度差小一些。
8
+
9
+ ## 功能
10
+
11
+ - **最近优先**:顶部「最近」区按最近活跃时间排序(默认 20 条)。
12
+ - **置顶**:手动置顶的会话单独一组。
13
+ - **自定义分组**:新建 / 重命名 / 删除分组,任意会话可移入分组(数据存 localStorage)。
14
+ - **工作区树**:📁 工作区节点可折叠,展开列出各工作区;📌 标记当前工作区,点击工作区名即可切换(调用宿主 `openWorkspace`)。
15
+ - **归档**:已归档会话收进「已归档」分组,可展开查看 / 取消归档。
16
+ - **搜索**:顶部搜索框按标题过滤,`Esc` 清空。
17
+ - **状态点**(官方 StateDot 同源数据):
18
+ - 待审批 → 琥珀圆点
19
+ - 运行中 → 蓝色转圈
20
+ - 已完成未读 → 绿色圆点
21
+ - 空闲但设置了定时任务 → 线性时钟图标(代替灰点)
22
+ - 空闲 → 灰点
23
+ - **拖动排序**:会话行可拖动。落点在目标行的**上半 → 插到它前面**、**下半 → 插到它后面**(蓝线标出落点),松手即生效;向下拖一格也能直接换位。工作区树内拖动写入宿主 `insertSessionBefore`(宿主拒绝时退回本地视图顺序);「最近 / 置顶 / 分组 / 未分组 / 已归档」区的拖动记在视图顺序里(随会话组一起存 localStorage,刷新保持)。「最近」标题上的 ↺ 恢复按活跃时间排序。
24
+ - **行内操作**(悬停「⋯」):置顶、重命名、分叉、复制 Session ID、复制工作目录、移动到分组、归档。
25
+
26
+ ## 安装
27
+
28
+ 尚未发布到 npm,用 GitHub Release 里的 tarball 安装:
29
+
30
+ ```bash
31
+ dsh plugin --profile web add https://github.com/sss-1012/dsh-sidebar-sessions/releases/download/v0.1.2/dsh-sidebar-sessions-0.1.2.tgz
32
+ ```
33
+
34
+ 装完重启 `dsh web`(已开着的话按 Ctrl+R 刷新页面)。
35
+
36
+ 本地开发(符号链接,改代码即时生效):
37
+
38
+ ```bash
39
+ dsh plugin --profile web add link:E:\Work\tools\dsh-sidebar-sessions
40
+ ```
41
+
42
+ ## 开发
43
+
44
+ 无构建步骤:`lib/index.js` 是空的 host 半边,`lib/client.js` 是浏览器 bundle(`window.__ModuleLoader__.load` 格式,直接以 ESM 加载)。
45
+
46
+ ```bash
47
+ node --check lib/client.js
48
+ node test/order.test.mjs
49
+ ```
50
+
51
+ ## 数据与限制
52
+
53
+ - 分组、折叠状态、隐藏工作区、当前工作区存在浏览器 `localStorage`(key `dsh-session-groups.v1`,兼容早期版本);各视图的拖动顺序也存在同一个 key 的 `order` 字段里。
54
+ - 宿主拥有会话、置顶、归档、工作区与宿主顺序的最终状态;插件只做展示与写入调用。
55
+ - **接管式**:`sidebar.workspaces` 是独占插槽,安装后官方 WorkspaceBrowser 不再渲染,其逐项能力由本插件自行实现。
56
+ - 工作区「隐藏」是本地显示开关(DSH 0.2.1 客户端未暴露工作区归档 API),不是官方归档。
57
+ - 工作区树里跨工作区拖动会被忽略(宿主只接受同一工作区内的移动);平铺区(最近 / 分组等)的拖动只改本视图顺序,不会把会话搬进别的分组或工作区。
58
+
59
+ ## License
60
+
61
+ MIT
@@ -0,0 +1,6 @@
1
+ # dsh-sidebar-sessions — client-only bundle registration.
2
+ # All behavior lives in lib/client.js; this row only mounts the package.
3
+ - insert:
4
+ - id: dsh-sidebar-sessions
5
+ name: dsh-sidebar-sessions
6
+ config: {}
package/lib/client.js ADDED
@@ -0,0 +1,817 @@
1
+ /* dsh-sidebar-sessions client bundle — plain ESM, no build step.
2
+ *
3
+ * sidebar.workspaces implementation:
4
+ * - recent-first session list, user groups, archive bucket
5
+ * - workspace node styled like a group, marked as a workspace: expanding it
6
+ * lists the workspaces (not sessions), each with its own fold state
7
+ * - drag-to-reorder: a drop moves the dragged row before the row it lands
8
+ * on. The workspace tree writes host order (insertSessionBefore); the
9
+ * recency sections (最近/置顶/分组/未分组/已归档) keep a local manual order,
10
+ * because re-sorting them by updatedAt would erase every drop
11
+ * - hidden entirely when the sidebar collapses to a narrow rail (CSS container
12
+ * query — no JS measurement, so no flicker)
13
+ */
14
+ window.__ModuleLoader__.load({
15
+ id: "dsh-sidebar-sessions",
16
+ factory: (require) => {
17
+ const React = require("react");
18
+ const h = React.createElement;
19
+ const { memo, useCallback, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } = React;
20
+ const inject = ["slots", "sessions", "workspaces", "uiWorkspace", "uiSession", "remote", "remote.schedule"];
21
+
22
+ const STORE_KEY = "dsh-session-groups.v1";
23
+ const RECENT_LIMIT = 20;
24
+
25
+ const CSS = `
26
+ .dsg-root{container-type:inline-size;display:flex;flex-direction:column;gap:1px;padding:4px 6px 8px}
27
+ @container (max-width:150px){.dsg-root > *{display:none}}
28
+ .dsg-head{position:sticky;top:0;z-index:2;display:flex;align-items:center;height:32px;padding:0 8px;box-sizing:border-box;color:var(--dsw-alias-label-secondary,#6b7280);font-size:12px;font-weight:600;cursor:pointer;user-select:none;background:var(--dsw-alias-bg-base,transparent)}
29
+ .dsg-head:hover{background:var(--dsw-alias-interactive-bg-hover)}
30
+ .dsg-caret{width:14px;flex:none;color:var(--dsw-alias-label-tertiary,#9ca3af);font-size:10px}
31
+ .dsg-head-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
32
+ .dsg-count{font-size:10px;color:var(--dsw-alias-label-tertiary,#9ca3af);flex:none;margin-left:6px}
33
+ .dsg-row{position:relative;display:flex;align-items:center;box-sizing:border-box;width:100%;height:32px;padding:0 4px 0 10px;border-radius:var(--dsw-radius-md,12px);color:var(--dsw-alias-label-primary,#111827);cursor:pointer;user-select:none}
34
+ .dsg-row:hover{background:var(--dsw-alias-interactive-bg-hover)}
35
+ .dsg-row:focus-visible{outline:2px solid var(--dsw-alias-focus-ring,#4d6bfe);outline-offset:-2px}
36
+ .dsg-row[data-over="before"]{box-shadow:inset 0 2px 0 0 var(--dsw-alias-state-business-primary,#4d6bfe)}
37
+ .dsg-row[data-over="after"]{box-shadow:inset 0 -2px 0 0 var(--dsw-alias-state-business-primary,#4d6bfe)}
38
+ .dsg-row[data-dragging="true"]{opacity:.45}
39
+ .dsg-dot{flex:none;width:8px;height:8px;border-radius:50%;margin-right:8px;background:var(--dsw-alias-label-tertiary,#9ca3af);box-sizing:border-box}
40
+ .dsg-dot[data-state="running"]{background:transparent;border:1.5px solid var(--dsw-alias-state-business-primary,#4d6bfe);border-top-color:transparent;animation:dsg-spin .8s linear infinite}
41
+ .dsg-dot[data-state="pending"]{background:var(--dsw-alias-state-warning-primary,#f7ad31)}
42
+ .dsg-dot[data-state="unread"]{background:var(--dsw-alias-state-success-primary,#22c55e)}
43
+ @keyframes dsg-spin{to{transform:rotate(360deg)}}
44
+ .dsg-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;line-height:20px;margin:0 4px 0 0;text-align:left}
45
+ .dsg-time{flex:0 0 4.5em;width:4.5em;margin-left:6px;text-align:right;white-space:nowrap;font-size:10px;line-height:16px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-tertiary,#9ca3af)}
46
+ .dsg-actions{display:flex;flex:none;gap:2px;opacity:0;margin-left:4px}
47
+ .dsg-row:hover .dsg-actions,.dsg-row:focus-within .dsg-actions{opacity:1}
48
+ .dsg-icon{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:22px;height:22px;border:none;background:transparent;color:var(--dsw-alias-label-secondary,#6b7280);cursor:pointer;font-size:13px;line-height:1;padding:0;border-radius:var(--dsw-radius-s,8px)}
49
+ .dsg-icon:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary,#111827)}
50
+ .dsg-pin{flex:none;color:var(--dsw-alias-state-business-primary,#4d6bfe);font-size:11px;margin-right:4px}
51
+ .dsg-dot-clock{flex:none;display:inline-flex;align-items:center;justify-content:center;width:12px;height:12px;margin-right:6px;color:var(--dsw-alias-label-tertiary,#9ca3af)}
52
+ .dsg-menu{position:fixed;z-index:9999;min-width:190px;padding:4px;background:var(--dsw-alias-bg-layer-2,#24272c);border:1px solid var(--dsw-alias-border-l4,rgba(127,127,127,.3));border-radius:var(--dsw-radius-md,12px);box-shadow:0 8px 24px rgba(0,0,0,.28)}
53
+ .dsg-menu-item{display:flex;align-items:center;gap:8px;height:30px;padding:0 10px;font-size:13px;color:var(--dsw-alias-label-primary,#111827);cursor:pointer;border-radius:var(--dsw-radius-s,8px);white-space:nowrap}
54
+ .dsg-menu-item:hover{background:var(--dsw-alias-interactive-bg-hover)}
55
+ .dsg-menu-sep{height:1px;margin:4px 6px;background:var(--dsw-alias-border-l2,rgba(127,127,127,.2))}
56
+ .dsg-menu-label{display:flex;align-items:center;height:24px;padding:0 10px;font-size:11px;color:var(--dsw-alias-label-tertiary,#9ca3af);cursor:default}
57
+ .dsg-dot-sm{color:var(--dsw-alias-state-business-primary,#4d6bfe);font-size:10px}
58
+ .dsg-search{display:flex;align-items:center;gap:6px;margin:0 2px 8px;padding:0 10px;height:34px;box-sizing:border-box;border-radius:var(--dsw-radius-sm,8px);background:var(--dsw-alias-bg-layer-1,#1a1d21);border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.15))}
59
+ .dsg-search input{flex:1;min-width:0;height:32px;line-height:32px;background:transparent;border:none;outline:none;color:var(--dsw-alias-label-primary,#e5e7eb);font-size:13px}
60
+ .dsg-search input::placeholder{color:var(--dsw-alias-label-tertiary,#9ca3af)}
61
+ .dsg-empty{padding:6px 10px;font-size:12px;color:var(--dsw-alias-label-tertiary,#9ca3af);line-height:18px}
62
+ .dsg-ws{display:flex;align-items:center;gap:4px;padding:2px 8px 8px}
63
+ .dsg-ws-btn{flex:1;display:flex;align-items:center;justify-content:center;height:34px;box-sizing:border-box;border:1px dashed var(--dsw-alias-border-l2,rgba(127,127,127,.25));background:transparent;color:var(--dsw-alias-label-secondary,#6b7280);font-size:13px;line-height:1;border-radius:var(--dsw-radius-sm,8px);cursor:pointer}
64
+ .dsg-ws-btn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
65
+ .dsg-ws-row{display:flex;align-items:center;height:28px;padding:0 8px;font-size:12px;color:var(--dsw-alias-label-tertiary,#9ca3af)}
66
+ `;
67
+
68
+ function injectStyles() {
69
+ const id = "dsh-sidebar-sessions-style";
70
+ if (document.getElementById(id)) return () => {};
71
+ const style = document.createElement("style");
72
+ style.id = id;
73
+ style.textContent = CSS;
74
+ document.head.appendChild(style);
75
+ return () => style.remove();
76
+ }
77
+
78
+ const EMPTY = { groups: [], assign: {}, collapsed: {}, hiddenWorkspaces: [], activeWorkspace: null, order: {} };
79
+
80
+ function readStore() {
81
+ try {
82
+ const raw = window.localStorage.getItem(STORE_KEY);
83
+ if (!raw) return { ...EMPTY };
84
+ const parsed = JSON.parse(raw);
85
+ return {
86
+ groups: Array.isArray(parsed.groups) ? parsed.groups : [],
87
+ assign: parsed.assign && typeof parsed.assign === "object" ? parsed.assign : {},
88
+ collapsed: parsed.collapsed && typeof parsed.collapsed === "object" ? parsed.collapsed : {},
89
+ hiddenWorkspaces: Array.isArray(parsed.hiddenWorkspaces) ? parsed.hiddenWorkspaces : [],
90
+ activeWorkspace: typeof parsed.activeWorkspace === "string" ? parsed.activeWorkspace : null,
91
+ order: parsed.order && typeof parsed.order === "object" ? parsed.order : {},
92
+ };
93
+ } catch {
94
+ return { ...EMPTY };
95
+ }
96
+ }
97
+
98
+ function writeStore(next) {
99
+ try {
100
+ window.localStorage.setItem(STORE_KEY, JSON.stringify(next));
101
+ } catch {}
102
+ }
103
+
104
+ const store = (() => {
105
+ let state = readStore();
106
+ const listeners = new Set();
107
+ const emit = () => {
108
+ for (const fn of listeners) fn();
109
+ };
110
+ return {
111
+ get: () => state,
112
+ set(next) {
113
+ state = next;
114
+ writeStore(state);
115
+ emit();
116
+ },
117
+ subscribe(fn) {
118
+ listeners.add(fn);
119
+ return () => listeners.delete(fn);
120
+ },
121
+ };
122
+ })();
123
+
124
+ function useGroups() {
125
+ return useSyncExternalStore(store.subscribe, store.get, store.get);
126
+ }
127
+
128
+ function newGroupId() {
129
+ return "g_" + Math.random().toString(36).slice(2, 9);
130
+ }
131
+
132
+ function titleOf(row, id) {
133
+ return String(row?.displayTitle || row?.title || id);
134
+ }
135
+
136
+ function updatedAt(row) {
137
+ const n = Number(row?.updatedAt);
138
+ return Number.isFinite(n) ? n : 0;
139
+ }
140
+
141
+ function sortRecent(ids, byId) {
142
+ return [...ids].sort((a, b) => {
143
+ const d = updatedAt(byId[b]) - updatedAt(byId[a]);
144
+ if (d !== 0) return d;
145
+ return String(a).localeCompare(String(b));
146
+ });
147
+ }
148
+
149
+ /**
150
+ * Layer a section's saved manual order over its base order. Ids the saved
151
+ * order never saw (a new session, or one that just entered the section)
152
+ * come first, newest first, so fresh activity stays on top; the ids it did
153
+ * see keep the order the user dragged them into. Only display order: the
154
+ * caller still decides what belongs in the section.
155
+ */
156
+ function applyManualOrder(ids, saved) {
157
+ if (!Array.isArray(saved) || saved.length === 0) return ids;
158
+ const present = new Set(ids);
159
+ const kept = saved.filter((id) => present.has(id));
160
+ if (kept.length === 0) return ids;
161
+ const keptSet = new Set(kept);
162
+ const fresh = ids.filter((id) => !keptSet.has(id));
163
+ return fresh.concat(kept);
164
+ }
165
+
166
+ /**
167
+ * Move `src` to the dropped row: `half` is the pointer's half of that row,
168
+ * so dropping on the lower half lands the row after the target and the
169
+ * upper half lands it before. A move that changes nothing returns undefined.
170
+ */
171
+ function moveTo(ids, src, targetId, half) {
172
+ if (src === targetId) return undefined;
173
+ if (!ids.includes(src) || !ids.includes(targetId)) return undefined;
174
+ const without = ids.filter((id) => id !== src);
175
+ const at = without.indexOf(targetId);
176
+ const insertAt = half === "after" ? at + 1 : at;
177
+ const next = without.slice(0, insertAt).concat([src], without.slice(insertAt));
178
+ return next.every((id, index) => id === ids[index]) ? undefined : next;
179
+ }
180
+
181
+ /** Anchor for host `insertSessionBefore`: the id that must follow `src`. */
182
+ function anchorAfter(ids, src, targetId) {
183
+ const without = ids.filter((id) => id !== src);
184
+ return without[without.indexOf(targetId) + 1];
185
+ }
186
+
187
+ /** Which half of the row the pointer is in: "before" (top) or "after". */
188
+ function rowHalf(event) {
189
+ const el = event.currentTarget;
190
+ const rect = el && el.getBoundingClientRect ? el.getBoundingClientRect() : null;
191
+ if (!rect) return "before";
192
+ return event.clientY - rect.top > rect.height / 2 ? "after" : "before";
193
+ }
194
+
195
+ function isSubagent(row) {
196
+ return row?.origin === "subagent";
197
+ }
198
+
199
+ function pendingKind(value) {
200
+ if (value === undefined || value === null) return undefined;
201
+ if (typeof value === "string") return value;
202
+ return value.kind || "pending";
203
+ }
204
+
205
+ function dotState(status) {
206
+ if (pendingKind(status?.pendingInteraction) !== undefined) return "pending";
207
+ if (status?.running === true) return "running";
208
+ if (status?.completionUnread === true) return "unread";
209
+ return "idle";
210
+ }
211
+
212
+ function fmtTime(ms) {
213
+ if (!ms) return "";
214
+ const now = Date.now();
215
+ const diff = now - ms;
216
+ if (diff < 60_000) return "刚刚";
217
+ if (diff < 3_600_000) return Math.floor(diff / 60_000) + " 分";
218
+ if (diff < 86_400_000) return Math.floor(diff / 3_600_000) + " 时";
219
+ if (diff < 7 * 86_400_000) return Math.floor(diff / 86_400_000) + " 天";
220
+ const d = new Date(ms);
221
+ return d.getMonth() + 1 + "/" + d.getDate();
222
+ }
223
+
224
+ const Row = memo(function Row(props) {
225
+ const { id, section, row, pinned, archived, status, scheduled, dragging, over, onOpen, onMenu, onDragStart, onDragOver, onDrop } = props;
226
+ const label = titleOf(row, id);
227
+ return h(
228
+ "div",
229
+ {
230
+ className: "dsg-row",
231
+ "data-dragging": dragging ? "true" : undefined,
232
+ "data-over": over || undefined,
233
+ draggable: true,
234
+ onClick: () => onOpen(id),
235
+ title: label,
236
+ onDragStart: (e) => {
237
+ try { e.dataTransfer.setData("text/plain", id); e.dataTransfer.effectAllowed = "move"; } catch {}
238
+ onDragStart(id);
239
+ },
240
+ onDragOver: (e) => {
241
+ e.preventDefault();
242
+ try { e.dataTransfer.dropEffect = "move"; } catch {}
243
+ onDragOver(section || "recent", id, rowHalf(e));
244
+ },
245
+ onDragLeave: () => onDragOver(null, null, null),
246
+ onDrop: (e) => {
247
+ e.preventDefault();
248
+ onDrop(section || "recent", id, rowHalf(e));
249
+ },
250
+ },
251
+ scheduled && dotState(status) === "idle"
252
+ ? h("span", { className: "dsg-dot-clock", title: "已设置定时任务", "aria-label": "已设置定时任务" },
253
+ h("svg", { width: 12, height: 12, viewBox: "0 0 16 16", fill: "none" },
254
+ h("circle", { cx: 8, cy: 8, r: 6.25, stroke: "currentColor", strokeWidth: 1.5 }),
255
+ h("path", { d: "M8 4.5V8l2.5 1.5", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" })))
256
+ : h("span", { className: "dsg-dot", "data-state": dotState(status) }),
257
+ h("span", { className: "dsg-title" }, label),
258
+ pinned ? h("span", { className: "dsg-pin" }, "★") : null,
259
+ h("span", { className: "dsg-time" }, fmtTime(updatedAt(row))),
260
+ h(
261
+ "span",
262
+ { className: "dsg-actions" },
263
+ h("button", {
264
+ className: "dsg-icon",
265
+ title: "更多操作",
266
+ onClick: (e) => {
267
+ e.stopPropagation();
268
+ onMenu(id, e.currentTarget);
269
+ },
270
+ }, "⋯")
271
+ )
272
+ );
273
+ });
274
+
275
+ class RegionBoundary extends React.Component {
276
+ constructor(props) {
277
+ super(props);
278
+ this.state = { error: null };
279
+ }
280
+ static getDerivedStateFromError(error) {
281
+ return { error };
282
+ }
283
+ componentDidCatch(error) {
284
+ try {
285
+ console.error("[dsh-sidebar-sessions] region failed", error);
286
+ } catch {}
287
+ }
288
+ render() {
289
+ if (this.state.error) {
290
+ return h("div", { className: "dsg-empty" }, "会话分组暂不可用(", String(this.state.error?.message || this.state.error), ")");
291
+ }
292
+ return this.props.children;
293
+ }
294
+ }
295
+
296
+ function GuardedRegion(props) {
297
+ return h(RegionBoundary, null, h(Region, props));
298
+ }
299
+
300
+ function Region(props) {
301
+ const {
302
+ useSessions, useWorkspaces, useSessionStatus, useScheduleCatalog, open,
303
+ pinSession, unpinSession, archiveSession, unarchiveSession,
304
+ renameSession, forkSession, createWorkspace, pickDirectory, insertSessionBefore, openWorkspace,
305
+ } = props;
306
+ const list = useSessions((s) => s);
307
+ const ws = useWorkspaces((s) => s);
308
+ const useStatus = typeof useSessionStatus === "function" ? useSessionStatus : () => ({});
309
+ const statuses = useStatus((s) => s);
310
+ const useSchedules = typeof useScheduleCatalog === "function" ? useScheduleCatalog : () => [];
311
+ const schedules = useSchedules();
312
+ const scheduledOf = useCallback((id) => {
313
+ if (!Array.isArray(schedules)) return false;
314
+ return schedules.some((row) => row && row.sessionId === id && row.status === "active");
315
+ }, [schedules]);
316
+ const groups = useGroups();
317
+ const [showArchived, setShowArchived] = useState(false);
318
+ const [showHidden, setShowHidden] = useState(false);
319
+ const [menu, setMenu] = useState(null);
320
+ const [query, setQuery] = useState("");
321
+ const [dragId, setDragId] = useState(null);
322
+ const [dragOver, setDragOver] = useState(null);
323
+ const [compact, setCompact] = useState(false);
324
+ const rootRef = useRef(null);
325
+ /* Current rendered order per section key, read by the drop handler. */
326
+ const sectionIdsRef = useRef({});
327
+
328
+ useLayoutEffect(() => {
329
+ const el = rootRef.current;
330
+ if (!el) return undefined;
331
+ const measure = () => {
332
+ const w = el.getBoundingClientRect().width;
333
+ setCompact(w > 0 && w < 150);
334
+ };
335
+ measure();
336
+ const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(measure) : undefined;
337
+ if (ro) ro.observe(el);
338
+ else window.addEventListener("resize", measure);
339
+ return () => {
340
+ if (ro) ro.disconnect();
341
+ else window.removeEventListener("resize", measure);
342
+ };
343
+ }, []);
344
+ const searching = query.trim().length > 0;
345
+
346
+ const byId = list?.byId || {};
347
+ const pinnedSet = useMemo(() => new Set(ws?.pinnedSessionIds || []), [ws]);
348
+ const archivedSet = useMemo(() => new Set(ws?.archivedSessionIds || []), [ws]);
349
+ const assign = groups.assign || {};
350
+ const collapsed = groups.collapsed || {};
351
+ const orders = groups.order || {};
352
+ const hidden = store.get().hiddenWorkspaces || [];
353
+
354
+ const ids = useMemo(() => (list?.ids || []).filter((id) => byId[id] && !isSubagent(byId[id])), [list, byId]);
355
+ const archived = useMemo(() => ids.filter((id) => archivedSet.has(id)), [ids, archivedSet]);
356
+ const live = useMemo(() => ids.filter((id) => !archivedSet.has(id)), [ids, archivedSet]);
357
+ const archivedOrdered = useMemo(() => applyManualOrder(archived, orders["archived"]), [archived, orders]);
358
+ const recent = useMemo(() => applyManualOrder(sortRecent(live, byId).slice(0, RECENT_LIMIT), orders.recent), [live, byId, orders]);
359
+ const pinned = useMemo(() => applyManualOrder(sortRecent(live.filter((id) => pinnedSet.has(id)), byId), orders.pinned), [live, byId, pinnedSet, orders]);
360
+
361
+ const accountOf = useCallback((id) => {
362
+ for (const item of ws?.items || []) {
363
+ if ((item.sessionIds || []).includes(id)) return item.workspaceId;
364
+ }
365
+ return undefined;
366
+ }, [ws]);
367
+
368
+ const visibleWorkspaces = useMemo(
369
+ () => (ws?.items || []).filter((it) => !hidden.includes(String(it.workspaceId))),
370
+ [ws, hidden]
371
+ );
372
+ const hiddenWorkspaces = useMemo(
373
+ () => (ws?.items || []).filter((it) => hidden.includes(String(it.workspaceId))),
374
+ [ws, hidden]
375
+ );
376
+
377
+ const groupRows = useMemo(() => {
378
+ const byGroup = new Map();
379
+ for (const g of groups.groups) byGroup.set(g.id, []);
380
+ const rest = [];
381
+ const shownInWorkspaces = new Set();
382
+ for (const item of visibleWorkspaces) for (const id of item.sessionIds || []) shownInWorkspaces.add(id);
383
+ for (const id of live) {
384
+ if (pinnedSet.has(id)) continue;
385
+ if (shownInWorkspaces.has(id)) continue;
386
+ const gid = assign[id];
387
+ if (gid && byGroup.has(gid)) byGroup.get(gid).push(id);
388
+ else rest.push(id);
389
+ }
390
+ for (const [gid, arr] of byGroup) byGroup.set(gid, applyManualOrder(sortRecent(arr, byId), orders["g:" + gid]));
391
+ return { byGroup, rest: applyManualOrder(sortRecent(rest, byId), orders.ungrouped) };
392
+ }, [live, byId, groups.groups, assign, pinnedSet, visibleWorkspaces, orders]);
393
+
394
+ const filtered = useMemo(() => {
395
+ const needle = query.trim().toLowerCase();
396
+ if (!needle) return null;
397
+ return sortRecent(ids.filter((id) => titleOf(byId[id], id).toLowerCase().includes(needle)), byId);
398
+ }, [query, ids, byId]);
399
+
400
+ /* Default workspace = the one holding the most recent live session. */
401
+ const currentWsId = useMemo(() => {
402
+ if (groups.activeWorkspace) return groups.activeWorkspace;
403
+ for (const id of recent) {
404
+ const found = (ws?.items || []).find((it) => (it.sessionIds || []).includes(id));
405
+ if (found) return found.workspaceId;
406
+ }
407
+ return visibleWorkspaces[0]?.workspaceId;
408
+ }, [groups.activeWorkspace, recent, ws, visibleWorkspaces]);
409
+
410
+ const toggle = useCallback((key) => {
411
+ const cur = store.get();
412
+ store.set({ ...cur, collapsed: { ...cur.collapsed, [key]: !(cur.collapsed || {})[key] } });
413
+ }, []);
414
+
415
+ const assignTo = useCallback((id, gid) => {
416
+ const cur = store.get();
417
+ const nextAssign = { ...cur.assign };
418
+ if (gid) nextAssign[id] = gid;
419
+ else delete nextAssign[id];
420
+ store.set({ ...cur, assign: nextAssign });
421
+ }, []);
422
+
423
+ const createGroup = useCallback((sessionId) => {
424
+ const name = window.prompt("新分组名称");
425
+ if (!name || !name.trim()) return;
426
+ const g = { id: newGroupId(), name: name.trim().slice(0, 20) };
427
+ const cur = store.get();
428
+ const next = { ...cur, groups: [...cur.groups, g] };
429
+ if (sessionId) next.assign = { ...cur.assign, [sessionId]: g.id };
430
+ store.set(next);
431
+ }, []);
432
+
433
+ const renameGroup = useCallback((g) => {
434
+ const name = window.prompt("分组名称", g.name);
435
+ if (!name || !name.trim()) return;
436
+ const cur = store.get();
437
+ store.set({ ...cur, groups: cur.groups.map((x) => (x.id === g.id ? { ...x, name: name.trim().slice(0, 20) } : x)) });
438
+ }, []);
439
+
440
+ const deleteGroup = useCallback((g) => {
441
+ if (!window.confirm(`删除分组「${g.name}」?组内会话会回到未分组。`)) return;
442
+ const cur = store.get();
443
+ const nextAssign = { ...cur.assign };
444
+ for (const [sid, gid] of Object.entries(nextAssign)) if (gid === g.id) delete nextAssign[sid];
445
+ store.set({ ...cur, groups: cur.groups.filter((x) => x.id !== g.id), assign: nextAssign });
446
+ }, []);
447
+
448
+ const switchWorkspace = useCallback((item) => {
449
+ const cur = store.get();
450
+ store.set({ ...cur, activeWorkspace: String(item.workspaceId) });
451
+ try {
452
+ if (openWorkspace) Promise.resolve(openWorkspace(item.workspaceId)).catch((err) => console.error("[dsh-sidebar-sessions] switch workspace failed", err));
453
+ } catch (err) {
454
+ console.error("[dsh-sidebar-sessions] switch workspace failed", err);
455
+ }
456
+ }, [openWorkspace]);
457
+
458
+ const hideWorkspace = useCallback((item) => {
459
+ const cur = store.get();
460
+ const id = String(item.workspaceId);
461
+ store.set({ ...cur, hiddenWorkspaces: [...new Set([...(cur.hiddenWorkspaces || []), id])] });
462
+ }, []);
463
+
464
+ const unhideWorkspace = useCallback((item) => {
465
+ const cur = store.get();
466
+ const id = String(item.workspaceId);
467
+ store.set({ ...cur, hiddenWorkspaces: (cur.hiddenWorkspaces || []).filter((x) => x !== id) });
468
+ }, []);
469
+
470
+ const closeMenu = useCallback(() => setMenu(null), []);
471
+ const openMenu = useCallback((id, el) => {
472
+ const r = el.getBoundingClientRect();
473
+ setMenu({ id, x: Math.min(r.right - 190, Math.max(8, window.innerWidth - 210)), y: Math.min(r.bottom + 2, window.innerHeight - 280) });
474
+ }, []);
475
+
476
+ const renameRow = useCallback(async (id) => {
477
+ const name = window.prompt("重命名对话", titleOf(byId[id], id));
478
+ if (!name || !name.trim() || !renameSession) return;
479
+ try {
480
+ await renameSession(id, name.trim());
481
+ } catch (err) {
482
+ console.error("[dsh-sidebar-sessions] rename failed", err);
483
+ }
484
+ }, [byId, renameSession]);
485
+
486
+ const copy = useCallback((text) => {
487
+ try {
488
+ if (navigator.clipboard?.writeText) navigator.clipboard.writeText(text);
489
+ } catch {}
490
+ }, []);
491
+
492
+ const commitSectionOrder = useCallback((sectionKey, next) => {
493
+ if (!next || sectionKey === "search") return;
494
+ const cur = store.get();
495
+ store.set({ ...cur, order: { ...(cur.order || {}), [sectionKey]: next } });
496
+ }, []);
497
+
498
+ const clearSectionOrder = useCallback((sectionKey) => {
499
+ const cur = store.get();
500
+ const order = { ...(cur.order || {}) };
501
+ if (!(sectionKey in order)) return;
502
+ delete order[sectionKey];
503
+ store.set({ ...cur, order });
504
+ }, []);
505
+
506
+ const handleDragOver = useCallback((section, id, half) => {
507
+ if (!id) {
508
+ setDragOver(null);
509
+ return;
510
+ }
511
+ /* No marker when the dragged row is not part of that list: a drop there
512
+ * cannot move anything, so promising a landing line would lie. */
513
+ const ids = sectionIdsRef.current[section];
514
+ if (!dragId || !ids || !ids.includes(dragId)) {
515
+ setDragOver(null);
516
+ return;
517
+ }
518
+ setDragOver({ section, id, half: half || "before" });
519
+ }, [dragId]);
520
+
521
+ /** End of any drag: no row may stay in its "being dragged" state. */
522
+ const handleDragEnd = useCallback(() => {
523
+ setDragId(null);
524
+ setDragOver(null);
525
+ }, []);
526
+
527
+ const onDropRow = useCallback((sectionKey, targetId, half) => {
528
+ const src = dragId;
529
+ setDragId(null);
530
+ setDragOver(null);
531
+ if (!src || src === targetId) return;
532
+ const ids = sectionIdsRef.current[sectionKey] || [];
533
+ const next = moveTo(ids, src, targetId, half);
534
+ /* Workspace tree: the host owns the order, so write it durably and
535
+ * fall back to the local view order only when the host refuses. */
536
+ if (typeof sectionKey === "string" && sectionKey.indexOf("ws:") === 0) {
537
+ if (!next) return;
538
+ const a = accountOf(src);
539
+ const b = accountOf(targetId);
540
+ if (a === undefined || a !== b) return;
541
+ /* A local order means the view already overrides the host; keep it local. */
542
+ if (orders[sectionKey]) {
543
+ commitSectionOrder(sectionKey, next);
544
+ return;
545
+ }
546
+ /* insertSessionBefore takes the id that must FOLLOW the moved row. */
547
+ const anchor = half === "after" ? anchorAfter(ids, src, targetId) : targetId;
548
+ if (anchor === src) return;
549
+ const keepLocal = () => commitSectionOrder(sectionKey, next);
550
+ if (!insertSessionBefore) return;
551
+ try {
552
+ Promise.resolve(insertSessionBefore(a, src, anchor))
553
+ .then((result) => {
554
+ if (result && result.ok === false) {
555
+ console.error("[dsh-sidebar-sessions] reorder rejected, keeping view order", result.error);
556
+ keepLocal();
557
+ } else clearSectionOrder(sectionKey);
558
+ })
559
+ .catch((err) => {
560
+ console.error("[dsh-sidebar-sessions] reorder failed", err);
561
+ keepLocal();
562
+ });
563
+ } catch (err) {
564
+ console.error("[dsh-sidebar-sessions] reorder failed", err);
565
+ keepLocal();
566
+ }
567
+ return;
568
+ }
569
+ /* Every other list is view order: keep it locally, or the recency
570
+ * sort would put the row straight back where it was. */
571
+ commitSectionOrder(sectionKey, next);
572
+ }, [dragId, accountOf, insertSessionBefore, commitSectionOrder, clearSectionOrder, orders]);
573
+
574
+ const sections = { recent, pinned, archived: archivedOrdered, search: filtered || [], ungrouped: groupRows.rest };
575
+ for (const g of groups.groups) sections["g:" + g.id] = groupRows.byGroup.get(g.id) || [];
576
+ for (const item of visibleWorkspaces) sections["ws:" + String(item.workspaceId)] = applyManualOrder((item.sessionIds || []).filter((id) => byId[id] && !archivedSet.has(id)), orders["ws:" + String(item.workspaceId)]);
577
+ sectionIdsRef.current = sections;
578
+
579
+ const renderRow = useCallback(
580
+ (id, opts) =>
581
+ h(Row, {
582
+ key: id,
583
+ id,
584
+ section: (opts && opts.section) || "recent",
585
+ row: byId[id],
586
+ pinned: pinnedSet.has(id),
587
+ archived: archivedSet.has(id),
588
+ status: statuses?.get?.(id),
589
+ scheduled: scheduledOf(id),
590
+ dragging: dragId === id,
591
+ over: dragOver !== null && dragOver.id === id && dragOver.section === ((opts && opts.section) || "recent") && dragId !== null && dragId !== id ? dragOver.half : null,
592
+ onOpen: open,
593
+ onMenu: openMenu,
594
+ onDragStart: setDragId,
595
+ onDragOver: handleDragOver,
596
+ onDrop: onDropRow,
597
+ ...(opts || {}),
598
+ }),
599
+ [byId, pinnedSet, archivedSet, statuses, scheduledOf, dragId, dragOver, open, openMenu, onDropRow, handleDragOver]
600
+ );
601
+
602
+ const head = (label, count, onToggle, caret, extra) =>
603
+ h(
604
+ "div",
605
+ { className: "dsg-head", onClick: onToggle },
606
+ h("span", { className: "dsg-caret" }, caret),
607
+ h("span", { className: "dsg-head-label" }, label),
608
+ h("span", { className: "dsg-count" }, String(count)),
609
+ extra || null
610
+ );
611
+
612
+ const section = (key, label, count, body, extra) =>
613
+ h(
614
+ "div",
615
+ { key },
616
+ head(label, count, () => toggle(key), collapsed[key] ? "▸" : "▾", extra),
617
+ collapsed[key] ? null : body
618
+ );
619
+ const menuEl = menu
620
+ ? h(
621
+ "div",
622
+ { className: "dsg-menu", style: { left: menu.x, top: menu.y }, onMouseLeave: closeMenu },
623
+ h("div", { className: "dsg-menu-item", onClick: () => { pinnedSet.has(menu.id) ? unpinSession(menu.id) : pinSession(menu.id); closeMenu(); } },
624
+ pinnedSet.has(menu.id) ? "取消置顶" : "置顶"),
625
+ h("div", { className: "dsg-menu-item", onClick: () => { renameRow(menu.id); closeMenu(); } }, "重命名"),
626
+ h("div", { className: "dsg-menu-item", onClick: () => { if (forkSession) forkSession(menu.id); closeMenu(); } }, "分叉会话"),
627
+ h("div", { className: "dsg-menu-item", onClick: () => { copy(menu.id); closeMenu(); } }, "复制 Session ID"),
628
+ h("div", { className: "dsg-menu-item", onClick: () => { const item = (ws?.items || []).find((x) => (x.sessionIds || []).includes(menu.id)); if (item?.path) copy(item.path); closeMenu(); } }, "复制工作目录"),
629
+ h("div", { className: "dsg-menu-sep" }),
630
+ h("div", { className: "dsg-menu-label" }, "移动到分组"),
631
+ h("div", { className: "dsg-menu-item", onClick: () => { assignTo(menu.id, null); closeMenu(); } }, "未分组"),
632
+ groups.groups.map((g) =>
633
+ h("div", { key: g.id, className: "dsg-menu-item", onClick: () => { assignTo(menu.id, g.id); closeMenu(); } },
634
+ h("span", { className: "dsg-dot-sm" }, "●"), g.name)
635
+ ),
636
+ h("div", { className: "dsg-menu-item", onClick: () => { createGroup(menu.id); closeMenu(); } }, "+ 新建分组…"),
637
+ h("div", { className: "dsg-menu-sep" }),
638
+ h("div", { className: "dsg-menu-item", onClick: () => { archivedSet.has(menu.id) ? unarchiveSession(menu.id) : archiveSession(menu.id); closeMenu(); } },
639
+ archivedSet.has(menu.id) ? "取消归档" : "归档")
640
+ )
641
+ : null;
642
+
643
+ return h(
644
+ "div",
645
+ {
646
+ className: "dsg-root",
647
+ ref: rootRef,
648
+ onClick: menu ? closeMenu : undefined,
649
+ /* A drag can end without a drop on a row (released on a header, the
650
+ * gap between sections, or cancelled with Esc); dragend is the only
651
+ * event that always fires, and without it that row keeps the 45%
652
+ * "being dragged" dimming until the next drop or a reload. */
653
+ onDragEnd: handleDragEnd,
654
+ onDrop: (e) => { e.preventDefault(); handleDragEnd(); },
655
+ },
656
+ compact ? null : h(React.Fragment, null,
657
+ h("div", { className: "dsg-ws" },
658
+ h("button", { className: "dsg-ws-btn", onClick: async () => {
659
+ try {
660
+ if (pickDirectory && createWorkspace) {
661
+ const dir = await pickDirectory();
662
+ if (dir) await createWorkspace(dir);
663
+ }
664
+ } catch (err) {
665
+ console.error("[dsh-sidebar-sessions] create workspace failed", err);
666
+ }
667
+ } }, "+ 新建工作区")),
668
+ h("div", { className: "dsg-search" },
669
+ h("input", {
670
+ value: query,
671
+ placeholder: "搜索对话",
672
+ onChange: (e) => setQuery(e.target.value),
673
+ onKeyDown: (e) => { if (e.key === "Escape") setQuery(""); },
674
+ }),
675
+ query ? h("button", { className: "dsg-icon", title: "清除", onClick: () => setQuery("") }, "✕") : null),
676
+ searching
677
+ ? h("div", null,
678
+ head("搜索结果", (filtered || []).length, () => {}, "▾"),
679
+ (filtered || []).length
680
+ ? h("div", null, filtered.map((id) => renderRow(id, { section: "search" })))
681
+ : h("div", { className: "dsg-empty" }, "没有匹配的对话"))
682
+ : h(React.Fragment, null,
683
+ pinned.length ? section("pinned", "置顶", pinned.length, h("div", null, pinned.map((id) => renderRow(id, { section: "pinned" })))) : null,
684
+ section("recent", "最近", recent.length, h("div", null, recent.map((id) => renderRow(id, { section: "recent" }))),
685
+ Array.isArray(orders.recent) && orders.recent.length
686
+ ? h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11, flex: "none" }, title: "恢复最近排序", onClick: (e) => { e.stopPropagation(); clearSectionOrder("recent"); } }, "↺")
687
+ : null),
688
+ groups.groups.map((g) => {
689
+ const rows = groupRows.byGroup.get(g.id) || [];
690
+ return h("div", { key: g.id },
691
+ h("div", { className: "dsg-head", onClick: () => toggle("g:" + g.id) },
692
+ h("span", { className: "dsg-caret" }, collapsed["g:" + g.id] ? "▸" : "▾"),
693
+ h("span", { className: "dsg-head-label" }, g.name),
694
+ h("span", { className: "dsg-count" }, String(rows.length)),
695
+ h("span", { style: { display: "flex", gap: 2, flex: "none" }, onClick: (e) => e.stopPropagation() },
696
+ h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11 }, title: "重命名", onClick: () => renameGroup(g) }, "✎"),
697
+ h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11 }, title: "删除分组", onClick: () => deleteGroup(g) }, "✕"))),
698
+ collapsed["g:" + g.id] ? null : h("div", null, rows.map((id) => renderRow(id, { section: "g:" + g.id }))));
699
+ }),
700
+ section("ungrouped", "未分组", groupRows.rest.length, h("div", null, groupRows.rest.map((id) => renderRow(id, { section: "ungrouped" })))),
701
+ archivedOrdered.length
702
+ ? h("div", { key: "archived" },
703
+ head("已归档", archivedOrdered.length, () => setShowArchived((v) => !v), showArchived ? "▾" : "▸"),
704
+ showArchived ? h("div", null, archivedOrdered.map((id) => renderRow(id, { archived: true, section: "archived" }))) : null)
705
+ : null,
706
+ /* Workspace block: same shape as a group, marked as a workspace. */
707
+ h("div", { key: "wsroot" },
708
+ h("div", { className: "dsg-head", onClick: () => toggle("ws:root") },
709
+ h("span", { className: "dsg-caret" }, collapsed["ws:root"] ? "▸" : "▾"),
710
+ h("span", { className: "dsg-head-label" }, "📁 工作区"),
711
+ h("span", { className: "dsg-count" }, String(visibleWorkspaces.length))),
712
+ collapsed["ws:root"] ? null : h("div", null,
713
+ visibleWorkspaces.length === 0
714
+ ? h("div", { className: "dsg-empty" }, "还没有工作区,点上方「+ 新建工作区」")
715
+ : visibleWorkspaces.map((item) => {
716
+ const key = "ws:" + String(item.workspaceId);
717
+ const members = applyManualOrder((item.sessionIds || []).filter((id) => byId[id] && !archivedSet.has(id)), orders[key]);
718
+ const isCurrent = String(currentWsId) === String(item.workspaceId);
719
+ const label = item.title || item.path || String(item.workspaceId);
720
+ return h("div", { key },
721
+ h("div", { className: "dsg-head", onClick: () => { switchWorkspace(item); if (collapsed[key]) toggle(key); } },
722
+ h("span", { className: "dsg-caret", onClick: (e) => { e.stopPropagation(); toggle(key); } }, collapsed[key] ? "▸" : "▾"),
723
+ h("span", { className: "dsg-head-label" }, (isCurrent ? "📌 " : "📁 ") + label),
724
+ h("span", { className: "dsg-count" }, String(members.length)),
725
+ h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11 }, title: "隐藏工作区", onClick: (e) => { e.stopPropagation(); hideWorkspace(item); } }, "✕")),
726
+ collapsed[key] ? null : h("div", null, members.map((id) => renderRow(id, { section: key }))));
727
+ }))),
728
+ hiddenWorkspaces.length
729
+ ? h("div", { key: "hiddenws" },
730
+ head("已隐藏的工作区", hiddenWorkspaces.length, () => setShowHidden((v) => !v), showHidden ? "▾" : "▸"),
731
+ showHidden
732
+ ? h("div", null, hiddenWorkspaces.map((item) =>
733
+ h("div", { key: String(item.workspaceId), className: "dsg-ws-row" },
734
+ h("span", { style: { flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, item.title || item.path || String(item.workspaceId)),
735
+ h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11 }, title: "恢复显示", onClick: () => unhideWorkspace(item) }, "↩"))))
736
+ : null)
737
+ : null),
738
+ ),
739
+ menuEl
740
+ );
741
+ }
742
+
743
+ function apply(ctx) {
744
+ ctx.effect(() => injectStyles(), "dsh-sidebar-sessions: styles");
745
+
746
+ /* Schedule catalog: active (not yet fired) reminders, refreshed on change. */
747
+ const scheduleStore = (() => {
748
+ let state = [];
749
+ const listeners = new Set();
750
+ return {
751
+ get: () => state,
752
+ set(next) {
753
+ state = next;
754
+ for (const fn of listeners) fn();
755
+ },
756
+ subscribe(fn) {
757
+ listeners.add(fn);
758
+ return () => listeners.delete(fn);
759
+ },
760
+ };
761
+ })();
762
+
763
+ const reloadSchedules = () => {
764
+ try {
765
+ const remote = ctx.remote && ctx.remote.schedule;
766
+ if (!remote || typeof remote.catalog !== "function") return;
767
+ Promise.resolve(remote.catalog())
768
+ .then((result) => {
769
+ const rows = Array.isArray(result) ? result : (result && Array.isArray(result.value) ? result.value : []);
770
+ scheduleStore.set(rows);
771
+ })
772
+ .catch((err) => console.error("[dsh-sidebar-sessions] schedule catalog failed", err));
773
+ } catch {}
774
+ };
775
+
776
+ ctx.effect(() => {
777
+ reloadSchedules();
778
+ const off = typeof ctx.on === "function" ? ctx.on("schedule/changed", reloadSchedules) : undefined;
779
+ return () => {
780
+ if (typeof off === "function") off();
781
+ };
782
+ }, "dsh-sidebar-sessions: schedules");
783
+ ctx.slots.inject("sidebar.workspaces", () =>
784
+ ctx.slots.register(
785
+ {
786
+ name: "sidebar.workspaces",
787
+ id: "dsh-sidebar-sessions",
788
+ priority: -2,
789
+ registrant: "dsh-sidebar-sessions",
790
+ inject: () => ({
791
+ open: (sessionId) => ctx.uiWorkspace.openSession(sessionId),
792
+ pinSession: (sessionId) => ctx.uiWorkspace.pinSession(sessionId),
793
+ unpinSession: (sessionId) => ctx.uiWorkspace.unpinSession(sessionId),
794
+ archiveSession: (sessionId) => ctx.uiWorkspace.archiveSession(sessionId),
795
+ unarchiveSession: (sessionId) => ctx.uiWorkspace.unarchiveSession(sessionId),
796
+ forkSession: (sessionId) => ctx.uiWorkspace.forkSession(sessionId),
797
+ pickDirectory: () => ctx.uiWorkspace.pickDirectory(),
798
+ openWorkspace: (workspaceId) => ctx.uiWorkspace.openWorkspace(workspaceId),
799
+ createWorkspace: (input) => ctx.workspaces.create(input),
800
+ insertSessionBefore: (accountId, sessionId, anchor) => ctx.workspaces.insertSessionBefore(accountId, sessionId, anchor),
801
+ useScheduleCatalog: () => useSyncExternalStore(scheduleStore.subscribe, scheduleStore.get, scheduleStore.get),
802
+ renameSession: (sessionId, title) =>
803
+ ctx.sessions.using(sessionId, { source: "workspaceOperation" }, (ref) =>
804
+ ref.binding.session.rename(title)
805
+ ).then((result) => {
806
+ if (result?.ok === false) throw new Error(result.error?.message || "rename failed");
807
+ }),
808
+ }),
809
+ },
810
+ GuardedRegion
811
+ )
812
+ );
813
+ }
814
+
815
+ return { inject, apply };
816
+ },
817
+ });
package/lib/index.js ADDED
@@ -0,0 +1,3 @@
1
+ // Host half is intentionally empty: this plugin renders in the web client only.
2
+ export const name = 'dsh-session-groups'
3
+ export function apply() {}
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "dsh-sidebar-sessions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.3",
4
+ "description": "Recent-first session sidebar for DeepSeek Harness: user groups, workspace tree, archive bucket, status dots, drag reorder and scheduled-task marks.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./client": "./lib/client.js"
10
+ },
11
+ "files": [
12
+ "lib",
13
+ "cordis.patch.yml",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "license": "MIT",
18
+ "author": "sss-1012",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/sss-1012/dsh-sidebar-sessions.git"
22
+ },
23
+ "homepage": "https://github.com/sss-1012/dsh-sidebar-sessions#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/sss-1012/dsh-sidebar-sessions/issues"
26
+ },
27
+ "keywords": [
28
+ "dsh",
29
+ "dsh-plugin",
30
+ "deepseek-harness",
31
+ "sidebar",
32
+ "sessions",
33
+ "workspace",
34
+ "archive"
35
+ ],
36
+ "engines": {
37
+ "dsh": ">=0.2.1-rc.3 <0.3.0"
38
+ },
39
+ "dsh": {
40
+ "manifestVersion": 1,
41
+ "bundle": {
42
+ "patch": "./cordis.patch.yml"
43
+ },
44
+ "client": {
45
+ "platform": "web",
46
+ "immediately": true,
47
+ "inject": [
48
+ "@deepseek-ai/dsh-api-session-controller",
49
+ "@deepseek-ai/dsh-api-workspace-controller",
50
+ "@deepseek-ai/dsh-client-connection",
51
+ "@deepseek-ai/dsh-client-ui-session",
52
+ "@deepseek-ai/dsh-client-ui-workspace"
53
+ ]
54
+ }
55
+ }
56
+ }