dsh-sidebar-sessions 0.1.3 → 0.1.6

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.
Files changed (3) hide show
  1. package/README.md +12 -5
  2. package/lib/client.js +1066 -817
  3. package/package.json +1 -1
package/lib/client.js CHANGED
@@ -1,817 +1,1066 @@
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
- });
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, useEffect, 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;flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain}
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-more{display:flex;align-items:center;justify-content:center;height:30px;margin:2px 2px 4px;border-radius:var(--dsw-radius-s,8px);color:var(--dsw-alias-label-tertiary,#9ca3af);font-size:12px;line-height:1;cursor:pointer;user-select:none}
63
+ .dsg-more:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary,#6b7280)}
64
+ .dsg-more:focus-visible{outline:2px solid var(--dsw-alias-focus-ring,#4d6bfe);outline-offset:-2px}
65
+ .dsg-more-end{cursor:default;font-size:11px}
66
+ .dsg-more-end:hover{background:transparent;color:var(--dsw-alias-label-tertiary,#9ca3af)}
67
+ .dsg-ws{display:flex;align-items:center;gap:4px;padding:2px 8px 8px}
68
+ .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}
69
+ .dsg-ws-btn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
70
+ .dsg-ws-row{display:flex;align-items:center;height:28px;padding:0 8px;font-size:12px;color:var(--dsw-alias-label-tertiary,#9ca3af)}
71
+ `;
72
+
73
+ function injectStyles() {
74
+ const id = "dsh-sidebar-sessions-style";
75
+ if (document.getElementById(id)) return () => {};
76
+ const style = document.createElement("style");
77
+ style.id = id;
78
+ style.textContent = CSS;
79
+ document.head.appendChild(style);
80
+ return () => style.remove();
81
+ }
82
+
83
+ const EMPTY = { groups: [], assign: {}, collapsed: {}, hiddenWorkspaces: [], activeWorkspace: null, order: {}, autoRules: [], autoDone: {} };
84
+
85
+ function readStore() {
86
+ try {
87
+ const raw = window.localStorage.getItem(STORE_KEY);
88
+ if (!raw) return { ...EMPTY };
89
+ const parsed = JSON.parse(raw);
90
+ return {
91
+ groups: Array.isArray(parsed.groups) ? parsed.groups : [],
92
+ assign: parsed.assign && typeof parsed.assign === "object" ? parsed.assign : {},
93
+ collapsed: parsed.collapsed && typeof parsed.collapsed === "object" ? parsed.collapsed : {},
94
+ hiddenWorkspaces: Array.isArray(parsed.hiddenWorkspaces) ? parsed.hiddenWorkspaces : [],
95
+ activeWorkspace: typeof parsed.activeWorkspace === "string" ? parsed.activeWorkspace : null,
96
+ order: parsed.order && typeof parsed.order === "object" ? parsed.order : {},
97
+ autoRules: Array.isArray(parsed.autoRules) ? parsed.autoRules : [],
98
+ autoDone: parsed.autoDone && typeof parsed.autoDone === "object" ? parsed.autoDone : {},
99
+ };
100
+ } catch {
101
+ return { ...EMPTY };
102
+ }
103
+ }
104
+
105
+ function writeStore(next) {
106
+ try {
107
+ window.localStorage.setItem(STORE_KEY, JSON.stringify(next));
108
+ } catch {}
109
+ }
110
+
111
+ const store = (() => {
112
+ let state = readStore();
113
+ const listeners = new Set();
114
+ const emit = () => {
115
+ for (const fn of listeners) fn();
116
+ };
117
+ return {
118
+ get: () => state,
119
+ set(next) {
120
+ state = next;
121
+ writeStore(state);
122
+ emit();
123
+ },
124
+ subscribe(fn) {
125
+ listeners.add(fn);
126
+ return () => listeners.delete(fn);
127
+ },
128
+ };
129
+ })();
130
+
131
+ function useGroups() {
132
+ return useSyncExternalStore(store.subscribe, store.get, store.get);
133
+ }
134
+
135
+ /* 自动分组:定时任务现在每次投递到新会话,新会话标题由投递词生成。
136
+ * 命中规则的新会话自动放进指定分组(分组不存在则创建)。
137
+ * 处理过一次就记进 autoDone,之后你手动挪走也不会被拉回来。
138
+ * 想改规则:localStorage 里 dsh-session-groups.v1 的 autoRules 字段
139
+ * ([{ groupName, any: [关键词...], none: [排除词...] }]),留空用默认值。 */
140
+ const DEFAULT_AUTO_RULES = [
141
+ { id: "r_brief", groupName: "每日简报", any: ["新闻简报", "每日简报"], schedules: ["新闻简报", "每日简报"] },
142
+ { id: "r_radar", groupName: "个人开发工具", any: ["项目数据雷达", "数据雷达", "npm 与 GitHub 项目数据"], schedules: ["项目数据雷达", "数据雷达"] },
143
+ ];
144
+
145
+ function matchAutoRule(rule, text) {
146
+ if (!rule || !text) return false;
147
+ const hay = String(text).toLowerCase();
148
+ const any = Array.isArray(rule.any) ? rule.any : [];
149
+ const none = Array.isArray(rule.none) ? rule.none : [];
150
+ if (none.some((k) => hay.includes(String(k).toLowerCase()))) return false;
151
+ return any.length === 0 || any.some((k) => hay.includes(String(k).toLowerCase()));
152
+ }
153
+
154
+ function newGroupId() {
155
+ return "g_" + Math.random().toString(36).slice(2, 9);
156
+ }
157
+
158
+ function titleOf(row, id) {
159
+ return String(row?.displayTitle || row?.title || id);
160
+ }
161
+
162
+ function updatedAt(row) {
163
+ const n = Number(row?.updatedAt);
164
+ return Number.isFinite(n) ? n : 0;
165
+ }
166
+
167
+ function sortRecent(ids, byId) {
168
+ return [...ids].sort((a, b) => {
169
+ const d = updatedAt(byId[b]) - updatedAt(byId[a]);
170
+ if (d !== 0) return d;
171
+ return String(a).localeCompare(String(b));
172
+ });
173
+ }
174
+
175
+ /**
176
+ * Layer a section's saved manual order over its base order. Ids the saved
177
+ * order never saw (a new session, or one that just entered the section)
178
+ * come first, newest first, so fresh activity stays on top; the ids it did
179
+ * see keep the order the user dragged them into. Only display order: the
180
+ * caller still decides what belongs in the section.
181
+ */
182
+ function applyManualOrder(ids, saved) {
183
+ if (!Array.isArray(saved) || saved.length === 0) return ids;
184
+ const present = new Set(ids);
185
+ const kept = saved.filter((id) => present.has(id));
186
+ if (kept.length === 0) return ids;
187
+ const keptSet = new Set(kept);
188
+ const fresh = ids.filter((id) => !keptSet.has(id));
189
+ return fresh.concat(kept);
190
+ }
191
+
192
+ /**
193
+ * Move `src` to the dropped row: `half` is the pointer's half of that row,
194
+ * so dropping on the lower half lands the row after the target and the
195
+ * upper half lands it before. A move that changes nothing returns undefined.
196
+ */
197
+ function moveTo(ids, src, targetId, half) {
198
+ if (src === targetId) return undefined;
199
+ if (!ids.includes(src) || !ids.includes(targetId)) return undefined;
200
+ const without = ids.filter((id) => id !== src);
201
+ const at = without.indexOf(targetId);
202
+ const insertAt = half === "after" ? at + 1 : at;
203
+ const next = without.slice(0, insertAt).concat([src], without.slice(insertAt));
204
+ return next.every((id, index) => id === ids[index]) ? undefined : next;
205
+ }
206
+
207
+ /** Anchor for host `insertSessionBefore`: the id that must follow `src`. */
208
+ function anchorAfter(ids, src, targetId) {
209
+ const without = ids.filter((id) => id !== src);
210
+ return without[without.indexOf(targetId) + 1];
211
+ }
212
+
213
+ /** Which half of the row the pointer is in: "before" (top) or "after". */
214
+ function rowHalf(event) {
215
+ const el = event.currentTarget;
216
+ const rect = el && el.getBoundingClientRect ? el.getBoundingClientRect() : null;
217
+ if (!rect) return "before";
218
+ return event.clientY - rect.top > rect.height / 2 ? "after" : "before";
219
+ }
220
+
221
+ /**
222
+ * Viewport-relative bottom of the list's scrolling ancestor (or the window
223
+ * when the page itself scrolls): paging measures against the box the user
224
+ * actually sees, so a short sidebar loads one screen at a time.
225
+ */
226
+ function scrollBottom(el) {
227
+ if (!el || typeof getComputedStyle !== "function") return (window.innerHeight || 0);
228
+ for (let node = el.parentElement; node; node = node.parentElement) {
229
+ const style = getComputedStyle(node);
230
+ if (!/(auto|scroll|overlay)/.test(style.overflowY || "")) continue;
231
+ if (node.scrollHeight > node.clientHeight) return node.getBoundingClientRect().bottom;
232
+ }
233
+ return (window.innerHeight || 0);
234
+ }
235
+
236
+ /** Whether one schedule catalog row targets or involves this session. */
237
+ function taskInvolvesSession(row, id) {
238
+ if (!row) return false;
239
+ if (row.sessionId === id) return true;
240
+ if (Array.isArray(row.involvedSessionIds) && row.involvedSessionIds.indexOf(id) !== -1) return true;
241
+ const target = row.target;
242
+ if (!target) return false;
243
+ if (target.kind === "new") return row.lastDelivery?.targetSessionId === id;
244
+ return target.sessionId === id;
245
+ }
246
+
247
+ function isSubagent(row) {
248
+ return row?.origin === "subagent";
249
+ }
250
+
251
+ function pendingKind(value) {
252
+ if (value === undefined || value === null) return undefined;
253
+ if (typeof value === "string") return value;
254
+ return value.kind || "pending";
255
+ }
256
+
257
+ function dotState(status) {
258
+ if (pendingKind(status?.pendingInteraction) !== undefined) return "pending";
259
+ if (status?.running === true) return "running";
260
+ if (status?.completionUnread === true) return "unread";
261
+ return "idle";
262
+ }
263
+
264
+ function fmtTime(ms) {
265
+ if (!ms) return "";
266
+ const now = Date.now();
267
+ const diff = now - ms;
268
+ if (diff < 60_000) return "刚刚";
269
+ if (diff < 3_600_000) return Math.floor(diff / 60_000) + " 分";
270
+ if (diff < 86_400_000) return Math.floor(diff / 3_600_000) + " 时";
271
+ if (diff < 7 * 86_400_000) return Math.floor(diff / 86_400_000) + " 天";
272
+ const d = new Date(ms);
273
+ return d.getMonth() + 1 + "/" + d.getDate();
274
+ }
275
+
276
+ const Row = memo(function Row(props) {
277
+ const { id, section, row, pinned, archived, status, scheduled, dragging, over, onOpen, onMenu, onDragStart, onDragOver, onDrop } = props;
278
+ const label = titleOf(row, id);
279
+ return h(
280
+ "div",
281
+ {
282
+ className: "dsg-row",
283
+ "data-section": section || "recent",
284
+ "data-dragging": dragging ? "true" : undefined,
285
+ "data-over": over || undefined,
286
+ draggable: true,
287
+ onClick: () => onOpen(id),
288
+ title: label,
289
+ onDragStart: (e) => {
290
+ try { e.dataTransfer.setData("text/plain", id); e.dataTransfer.effectAllowed = "move"; } catch {}
291
+ onDragStart(id);
292
+ },
293
+ onDragOver: (e) => {
294
+ e.preventDefault();
295
+ try { e.dataTransfer.dropEffect = "move"; } catch {}
296
+ onDragOver(section || "recent", id, rowHalf(e));
297
+ },
298
+ onDragLeave: () => onDragOver(null, null, null),
299
+ onDrop: (e) => {
300
+ e.preventDefault();
301
+ onDrop(section || "recent", id, rowHalf(e));
302
+ },
303
+ },
304
+ scheduled && dotState(status) === "idle"
305
+ ? h("span", { className: "dsg-dot-clock", title: "已设置定时任务", "aria-label": "已设置定时任务" },
306
+ h("svg", { width: 12, height: 12, viewBox: "0 0 16 16", fill: "none" },
307
+ h("circle", { cx: 8, cy: 8, r: 6.25, stroke: "currentColor", strokeWidth: 1.5 }),
308
+ h("path", { d: "M8 4.5V8l2.5 1.5", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" })))
309
+ : h("span", { className: "dsg-dot", "data-state": dotState(status) }),
310
+ h("span", { className: "dsg-title" }, label),
311
+ pinned ? h("span", { className: "dsg-pin" }, "★") : null,
312
+ h("span", { className: "dsg-time" }, fmtTime(updatedAt(row))),
313
+ h(
314
+ "span",
315
+ { className: "dsg-actions" },
316
+ h("button", {
317
+ className: "dsg-icon",
318
+ title: "更多操作",
319
+ onClick: (e) => {
320
+ e.stopPropagation();
321
+ onMenu(id, e.currentTarget);
322
+ },
323
+ }, "⋯")
324
+ )
325
+ );
326
+ });
327
+
328
+ class RegionBoundary extends React.Component {
329
+ constructor(props) {
330
+ super(props);
331
+ this.state = { error: null };
332
+ }
333
+ static getDerivedStateFromError(error) {
334
+ return { error };
335
+ }
336
+ componentDidCatch(error) {
337
+ try {
338
+ console.error("[dsh-sidebar-sessions] region failed", error);
339
+ } catch {}
340
+ }
341
+ render() {
342
+ if (this.state.error) {
343
+ return h("div", { className: "dsg-empty" }, "会话分组暂不可用(", String(this.state.error?.message || this.state.error), ")");
344
+ }
345
+ return this.props.children;
346
+ }
347
+ }
348
+
349
+ function GuardedRegion(props) {
350
+ return h(RegionBoundary, null, h(Region, props));
351
+ }
352
+
353
+ function Region(props) {
354
+ const {
355
+ useSessions, useWorkspaces, useSessionStatus, useScheduleCatalog, open,
356
+ pinSession, unpinSession, archiveSession, unarchiveSession,
357
+ renameSession, forkSession, createWorkspace, pickDirectory, insertSessionBefore, openWorkspace,
358
+ } = props;
359
+ const list = useSessions((s) => s);
360
+ const ws = useWorkspaces((s) => s);
361
+ const useStatus = typeof useSessionStatus === "function" ? useSessionStatus : () => ({});
362
+ const statuses = useStatus((s) => s);
363
+ const useSchedules = typeof useScheduleCatalog === "function" ? useScheduleCatalog : () => [];
364
+ const schedules = useSchedules();
365
+ /* A scheduler row belongs to a session when it targets it (the target
366
+ * session, or the reserved `new_once` id / last delivered id for a `new`
367
+ * target) or lists it among the involved sessions. Older Host builds put
368
+ * a bare `sessionId` on the row, so that shape is honoured too. */
369
+ const scheduledOf = useCallback((id) => {
370
+ if (!Array.isArray(schedules)) return false;
371
+ return schedules.some((row) => row && row.status === "active" && taskInvolvesSession(row, id));
372
+ }, [schedules]);
373
+ const groups = useGroups();
374
+ const [showArchived, setShowArchived] = useState(false);
375
+ const [showHidden, setShowHidden] = useState(false);
376
+ const [menu, setMenu] = useState(null);
377
+ const [query, setQuery] = useState("");
378
+ const [dragId, setDragId] = useState(null);
379
+ const [dragOver, setDragOver] = useState(null);
380
+ const [compact, setCompact] = useState(false);
381
+ const rootRef = useRef(null);
382
+ /* Current rendered order per section key, read by the drop handler. */
383
+ const sectionIdsRef = useRef({});
384
+
385
+ /* Paging: the 最近 list and the search results grow one screen at a time. */
386
+ const [recentLimit, setRecentLimit] = useState(RECENT_LIMIT);
387
+ const [searchLimit, setSearchLimit] = useState(RECENT_LIMIT);
388
+ const [loadingMore, setLoadingMore] = useState(null);
389
+ const moreRef = useRef(null);
390
+ const searchMoreRef = useRef(null);
391
+ const loadGuard = useRef(false);
392
+ const loadTimer = useRef(null);
393
+ /* One automatic batch per scroll burst: appending rows makes the browser
394
+ * anchor the scroll position, which would otherwise keep the footer in
395
+ * range and quietly load the whole history in one gesture. */
396
+ const autoPagerAt = useRef(0);
397
+ const liveSortedRef = useRef([]);
398
+ const recentLimitRef = useRef(RECENT_LIMIT);
399
+
400
+ useLayoutEffect(() => {
401
+ const el = rootRef.current;
402
+ if (!el) return undefined;
403
+ const measure = () => {
404
+ const w = el.getBoundingClientRect().width;
405
+ setCompact(w > 0 && w < 150);
406
+ };
407
+ measure();
408
+ const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(measure) : undefined;
409
+ if (ro) ro.observe(el);
410
+ else window.addEventListener("resize", measure);
411
+ return () => {
412
+ if (ro) ro.disconnect();
413
+ else window.removeEventListener("resize", measure);
414
+ };
415
+ }, []);
416
+ const searching = query.trim().length > 0;
417
+
418
+ const byId = list?.byId || {};
419
+ const pinnedSet = useMemo(() => new Set(ws?.pinnedSessionIds || []), [ws]);
420
+ const archivedSet = useMemo(() => new Set(ws?.archivedSessionIds || []), [ws]);
421
+ const assign = groups.assign || {};
422
+ const collapsed = groups.collapsed || {};
423
+ const orders = groups.order || {};
424
+ const hidden = store.get().hiddenWorkspaces || [];
425
+
426
+ const ids = useMemo(() => (list?.ids || []).filter((id) => byId[id] && !isSubagent(byId[id])), [list, byId]);
427
+ const archived = useMemo(() => ids.filter((id) => archivedSet.has(id)), [ids, archivedSet]);
428
+ const live = useMemo(() => ids.filter((id) => !archivedSet.has(id)), [ids, archivedSet]);
429
+
430
+ /* 自动分组落地:只处理既没手动分过、也没被自动处理过的会话。 */
431
+ useEffect(() => {
432
+ if (!live.length) return;
433
+ const cur = store.get();
434
+ const rules = Array.isArray(cur.autoRules) && cur.autoRules.length > 0 ? cur.autoRules : DEFAULT_AUTO_RULES;
435
+ const done = cur.autoDone || {};
436
+ const groupsNext = [...(cur.groups || [])];
437
+ const assignNext = { ...(cur.assign || {}) };
438
+ const doneNext = { ...done };
439
+ /* 判定优先级:先看「这个会话是不是某个定时任务刚创建的」——宿主会把新会话记在
440
+ * schedule.lastDelivery.targetSessionId;这比标题可靠得多。其次才看会话标题。 */
441
+ const bySchedule = new Map();
442
+ const FRESH_MS = 12 * 60 * 60 * 1000;
443
+ const now = Date.now();
444
+ for (const row of Array.isArray(schedules) ? schedules : []) {
445
+ const sid = row && row.lastDelivery && row.lastDelivery.targetSessionId;
446
+ if (!sid) continue;
447
+ /* 只认最近的投递:旧配置曾把任务投到已有会话,那些会话不该被动搬家。 */
448
+ const at = Date.parse((row.lastDelivery && row.lastDelivery.deliveredAt) || "");
449
+ if (!Number.isFinite(at) || now - at > FRESH_MS) continue;
450
+ bySchedule.set(sid, [row.title, row.prompt].filter(Boolean).join(" \n "));
451
+ }
452
+ let changed = false;
453
+ for (const id of live) {
454
+ if (assignNext[id] || doneNext[id]) continue;
455
+ const row = byId[id];
456
+ /* 标题匹配只认标题:预览/摘要里提到「简报」的老会话不该被拖进新分组。 */
457
+ const sessionText = titleOf(row, id);
458
+ const schText = bySchedule.get(id) || "";
459
+ let rule = rules.find((r) => schText && matchAutoRule(r, schText));
460
+ if (!rule) rule = rules.find((r) => matchAutoRule(r, sessionText));
461
+ if (!rule) continue;
462
+ const name = String(rule.groupName || "").trim();
463
+ if (!name) continue;
464
+ let g = groupsNext.find((x) => x.name === name);
465
+ if (!g) {
466
+ g = { id: newGroupId(), name: name.slice(0, 20) };
467
+ groupsNext.push(g);
468
+ }
469
+ assignNext[id] = g.id;
470
+ doneNext[id] = 1;
471
+ changed = true;
472
+ }
473
+ if (changed) store.set({ ...cur, groups: groupsNext, assign: assignNext, autoDone: doneNext });
474
+ }, [live, byId, schedules]);
475
+ const archivedOrdered = useMemo(() => applyManualOrder(archived, orders["archived"]), [archived, orders]);
476
+ const liveSorted = useMemo(() => sortRecent(live, byId), [live, byId]);
477
+ const recentBase = useMemo(() => liveSorted.slice(0, recentLimit), [liveSorted, recentLimit]);
478
+ const recent = useMemo(() => applyManualOrder(recentBase, orders.recent), [recentBase, orders]);
479
+ const remainingRecent = Math.max(0, live.length - recent.length);
480
+ liveSortedRef.current = liveSorted;
481
+ recentLimitRef.current = recentLimit;
482
+ const pinned = useMemo(() => applyManualOrder(sortRecent(live.filter((id) => pinnedSet.has(id)), byId), orders.pinned), [live, byId, pinnedSet, orders]);
483
+
484
+ const accountOf = useCallback((id) => {
485
+ for (const item of ws?.items || []) {
486
+ if ((item.sessionIds || []).includes(id)) return item.workspaceId;
487
+ }
488
+ return undefined;
489
+ }, [ws]);
490
+
491
+ const visibleWorkspaces = useMemo(
492
+ () => (ws?.items || []).filter((it) => !hidden.includes(String(it.workspaceId))),
493
+ [ws, hidden]
494
+ );
495
+ const hiddenWorkspaces = useMemo(
496
+ () => (ws?.items || []).filter((it) => hidden.includes(String(it.workspaceId))),
497
+ [ws, hidden]
498
+ );
499
+
500
+ const groupRows = useMemo(() => {
501
+ const byGroup = new Map();
502
+ for (const g of groups.groups) byGroup.set(g.id, []);
503
+ const rest = [];
504
+ const shownInWorkspaces = new Set();
505
+ for (const item of visibleWorkspaces) for (const id of item.sessionIds || []) shownInWorkspaces.add(id);
506
+ for (const id of live) {
507
+ if (pinnedSet.has(id)) continue;
508
+ /* 分组优先:明确分组的会话只出现在它所属分组里,不在工作区树重复一份。 */
509
+ const gid = assign[id];
510
+ const grouped = gid && byGroup.has(gid);
511
+ if (!grouped && shownInWorkspaces.has(id)) continue;
512
+ if (grouped) byGroup.get(gid).push(id);
513
+ else rest.push(id);
514
+ }
515
+ for (const [gid, arr] of byGroup) byGroup.set(gid, applyManualOrder(sortRecent(arr, byId), orders["g:" + gid]));
516
+ return { byGroup, rest: applyManualOrder(sortRecent(rest, byId), orders.ungrouped) };
517
+ }, [live, byId, groups.groups, assign, pinnedSet, visibleWorkspaces, orders]);
518
+
519
+ const filteredAll = useMemo(() => {
520
+ const needle = query.trim().toLowerCase();
521
+ if (!needle) return null;
522
+ return sortRecent(ids.filter((id) => titleOf(byId[id], id).toLowerCase().includes(needle)), byId);
523
+ }, [query, ids, byId]);
524
+ const filtered = useMemo(() => (filteredAll ? filteredAll.slice(0, searchLimit) : null), [filteredAll, searchLimit]);
525
+ const remainingSearch = filteredAll ? Math.max(0, filteredAll.length - (filtered ? filtered.length : 0)) : 0;
526
+
527
+ /* Grow one batch; a drag suppresses it so a list never reflows under the
528
+ * pointer. The 140ms window is the "加载中…" state, not a wait. */
529
+ const growRecent = useCallback(() => {
530
+ if (loadGuard.current || dragId) return;
531
+ loadGuard.current = true;
532
+ setLoadingMore("recent");
533
+ loadTimer.current = setTimeout(() => {
534
+ loadGuard.current = false;
535
+ setLoadingMore(null);
536
+ const limit = recentLimitRef.current;
537
+ const next = limit + RECENT_LIMIT;
538
+ /* A manual order must absorb the newly revealed rows, or the ones it
539
+ * never saw would jump above it (fresh rows render first). */
540
+ const cur = store.get();
541
+ const saved = cur.order && cur.order.recent;
542
+ if (Array.isArray(saved) && saved.length > 0) {
543
+ const seen = new Set(saved);
544
+ const revealed = liveSortedRef.current.slice(limit, next).filter((id) => !seen.has(id));
545
+ if (revealed.length > 0) store.set({ ...cur, order: { ...cur.order, recent: saved.concat(revealed) } });
546
+ }
547
+ setRecentLimit(next);
548
+ }, 140);
549
+ }, [dragId]);
550
+
551
+ const growSearch = useCallback(() => {
552
+ if (loadGuard.current || dragId) return;
553
+ loadGuard.current = true;
554
+ setLoadingMore("search");
555
+ loadTimer.current = setTimeout(() => {
556
+ loadGuard.current = false;
557
+ setLoadingMore(null);
558
+ setSearchLimit((n) => n + RECENT_LIMIT);
559
+ }, 140);
560
+ }, [dragId]);
561
+
562
+ useEffect(() => () => { if (loadTimer.current) clearTimeout(loadTimer.current); }, []);
563
+ useEffect(() => { setSearchLimit(RECENT_LIMIT); }, [query]);
564
+
565
+ /* Auto-grow when the footer nears the bottom of the visible box; clicking
566
+ * it does the same, so a fast scroll and a deliberate click agree. */
567
+ useEffect(() => {
568
+ const el = moreRef.current;
569
+ if (!el || remainingRecent <= 0) return undefined;
570
+ let ticking = false;
571
+ const check = () => {
572
+ ticking = false;
573
+ if (Date.now() - autoPagerAt.current < 900) return;
574
+ if (el.getBoundingClientRect().top < scrollBottom(el) + 240) {
575
+ autoPagerAt.current = Date.now();
576
+ growRecent();
577
+ }
578
+ };
579
+ const onScroll = () => { if (!ticking) { ticking = true; requestAnimationFrame(check); } };
580
+ check();
581
+ window.addEventListener("scroll", onScroll, true);
582
+ window.addEventListener("resize", onScroll);
583
+ return () => {
584
+ window.removeEventListener("scroll", onScroll, true);
585
+ window.removeEventListener("resize", onScroll);
586
+ };
587
+ }, [remainingRecent, recentLimit, growRecent, searching]);
588
+
589
+ useEffect(() => {
590
+ const el = searchMoreRef.current;
591
+ if (!el || remainingSearch <= 0) return undefined;
592
+ let ticking = false;
593
+ const check = () => {
594
+ ticking = false;
595
+ if (Date.now() - autoPagerAt.current < 900) return;
596
+ if (el.getBoundingClientRect().top < scrollBottom(el) + 240) {
597
+ autoPagerAt.current = Date.now();
598
+ growSearch();
599
+ }
600
+ };
601
+ const onScroll = () => { if (!ticking) { ticking = true; requestAnimationFrame(check); } };
602
+ check();
603
+ window.addEventListener("scroll", onScroll, true);
604
+ window.addEventListener("resize", onScroll);
605
+ return () => {
606
+ window.removeEventListener("scroll", onScroll, true);
607
+ window.removeEventListener("resize", onScroll);
608
+ };
609
+ }, [remainingSearch, searchLimit, growSearch]);
610
+
611
+ /* Default workspace = the one holding the most recent live session. */
612
+ const currentWsId = useMemo(() => {
613
+ if (groups.activeWorkspace) return groups.activeWorkspace;
614
+ for (const id of recent) {
615
+ const found = (ws?.items || []).find((it) => (it.sessionIds || []).includes(id));
616
+ if (found) return found.workspaceId;
617
+ }
618
+ return visibleWorkspaces[0]?.workspaceId;
619
+ }, [groups.activeWorkspace, recent, ws, visibleWorkspaces]);
620
+
621
+ const toggle = useCallback((key) => {
622
+ const cur = store.get();
623
+ store.set({ ...cur, collapsed: { ...cur.collapsed, [key]: !(cur.collapsed || {})[key] } });
624
+ }, []);
625
+
626
+ const assignTo = useCallback((id, gid) => {
627
+ const cur = store.get();
628
+ const nextAssign = { ...cur.assign };
629
+ if (gid) nextAssign[id] = gid;
630
+ else delete nextAssign[id];
631
+ store.set({ ...cur, assign: nextAssign });
632
+ }, []);
633
+
634
+ const createGroup = useCallback((sessionId) => {
635
+ const name = window.prompt("新分组名称");
636
+ if (!name || !name.trim()) return;
637
+ const g = { id: newGroupId(), name: name.trim().slice(0, 20) };
638
+ const cur = store.get();
639
+ const next = { ...cur, groups: [...cur.groups, g] };
640
+ if (sessionId) next.assign = { ...cur.assign, [sessionId]: g.id };
641
+ store.set(next);
642
+ }, []);
643
+
644
+ const renameGroup = useCallback((g) => {
645
+ const name = window.prompt("分组名称", g.name);
646
+ if (!name || !name.trim()) return;
647
+ const cur = store.get();
648
+ store.set({ ...cur, groups: cur.groups.map((x) => (x.id === g.id ? { ...x, name: name.trim().slice(0, 20) } : x)) });
649
+ }, []);
650
+
651
+ const deleteGroup = useCallback((g) => {
652
+ if (!window.confirm(`删除分组「${g.name}」?组内会话会回到未分组。`)) return;
653
+ const cur = store.get();
654
+ const nextAssign = { ...cur.assign };
655
+ for (const [sid, gid] of Object.entries(nextAssign)) if (gid === g.id) delete nextAssign[sid];
656
+ store.set({ ...cur, groups: cur.groups.filter((x) => x.id !== g.id), assign: nextAssign });
657
+ }, []);
658
+
659
+ const switchWorkspace = useCallback((item) => {
660
+ const cur = store.get();
661
+ store.set({ ...cur, activeWorkspace: String(item.workspaceId) });
662
+ try {
663
+ if (openWorkspace) Promise.resolve(openWorkspace(item.workspaceId)).catch((err) => console.error("[dsh-sidebar-sessions] switch workspace failed", err));
664
+ } catch (err) {
665
+ console.error("[dsh-sidebar-sessions] switch workspace failed", err);
666
+ }
667
+ }, [openWorkspace]);
668
+
669
+ const hideWorkspace = useCallback((item) => {
670
+ const cur = store.get();
671
+ const id = String(item.workspaceId);
672
+ store.set({ ...cur, hiddenWorkspaces: [...new Set([...(cur.hiddenWorkspaces || []), id])] });
673
+ }, []);
674
+
675
+ const unhideWorkspace = useCallback((item) => {
676
+ const cur = store.get();
677
+ const id = String(item.workspaceId);
678
+ store.set({ ...cur, hiddenWorkspaces: (cur.hiddenWorkspaces || []).filter((x) => x !== id) });
679
+ }, []);
680
+
681
+ const closeMenu = useCallback(() => setMenu(null), []);
682
+ const openMenu = useCallback((id, el) => {
683
+ const r = el.getBoundingClientRect();
684
+ setMenu({ id, x: Math.min(r.right - 190, Math.max(8, window.innerWidth - 210)), y: Math.min(r.bottom + 2, window.innerHeight - 280) });
685
+ }, []);
686
+
687
+ const renameRow = useCallback(async (id) => {
688
+ const name = window.prompt("重命名对话", titleOf(byId[id], id));
689
+ if (!name || !name.trim() || !renameSession) return;
690
+ try {
691
+ await renameSession(id, name.trim());
692
+ } catch (err) {
693
+ console.error("[dsh-sidebar-sessions] rename failed", err);
694
+ }
695
+ }, [byId, renameSession]);
696
+
697
+ const copy = useCallback((text) => {
698
+ try {
699
+ if (navigator.clipboard?.writeText) navigator.clipboard.writeText(text);
700
+ } catch {}
701
+ }, []);
702
+
703
+ const commitSectionOrder = useCallback((sectionKey, next) => {
704
+ if (!next || sectionKey === "search") return;
705
+ const cur = store.get();
706
+ store.set({ ...cur, order: { ...(cur.order || {}), [sectionKey]: next } });
707
+ }, []);
708
+
709
+ const clearSectionOrder = useCallback((sectionKey) => {
710
+ const cur = store.get();
711
+ const order = { ...(cur.order || {}) };
712
+ if (!(sectionKey in order)) return;
713
+ delete order[sectionKey];
714
+ store.set({ ...cur, order });
715
+ }, []);
716
+
717
+ const handleDragOver = useCallback((section, id, half) => {
718
+ if (!id) {
719
+ setDragOver(null);
720
+ return;
721
+ }
722
+ /* No marker when the dragged row is not part of that list: a drop there
723
+ * cannot move anything, so promising a landing line would lie. */
724
+ const ids = sectionIdsRef.current[section];
725
+ if (!dragId || !ids || !ids.includes(dragId)) {
726
+ setDragOver(null);
727
+ return;
728
+ }
729
+ setDragOver({ section, id, half: half || "before" });
730
+ }, [dragId]);
731
+
732
+ /** End of any drag: no row may stay in its "being dragged" state. */
733
+ const handleDragEnd = useCallback(() => {
734
+ setDragId(null);
735
+ setDragOver(null);
736
+ }, []);
737
+
738
+ const onDropRow = useCallback((sectionKey, targetId, half) => {
739
+ const src = dragId;
740
+ setDragId(null);
741
+ setDragOver(null);
742
+ if (!src || src === targetId) return;
743
+ const ids = sectionIdsRef.current[sectionKey] || [];
744
+ const next = moveTo(ids, src, targetId, half);
745
+ /* Workspace tree: the host owns the order, so write it durably and
746
+ * fall back to the local view order only when the host refuses. */
747
+ if (typeof sectionKey === "string" && sectionKey.indexOf("ws:") === 0) {
748
+ if (!next) return;
749
+ const a = accountOf(src);
750
+ const b = accountOf(targetId);
751
+ if (a === undefined || a !== b) return;
752
+ /* A local order means the view already overrides the host; keep it local. */
753
+ if (orders[sectionKey]) {
754
+ commitSectionOrder(sectionKey, next);
755
+ return;
756
+ }
757
+ /* insertSessionBefore takes the id that must FOLLOW the moved row. */
758
+ const anchor = half === "after" ? anchorAfter(ids, src, targetId) : targetId;
759
+ if (anchor === src) return;
760
+ const keepLocal = () => commitSectionOrder(sectionKey, next);
761
+ if (!insertSessionBefore) return;
762
+ try {
763
+ Promise.resolve(insertSessionBefore(a, src, anchor))
764
+ .then((result) => {
765
+ if (result && result.ok === false) {
766
+ console.error("[dsh-sidebar-sessions] reorder rejected, keeping view order", result.error);
767
+ keepLocal();
768
+ } else clearSectionOrder(sectionKey);
769
+ })
770
+ .catch((err) => {
771
+ console.error("[dsh-sidebar-sessions] reorder failed", err);
772
+ keepLocal();
773
+ });
774
+ } catch (err) {
775
+ console.error("[dsh-sidebar-sessions] reorder failed", err);
776
+ keepLocal();
777
+ }
778
+ return;
779
+ }
780
+ /* Every other list is view order: keep it locally, or the recency
781
+ * sort would put the row straight back where it was. */
782
+ commitSectionOrder(sectionKey, next);
783
+ }, [dragId, accountOf, insertSessionBefore, commitSectionOrder, clearSectionOrder, orders]);
784
+
785
+ const sections = { recent, pinned, archived: archivedOrdered, search: filtered || [], ungrouped: groupRows.rest };
786
+ for (const g of groups.groups) sections["g:" + g.id] = groupRows.byGroup.get(g.id) || [];
787
+ const isGrouped = (id) => { const gid = assign[id]; return !!(gid && (groups.groups || []).some((g) => g.id === gid)); };
788
+ for (const item of visibleWorkspaces) sections["ws:" + String(item.workspaceId)] = applyManualOrder((item.sessionIds || []).filter((id) => byId[id] && !archivedSet.has(id) && !isGrouped(id)), orders["ws:" + String(item.workspaceId)]);
789
+ sectionIdsRef.current = sections;
790
+
791
+ const renderRow = useCallback(
792
+ (id, opts) =>
793
+ h(Row, {
794
+ key: id,
795
+ id,
796
+ section: (opts && opts.section) || "recent",
797
+ row: byId[id],
798
+ pinned: pinnedSet.has(id),
799
+ archived: archivedSet.has(id),
800
+ status: statuses?.get?.(id),
801
+ scheduled: scheduledOf(id),
802
+ dragging: dragId === id,
803
+ over: dragOver !== null && dragOver.id === id && dragOver.section === ((opts && opts.section) || "recent") && dragId !== null && dragId !== id ? dragOver.half : null,
804
+ onOpen: open,
805
+ onMenu: openMenu,
806
+ onDragStart: setDragId,
807
+ onDragOver: handleDragOver,
808
+ onDrop: onDropRow,
809
+ ...(opts || {}),
810
+ }),
811
+ [byId, pinnedSet, archivedSet, statuses, scheduledOf, dragId, dragOver, open, openMenu, onDropRow, handleDragOver]
812
+ );
813
+
814
+ const head = (label, count, onToggle, caret, extra) =>
815
+ h(
816
+ "div",
817
+ { className: "dsg-head", onClick: onToggle },
818
+ h("span", { className: "dsg-caret" }, caret),
819
+ h("span", { className: "dsg-head-label" }, label),
820
+ h("span", { className: "dsg-count" }, String(count)),
821
+ extra || null
822
+ );
823
+
824
+ const section = (key, label, count, body, extra) =>
825
+ h(
826
+ "div",
827
+ { key },
828
+ head(label, count, () => toggle(key), collapsed[key] ? "▸" : "▾", extra),
829
+ collapsed[key] ? null : body
830
+ );
831
+
832
+ /* Footer of a paged list: 还能翻 / 加载中 / 到底了. */
833
+ const moreButton = (onClick) => ({
834
+ role: "button",
835
+ tabIndex: 0,
836
+ onClick,
837
+ onKeyDown: (ev) => {
838
+ if (ev.key !== "Enter" && ev.key !== " ") return;
839
+ ev.preventDefault();
840
+ onClick();
841
+ },
842
+ });
843
+
844
+ const recentFooter = (() => {
845
+ if (loadingMore === "recent") return h("div", { className: "dsg-more", "data-pager": "recent", ref: moreRef }, "加载中…");
846
+ if (remainingRecent > 0) {
847
+ return h("div", { ...moreButton(growRecent), ref: moreRef, className: "dsg-more", "data-pager": "recent", title: "加载更多对话" },
848
+ `显示更多(还有 ${remainingRecent} 条)`);
849
+ }
850
+ if (live.length > RECENT_LIMIT) {
851
+ return h("div", { className: "dsg-more dsg-more-end", "data-pager": "recent" }, `已经是最早的对话了 · 共 ${live.length} 条`);
852
+ }
853
+ return null;
854
+ })();
855
+
856
+ const searchFooter = (() => {
857
+ if (!filteredAll || filteredAll.length === 0) return null;
858
+ if (loadingMore === "search") return h("div", { className: "dsg-more", "data-pager": "search", ref: searchMoreRef }, "加载中…");
859
+ if (remainingSearch > 0) {
860
+ return h("div", { ...moreButton(growSearch), ref: searchMoreRef, className: "dsg-more", "data-pager": "search", title: "加载更多匹配" },
861
+ `还有 ${remainingSearch} 条匹配`);
862
+ }
863
+ if (filteredAll.length > RECENT_LIMIT) {
864
+ return h("div", { className: "dsg-more dsg-more-end", "data-pager": "search" }, `全部 ${filteredAll.length} 条匹配都在这了`);
865
+ }
866
+ return null;
867
+ })();
868
+ const menuEl = menu
869
+ ? h(
870
+ "div",
871
+ { className: "dsg-menu", style: { left: menu.x, top: menu.y }, onMouseLeave: closeMenu },
872
+ h("div", { className: "dsg-menu-item", onClick: () => { pinnedSet.has(menu.id) ? unpinSession(menu.id) : pinSession(menu.id); closeMenu(); } },
873
+ pinnedSet.has(menu.id) ? "取消置顶" : "置顶"),
874
+ h("div", { className: "dsg-menu-item", onClick: () => { renameRow(menu.id); closeMenu(); } }, "重命名"),
875
+ h("div", { className: "dsg-menu-item", onClick: () => { if (forkSession) forkSession(menu.id); closeMenu(); } }, "分叉会话"),
876
+ h("div", { className: "dsg-menu-item", onClick: () => { copy(menu.id); closeMenu(); } }, "复制 Session ID"),
877
+ 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(); } }, "复制工作目录"),
878
+ h("div", { className: "dsg-menu-sep" }),
879
+ h("div", { className: "dsg-menu-label" }, "移动到分组"),
880
+ h("div", { className: "dsg-menu-item", onClick: () => { assignTo(menu.id, null); closeMenu(); } }, "未分组"),
881
+ groups.groups.map((g) =>
882
+ h("div", { key: g.id, className: "dsg-menu-item", onClick: () => { assignTo(menu.id, g.id); closeMenu(); } },
883
+ h("span", { className: "dsg-dot-sm" }, "●"), g.name)
884
+ ),
885
+ h("div", { className: "dsg-menu-item", onClick: () => { createGroup(menu.id); closeMenu(); } }, "+ 新建分组…"),
886
+ h("div", { className: "dsg-menu-sep" }),
887
+ h("div", { className: "dsg-menu-item", onClick: () => { archivedSet.has(menu.id) ? unarchiveSession(menu.id) : archiveSession(menu.id); closeMenu(); } },
888
+ archivedSet.has(menu.id) ? "取消归档" : "归档")
889
+ )
890
+ : null;
891
+
892
+ return h(
893
+ "div",
894
+ {
895
+ className: "dsg-root",
896
+ ref: rootRef,
897
+ onClick: menu ? closeMenu : undefined,
898
+ /* A drag can end without a drop on a row (released on a header, the
899
+ * gap between sections, or cancelled with Esc); dragend is the only
900
+ * event that always fires, and without it that row keeps the 45%
901
+ * "being dragged" dimming until the next drop or a reload. */
902
+ onDragEnd: handleDragEnd,
903
+ onDrop: (e) => { e.preventDefault(); handleDragEnd(); },
904
+ },
905
+ compact ? null : h(React.Fragment, null,
906
+ h("div", { className: "dsg-ws" },
907
+ h("button", { className: "dsg-ws-btn", onClick: async () => {
908
+ try {
909
+ if (pickDirectory && createWorkspace) {
910
+ const dir = await pickDirectory();
911
+ if (dir) await createWorkspace(dir);
912
+ }
913
+ } catch (err) {
914
+ console.error("[dsh-sidebar-sessions] create workspace failed", err);
915
+ }
916
+ } }, "+ 新建工作区")),
917
+ h("div", { className: "dsg-search" },
918
+ h("input", {
919
+ value: query,
920
+ placeholder: "搜索对话",
921
+ onChange: (e) => setQuery(e.target.value),
922
+ onKeyDown: (e) => { if (e.key === "Escape") setQuery(""); },
923
+ }),
924
+ query ? h("button", { className: "dsg-icon", title: "清除", onClick: () => setQuery("") }, "✕") : null),
925
+ searching
926
+ ? h("div", null,
927
+ head("搜索结果", (filtered || []).length, () => {}, "▾"),
928
+ (filtered || []).length
929
+ ? h("div", null, filtered.map((id) => renderRow(id, { section: "search" })), searchFooter)
930
+ : h("div", { className: "dsg-empty" }, "没有匹配的对话"))
931
+ : h(React.Fragment, null,
932
+ pinned.length ? section("pinned", "置顶", pinned.length, h("div", null, pinned.map((id) => renderRow(id, { section: "pinned" })))) : null,
933
+ section("recent", "最近", recent.length, h("div", null, recent.map((id) => renderRow(id, { section: "recent" })), recentFooter),
934
+ Array.isArray(orders.recent) && orders.recent.length
935
+ ? h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11, flex: "none" }, title: "恢复最近排序", onClick: (e) => { e.stopPropagation(); clearSectionOrder("recent"); } }, "↺")
936
+ : null),
937
+ groups.groups.map((g) => {
938
+ const rows = groupRows.byGroup.get(g.id) || [];
939
+ return h("div", { key: g.id },
940
+ h("div", { className: "dsg-head", onClick: () => toggle("g:" + g.id) },
941
+ h("span", { className: "dsg-caret" }, collapsed["g:" + g.id] ? "▸" : "▾"),
942
+ h("span", { className: "dsg-head-label" }, g.name),
943
+ h("span", { className: "dsg-count" }, String(rows.length)),
944
+ h("span", { style: { display: "flex", gap: 2, flex: "none" }, onClick: (e) => e.stopPropagation() },
945
+ h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11 }, title: "重命名", onClick: () => renameGroup(g) }, "✎"),
946
+ h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11 }, title: "删除分组", onClick: () => deleteGroup(g) }, "✕"))),
947
+ collapsed["g:" + g.id] ? null : h("div", null, rows.map((id) => renderRow(id, { section: "g:" + g.id }))));
948
+ }),
949
+ section("ungrouped", "未分组", groupRows.rest.length, h("div", null, groupRows.rest.map((id) => renderRow(id, { section: "ungrouped" })))),
950
+ archivedOrdered.length
951
+ ? h("div", { key: "archived" },
952
+ head("已归档", archivedOrdered.length, () => setShowArchived((v) => !v), showArchived ? "▾" : "▸"),
953
+ showArchived ? h("div", null, archivedOrdered.map((id) => renderRow(id, { archived: true, section: "archived" }))) : null)
954
+ : null,
955
+ /* Workspace block: same shape as a group, marked as a workspace. */
956
+ h("div", { key: "wsroot" },
957
+ h("div", { className: "dsg-head", onClick: () => toggle("ws:root") },
958
+ h("span", { className: "dsg-caret" }, collapsed["ws:root"] ? "▸" : "▾"),
959
+ h("span", { className: "dsg-head-label" }, "📁 工作区"),
960
+ h("span", { className: "dsg-count" }, String(visibleWorkspaces.length))),
961
+ collapsed["ws:root"] ? null : h("div", null,
962
+ visibleWorkspaces.length === 0
963
+ ? h("div", { className: "dsg-empty" }, "还没有工作区,点上方「+ 新建工作区」")
964
+ : visibleWorkspaces.map((item) => {
965
+ const key = "ws:" + String(item.workspaceId);
966
+ const members = applyManualOrder((item.sessionIds || []).filter((id) => byId[id] && !archivedSet.has(id) && !isGrouped(id)), orders[key]);
967
+ const isCurrent = String(currentWsId) === String(item.workspaceId);
968
+ const label = item.title || item.path || String(item.workspaceId);
969
+ return h("div", { key },
970
+ h("div", { className: "dsg-head", onClick: () => { switchWorkspace(item); if (collapsed[key]) toggle(key); } },
971
+ h("span", { className: "dsg-caret", onClick: (e) => { e.stopPropagation(); toggle(key); } }, collapsed[key] ? "▸" : "▾"),
972
+ h("span", { className: "dsg-head-label" }, (isCurrent ? "📌 " : "📁 ") + label),
973
+ h("span", { className: "dsg-count" }, String(members.length)),
974
+ h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11 }, title: "隐藏工作区", onClick: (e) => { e.stopPropagation(); hideWorkspace(item); } }, "✕")),
975
+ collapsed[key] ? null : h("div", null, members.map((id) => renderRow(id, { section: key }))));
976
+ }))),
977
+ hiddenWorkspaces.length
978
+ ? h("div", { key: "hiddenws" },
979
+ head("已隐藏的工作区", hiddenWorkspaces.length, () => setShowHidden((v) => !v), showHidden ? "▾" : "▸"),
980
+ showHidden
981
+ ? h("div", null, hiddenWorkspaces.map((item) =>
982
+ h("div", { key: String(item.workspaceId), className: "dsg-ws-row" },
983
+ h("span", { style: { flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, item.title || item.path || String(item.workspaceId)),
984
+ h("button", { className: "dsg-icon", style: { width: 18, height: 18, fontSize: 11 }, title: "恢复显示", onClick: () => unhideWorkspace(item) }, "↩"))))
985
+ : null)
986
+ : null),
987
+ ),
988
+ menuEl
989
+ );
990
+ }
991
+
992
+ function apply(ctx) {
993
+ ctx.effect(() => injectStyles(), "dsh-sidebar-sessions: styles");
994
+
995
+ /* Schedule catalog: active (not yet fired) reminders, refreshed on change. */
996
+ const scheduleStore = (() => {
997
+ let state = [];
998
+ const listeners = new Set();
999
+ return {
1000
+ get: () => state,
1001
+ set(next) {
1002
+ state = next;
1003
+ for (const fn of listeners) fn();
1004
+ },
1005
+ subscribe(fn) {
1006
+ listeners.add(fn);
1007
+ return () => listeners.delete(fn);
1008
+ },
1009
+ };
1010
+ })();
1011
+
1012
+ const reloadSchedules = () => {
1013
+ try {
1014
+ const remote = ctx.remote && ctx.remote.schedule;
1015
+ if (!remote || typeof remote.catalog !== "function") return;
1016
+ Promise.resolve(remote.catalog())
1017
+ .then((result) => {
1018
+ const rows = Array.isArray(result) ? result : (result && Array.isArray(result.value) ? result.value : []);
1019
+ scheduleStore.set(rows);
1020
+ })
1021
+ .catch((err) => console.error("[dsh-sidebar-sessions] schedule catalog failed", err));
1022
+ } catch {}
1023
+ };
1024
+
1025
+ ctx.effect(() => {
1026
+ reloadSchedules();
1027
+ const off = typeof ctx.on === "function" ? ctx.on("schedule/changed", reloadSchedules) : undefined;
1028
+ return () => {
1029
+ if (typeof off === "function") off();
1030
+ };
1031
+ }, "dsh-sidebar-sessions: schedules");
1032
+ ctx.slots.inject("sidebar.workspaces", () =>
1033
+ ctx.slots.register(
1034
+ {
1035
+ name: "sidebar.workspaces",
1036
+ id: "dsh-sidebar-sessions",
1037
+ priority: -2,
1038
+ registrant: "dsh-sidebar-sessions",
1039
+ inject: () => ({
1040
+ open: (sessionId) => ctx.uiWorkspace.openSession(sessionId),
1041
+ pinSession: (sessionId) => ctx.uiWorkspace.pinSession(sessionId),
1042
+ unpinSession: (sessionId) => ctx.uiWorkspace.unpinSession(sessionId),
1043
+ archiveSession: (sessionId) => ctx.uiWorkspace.archiveSession(sessionId),
1044
+ unarchiveSession: (sessionId) => ctx.uiWorkspace.unarchiveSession(sessionId),
1045
+ forkSession: (sessionId) => ctx.uiWorkspace.forkSession(sessionId),
1046
+ pickDirectory: () => ctx.uiWorkspace.pickDirectory(),
1047
+ openWorkspace: (workspaceId) => ctx.uiWorkspace.openWorkspace(workspaceId),
1048
+ createWorkspace: (input) => ctx.workspaces.create(input),
1049
+ insertSessionBefore: (accountId, sessionId, anchor) => ctx.workspaces.insertSessionBefore(accountId, sessionId, anchor),
1050
+ useScheduleCatalog: () => useSyncExternalStore(scheduleStore.subscribe, scheduleStore.get, scheduleStore.get),
1051
+ renameSession: (sessionId, title) =>
1052
+ ctx.sessions.using(sessionId, { source: "workspaceOperation" }, (ref) =>
1053
+ ref.binding.session.rename(title)
1054
+ ).then((result) => {
1055
+ if (result?.ok === false) throw new Error(result.error?.message || "rename failed");
1056
+ }),
1057
+ }),
1058
+ },
1059
+ GuardedRegion
1060
+ )
1061
+ );
1062
+ }
1063
+
1064
+ return { inject, apply };
1065
+ },
1066
+ });