dsh-workspace-browser 0.4.13 → 0.4.16

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/src/client.js CHANGED
@@ -1,1087 +1,1275 @@
1
- const { createElement: h, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } = react;
2
- const {
3
- Button, MenuItemButton, StateDot, IconCheckOutlineRegular, IconChevronLeftOutlineRegular, IconChevronRightOutlineRegular,
4
- IconChevronUpOutlineRegular, IconFolderOpenRegular,
5
- IconPinFillRegular, IconArchiveOutlineRegular, IconClockOutlineRegular,
6
- } = ui;
7
-
8
- const inject = ['slots', 'locale', 'workspaces', 'sessions', 'uiSession', 'uiWorkspace', 'layout', 'remote', 'remote.schedule'];
9
- const ungrouped = '';
10
- const defaultOptions = {};
11
- const emptyView = { getSnapshot: () => defaultOptions, subscribe: () => () => {} };
12
- const preferenceKey = `${id}.sidebar`;
13
- const unreadKey = preferenceKey + '.unread';
14
- const emptyOrder = {};
15
- const emptySchedule = { records: [] };
16
- function scheduleSourceFor(ctx) {
17
- let snapshot = emptySchedule;
18
- let revision = 0;
19
- return {
20
- getSnapshot: () => snapshot,
21
- subscribe(listener) {
22
- async function refresh() {
23
- const request = ++revision;
24
- try {
25
- const result = await ctx.remote.schedule.catalog();
26
- if (request !== revision || !result.ok) return;
27
- snapshot = { records: result.value };
28
- listener();
29
- } catch {
30
- // A later catalog change or reconnect retries the read.
31
- }
32
- }
33
- const stopChanged = ctx.remote.$on('schedule/changed', refresh);
34
- const stopReset = ctx.on('connection/reset', refresh);
35
- refresh();
36
- return () => {
37
- revision++;
38
- stopChanged();
39
- stopReset();
40
- };
41
- },
42
- };
43
- }
44
- const folderKey = key => 'folder:' + key;
45
- const sessionKey = key => 'session:' + key;
46
- const pageKey = folder => folder === null ? 'home' : folderKey(folder);
47
-
48
- // The native new-session button carries no stable attribute, so it is recognised
49
- // by its own new-chat glyph or by a shortcut, minus the sidebar toggles and
50
- // everything inside the workspaces region (add workspace also has a shortcut).
51
- function isNewSessionButton(button) {
52
- if (!button || button.disabled) return false;
53
- if (button.closest('[data-sidebar-toggle], [data-sidebar-opener], [data-slot="sidebar.workspaces"]')) return false;
54
- return Boolean(button.querySelector('[data-icon^="dsw-icon-new-chat"]')) || button.hasAttribute('aria-keyshortcuts');
55
- }
56
-
57
- function getNewSessionButton(event) {
58
- const button = event.target instanceof Element ? event.target.closest('button') : null;
59
- return isNewSessionButton(button) && button.closest('[data-slot="sidebar"]') ? button : null;
60
- }
61
-
62
- const dictionaries = {
63
- zh: {
64
- panel: '文件夹浏览', home: '主页', path: '工作区路径', back: '后退', forward: '前进', up: '上一级',
65
- ungrouped: '未分组会话', locate: '回到当前会话', createError: '暂时无法新建会话。',
66
- loading: '正在加载…', loadError: '暂时无法读取工作区。', openError: '暂时无法打开此会话。',
67
- emptyHome: '还没有工作区。', emptyFolder: '此工作区没有子工作区或会话。', noArchives: '没有已归档会话。',
68
- archived: '已归档会话', scheduled: '有定时任务', running: '运行中', oneRunningSession: '1 个会话运行中', runningSessions: '{n} 个会话运行中',
69
- gestureUp: '返回上一级', gestureInvalid: '无效手势',
70
- display: '视图选项', icons: '大图标', list: '列表', resize: '调整工作区分隔位置',
71
- },
72
- en: {
73
- panel: 'Browse folders', home: 'Home', path: 'Workspace path', back: 'Back', forward: 'Forward', up: 'Up one level',
74
- ungrouped: 'Ungrouped sessions', locate: 'Go to current session', createError: 'Could not start a new session.',
75
- loading: 'Loading…', loadError: 'Could not load workspaces.', openError: 'Could not open this session.',
76
- emptyHome: 'No workspaces yet.', emptyFolder: 'No child workspaces or sessions in this workspace.',
77
- noArchives: 'No archived sessions.', archived: 'Archived session', scheduled: 'Has scheduled tasks', running: 'Running',
78
- runningSessions: '{n} sessions running', oneRunningSession: '1 session running',
79
- gestureUp: 'Up one level', gestureInvalid: 'Invalid gesture',
80
- display: 'View options', icons: 'Large icons', list: 'List', resize: 'Resize workspace area',
81
- },
82
- };
83
-
84
- function workspacePath(path) {
85
- const windows = /^[A-Za-z]:[/\\]/.test(path) || path.startsWith('\\\\');
86
- const normalized = (windows ? path.replaceAll('\\', '/') : path).replace(/\/+$/, '');
87
- return { normalized, folded: windows ? normalized.toLowerCase() : undefined };
88
- }
89
-
90
- function workspaceTree(items) {
91
- const byId = new Map(items.map(item => [item.workspaceId, item]));
92
- const paths = new Map(items.map(item => [item.path, item.workspaceId]));
93
- const folders = [...paths].map(([path, id]) => ({ ...workspacePath(path), id }));
94
- const parents = new Map();
95
- const children = new Map();
96
- for (const item of items) {
97
- const child = workspacePath(item.path);
98
- let parent = null;
99
- let length = -1;
100
- let exactParent = false;
101
- for (const folder of folders) {
102
- if (folder.normalized.length >= child.normalized.length || folder.normalized.length < length) continue;
103
- const exact = child.normalized.startsWith(`${folder.normalized}/`);
104
- const folded = folder.folded !== undefined && child.folded?.startsWith(`${folder.folded}/`);
105
- if ((!exact && !folded) || (folder.normalized.length === length && (exactParent || !exact))) continue;
106
- parent = folder.id;
107
- length = folder.normalized.length;
108
- exactParent = exact;
109
- }
110
- parents.set(item.workspaceId, parent);
111
- if (!children.has(parent)) children.set(parent, []);
112
- children.get(parent).push(item);
113
- }
114
- return { byId, parents, children };
115
- }
116
-
117
- function manualOrders(workspaces, sessions) {
118
- const assigned = new Set(workspaces.items.flatMap(item => item.sessionIds));
119
- const byRecency = ids => ids.filter(id => sessions.byId[id]).sort((a, b) =>
120
- sessions.byId[b].updatedAt - sessions.byId[a].updatedAt || (a < b ? -1 : 1));
121
- const activeBlank = sessions.ids.find(id => sessions.byId[id]?.blank && sessions.byId[id].retainedBy?.mainView > 0);
122
- const order = ids => {
123
- const sorted = byRecency(ids);
124
- return sorted.includes(activeBlank) ? [activeBlank, ...sorted.filter(id => id !== activeBlank)] : sorted;
125
- };
126
- return Object.fromEntries([
127
- ...workspaces.items.map(item => [item.workspaceId, order(item.sessionIds)]),
128
- [ungrouped, order(sessions.ids.filter(id => !assigned.has(id)))],
129
- ['__flat_session_order__', order(sessions.ids.filter(id => {
130
- const session = sessions.byId[id];
131
- return session && session.origin !== 'subagent' && (!session.blank || id === activeBlank);
132
- }))],
133
- ]);
134
- }
135
-
136
- function sessionRows(workspaceState, sessions, options) {
137
- const { byId, ids } = sessions;
138
- const archived = new Set(workspaceState.archivedSessionIds);
139
- const pinned = new Set(workspaceState.pinnedSessionIds);
140
- const assigned = new Set(workspaceState.items.flatMap(workspace => workspace.sessionIds));
141
- const filter = options.archivedFilter ?? 'default';
142
- const visible = session => session && session.origin !== 'subagent' && (!session.blank || session.retainedBy?.mainView > 0)
143
- && (filter === 'show' || (filter === 'only') === archived.has(session.id));
144
- const sorted = (members, account) => {
145
- const manual = options.orderBy === 'manual';
146
- const order = new Map((manual ? options.sessionOrderByAccount?.[account] ?? [] : []).map((id, index) => [id, index]));
147
- const rank = session => session.blank ? 0 : pinned.has(session.id) && !archived.has(session.id) ? 1 : 2;
148
- return members.map(id => byId[id]).filter(visible).sort((a, b) => rank(a) - rank(b)
149
- || (order.get(a.id) ?? Infinity) - (order.get(b.id) ?? Infinity)
150
- || (manual ? Number(archived.has(a.id)) - Number(archived.has(b.id)) : 0)
151
- || b.updatedAt - a.updatedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
152
- };
153
- const byWorkspace = new Map(workspaceState.items.map(workspace => [workspace.workspaceId, sorted(workspace.sessionIds, workspace.workspaceId)]));
154
- byWorkspace.set(ungrouped, sorted(ids.filter(id => !assigned.has(id)), ungrouped));
155
- return { byWorkspace, pinned, archived };
156
- }
157
-
158
- const statusDetails = {
159
- approval: { state: 'error', label: 'status.waitingApproval', priority: 3 },
160
- question: { state: 'warning', label: 'status.waitingAnswer', priority: 2 },
161
- 'plan-review': { state: 'warning', label: 'status.planReview', priority: 2 },
162
- completed: { state: 'done', label: 'status.completed', priority: 1 },
163
- };
164
-
165
- function completionSource(ctx) {
166
- const list = ctx.sessions.list;
167
- const status = ctx.uiSession.sessionStatus;
168
- const panel = ctx.layout.panelInfo;
169
- const listeners = new Set();
170
- let unread = new Set();
171
- try {
172
- const saved = JSON.parse(localStorage.getItem(unreadKey));
173
- if (Array.isArray(saved)) unread = new Set(saved.filter(id => typeof id === 'string'));
174
- } catch { /* Storage may be unavailable. */ }
175
-
176
- let previous = new Set();
177
- function sync() {
178
- const sessions = list.getSnapshot();
179
- const completed = new Set();
180
- const next = new Set(unread);
181
- for (const [id, state] of status.getSnapshot()) {
182
- if (!state.completionUnread) continue;
183
- completed.add(id);
184
- if (!previous.has(id)) next.add(id);
185
- }
186
- previous = completed;
187
-
188
- const conversationVisible = panel.getSnapshot().activePanelId === null;
189
- for (const id of next) {
190
- const session = sessions.byId[id];
191
- if ((!session && sessions.phase === 'ready') || (conversationVisible && session?.retainedBy?.mainView > 0)) {
192
- next.delete(id);
193
- }
194
- }
195
- if (next.size === unread.size && [...next].every(id => unread.has(id))) return;
196
- unread = next;
197
- try { localStorage.setItem(unreadKey, JSON.stringify([...unread])); } catch { /* Keep the in-memory state. */ }
198
- for (const listener of listeners) listener();
199
- }
200
-
201
- ctx.effect(() => {
202
- const stops = [status.subscribe(sync), list.subscribe(sync), panel.subscribe(sync)];
203
- sync();
204
- return () => stops.forEach(stop => stop());
205
- });
206
- return {
207
- getSnapshot: () => unread,
208
- subscribe(listener) {
209
- listeners.add(listener);
210
- return () => listeners.delete(listener);
211
- },
212
- };
213
- }
214
-
215
- function workspaceNotifications(workspaces, sessions, statuses, parents, archived, unread) {
216
- const owners = new Map();
217
- for (const workspace of workspaces) {
218
- for (const sessionId of workspace.sessionIds) owners.set(sessionId, workspace.workspaceId);
219
- }
220
- const bySession = new Map();
221
- const byFolder = new Map();
222
- const runningBySession = new Map();
223
- const runningByFolder = new Map();
224
- for (const id of sessions.ids) {
225
- const session = sessions.byId[id];
226
- if (!session || session.blank || session.origin === 'subagent' || archived.has(id)) continue;
227
- const running = (statuses.get(id)?.running ?? session.running) === true;
228
- const subagents = sessions.projectionsBySession?.[id]?.values?.subagentCatalog?.filter(child =>
229
- (statuses.get(child.id)?.running ?? sessions.byId[child.id]?.running) === true).length ?? 0;
230
- if (running || subagents > 0) runningBySession.set(id, { running, subagents });
231
- if (!running) continue;
232
- for (let folder = owners.get(id) ?? ungrouped; folder !== null; folder = parents.get(folder) ?? null) {
233
- runningByFolder.set(folder, (runningByFolder.get(folder) ?? 0) + 1);
234
- }
235
- }
236
- const all = [];
237
- for (const sessionId of sessions.ids) {
238
- const session = sessions.byId[sessionId];
239
- if (!session || session.blank || session.origin === 'subagent' || archived.has(sessionId)) continue;
240
- const detail = statusDetails[statuses.get(sessionId)?.pendingInteraction?.kind]
241
- ?? (unread.has(sessionId) && !runningBySession.has(sessionId) ? statusDetails.completed : undefined);
242
- if (!detail) continue;
243
- const notification = { ...detail, sessionId };
244
- bySession.set(sessionId, notification);
245
- all.push(notification);
246
- for (let folder = owners.get(sessionId) ?? ungrouped; folder !== null; folder = parents.get(folder) ?? null) {
247
- if (!byFolder.has(folder)) byFolder.set(folder, []);
248
- byFolder.get(folder).push(notification);
249
- }
250
- }
251
- for (const notifications of byFolder.values()) notifications.sort((a, b) => b.priority - a.priority);
252
- return { bySession, byFolder, all, runningBySession, runningByFolder };
253
- }
254
-
255
- function NotificationDots({ entries, translate, size }) {
256
- return h('span', { className: 'dwb-notifications' }, entries.map(entry => {
257
- const label = translate(entry.label);
258
- return h('span', { key: entry.sessionId, role: 'img', 'aria-label': label, title: label,
259
- className: 'dwb-notification', 'data-dwb-notification': entry.state }, h(StateDot, { state: entry.state, size }));
260
- }));
261
- }
262
-
263
- function readPreference() {
264
- try { return JSON.parse(localStorage.getItem(preferenceKey)) ?? {}; }
265
- catch { return {}; }
266
- }
267
-
268
- function savePreference(value) {
269
- try { localStorage.setItem(preferenceKey, JSON.stringify(value)); }
270
- catch { /* The view can still be used without storage. */ }
271
- }
272
-
273
- function usePageFade() {
274
- const running = useRef(new Map());
275
- useEffect(() => () => {
276
- for (const animation of running.current.values()) animation.cancel();
277
- running.current.clear();
278
- }, []);
279
-
280
- const [fade] = useState(() => async (element, update) => {
281
- if (!element?.isConnected || matchMedia('(prefers-reduced-motion: reduce)').matches) {
282
- update();
283
- return;
284
- }
285
- const animations = running.current;
286
- const opacity = getComputedStyle(element).opacity;
287
- animations.get(element)?.cancel();
288
- const outgoing = element.animate([{ opacity }, { opacity: 0 }], { duration: 42.5, easing: 'ease-out', fill: 'forwards' });
289
- animations.set(element, outgoing);
290
- try {
291
- await outgoing.finished;
292
- if (animations.get(element) !== outgoing || !element.isConnected) return;
293
- flushSync(update);
294
- const incoming = element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 67.5, easing: 'ease-in-out' });
295
- outgoing.cancel();
296
- animations.set(element, incoming);
297
- await incoming.finished;
298
- if (animations.get(element) === incoming) animations.delete(element);
299
- } catch (error) {
300
- if (error.name !== 'AbortError') console.warn(`${id}: page transition failed`, error);
301
- } finally {
302
- if (animations.get(element) === outgoing) {
303
- outgoing.cancel();
304
- animations.delete(element);
305
- }
306
- }
307
- });
308
- return fade;
309
- }
310
-
311
- // Slot wrappers use `display: contents` and own no box, so climb past them
312
- // before reading a container's geometry.
313
- function containerOf(node) {
314
- let current = node ?? null;
315
- while (current && current !== document.body && getComputedStyle(current).display === 'contents') {
316
- current = current.parentElement;
317
- }
318
- return current && current !== document.body ? current : null;
319
- }
320
-
321
- // The host has no grouping-item slot. Walk down from the one stable anchor
322
- // (`[data-slot="sidebar.workspaces"]`) and read the browser's own boxes by
323
- // position: our mounts are known by class, the header is the first native child
324
- // of the region and the list is the last one.
325
- function useSidebarMounts(nativeText) {
326
- const [mounts, setMounts] = useState({});
327
- useLayoutEffect(() => {
328
- const grid = document.createElement('div');
329
- grid.className = 'dwb-mount';
330
- grid.hidden = true;
331
- const toolbar = document.createElement('div');
332
- toolbar.className = 'dwb-toolbar-mount';
333
- toolbar.hidden = true;
334
- const address = document.createElement('div');
335
- address.className = 'dwb-address-mount';
336
- address.hidden = true;
337
- const heading = document.createElement('span');
338
- heading.className = 'dwb-heading';
339
- heading.hidden = true;
340
- const menuMount = document.createElement('div');
341
- menuMount.className = 'dwb-menu-mount';
342
- let active;
343
- let workspace;
344
- let frame = 0;
345
-
346
- function sync() {
347
- workspace = document.querySelector('[data-slot="sidebar.workspaces"]');
348
- const region = containerOf(workspace?.firstElementChild);
349
- const area = containerOf(region?.parentElement);
350
- const panel = containerOf(area?.parentElement);
351
- const natives = region
352
- ? [...region.children].filter(child => ![...child.classList].some(name => name.startsWith('dwb-')))
353
- : [];
354
- const header = natives.length > 1 ? natives[0] : null;
355
- const list = natives.length > 1 ? natives[natives.length - 1] : null;
356
- const trigger = [...header?.querySelectorAll('button[aria-label]') ?? []]
357
- .find(button => button.getAttribute('aria-label') === nativeText('viewOptions.label'));
358
- const searchButton = header?.querySelector('button[aria-expanded]') ?? null;
359
- const searchInput = header?.querySelector('input[type="text"], input[type="search"]') ?? null;
360
- // The native title sits immediately before the search control.
361
- const title = searchButton?.parentElement?.parentElement?.previousElementSibling ?? null;
362
- const nativeHeading = title?.matches('span:not(.dwb-heading)') ? title : null;
363
- // The popup is recognised by the grouping rows it is the only menu to list
364
- // (the same localized strings the trigger is found by), so the body-level
365
- // workspace context menu -- a menu too, with other rows -- never adopts us.
366
- const groupLabels = ['groupBy.workspace', 'groupBy.workspaceTree', 'groupBy.flat'].map(key => {
367
- try {
368
- return nativeText(key);
369
- } catch {
370
- return null;
371
- }
372
- });
373
- let menu = active?.menu?.isConnected ? active.menu : null;
374
- if (!menu) {
375
- const menus = [...document.body.querySelectorAll(':scope > [role="menu"]:not([data-context-menu])')];
376
- menu = menus.reverse().find(node => [...node.querySelectorAll('button[role="menuitem"]')]
377
- .some(row => !menuMount.contains(row) && groupLabels.includes(row.textContent?.trim()))) ?? null;
378
- }
379
- // Our own separator lives inside the mount, so skip it and take the first
380
- // native one: every grouping row precedes it and nothing else does.
381
- const menuSeparator = menu
382
- ? [...menu.querySelectorAll('[role="separator"]')].find(node => !menuMount.contains(node)) ?? null
383
- : null;
384
- const groupRows = menu && menuSeparator
385
- ? [...menu.querySelectorAll('button[role="menuitem"]')].filter(row => !menuMount.contains(row)
386
- && Boolean(menuSeparator.compareDocumentPosition(row) & Node.DOCUMENT_POSITION_PRECEDING))
387
- : [];
388
- const lastGroup = groupRows.length > 0 ? groupRows[groupRows.length - 1].parentElement : null;
389
- const menuBody = groupRows.length > 0 ? groupRows[0].parentElement?.parentElement ?? null : null;
390
- const label = menuSeparator?.nextElementSibling ?? null;
391
- const menuLabel = label?.getAttribute('role') === 'presentation' ? label : null;
392
-
393
- if (trigger && header && list) {
394
- if (toolbar.nextElementSibling !== header) header.before(toolbar);
395
- if (header.nextElementSibling !== address) header.after(address);
396
- if (grid.parentElement !== list) list.prepend(grid);
397
- } else {
398
- toolbar.remove();
399
- address.remove();
400
- grid.remove();
401
- }
402
- if (nativeHeading) {
403
- if (heading.nextElementSibling !== nativeHeading) nativeHeading.before(heading);
404
- } else heading.remove();
405
- if (lastGroup) {
406
- groupRows.forEach(row => row.classList.add('dwb-native-group'));
407
- if (lastGroup.nextElementSibling !== menuMount) lastGroup.after(menuMount);
408
- } else menuMount.remove();
409
- const searchOpen = searchButton?.getAttribute('aria-expanded') === 'true';
410
- const searching = Boolean(searchOpen && searchInput?.value.trim());
411
- const next = { grid, list, toolbar, address, header, heading, nativeHeading, trigger, menu, menuMount, menuSeparator, menuLabel, groupRows, searching, searchOpen, region, area, panel, menuBody };
412
- const changed = active?.menu !== menu || active?.list !== list || active?.header !== header
413
- || active?.nativeHeading !== nativeHeading || active?.trigger !== trigger || active?.searching !== searching
414
- || active?.searchOpen !== searchOpen || active?.region !== region || active?.area !== area
415
- || active?.panel !== panel || active?.menuBody !== menuBody;
416
- active = next;
417
- if (changed) setMounts(next);
418
- }
419
-
420
- function schedule() {
421
- if (frame) return;
422
- frame = requestAnimationFrame(() => { frame = 0; sync(); });
423
- }
424
-
425
- const observer = new MutationObserver(records => {
426
- if (!workspace?.isConnected || records.some(record =>
427
- workspace.contains(record.target) || active?.menu?.contains(record.target)
428
- || (record.target === document.body && [...record.addedNodes, ...record.removedNodes]
429
- .some(node => node instanceof Element && node.matches('[role="menu"]'))))) schedule();
430
- });
431
- observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-expanded', 'aria-label'] });
432
- document.addEventListener('input', schedule);
433
- sync();
434
- return () => {
435
- observer.disconnect();
436
- cancelAnimationFrame(frame);
437
- document.removeEventListener('input', schedule);
438
- grid.remove();
439
- toolbar.remove();
440
- address.remove();
441
- heading.remove();
442
- menuMount.remove();
443
- };
444
- }, [nativeText]);
445
- return mounts;
446
- }
447
-
448
- function NavButton({ icon, label, disabled, onClick }) {
449
- return h(Button, {
450
- size: 'sm', className: 'dwb-nav-button', icon: icon && h(icon, { size: 16, 'aria-hidden': true }),
451
- title: label, 'aria-label': label, disabled, onClick,
452
- });
453
- }
454
-
455
- function LocateIcon({ size }) {
456
- return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': true,
457
- stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round' },
458
- h('circle', { cx: 12, cy: 12, r: 7 }),
459
- h('path', { d: 'M12 2v4m0 12v4M2 12h4m12 0h4' }),
460
- h('circle', { cx: 12, cy: 12, r: 1.5, fill: 'currentColor', stroke: 'none' }));
461
- }
462
-
463
- function SidebarDivider({ label, toolbar, area, ratio, saveRatio }) {
464
- const drag = useRef(null);
465
- // The region area owns the navigation list right above it.
466
- const navigation = area?.previousElementSibling ?? null;
467
- const upper = navigation?.matches('nav') ? navigation : null;
468
-
469
- function maximum() {
470
- const viewport = upper.parentElement;
471
- return Math.max(0, viewport.getBoundingClientRect().bottom - upper.getBoundingClientRect().top - 138);
472
- }
473
-
474
- useLayoutEffect(() => {
475
- if (!upper || !Number.isFinite(ratio)) return;
476
- const resize = () => upper.style.setProperty('--dwb-navigation-height', `${Math.round(ratio * maximum())}px`);
477
- upper.setAttribute('data-dwb-resized-navigation', '');
478
- const observer = new ResizeObserver(resize);
479
- observer.observe(upper.parentElement);
480
- resize();
481
- return () => {
482
- observer.disconnect();
483
- upper.removeAttribute('data-dwb-resized-navigation');
484
- upper.style.removeProperty('--dwb-navigation-height');
485
- };
486
- }, [upper, ratio]);
487
-
488
- function resize(height) {
489
- const available = maximum();
490
- if (available > 0) saveRatio(Math.max(0, Math.min(1, height / available)));
491
- }
492
-
493
- return h('div', {
494
- className: 'dwb-divider',
495
- ...(upper && {
496
- role: 'separator', 'aria-label': label, 'aria-orientation': 'horizontal', tabIndex: 0,
497
- 'aria-valuenow': Math.round((ratio ?? Math.min(1, upper.offsetHeight / Math.max(1, maximum()))) * 100),
498
- onPointerDown: event => {
499
- if (event.button !== 0) return;
500
- event.preventDefault();
501
- event.currentTarget.setPointerCapture(event.pointerId);
502
- drag.current = { y: event.clientY, height: upper.offsetHeight };
503
- },
504
- onPointerMove: event => {
505
- if (!drag.current || !event.currentTarget.hasPointerCapture(event.pointerId)) return;
506
- const distance = event.clientY - drag.current.y;
507
- if (distance !== 0) resize(drag.current.height + distance);
508
- },
509
- onLostPointerCapture: () => { drag.current = null; },
510
- onDoubleClick: () => saveRatio(null),
511
- onKeyDown: event => {
512
- if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
513
- event.preventDefault();
514
- resize(upper.offsetHeight + (event.key === 'ArrowUp' ? -16 : 16));
515
- },
516
- }),
517
- });
518
- }
519
-
520
- function FolderIcon({ size }) {
521
- return h('img', { src: folderIcon, alt: '', width: size, height: size, draggable: false });
522
- }
523
-
524
- function SessionIcon({ size }) {
525
- return h('span', { className: 'dwb-session-icon', style: { width: size, height: size, maskImage: `url("${sessionIcon}")` } });
526
- }
527
-
528
- function Browser({ t, nativeText, workspaceSource, sessionSource, view, startFolder, rememberFolder, openSession, toolbar, address, heading, area, panel, display, split, saveSplit, animatePage, useContextMenu, useSessionStatus, startSession, placements, savePlacement, panelSource, scheduleSource, unreadSource }) {
529
- const { getTriggerProps } = useContextMenu();
530
- const workspaceState = useSyncExternalStore(workspaceSource.subscribe, workspaceSource.getSnapshot);
531
- const sessions = useSyncExternalStore(sessionSource.subscribe, sessionSource.getSnapshot);
532
- const statuses = useSessionStatus(snapshot => snapshot);
533
- const unread = useSyncExternalStore(unreadSource.subscribe, unreadSource.getSnapshot);
534
- const { activePanelId } = useSyncExternalStore(panelSource.subscribe, panelSource.getSnapshot);
535
- const sessionVisible = activePanelId === null;
536
- const catalog = useSyncExternalStore(scheduleSource.subscribe, scheduleSource.getSnapshot);
537
- const scheduledSessions = useMemo(() => {
538
- const ids = new Set();
539
- for (const task of catalog.records) {
540
- if (task.status !== 'active') continue;
541
- for (const id of task.involvedSessionIds) ids.add(id);
542
- const target = task.target.kind === 'new' ? task.lastDelivery?.targetSessionId : task.target.sessionId;
543
- if (target) ids.add(target);
544
- }
545
- return ids;
546
- }, [catalog.records]);
547
- const options = useSyncExternalStore(view.subscribe, view.getSnapshot);
548
- const { byId, parents, children } = useMemo(() => workspaceTree(workspaceState.items), [workspaceState.items]);
549
- const { byWorkspace, pinned, archived } = useMemo(() => sessionRows(workspaceState, sessions, options), [workspaceState, sessions, options]);
550
- const notifications = useMemo(() => workspaceNotifications(workspaceState.items, sessions, statuses, parents, archived, unread),
551
- [workspaceState.items, sessions, statuses, parents, archived, unread]);
552
- const [history, setHistory] = useState(() => startFolder === null
553
- ? { entries: [null], index: 0 } : { entries: [null, startFolder], index: 1 });
554
- const [openError, setOpenError] = useState(null);
555
- const [selectedFolder, setSelectedFolder] = useState(null);
556
- const [dropTarget, setDropTarget] = useState(null);
557
- const dragged = useRef(null);
558
- const locate = useRef(null);
559
- const crumbsRef = useRef(null);
560
- useEffect(() => {
561
- const path = crumbsRef.current;
562
- function scrollPath(event) {
563
- if (event.ctrlKey || event.metaKey || event.deltaX !== 0 || event.deltaY === 0 || path.scrollWidth <= path.clientWidth) return;
564
- const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? path.clientWidth : 1;
565
- event.preventDefault();
566
- event.stopPropagation();
567
- path.scrollLeft += event.deltaY * scale;
568
- }
569
- path.addEventListener('wheel', scrollPath, { passive: false });
570
- return () => path.removeEventListener('wheel', scrollPath);
571
- }, [address]);
572
- const browserRef = useRef(null);
573
- useEffect(() => {
574
- if (selectedFolder === null) return;
575
- function clearSelection(event) {
576
- if (event.button !== 0 || (event.type === 'click' && event.detail > 0)) return;
577
- if (getNewSessionButton(event)) return;
578
- const selectedTile = browserRef.current?.querySelector('.dwb-tile[data-dwb-kind="folder"][aria-pressed="true"]');
579
- if (!event.composedPath().includes(selectedTile)) setSelectedFolder(null);
580
- }
581
- window.addEventListener('pointerdown', clearSelection, true);
582
- window.addEventListener('click', clearSelection, true);
583
- return () => {
584
- window.removeEventListener('pointerdown', clearSelection, true);
585
- window.removeEventListener('click', clearSelection, true);
586
- };
587
- }, [selectedFolder]);
588
-
589
- const exists = key => key === null || key === ungrouped || byId.has(key);
590
- const current = history.entries[history.index];
591
- const folder = exists(current) ? current : null;
592
- const parent = parents.get(folder) ?? null;
593
- const activeSession = Object.values(sessions.byId).find(session => session.retainedBy?.mainView > 0);
594
- const activeOwner = activeSession && workspaceState.items.find(item => item.sessionIds.includes(activeSession.id));
595
- let guideFolder;
596
- if (activeSession) {
597
- for (let child = activeOwner?.workspaceId ?? ungrouped; child !== null && child !== folder; child = parents.get(child) ?? null) {
598
- if ((parents.get(child) ?? null) !== folder) continue;
599
- guideFolder = child;
600
- break;
601
- }
602
- }
603
- const onlyArchived = options.archivedFilter === 'only';
604
- const foldersWithArchives = useMemo(() => {
605
- const visible = new Set();
606
- if (onlyArchived) for (const [key, rows] of byWorkspace) {
607
- if (rows.length === 0) continue;
608
- for (let item = key; item !== null && !visible.has(item); item = parents.get(item) ?? null) visible.add(item);
609
- }
610
- return visible;
611
- }, [byWorkspace, onlyArchived, parents]);
612
- const folders = (children.get(folder) ?? []).filter(item => !onlyArchived || foldersWithArchives.has(item.workspaceId));
613
- const placement = placements?.[pageKey(folder)];
614
- const order = placement?.order ?? [];
615
- const rows = byWorkspace.get(folder) ?? [];
616
- const rowIds = new Set(rows.map(row => row.id));
617
- const shortcuts = (placement?.shortcuts ?? []).map(id => sessions.byId[id]).filter(session => session
618
- && !rowIds.has(session.id) && (!session.blank || session.retainedBy?.mainView > 0)
619
- && (options.archivedFilter === 'show' || onlyArchived === archived.has(session.id)));
620
- const inside = new Set(notifications.byFolder.get(folder)?.map(entry => entry.sessionId));
621
- for (const session of shortcuts) inside.add(session.id);
622
- const outside = folder === null ? undefined : notifications.all.reduce((highest, entry) =>
623
- !inside.has(entry.sessionId) && entry.priority > (highest?.priority ?? 0) ? entry : highest, undefined);
624
- const workspaceLabel = workspace => workspace.title === 'default-workspace' ? nativeText('workspace.defaultName') : workspace.title;
625
- const crumbs = [{ key: null, label: t('home') }];
626
- if (folder === ungrouped) {
627
- crumbs.push({ key: ungrouped, label: t('ungrouped') });
628
- } else if (folder !== null) {
629
- const trail = [];
630
- for (let key = folder; key !== null; key = parents.get(key) ?? null) {
631
- const workspace = byId.get(key);
632
- trail.push({ key, label: workspaceLabel(workspace), path: workspace.path });
633
- }
634
- crumbs.push(...trail.reverse());
635
- }
636
-
637
- function visit(key) {
638
- if (key === folder) return;
639
- animatePage(() => {
640
- setOpenError(null);
641
- setSelectedFolder(null);
642
- rememberFolder(key);
643
- setHistory(previous => ({
644
- entries: [...previous.entries.slice(0, previous.index + 1), key], index: previous.index + 1,
645
- }));
646
- });
647
- }
648
-
649
- function historyTarget(direction) {
650
- let index = history.index + direction;
651
- while (index >= 0 && index < history.entries.length) {
652
- if (exists(history.entries[index])) return index;
653
- index += direction;
654
- }
655
- return undefined;
656
- }
657
-
658
- function go(index) {
659
- animatePage(() => {
660
- setOpenError(null);
661
- setSelectedFolder(null);
662
- rememberFolder(history.entries[index]);
663
- setHistory(previous => ({ ...previous, index }));
664
- });
665
- }
666
-
667
- const back = historyTarget(-1);
668
- const forward = historyTarget(1);
669
- const gestureAction = useRef(null);
670
- useLayoutEffect(() => {
671
- gestureAction.current = direction => {
672
- if (direction === 'up') { visit(parent); return; }
673
- const index = direction === 'left' ? back : forward;
674
- if (index !== undefined) go(index);
675
- };
676
- });
677
- useEffect(() => installMouseGestures(
678
- () => direction => gestureAction.current?.(direction),
679
- () => {
680
- const bounds = panel?.getBoundingClientRect();
681
- if (bounds?.width >= 112 && bounds.height >= 112) return bounds;
682
- },
683
- target => Boolean(panel?.contains(target)) && !panel.closest('[inert]') && !toolbar.hidden,
684
- direction => t({ left: 'back', right: 'forward', up: 'gestureUp', invalid: 'gestureInvalid' }[direction]),
685
- ), [toolbar, panel, t]);
686
- const hasUngrouped = folder === null && byWorkspace.get(ungrouped).length > 0;
687
- const loading = workspaceState.state !== 'error' && (workspaceState.phase !== 'ready' || sessions.phase !== 'ready');
688
- const entries = new Map([
689
- ...folders.map(item => [folderKey(item.workspaceId), item]),
690
- ...(hasUngrouped ? [[folderKey(ungrouped), null]] : []),
691
- ...[...rows, ...shortcuts].map(session => [sessionKey(session.id), session]),
692
- ]);
693
- const keys = [...new Set([...order.filter(key => entries.has(key)), ...entries.keys()])];
694
- const activeKey = activeSession && sessionKey(activeSession.id);
695
- const hasActiveTile = entries.has(activeKey);
696
- const empty = keys.length === 0;
697
-
698
- useLayoutEffect(() => {
699
- function createSession(event) {
700
- if (event.defaultPrevented || toolbar.hidden || !getNewSessionButton(event)) return;
701
- const selected = entries.get(selectedFolder);
702
- const inWorkspace = byId.has(folder);
703
- const workspaceId = inWorkspace ? folder : selected?.workspaceId ?? activeOwner?.workspaceId;
704
- if (!workspaceState.items.length) return;
705
- event.preventDefault();
706
- event.stopPropagation();
707
- const activeAnchor = hasActiveTile ? activeKey : folderKey(guideFolder);
708
- const anchor = entries.has(selectedFolder) ? selectedFolder : activeAnchor;
709
- setSelectedFolder(null);
710
- setOpenError(null);
711
- startSession(workspaceId, sessionId => {
712
- const key = sessionKey(sessionId);
713
- savePlacement(folder, (saved = {}) => {
714
- const next = [...new Set([...(saved.order ?? []), ...keys])].filter(item => item !== key);
715
- const index = next.indexOf(anchor);
716
- next.splice(index < 0 ? next.length : index + 1, 0, key);
717
- const shortcuts = saved.shortcuts ?? [];
718
- return { order: next, shortcuts: inWorkspace || shortcuts.includes(sessionId) ? shortcuts : [...shortcuts, sessionId] };
719
- });
720
- }).catch(() => setOpenError('create'));
721
- }
722
-
723
- document.addEventListener('click', createSession, true);
724
- return () => document.removeEventListener('click', createSession, true);
725
- });
726
-
727
- function locateCurrentSession() {
728
- locate.current = activeSession.id;
729
- if (!hasActiveTile && folder !== (activeOwner?.workspaceId ?? ungrouped) && !onlyArchived) {
730
- visit(activeOwner?.workspaceId ?? ungrouped);
731
- } else {
732
- revealCurrentSession();
733
- }
734
- }
735
-
736
- function revealCurrentSession() {
737
- if (locate.current === null) return;
738
- const item = browserRef.current.querySelector('[data-dwb-session-id="' + CSS.escape(locate.current) + '"] > button');
739
- if (!item) { locate.current = null; return; }
740
- locate.current = null;
741
- item.focus({ preventScroll: true });
742
- item.scrollIntoView({ block: 'nearest' });
743
- }
744
-
745
- function draggedPosition(event) {
746
- const box = event.currentTarget.getBoundingClientRect();
747
- if (display === 'list') return event.clientY < box.top + box.height / 2 ? 'before' : 'after';
748
- const before = event.clientX < box.left + box.width / 2;
749
- return before !== (getComputedStyle(event.currentTarget).direction === 'rtl') ? 'before' : 'after';
750
- }
751
-
752
- function dragProps(key) {
753
- return {
754
- draggable: true,
755
- 'data-dwb-drop': dropTarget?.key === key ? dropTarget.position : undefined,
756
- onDragStart: event => {
757
- dragged.current = key;
758
- event.dataTransfer.effectAllowed = 'move';
759
- event.dataTransfer.setData('application/x-dsh-workspace-browser', key);
760
- },
761
- onDragOver: event => {
762
- if (dragged.current === null || dragged.current === key) {
763
- setDropTarget(null);
764
- return;
765
- }
766
- event.preventDefault();
767
- event.dataTransfer.dropEffect = 'move';
768
- const position = draggedPosition(event);
769
- setDropTarget(previous => previous?.key === key && previous.position === position ? previous : { key, position });
770
- },
771
- onDragLeave: event => {
772
- if (event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget)) return;
773
- setDropTarget(previous => previous?.key === key ? null : previous);
774
- },
775
- onDrop: event => {
776
- const source = dragged.current;
777
- if (source === null || source === key || !entries.has(source)) return;
778
- event.preventDefault();
779
- const position = draggedPosition(event);
780
- const next = keys.filter(item => item !== source);
781
- next.splice(next.indexOf(key) + (position === 'after' ? 1 : 0), 0, source);
782
- savePlacement(folder, (saved = {}) => {
783
- let index = 0;
784
- const order = (saved.order ?? []).map(item => entries.has(item) ? next[index++] : item);
785
- return { ...saved, order: [...order, ...next.slice(index)] };
786
- });
787
- dragged.current = null;
788
- setDropTarget(null);
789
- },
790
- onDragEnd: () => {
791
- dragged.current = null;
792
- setDropTarget(null);
793
- },
794
- };
795
- }
796
-
797
- useLayoutEffect(() => {
798
- const crumbsElement = crumbsRef.current;
799
- crumbsElement.scrollLeft = crumbsElement.scrollWidth;
800
- const list = browserRef.current.closest('[data-dwb-grid]');
801
- if (list) list.scrollTop = 0;
802
- revealCurrentSession();
803
- }, [folder, display]);
804
-
805
- function tile({ key, label, title = label, icon, kind, activate, active, guided, pinned, archived, scheduled, menuTarget, dots, sessionId, runningText, runningCount, subagents }) {
806
- const subagentLabel = subagents ? nativeText(subagents === 1 ? 'status.subagentsRunning.one' : 'status.subagentsRunning.other', { n: subagents }) : undefined;
807
- const countBadge = display === 'icons' && runningCount > 0;
808
- const description = [runningText, subagentLabel, scheduled && t('scheduled'), ...(dots ?? []).map(entry => nativeText(entry.label))].filter(Boolean).join(', ');
809
- return h('li', { key, 'data-dwb-session-id': sessionId, ...dragProps(key) }, h(Button, {
810
- className: 'dwb-tile', title, 'data-dwb-kind': kind,
811
- 'aria-label': label,
812
- 'aria-description': description || undefined,
813
- 'aria-current': active ? 'true' : undefined,
814
- 'data-dwb-guide': guided ? '' : undefined,
815
- 'aria-pressed': kind === 'folder' ? selectedFolder === key : undefined,
816
- ...getTriggerProps(menuTarget),
817
- onClick: event => {
818
- if (kind === 'session' || event.detail === 0) activate();
819
- else setSelectedFolder(key);
820
- },
821
- onDoubleClick: kind === 'folder' ? activate : undefined,
822
- }, h('span', { className: 'dwb-tile-icon', 'aria-hidden': true }, h(icon, { size: display === 'list' ? 16 : 30 })),
823
- h('span', { className: 'dwb-label' }, label),
824
- h('span', { className: 'dwb-tile-status' },
825
- runningText && h('span', {
826
- className: 'dwb-running', 'data-dwb-running-count': countBadge ? '' : undefined, 'aria-hidden': true,
827
- }, countBadge ? runningCount : runningText),
828
- dots?.length > 0 && h(NotificationDots, { entries: dots, translate: nativeText, size: 22 }),
829
- (subagentLabel || scheduled || pinned || archived) && h('span', { className: 'dwb-status-marks' },
830
- subagentLabel && h('span', { className: 'dwb-row-mark', role: 'img', 'aria-label': subagentLabel, title: subagentLabel },
831
- h(StateDot, { state: 'ongoing' })),
832
- scheduled && h(IconClockOutlineRegular, { className: 'dwb-row-mark', size: 14, 'aria-label': t('scheduled'), role: 'img' }),
833
- pinned && h(IconPinFillRegular, { className: 'dwb-row-mark', size: 13, 'aria-label': nativeText('menu.unpin'), role: 'img' }),
834
- archived && h(IconArchiveOutlineRegular, { className: 'dwb-row-mark', size: 13, 'aria-label': t('archived'), role: 'img' })))));
835
- }
836
-
837
- function folderTile(key, label, path) {
838
- const menuTarget = key === ungrouped ? undefined : { kind: 'workspace', value: { workspaceId: key, path, displayTitle: label } };
839
- const count = notifications.runningByFolder.get(key);
840
- const runningText = count ? t(count === 1 ? 'oneRunningSession' : 'runningSessions', { n: count }) : undefined;
841
- return tile({ key: folderKey(key), label, title: path ?? label, icon: FolderIcon, kind: 'folder',
842
- activate: () => visit(key), guided: sessionVisible && key === guideFolder, menuTarget, runningText, runningCount: count, dots: notifications.byFolder.get(key) });
843
- }
844
-
845
- return h('section', { className: 'dwb-browser', 'aria-label': t('panel'), ref: browserRef },
846
- createPortal(h(react.Fragment, null, outside && h(NotificationDots, { entries: [outside], translate: nativeText, size: 22 }),
847
- h('span', { className: 'dwb-heading-name' }, folder === null ? nativeText('section.workspaces') : crumbs.at(-1).label)), heading),
848
- createPortal(h('div', { className: 'dwb-toolbar' },
849
- h(SidebarDivider, { label: t('resize'), toolbar, area, ratio: split, saveRatio: saveSplit }),
850
- h('div', { className: 'dwb-reveal-zone' }),
851
- h('div', { className: 'dwb-nav-buttons dwb-reveal-control' },
852
- h(NavButton, { icon: outside ? undefined : IconChevronLeftOutlineRegular, label: t('back'), disabled: back === undefined, onClick: () => go(back) }),
853
- h(NavButton, { icon: IconChevronRightOutlineRegular, label: t('forward'), disabled: forward === undefined, onClick: () => go(forward) }),
854
- h(NavButton, { icon: IconChevronUpOutlineRegular, label: t('up'), disabled: folder === null, onClick: () => visit(parent) }),
855
- h(NavButton, { icon: LocateIcon, label: t('locate'), disabled: !activeSession || (onlyArchived && !hasActiveTile),
856
- onClick: locateCurrentSession }))), toolbar),
857
- createPortal(h('nav', { className: 'dwb-path dwb-reveal-control', 'aria-label': t('path'), ref: crumbsRef },
858
- h(IconFolderOpenRegular, { size: 16, className: 'dwb-indicator', 'aria-hidden': true }),
859
- crumbs.map(({ key, label, path }, index) => h('span', { className: 'dwb-crumb', key: key === ungrouped ? 'ungrouped' : key ?? 'home' },
860
- index > 0 && h(IconChevronRightOutlineRegular, { size: 12, className: 'dwb-indicator', 'aria-hidden': true }),
861
- index === crumbs.length - 1
862
- ? h('span', { className: 'dwb-current', title: path, 'aria-current': 'location' }, label)
863
- : h(Button, { size: 'sm', title: path, onClick: () => visit(key) }, label)))), address),
864
- h('div', { 'aria-busy': loading },
865
- workspaceState.state === 'error' && h('p', { className: 'dwb-status', role: 'status' }, t('loadError')),
866
- openError && h('p', { className: 'dwb-status', role: 'alert' }, openError === 'archived'
867
- ? nativeText('toast.archivedNotOpenable') : t(openError === 'create' ? 'createError' : 'openError')),
868
- empty && workspaceState.state !== 'error' && h('p', { className: 'dwb-status', role: 'status' },
869
- t(loading ? 'loading' : onlyArchived ? 'noArchives' : folder === null ? 'emptyHome' : 'emptyFolder')),
870
- !empty && h('ul', { className: 'dwb-list', 'data-dwb-display': display },
871
- keys.map(key => {
872
- const item = entries.get(key);
873
- if (item === null) return folderTile(ungrouped, t('ungrouped'));
874
- if (key.startsWith('folder:')) return folderTile(item.workspaceId, workspaceLabel(item), item.path);
875
- const session = item;
876
- const label = session.blank ? nativeText('session.new') : session.title?.trim() || nativeText('session.untitled');
877
- const isArchived = archived.has(session.id);
878
- const activity = notifications.runningBySession.get(session.id);
879
- const active = sessionVisible && activeKey === key;
880
- return tile({ key, sessionId: session.id, label, title: isArchived ? `${label} · ${t('archived')}` : label,
881
- icon: SessionIcon, kind: 'session',
882
- pinned: !isArchived && pinned.has(session.id), archived: isArchived, scheduled: !isArchived && !session.blank && scheduledSessions.has(session.id), active,
883
- runningText: activity?.running ? t('running') : undefined, subagents: activity?.subagents,
884
- dots: notifications.bySession.has(session.id) ? [notifications.bySession.get(session.id)] : undefined,
885
- menuTarget: session.blank ? undefined : { kind: 'session', value: { sessionId: session.id, displayTitle: label } },
886
- activate: () => {
887
- setOpenError(isArchived ? 'archived' : null);
888
- if (!isArchived && !active) openSession(session.id, () => setOpenError('open'));
889
- },
890
- });
891
- }))));
892
- }
893
-
894
- function SidebarExtension({ t, nativeText, workspaceSource, sessionSource, nativeEntry, openSession, startSession, useContextMenu, useSessionStatus, panelSource, scheduleSource, unreadSource }) {
895
- const [preference, setPreference] = useState(readPreference);
896
- const enabled = preference.enabled === true;
897
- const fade = usePageFade();
898
- const [actions] = useState(() => ({
899
- setEnabled: (enabled, list) => {
900
- const update = () => setPreference(previous => ({ ...previous, enabled }));
901
- if (list?.hasAttribute('data-dwb-grid') === enabled) return;
902
- fade(list, update);
903
- },
904
- rememberFolder: folder => setPreference(previous => ({ ...previous, folder })),
905
- setDisplay: display => setPreference(previous => ({ ...previous, display })),
906
- saveSplit: split => setPreference(previous => ({ ...previous, split })),
907
- savePlacement: (folder, update) => setPreference(previous => {
908
- const placements = previous.placements ?? emptyOrder;
909
- const key = pageKey(folder);
910
- return { ...previous, placements: { ...placements, [key]: update(placements[key]) } };
911
- }),
912
- }));
913
- const { grid, list, toolbar, address, header, heading, nativeHeading, trigger, menu, menuMount, menuSeparator, menuLabel, searching, searchOpen, region, area, panel } = useSidebarMounts(nativeText);
914
- const display = preference.display === 'list' ? 'list' : 'icons';
915
- const entry = useSyncExternalStore(nativeEntry.subscribe, nativeEntry.getSnapshot);
916
- const view = useMemo(() => entry?.store?.create() ?? emptyView, [entry]);
917
- const animatePage = update => fade(list, update);
918
-
919
- function openConversation(sessionId, onError) {
920
- const main = document.querySelector('[data-slot="main"]');
921
- fade(main?.parentElement, () => {
922
- try { openSession(sessionId); } catch { onError(); }
923
- });
924
- }
925
-
926
- useEffect(() => { savePreference(preference); }, [preference]);
927
- useLayoutEffect(() => {
928
- if (!grid || !list || !header || !region) return;
929
- const show = enabled && Boolean(trigger);
930
- grid.hidden = !show || searching;
931
- toolbar.hidden = !show;
932
- address.hidden = !show;
933
- heading.hidden = !show;
934
- nativeHeading?.toggleAttribute('data-dwb-replaced-heading', show);
935
- region.toggleAttribute('data-dwb-layout', show);
936
- header.toggleAttribute('data-dwb-header', show);
937
- list.toggleAttribute('data-dwb-grid', show && !searching);
938
- return () => {
939
- region.removeAttribute('data-dwb-layout');
940
- header.removeAttribute('data-dwb-header');
941
- list.removeAttribute('data-dwb-grid');
942
- grid.hidden = true;
943
- toolbar.hidden = true;
944
- address.hidden = true;
945
- heading.hidden = true;
946
- nativeHeading?.removeAttribute('data-dwb-replaced-heading');
947
- };
948
- }, [grid, list, toolbar, address, header, heading, nativeHeading, enabled, trigger, searching, region]);
949
- useLayoutEffect(() => {
950
- region?.toggleAttribute('data-dwb-reveal-held', enabled && Boolean(searchOpen || menu));
951
- return () => region?.removeAttribute('data-dwb-reveal-held');
952
- }, [region, enabled, searchOpen, menu]);
953
- useLayoutEffect(() => {
954
- if (!enabled || !trigger || !header || !toolbar || !address || !region) return;
955
- const sidebar = panel ?? region;
956
- const divider = toolbar.querySelector('.dwb-divider');
957
- if (!divider) return;
958
- const clear = () => region.removeAttribute('data-dwb-reveal-hover');
959
- function update(event) {
960
- if (event.pointerType === 'touch') return;
961
- const { clientX: x, clientY: y } = event;
962
- const { left, right } = sidebar.getBoundingClientRect();
963
- const top = divider.getBoundingClientRect().bottom;
964
- const bottom = address.getBoundingClientRect().bottom;
965
- region.toggleAttribute('data-dwb-reveal-hover', x >= left && x < right && y >= top && y < bottom);
966
- }
967
- window.addEventListener('pointermove', update);
968
- sidebar.addEventListener('pointerleave', clear);
969
- window.addEventListener('blur', clear);
970
- return () => {
971
- window.removeEventListener('pointermove', update);
972
- sidebar.removeEventListener('pointerleave', clear);
973
- window.removeEventListener('blur', clear);
974
- clear();
975
- };
976
- }, [enabled, trigger, header, toolbar, address, region, panel]);
977
- useLayoutEffect(() => {
978
- if (!menu) return;
979
- menu.toggleAttribute('data-dwb-selected', enabled);
980
- return () => menu.removeAttribute('data-dwb-selected');
981
- }, [menu, enabled]);
982
-
983
- useLayoutEffect(() => {
984
- if (!menu || !trigger || !view.actions) return;
985
- const { setGroupBy, setOrderBy, setArchivedFilter } = view.actions;
986
- const select = new Map([
987
- [nativeText('groupBy.workspace'), () => { actions.setEnabled(false, list); setGroupBy('workspace'); }],
988
- [nativeText('groupBy.workspaceTree'), () => { actions.setEnabled(false, list); setGroupBy('workspace-tree'); }],
989
- [nativeText('groupBy.flat'), () => { actions.setEnabled(false, list); setGroupBy('flat'); }],
990
- [nativeText('orderBy.manual'), () => setOrderBy('manual', manualOrders(workspaceSource.getSnapshot(), sessionSource.getSnapshot()))],
991
- [nativeText('orderBy.updated'), () => setOrderBy('updated', {})],
992
- [nativeText('viewOptions.hideArchived'), () => setArchivedFilter('default')],
993
- [nativeText('viewOptions.showArchived'), () => setArchivedFilter('show')],
994
- [nativeText('viewOptions.onlyArchived'), () => setArchivedFilter('only')],
995
- ]);
996
- function selectNative(event) {
997
- const button = event.target instanceof Element && event.target.closest('button[role="menuitem"]');
998
- if (!button || menuMount.contains(button)) return;
999
- const apply = select.get(button.textContent.trim());
1000
- if (!apply) return;
1001
- event.preventDefault();
1002
- event.stopPropagation();
1003
- apply();
1004
- }
1005
- let closing = false;
1006
- function dismissOutside(event) {
1007
- if (closing || menu.contains(event.target) || trigger.contains(event.target)) return;
1008
- closing = true;
1009
- trigger.click();
1010
- }
1011
- menu.addEventListener('click', selectNative, true);
1012
- document.addEventListener('wheel', dismissOutside, { capture: true, passive: true });
1013
- document.addEventListener('contextmenu', dismissOutside, true);
1014
- return () => {
1015
- menu.removeEventListener('click', selectNative, true);
1016
- document.removeEventListener('wheel', dismissOutside, true);
1017
- document.removeEventListener('contextmenu', dismissOutside, true);
1018
- };
1019
- }, [menu, trigger, menuMount, view, actions, list, nativeText, workspaceSource, sessionSource]);
1020
-
1021
- function menuItem(label, src, current, select) {
1022
- const icon = h('img', { className: 'dwb-menu-icon', src, alt: '', width: 16, height: 16, draggable: false });
1023
- return h(MenuItemButton, { current, icon, onSelect: select },
1024
- h('span', { className: 'dwb-menu-label' }, t(label), current && h(IconCheckOutlineRegular, { size: 14, 'aria-hidden': true })));
1025
- }
1026
-
1027
- return h(react.Fragment, null,
1028
- menu && createPortal(h(react.Fragment, null,
1029
- menuItem('panel', menuFolderIcon, enabled, () => actions.setEnabled(true, list)),
1030
- enabled && h(react.Fragment, null,
1031
- h('div', { role: 'separator', className: menuSeparator?.className }),
1032
- h('div', { role: 'presentation', className: menuLabel?.className }, t('display')),
1033
- menuItem('icons', largeIconsMenuIcon, display === 'icons', () => {
1034
- if (display !== 'icons') animatePage(() => actions.setDisplay('icons'));
1035
- }),
1036
- menuItem('list', listMenuIcon, display === 'list', () => {
1037
- if (display !== 'list') animatePage(() => actions.setDisplay('list'));
1038
- }),
1039
- )), menuMount),
1040
- enabled && grid && createPortal(h(Browser, {
1041
- t, nativeText, workspaceSource, sessionSource, view, openSession: openConversation, toolbar, address, heading, area, panel, display, animatePage, useContextMenu, useSessionStatus,
1042
- split: !trigger ? null : preference.split, saveSplit: actions.saveSplit,
1043
- startSession, placements: preference.placements, savePlacement: actions.savePlacement, panelSource, scheduleSource, unreadSource,
1044
- startFolder: typeof preference.folder === 'string' ? preference.folder : null, rememberFolder: actions.rememberFolder,
1045
- }), grid));
1046
- }
1047
-
1048
- function apply(ctx) {
1049
- const nativeText = ctx.locale.bind('workspace');
1050
- const slots = ctx.slots;
1051
- ctx.effect(() => ctx.locale.register(id, dictionaries));
1052
- ctx.effect(() => {
1053
- const style = document.createElement('style');
1054
- style.textContent = css;
1055
- document.head.append(style);
1056
- return () => style.remove();
1057
- });
1058
- const workspaces = ctx.workspaces.list;
1059
- const sessions = ctx.sessions.list;
1060
- const navigation = ctx.uiWorkspace;
1061
- const panel = ctx.layout.panelInfo;
1062
- const panelSource = { subscribe: listener => panel.subscribe(listener), getSnapshot: () => panel.getSnapshot() };
1063
- const workspaceSource = { subscribe: listener => workspaces.subscribe(listener), getSnapshot: () => workspaces.getSnapshot() };
1064
- const sessionSource = { subscribe: listener => sessions.subscribe(listener), getSnapshot: () => sessions.getSnapshot() };
1065
- const nativeEntry = {
1066
- subscribe: listener => slots.subscribe('sidebar.workspaces', listener),
1067
- getSnapshot: () => slots.entries('sidebar.workspaces').find(entry => entry.locale === 'workspace' && entry.store),
1068
- };
1069
- const scheduleSource = scheduleSourceFor(ctx);
1070
- const unreadSource = completionSource(ctx);
1071
- slots.inject('shell.overlay', () => slots.register({
1072
- name: 'shell.overlay', id, locale: id,
1073
- inject: () => ({
1074
- nativeText, workspaceSource, sessionSource, nativeEntry, panelSource, scheduleSource, unreadSource,
1075
- openSession: sessionId => navigation.openSession(sessionId),
1076
- startSession: (workspaceId, onCreated) => {
1077
- const snapshot = sessions.getSnapshot();
1078
- const target = workspaceId ?? workspaces.getSnapshot().items.reduce((recent, item) => {
1079
- const latest = item.sessionIds.reduce((time, id) => Math.max(time, snapshot.byId[id]?.updatedAt ?? -Infinity), -Infinity);
1080
- const activity = latest === -Infinity ? Date.parse(item.createdAt) : latest;
1081
- return !recent || activity > recent.activity ? { workspaceId: item.workspaceId, activity } : recent;
1082
- }, undefined)?.workspaceId;
1083
- return target === undefined ? Promise.resolve() : navigation.openWorkspace(target, onCreated);
1084
- },
1085
- }),
1086
- }, SidebarExtension));
1087
- }
1
+ const { createElement: h, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } = react;
2
+ const {
3
+ Button, MenuItemButton, StateDot, IconCheckOutlineRegular, IconChevronLeftOutlineRegular, IconChevronRightOutlineRegular,
4
+ IconChevronUpOutlineRegular, IconFolderOpenRegular,
5
+ IconPinFillRegular, IconArchiveOutlineRegular, IconClockOutlineRegular,
6
+ } = ui;
7
+
8
+ const inject = ['slots', 'locale', 'workspaces', 'sessions', 'uiSession', 'uiWorkspace', 'layout', 'remote', 'remote.schedule'];
9
+ const ungrouped = '';
10
+ const defaultOptions = {};
11
+ const emptyView = { getSnapshot: () => defaultOptions, subscribe: () => () => {} };
12
+ const preferenceKey = `${id}.sidebar`;
13
+ const unreadKey = preferenceKey + '.unread';
14
+ const emptyPlacements = {};
15
+ const emptySchedule = { records: [] };
16
+ function scheduleSourceFor(ctx) {
17
+ let snapshot = emptySchedule;
18
+ let revision = 0;
19
+ return {
20
+ getSnapshot: () => snapshot,
21
+ subscribe(listener) {
22
+ async function refresh() {
23
+ const request = ++revision;
24
+ try {
25
+ const result = await ctx.remote.schedule.catalog();
26
+ if (request !== revision || !result.ok) return;
27
+ snapshot = { records: result.value };
28
+ listener();
29
+ } catch {
30
+ // A later catalog change or reconnect retries the read.
31
+ }
32
+ }
33
+ const stopChanged = ctx.remote.$on('schedule/changed', refresh);
34
+ const stopReset = ctx.on('connection/reset', refresh);
35
+ refresh();
36
+ return () => {
37
+ revision++;
38
+ stopChanged();
39
+ stopReset();
40
+ };
41
+ },
42
+ };
43
+ }
44
+ const folderKey = key => 'folder:' + key;
45
+ const sessionKey = key => 'session:' + key;
46
+ const pageKey = folder => folder === null ? 'home' : folderKey(folder);
47
+
48
+ // The native new-session button carries no stable attribute, so it is recognised
49
+ // by its own new-chat glyph or by a shortcut, minus the sidebar toggles and
50
+ // everything inside the workspaces region (add workspace also has a shortcut).
51
+ function isNewSessionButton(button) {
52
+ if (!button || button.disabled) return false;
53
+ if (button.closest('[data-sidebar-toggle], [data-sidebar-opener], [data-slot="sidebar.workspaces"]')) return false;
54
+ return Boolean(button.querySelector('[data-icon^="dsw-icon-new-chat"]')) || button.hasAttribute('aria-keyshortcuts');
55
+ }
56
+
57
+ function getNewSessionButton(event) {
58
+ const button = event.target instanceof Element ? event.target.closest('button') : null;
59
+ return isNewSessionButton(button) && button.closest('[data-slot="sidebar"]') ? button : null;
60
+ }
61
+
62
+ const dictionaries = {
63
+ zh: {
64
+ panel: '文件夹浏览', home: '主页', path: '工作区路径', back: '后退', forward: '前进', up: '上一级',
65
+ ungrouped: '未分组会话', locate: '回到当前会话', createError: '暂时无法新建会话。',
66
+ loading: '正在加载…', loadError: '暂时无法读取工作区。', openError: '暂时无法打开此会话。',
67
+ emptyHome: '还没有工作区。', emptyFolder: '此工作区没有子工作区或会话。', noArchives: '没有已归档会话。',
68
+ archived: '已归档会话', scheduled: '有定时任务', running: '运行中', oneRunningSession: '1 个会话运行中', runningSessions: '{n} 个会话运行中',
69
+ gestureUp: '返回上一级', gestureInvalid: '无效手势',
70
+ display: '视图选项', icons: '大图标', list: '列表', resize: '调整工作区分隔位置',
71
+ },
72
+ en: {
73
+ panel: 'Browse folders', home: 'Home', path: 'Workspace path', back: 'Back', forward: 'Forward', up: 'Up one level',
74
+ ungrouped: 'Ungrouped sessions', locate: 'Go to current session', createError: 'Could not start a new session.',
75
+ loading: 'Loading…', loadError: 'Could not load workspaces.', openError: 'Could not open this session.',
76
+ emptyHome: 'No workspaces yet.', emptyFolder: 'No child workspaces or sessions in this workspace.',
77
+ noArchives: 'No archived sessions.', archived: 'Archived session', scheduled: 'Has scheduled tasks', running: 'Running',
78
+ runningSessions: '{n} sessions running', oneRunningSession: '1 session running',
79
+ gestureUp: 'Up one level', gestureInvalid: 'Invalid gesture',
80
+ display: 'View options', icons: 'Large icons', list: 'List', resize: 'Resize workspace area',
81
+ },
82
+ };
83
+
84
+ function workspacePath(path) {
85
+ const windows = /^[A-Za-z]:[/\\]/.test(path) || path.startsWith('\\\\');
86
+ const normalized = (windows ? path.replaceAll('\\', '/') : path).replace(/\/+$/, '');
87
+ return { normalized, folded: windows ? normalized.toLowerCase() : undefined };
88
+ }
89
+
90
+ function workspaceTree(items) {
91
+ const byId = new Map(items.map(item => [item.workspaceId, item]));
92
+ const paths = new Map(items.map(item => [item.path, item.workspaceId]));
93
+ const folders = [...paths].map(([path, id]) => ({ ...workspacePath(path), id }));
94
+ const parents = new Map();
95
+ const children = new Map();
96
+ for (const item of items) {
97
+ const child = workspacePath(item.path);
98
+ let parent = null;
99
+ let length = -1;
100
+ let exactParent = false;
101
+ for (const folder of folders) {
102
+ if (folder.normalized.length >= child.normalized.length || folder.normalized.length < length) continue;
103
+ const exact = child.normalized.startsWith(`${folder.normalized}/`);
104
+ const folded = folder.folded !== undefined && child.folded?.startsWith(`${folder.folded}/`);
105
+ if ((!exact && !folded) || (folder.normalized.length === length && (exactParent || !exact))) continue;
106
+ parent = folder.id;
107
+ length = folder.normalized.length;
108
+ exactParent = exact;
109
+ }
110
+ parents.set(item.workspaceId, parent);
111
+ if (!children.has(parent)) children.set(parent, []);
112
+ children.get(parent).push(item);
113
+ }
114
+ return { byId, parents, children };
115
+ }
116
+
117
+ /* The order that is on screen right now, per account: the native store freezes exactly this into manual mode. */
118
+ function displayedOrders(workspaceState, sessions, options) {
119
+ const { byId, ids } = sessions;
120
+ const archived = new Set(workspaceState.archivedSessionIds);
121
+ const pinned = new Set(workspaceState.pinnedSessionIds);
122
+ const assigned = new Set(workspaceState.items.flatMap(workspace => workspace.sessionIds));
123
+ const rank = session => session.blank ? 0 : pinned.has(session.id) && !archived.has(session.id) ? 1 : 2;
124
+ const order = (members, account) => {
125
+ const manual = options.orderBy === 'manual';
126
+ const stored = new Map((manual ? options.sessionOrderByAccount?.[account] ?? [] : []).map((id, index) => [id, index]));
127
+ return members.map(id => byId[id]).filter(session => session && session.origin !== 'subagent').sort((a, b) => rank(a) - rank(b)
128
+ || (stored.get(a.id) ?? Infinity) - (stored.get(b.id) ?? Infinity)
129
+ || (manual ? Number(archived.has(a.id)) - Number(archived.has(b.id)) : 0)
130
+ || b.updatedAt - a.updatedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)).map(session => session.id);
131
+ };
132
+ return Object.fromEntries([
133
+ ...workspaceState.items.map(workspace => [workspace.workspaceId, order(workspace.sessionIds, workspace.workspaceId)]),
134
+ [ungrouped, order(ids.filter(id => !assigned.has(id)), ungrouped)],
135
+ ['__flat_session_order__', order(ids, '__flat_session_order__')],
136
+ ]);
137
+ }
138
+
139
+ function sessionRows(workspaceState, sessions, options) {
140
+ const { byId, ids } = sessions;
141
+ const archived = new Set(workspaceState.archivedSessionIds);
142
+ const pinned = new Set(workspaceState.pinnedSessionIds);
143
+ const assigned = new Set(workspaceState.items.flatMap(workspace => workspace.sessionIds));
144
+ const filter = options.archivedFilter ?? 'default';
145
+ const visible = session => session && session.origin !== 'subagent' && (!session.blank || session.retainedBy?.mainView > 0)
146
+ && (filter === 'show' || (filter === 'only') === archived.has(session.id));
147
+ const sorted = (members, account) => {
148
+ const manual = options.orderBy === 'manual';
149
+ const order = new Map((manual ? options.sessionOrderByAccount?.[account] ?? [] : []).map((id, index) => [id, index]));
150
+ const rank = session => session.blank ? 0 : pinned.has(session.id) && !archived.has(session.id) ? 1 : 2;
151
+ return members.map(id => byId[id]).filter(visible).sort((a, b) => rank(a) - rank(b)
152
+ || (order.get(a.id) ?? Infinity) - (order.get(b.id) ?? Infinity)
153
+ || (manual ? Number(archived.has(a.id)) - Number(archived.has(b.id)) : 0)
154
+ || b.updatedAt - a.updatedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
155
+ };
156
+ const byWorkspace = new Map(workspaceState.items.map(workspace => [workspace.workspaceId, sorted(workspace.sessionIds, workspace.workspaceId)]));
157
+ byWorkspace.set(ungrouped, sorted(ids.filter(id => !assigned.has(id)), ungrouped));
158
+ return { byWorkspace, pinned, archived };
159
+ }
160
+
161
+ /* Mirrors the native tree: one pinned section at a time, and the blank session stays where the sort puts it. */
162
+ function sessionDragOrder(order, rows, drag, over, isPinned) {
163
+ const source = rows.find(row => row.id === drag.id);
164
+ const target = rows.find(row => row.id === over.id);
165
+ if (!source || !target || source.blank) return undefined;
166
+ if (isPinned(source.id) !== drag.pinned || isPinned(target.id) !== drag.pinned) return undefined;
167
+ if (source.id === target.id || !order.includes(source.id)) return undefined;
168
+ const section = rows.filter(row => isPinned(row.id) === drag.pinned);
169
+ const sourceIndex = section.findIndex(row => row.id === source.id);
170
+ const targetIndex = section.filter(row => row.id !== source.id).findIndex(row => row.id === target.id);
171
+ if (targetIndex + (over.side === 'after' ? 1 : 0) === sourceIndex) return undefined;
172
+ const next = order.filter(id => id !== source.id);
173
+ const index = next.indexOf(target.id);
174
+ if (index === -1) return undefined;
175
+ next.splice(index + (over.side === 'after' ? 1 : 0), 0, source.id);
176
+ return next;
177
+ }
178
+
179
+ const statusDetails = {
180
+ approval: { state: 'error', label: 'status.waitingApproval', priority: 3 },
181
+ question: { state: 'warning', label: 'status.waitingAnswer', priority: 2 },
182
+ 'plan-review': { state: 'warning', label: 'status.planReview', priority: 2 },
183
+ completed: { state: 'done', label: 'status.completed', priority: 1 },
184
+ };
185
+
186
+ function completionSource(ctx) {
187
+ const list = ctx.sessions.list;
188
+ const status = ctx.uiSession.sessionStatus;
189
+ const panel = ctx.layout.panelInfo;
190
+ const listeners = new Set();
191
+ const persistedIds = value => Array.isArray(value) ? value.filter(id => typeof id === 'string') : [];
192
+ let unread = new Set();
193
+ let awaitingInteraction = new Set();
194
+ try {
195
+ const saved = JSON.parse(localStorage.getItem(unreadKey));
196
+ unread = new Set(persistedIds(Array.isArray(saved) ? saved : saved?.unread));
197
+ awaitingInteraction = new Set(persistedIds(saved?.awaitingInteraction).filter(id => unread.has(id)));
198
+ } catch { /* Storage may be unavailable. */ }
199
+
200
+ let previous = new Map();
201
+ let previousTaskbarStatus = status.getSnapshot();
202
+ const pendingWhileAway = new Map();
203
+ const completedWhileAway = new Set();
204
+ const taskbar = window.dshDesktop?.taskbar;
205
+ let taskbarColor;
206
+ const hasAttention = () => document.visibilityState !== 'hidden' && document.hasFocus();
207
+
208
+ function save(next, protectedIds = awaitingInteraction) {
209
+ const changed = next.size !== unread.size || [...next].some(id => !unread.has(id));
210
+ const protectionChanged = protectedIds.size !== awaitingInteraction.size
211
+ || [...protectedIds].some(id => !awaitingInteraction.has(id));
212
+ if (!changed && !protectionChanged) return;
213
+ if (changed) unread = next;
214
+ awaitingInteraction = protectedIds;
215
+ try {
216
+ localStorage.setItem(unreadKey, JSON.stringify({ unread: [...unread], awaitingInteraction: [...awaitingInteraction] }));
217
+ } catch { /* Keep the in-memory state. */ }
218
+ if (changed) for (const listener of listeners) listener();
219
+ }
220
+
221
+ function updateTaskbar(sessions, statuses, focused) {
222
+ if (!taskbar?.setReminder) return;
223
+ if (focused) {
224
+ pendingWhileAway.clear();
225
+ completedWhileAway.clear();
226
+ }
227
+ const archived = new Set(ctx.workspaces.list.getSnapshot().archivedSessionIds);
228
+ let priority = 0;
229
+ if (!focused) for (const [id, state] of statuses) {
230
+ const session = sessions.byId[id];
231
+ if (!session || session.blank || session.origin === 'subagent' || archived.has(id)) {
232
+ pendingWhileAway.delete(id);
233
+ completedWhileAway.delete(id);
234
+ continue;
235
+ }
236
+ const before = previousTaskbarStatus.get(id);
237
+ const pending = state.pendingInteraction;
238
+ const previousPending = before?.pendingInteraction;
239
+ const pendingPriority = statusDetails[pending?.kind]?.priority ?? 0;
240
+ if (!pendingPriority) pendingWhileAway.delete(id);
241
+ else if (pending.kind !== previousPending?.kind || pending.key !== previousPending?.key) {
242
+ pendingWhileAway.set(id, pendingPriority);
243
+ }
244
+ if (state.running) completedWhileAway.delete(id);
245
+ else if (before?.running === true || (state.completionUnread && !before?.completionUnread)) completedWhileAway.add(id);
246
+ priority = Math.max(priority, pendingWhileAway.get(id) ?? 0, completedWhileAway.has(id) ? 1 : 0);
247
+ }
248
+ previousTaskbarStatus = statuses;
249
+ const color = ['normal', 'green', 'yellow', 'red'][priority];
250
+ if (color === taskbarColor) return;
251
+ taskbarColor = color;
252
+ taskbar.setReminder(color);
253
+ }
254
+
255
+ function sync() {
256
+ const sessions = list.getSnapshot();
257
+ const statuses = status.getSnapshot();
258
+ const focused = hasAttention();
259
+ const conversationVisible = panel.getSnapshot().activePanelId === null;
260
+ const next = new Set(unread);
261
+ const protectedIds = new Set(awaitingInteraction);
262
+ for (const [id, state] of statuses) {
263
+ const before = previous.get(id);
264
+ const session = sessions.byId[id];
265
+ if (!session) continue;
266
+ if (!focused && before?.running === true && state.running === false) {
267
+ next.add(id);
268
+ if (session.retainedBy?.mainView > 0) protectedIds.add(id);
269
+ } else if (state.completionUnread && !before?.completionUnread) {
270
+ next.add(id);
271
+ }
272
+ }
273
+ previous = statuses;
274
+ for (const id of next) {
275
+ const session = sessions.byId[id];
276
+ const removed = !session && sessions.phase === 'ready';
277
+ const read = focused && conversationVisible && session?.retainedBy?.mainView > 0 && !protectedIds.has(id);
278
+ if (!removed && !read) continue;
279
+ next.delete(id);
280
+ protectedIds.delete(id);
281
+ }
282
+ save(next, protectedIds);
283
+ updateTaskbar(sessions, statuses, focused);
284
+ }
285
+
286
+ function acknowledgeCurrent(event) {
287
+ if (!event.isTrusted || !hasAttention() || panel.getSnapshot().activePanelId !== null) return;
288
+ if (!(event.target instanceof Element) || !event.target.closest('[data-slot="main"]')) return;
289
+ const active = Object.values(list.getSnapshot().byId).find(session => session.retainedBy?.mainView > 0);
290
+ if (!active || !unread.has(active.id)) return;
291
+ const next = new Set(unread);
292
+ const protectedIds = new Set(awaitingInteraction);
293
+ next.delete(active.id);
294
+ protectedIds.delete(active.id);
295
+ save(next, protectedIds);
296
+ }
297
+
298
+ ctx.effect(() => {
299
+ const stops = [status.subscribe(sync), list.subscribe(sync), panel.subscribe(sync), ctx.workspaces.list.subscribe(sync)];
300
+ window.addEventListener('focus', sync);
301
+ window.addEventListener('blur', sync);
302
+ document.addEventListener('visibilitychange', sync);
303
+ document.addEventListener('pointerdown', acknowledgeCurrent, true);
304
+ document.addEventListener('drop', acknowledgeCurrent, true);
305
+ sync();
306
+ return () => {
307
+ stops.forEach(stop => stop());
308
+ taskbar?.setReminder?.('normal');
309
+ window.removeEventListener('focus', sync);
310
+ window.removeEventListener('blur', sync);
311
+ document.removeEventListener('visibilitychange', sync);
312
+ document.removeEventListener('pointerdown', acknowledgeCurrent, true);
313
+ document.removeEventListener('drop', acknowledgeCurrent, true);
314
+ };
315
+ });
316
+ return {
317
+ getSnapshot: () => unread,
318
+ subscribe(listener) {
319
+ listeners.add(listener);
320
+ return () => listeners.delete(listener);
321
+ },
322
+ };
323
+ }
324
+
325
+ function workspaceNotifications(workspaces, sessions, statuses, parents, archived, unread) {
326
+ const owners = new Map();
327
+ for (const workspace of workspaces) {
328
+ for (const sessionId of workspace.sessionIds) owners.set(sessionId, workspace.workspaceId);
329
+ }
330
+ const bySession = new Map();
331
+ const byFolder = new Map();
332
+ const runningBySession = new Map();
333
+ const runningByFolder = new Map();
334
+ for (const id of sessions.ids) {
335
+ const session = sessions.byId[id];
336
+ if (!session || session.blank || session.origin === 'subagent' || archived.has(id)) continue;
337
+ const running = (statuses.get(id)?.running ?? session.running) === true;
338
+ const subagents = sessions.projectionsBySession?.[id]?.values?.subagentCatalog?.filter(child =>
339
+ (statuses.get(child.id)?.running ?? sessions.byId[child.id]?.running) === true).length ?? 0;
340
+ if (running || subagents > 0) runningBySession.set(id, { running, subagents });
341
+ if (!running) continue;
342
+ for (let folder = owners.get(id) ?? ungrouped; folder !== null; folder = parents.get(folder) ?? null) {
343
+ runningByFolder.set(folder, (runningByFolder.get(folder) ?? 0) + 1);
344
+ }
345
+ }
346
+ const all = [];
347
+ for (const sessionId of sessions.ids) {
348
+ const session = sessions.byId[sessionId];
349
+ if (!session || session.blank || session.origin === 'subagent' || archived.has(sessionId)) continue;
350
+ const detail = statusDetails[statuses.get(sessionId)?.pendingInteraction?.kind]
351
+ ?? (unread.has(sessionId) && !runningBySession.has(sessionId) ? statusDetails.completed : undefined);
352
+ if (!detail) continue;
353
+ const notification = { ...detail, sessionId };
354
+ bySession.set(sessionId, notification);
355
+ all.push(notification);
356
+ for (let folder = owners.get(sessionId) ?? ungrouped; folder !== null; folder = parents.get(folder) ?? null) {
357
+ if (!byFolder.has(folder)) byFolder.set(folder, []);
358
+ byFolder.get(folder).push(notification);
359
+ }
360
+ }
361
+ for (const notifications of byFolder.values()) notifications.sort((a, b) => b.priority - a.priority);
362
+ return { bySession, byFolder, all, runningBySession, runningByFolder };
363
+ }
364
+
365
+ function NotificationDots({ entries, translate, size }) {
366
+ return h('span', { className: 'dwb-notifications' }, entries.map(entry => {
367
+ const label = translate(entry.label);
368
+ return h('span', { key: entry.sessionId, role: 'img', 'aria-label': label, title: label,
369
+ className: 'dwb-notification', 'data-dwb-notification': entry.state }, h(StateDot, { state: entry.state, size }));
370
+ }));
371
+ }
372
+
373
+ function readPreference() {
374
+ try { return JSON.parse(localStorage.getItem(preferenceKey)) ?? {}; }
375
+ catch { return {}; }
376
+ }
377
+
378
+ function savePreference(value) {
379
+ try { localStorage.setItem(preferenceKey, JSON.stringify(value)); }
380
+ catch { /* The view can still be used without storage. */ }
381
+ }
382
+
383
+ function usePageFade() {
384
+ const running = useRef(new Map());
385
+ useEffect(() => () => {
386
+ for (const animation of running.current.values()) animation.cancel();
387
+ running.current.clear();
388
+ }, []);
389
+
390
+ const [fade] = useState(() => async (element, update) => {
391
+ if (!element?.isConnected || matchMedia('(prefers-reduced-motion: reduce)').matches) {
392
+ update();
393
+ return;
394
+ }
395
+ const animations = running.current;
396
+ const opacity = getComputedStyle(element).opacity;
397
+ animations.get(element)?.cancel();
398
+ const outgoing = element.animate([{ opacity }, { opacity: 0 }], { duration: 42.5, easing: 'ease-out', fill: 'forwards' });
399
+ animations.set(element, outgoing);
400
+ try {
401
+ await outgoing.finished;
402
+ if (animations.get(element) !== outgoing || !element.isConnected) return;
403
+ flushSync(update);
404
+ const incoming = element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 67.5, easing: 'ease-in-out' });
405
+ outgoing.cancel();
406
+ animations.set(element, incoming);
407
+ await incoming.finished;
408
+ if (animations.get(element) === incoming) animations.delete(element);
409
+ } catch (error) {
410
+ if (error.name !== 'AbortError') console.warn(`${id}: page transition failed`, error);
411
+ } finally {
412
+ if (animations.get(element) === outgoing) {
413
+ outgoing.cancel();
414
+ animations.delete(element);
415
+ }
416
+ }
417
+ });
418
+ return fade;
419
+ }
420
+
421
+ // Slot wrappers use `display: contents` and own no box, so climb past them
422
+ // before reading a container's geometry.
423
+ function containerOf(node) {
424
+ let current = node ?? null;
425
+ while (current && current !== document.body && getComputedStyle(current).display === 'contents') {
426
+ current = current.parentElement;
427
+ }
428
+ return current && current !== document.body ? current : null;
429
+ }
430
+
431
+ // The host has no grouping-item slot. Walk down from the one stable anchor
432
+ // (`[data-slot="sidebar.workspaces"]`) and read the browser's own boxes by
433
+ // position: our mounts are known by class, the header is the first native child
434
+ // of the region and the list is the last one.
435
+ function useSidebarMounts(nativeText) {
436
+ const [mounts, setMounts] = useState({});
437
+ useLayoutEffect(() => {
438
+ const grid = document.createElement('div');
439
+ grid.className = 'dwb-mount';
440
+ grid.hidden = true;
441
+ const toolbar = document.createElement('div');
442
+ toolbar.className = 'dwb-toolbar-mount';
443
+ toolbar.hidden = true;
444
+ const address = document.createElement('div');
445
+ address.className = 'dwb-address-mount';
446
+ address.hidden = true;
447
+ const heading = document.createElement('span');
448
+ heading.className = 'dwb-heading';
449
+ heading.hidden = true;
450
+ const menuMount = document.createElement('div');
451
+ menuMount.className = 'dwb-menu-mount';
452
+ let active;
453
+ let workspace;
454
+ let frame = 0;
455
+
456
+ function sync() {
457
+ workspace = document.querySelector('[data-slot="sidebar.workspaces"]');
458
+ const region = containerOf(workspace?.firstElementChild);
459
+ const area = containerOf(region?.parentElement);
460
+ const scrollport = containerOf(area?.parentElement);
461
+ const panel = scrollport?.matches('[data-sidebar-scrollport]')
462
+ ? scrollport.closest('[class*="_sidebarCol"]') ?? scrollport
463
+ : scrollport;
464
+ const natives = region
465
+ ? [...region.children].filter(child => ![...child.classList].some(name => name.startsWith('dwb-')))
466
+ : [];
467
+ const header = natives.length > 1 ? natives[0] : null;
468
+ const list = natives.length > 1 ? natives[natives.length - 1] : null;
469
+ const trigger = [...header?.querySelectorAll('button[aria-label]') ?? []]
470
+ .find(button => button.getAttribute('aria-label') === nativeText('viewOptions.label'));
471
+ const searchButton = header?.querySelector('button[aria-expanded]') ?? null;
472
+ const searchInput = header?.querySelector('input[type="text"], input[type="search"]') ?? null;
473
+ // The native title sits immediately before the search control.
474
+ const title = searchButton?.parentElement?.parentElement?.previousElementSibling ?? null;
475
+ const nativeHeading = title?.matches('span:not(.dwb-heading)') ? title : null;
476
+ // The popup is recognised by the grouping rows it is the only menu to list
477
+ // (the same localized strings the trigger is found by), so the body-level
478
+ // workspace context menu -- a menu too, with other rows -- never adopts us.
479
+ const groupLabels = ['groupBy.workspace', 'groupBy.workspaceTree', 'groupBy.flat'].map(key => {
480
+ try {
481
+ return nativeText(key);
482
+ } catch {
483
+ return null;
484
+ }
485
+ });
486
+ let menu = active?.menu?.isConnected ? active.menu : null;
487
+ if (!menu) {
488
+ const menus = [...document.body.querySelectorAll(':scope > [role="menu"]:not([data-context-menu])')];
489
+ menu = menus.reverse().find(node => [...node.querySelectorAll('button[role="menuitem"]')]
490
+ .some(row => !menuMount.contains(row) && groupLabels.includes(row.textContent?.trim()))) ?? null;
491
+ }
492
+ // Our own separator lives inside the mount, so skip it and take the first
493
+ // native one: every grouping row precedes it and nothing else does.
494
+ const menuSeparator = menu
495
+ ? [...menu.querySelectorAll('[role="separator"]')].find(node => !menuMount.contains(node)) ?? null
496
+ : null;
497
+ const groupRows = menu && menuSeparator
498
+ ? [...menu.querySelectorAll('button[role="menuitem"]')].filter(row => !menuMount.contains(row)
499
+ && Boolean(menuSeparator.compareDocumentPosition(row) & Node.DOCUMENT_POSITION_PRECEDING))
500
+ : [];
501
+ const lastGroup = groupRows.length > 0 ? groupRows[groupRows.length - 1].parentElement : null;
502
+ const menuBody = groupRows.length > 0 ? groupRows[0].parentElement?.parentElement ?? null : null;
503
+ const label = menuSeparator?.nextElementSibling ?? null;
504
+ const menuLabel = label?.getAttribute('role') === 'presentation' ? label : null;
505
+
506
+ if (trigger && header && list) {
507
+ if (toolbar.nextElementSibling !== header) header.before(toolbar);
508
+ if (header.nextElementSibling !== address) header.after(address);
509
+ if (grid.parentElement !== list) list.prepend(grid);
510
+ } else {
511
+ toolbar.remove();
512
+ address.remove();
513
+ grid.remove();
514
+ }
515
+ if (nativeHeading) {
516
+ if (heading.nextElementSibling !== nativeHeading) nativeHeading.before(heading);
517
+ } else heading.remove();
518
+ if (lastGroup) {
519
+ groupRows.forEach(row => row.classList.add('dwb-native-group'));
520
+ if (lastGroup.nextElementSibling !== menuMount) lastGroup.after(menuMount);
521
+ } else menuMount.remove();
522
+ const searchOpen = searchButton?.getAttribute('aria-expanded') === 'true';
523
+ const searching = Boolean(searchOpen && searchInput?.value.trim());
524
+ const next = { grid, list, toolbar, address, header, heading, nativeHeading, trigger, menu, menuMount, menuSeparator, menuLabel, groupRows, searching, searchOpen, region, area, panel, menuBody };
525
+ const changed = active?.menu !== menu || active?.list !== list || active?.header !== header
526
+ || active?.nativeHeading !== nativeHeading || active?.trigger !== trigger || active?.searching !== searching
527
+ || active?.searchOpen !== searchOpen || active?.region !== region || active?.area !== area
528
+ || active?.panel !== panel || active?.menuBody !== menuBody;
529
+ active = next;
530
+ if (changed) setMounts(next);
531
+ }
532
+
533
+ function schedule() {
534
+ if (frame) return;
535
+ frame = requestAnimationFrame(() => { frame = 0; sync(); });
536
+ }
537
+
538
+ const observer = new MutationObserver(records => {
539
+ if (!workspace?.isConnected || records.some(record =>
540
+ workspace.contains(record.target) || active?.menu?.contains(record.target)
541
+ || (record.target === document.body && [...record.addedNodes, ...record.removedNodes]
542
+ .some(node => node instanceof Element && node.matches('[role="menu"]'))))) schedule();
543
+ });
544
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-expanded', 'aria-label'] });
545
+ document.addEventListener('input', schedule);
546
+ sync();
547
+ return () => {
548
+ observer.disconnect();
549
+ cancelAnimationFrame(frame);
550
+ document.removeEventListener('input', schedule);
551
+ grid.remove();
552
+ toolbar.remove();
553
+ address.remove();
554
+ heading.remove();
555
+ menuMount.remove();
556
+ };
557
+ }, [nativeText]);
558
+ return mounts;
559
+ }
560
+
561
+ function NavButton({ icon, label, disabled, onClick }) {
562
+ return h(Button, {
563
+ size: 'sm', className: 'dwb-nav-button', icon: icon && h(icon, { size: 16, 'aria-hidden': true }),
564
+ title: label, 'aria-label': label, disabled, onClick,
565
+ });
566
+ }
567
+
568
+ function LocateIcon({ size }) {
569
+ return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': true,
570
+ stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round' },
571
+ h('circle', { cx: 12, cy: 12, r: 7 }),
572
+ h('path', { d: 'M12 2v4m0 12v4M2 12h4m12 0h4' }),
573
+ h('circle', { cx: 12, cy: 12, r: 1.5, fill: 'currentColor', stroke: 'none' }));
574
+ }
575
+
576
+ function SidebarDivider({ label, toolbar, area, ratio, saveRatio }) {
577
+ const drag = useRef(null);
578
+ // The region area owns the navigation list right above it.
579
+ const navigation = area?.previousElementSibling ?? null;
580
+ const upper = navigation?.matches('nav') ? navigation : null;
581
+
582
+ function maximum() {
583
+ const viewport = upper.parentElement;
584
+ return Math.max(0, viewport.getBoundingClientRect().bottom - upper.getBoundingClientRect().top - 138);
585
+ }
586
+
587
+ useLayoutEffect(() => {
588
+ if (!upper || !Number.isFinite(ratio)) return;
589
+ const resize = () => upper.style.setProperty('--dwb-navigation-height', `${Math.round(ratio * maximum())}px`);
590
+ upper.setAttribute('data-dwb-resized-navigation', '');
591
+ const observer = new ResizeObserver(resize);
592
+ observer.observe(upper.parentElement);
593
+ resize();
594
+ return () => {
595
+ observer.disconnect();
596
+ upper.removeAttribute('data-dwb-resized-navigation');
597
+ upper.style.removeProperty('--dwb-navigation-height');
598
+ };
599
+ }, [upper, ratio]);
600
+
601
+ function resize(height) {
602
+ const available = maximum();
603
+ if (available > 0) saveRatio(Math.max(0, Math.min(1, height / available)));
604
+ }
605
+
606
+ return h('div', {
607
+ className: 'dwb-divider',
608
+ ...(upper && {
609
+ role: 'separator', 'aria-label': label, 'aria-orientation': 'horizontal', tabIndex: 0,
610
+ 'aria-valuenow': Math.round((ratio ?? Math.min(1, upper.offsetHeight / Math.max(1, maximum()))) * 100),
611
+ onPointerDown: event => {
612
+ if (event.button !== 0) return;
613
+ event.preventDefault();
614
+ event.currentTarget.setPointerCapture(event.pointerId);
615
+ drag.current = { y: event.clientY, height: upper.offsetHeight };
616
+ },
617
+ onPointerMove: event => {
618
+ if (!drag.current || !event.currentTarget.hasPointerCapture(event.pointerId)) return;
619
+ const distance = event.clientY - drag.current.y;
620
+ if (distance !== 0) resize(drag.current.height + distance);
621
+ },
622
+ onLostPointerCapture: () => { drag.current = null; },
623
+ onDoubleClick: () => saveRatio(null),
624
+ onKeyDown: event => {
625
+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
626
+ event.preventDefault();
627
+ resize(upper.offsetHeight + (event.key === 'ArrowUp' ? -16 : 16));
628
+ },
629
+ }),
630
+ });
631
+ }
632
+
633
+ function FolderIcon({ size }) {
634
+ return h('img', { src: folderIcon, alt: '', width: size, height: size, draggable: false });
635
+ }
636
+
637
+ function SessionIcon({ size }) {
638
+ return h('span', { className: 'dwb-session-icon', style: { width: size, height: size, maskImage: `url("${sessionIcon}")` } });
639
+ }
640
+
641
+ function Browser({ t, nativeText, workspaceSource, sessionSource, view, startFolder, rememberFolder, openSession, insertBefore, toolbar, address, heading, area, panel, display, split, saveSplit, animatePage, useContextMenu, useSessionStatus, startSession, placements, savePlacement, panelSource, scheduleSource, unreadSource }) {
642
+ const { getTriggerProps } = useContextMenu();
643
+ const workspaceState = useSyncExternalStore(workspaceSource.subscribe, workspaceSource.getSnapshot);
644
+ const sessions = useSyncExternalStore(sessionSource.subscribe, sessionSource.getSnapshot);
645
+ const statuses = useSessionStatus(snapshot => snapshot);
646
+ const unread = useSyncExternalStore(unreadSource.subscribe, unreadSource.getSnapshot);
647
+ const { activePanelId } = useSyncExternalStore(panelSource.subscribe, panelSource.getSnapshot);
648
+ const sessionVisible = activePanelId === null;
649
+ const catalog = useSyncExternalStore(scheduleSource.subscribe, scheduleSource.getSnapshot);
650
+ const scheduledSessions = useMemo(() => {
651
+ const ids = new Set();
652
+ for (const task of catalog.records) {
653
+ if (task.status !== 'active') continue;
654
+ for (const id of task.involvedSessionIds) ids.add(id);
655
+ const target = task.target.kind === 'new' ? task.lastDelivery?.targetSessionId : task.target.sessionId;
656
+ if (target) ids.add(target);
657
+ }
658
+ return ids;
659
+ }, [catalog.records]);
660
+ const options = useSyncExternalStore(view.subscribe, view.getSnapshot);
661
+ const { byId, parents, children } = useMemo(() => workspaceTree(workspaceState.items), [workspaceState.items]);
662
+ const { byWorkspace, pinned, archived } = useMemo(() => sessionRows(workspaceState, sessions, options), [workspaceState, sessions, options]);
663
+ const notifications = useMemo(() => workspaceNotifications(workspaceState.items, sessions, statuses, parents, archived, unread),
664
+ [workspaceState.items, sessions, statuses, parents, archived, unread]);
665
+ const [history, setHistory] = useState(() => startFolder === null
666
+ ? { entries: [null], index: 0 } : { entries: [null, startFolder], index: 1 });
667
+ const [openError, setOpenError] = useState(null);
668
+ const [selectedFolder, setSelectedFolder] = useState(null);
669
+ const locate = useRef(null);
670
+ const dragged = useRef(null);
671
+ const [dropTarget, setDropTarget] = useState(null);
672
+ const [lifted, setLifted] = useState(false);
673
+ const crumbsRef = useRef(null);
674
+ // 抓手光标只在真正开始拖动之后出现:按下后移动超过 6px 才算拖动,单纯点击不变。
675
+ const liftThreshold = 6;
676
+ useEffect(() => {
677
+ if (!lifted) return undefined;
678
+ const clear = () => setLifted(false);
679
+ // 松手、拖拽结束、拖到别处丢掉时都要落回普通光标,避免拖拽事件被浏览器吞掉后卡在抓手。
680
+ const types = ['pointerup', 'mouseup', 'pointercancel', 'dragend', 'drop', 'blur'];
681
+ for (const type of types) window.addEventListener(type, clear, true);
682
+ return () => {
683
+ for (const type of types) window.removeEventListener(type, clear, true);
684
+ };
685
+ }, [lifted]);
686
+ function draggedSide(event) {
687
+ const rect = event.currentTarget.getBoundingClientRect();
688
+ return display === 'list'
689
+ ? (event.clientY < rect.top + rect.height / 2 ? 'before' : 'after')
690
+ : (event.clientX < rect.left + rect.width / 2 ? 'before' : 'after');
691
+ }
692
+
693
+ function dragPayload(key) {
694
+ if (key.startsWith('session:')) {
695
+ const session = entries.get(key);
696
+ if (!session || session.blank) return null;
697
+ const owner = workspaceState.items.find(item => item.sessionIds.includes(session.id));
698
+ return { key, kind: 'session', id: session.id, accountKey: owner?.workspaceId ?? ungrouped,
699
+ pinned: pinned.has(session.id) && !archived.has(session.id) };
700
+ }
701
+ const item = entries.get(key);
702
+ return item ? { key, kind: 'folder', id: item.workspaceId, parent: folder } : null;
703
+ }
704
+
705
+ /* A drop only counts where the native tree would also take it: same account, same pinned section. */
706
+ function accepts(drag, target) {
707
+ if (!drag || drag.key === target.key || drag.kind !== target.kind) return false;
708
+ if (drag.kind === 'session') return drag.accountKey === target.accountKey && drag.pinned === target.pinned;
709
+ return drag.parent === target.parent;
710
+ }
711
+
712
+ function dropSession(drag, target, side) {
713
+ const snapshot = view.getSnapshot();
714
+ const actions = view.actions ?? {};
715
+ if (snapshot.orderBy !== 'manual' || !accepts(drag, target)) return;
716
+ if (typeof actions.setSessionOrder !== 'function') return;
717
+ const orders = displayedOrders(workspaceState, sessions, snapshot);
718
+ const rows = byWorkspace.get(drag.accountKey) ?? [];
719
+ const isPinned = id => pinned.has(id) && !archived.has(id);
720
+ const next = sessionDragOrder(orders[drag.accountKey] ?? [], rows, drag, { id: target.id, side }, isPinned);
721
+ if (!next) return;
722
+ actions.setSessionOrder(drag.accountKey, next, orders);
723
+ }
724
+
725
+ function dropFolder(drag, target, side) {
726
+ if (typeof insertBefore !== 'function' || !accepts(drag, target)) return;
727
+ const ids = (children.get(folder) ?? []).map(item => item.workspaceId);
728
+ if (!ids.includes(drag.id) || !ids.includes(target.id)) return;
729
+ const rest = ids.filter(id => id !== drag.id);
730
+ const index = rest.indexOf(target.id) + (side === 'after' ? 1 : 0);
731
+ rest.splice(index, 0, drag.id);
732
+ if (rest.join() === ids.join()) return;
733
+ try {
734
+ Promise.resolve(insertBefore(drag.id, rest[index + 1])).catch(() => {});
735
+ } catch { /* Older hosts hide the Workspace writer. */ }
736
+ }
737
+
738
+ function dragProps(key) {
739
+ if (options.orderBy !== 'manual' || key === folderKey(ungrouped)) return {};
740
+ const payload = dragPayload(key);
741
+ if (!payload) return {};
742
+ return {
743
+ draggable: true,
744
+ 'data-dwb-drop': dropTarget?.key === key ? dropTarget.side : undefined,
745
+ onPointerDown: event => {
746
+ if (event.button !== 0) return;
747
+ const startX = event.clientX;
748
+ const startY = event.clientY;
749
+ const finish = () => {
750
+ window.removeEventListener('pointermove', move);
751
+ window.removeEventListener('pointerup', release);
752
+ window.removeEventListener('pointercancel', release);
753
+ };
754
+ function move(moveEvent) {
755
+ if (Math.hypot(moveEvent.clientX - startX, moveEvent.clientY - startY) < liftThreshold) return;
756
+ setLifted(true);
757
+ finish();
758
+ }
759
+ function release() {
760
+ if (!dragged.current) setLifted(false);
761
+ finish();
762
+ }
763
+ window.addEventListener('pointermove', move);
764
+ window.addEventListener('pointerup', release);
765
+ window.addEventListener('pointercancel', release);
766
+ },
767
+ onDragStart: event => {
768
+ dragged.current = payload;
769
+ setLifted(true);
770
+ if (!event.dataTransfer) return;
771
+ event.dataTransfer.effectAllowed = 'move';
772
+ event.dataTransfer.setData('text/plain', key);
773
+ },
774
+ onDragOver: event => {
775
+ if (!accepts(dragged.current, payload)) return;
776
+ event.preventDefault();
777
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'move';
778
+ const side = draggedSide(event);
779
+ setDropTarget(current => (current?.key === key && current.side === side ? current : { key, side }));
780
+ },
781
+ onDragLeave: event => {
782
+ if (event.currentTarget.contains(event.relatedTarget)) return;
783
+ setDropTarget(current => (current?.key === key ? null : current));
784
+ },
785
+ onDrop: event => {
786
+ const drag = dragged.current;
787
+ dragged.current = null;
788
+ setDropTarget(null);
789
+ setLifted(false);
790
+ if (!accepts(drag, payload)) return;
791
+ event.preventDefault();
792
+ const side = draggedSide(event);
793
+ if (drag.kind === 'session') dropSession(drag, payload, side);
794
+ else dropFolder(drag, payload, side);
795
+ },
796
+ onDragEnd: () => {
797
+ dragged.current = null;
798
+ setDropTarget(null);
799
+ setLifted(false);
800
+ },
801
+ };
802
+ }
803
+
804
+ useEffect(() => {
805
+ const path = crumbsRef.current;
806
+ function scrollPath(event) {
807
+ if (event.ctrlKey || event.metaKey || event.deltaX !== 0 || event.deltaY === 0 || path.scrollWidth <= path.clientWidth) return;
808
+ const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? path.clientWidth : 1;
809
+ event.preventDefault();
810
+ event.stopPropagation();
811
+ path.scrollLeft += event.deltaY * scale;
812
+ }
813
+ path.addEventListener('wheel', scrollPath, { passive: false });
814
+ return () => path.removeEventListener('wheel', scrollPath);
815
+ }, [address]);
816
+ const browserRef = useRef(null);
817
+ useEffect(() => {
818
+ if (selectedFolder === null) return;
819
+ function clearSelection(event) {
820
+ if (event.button !== 0 || (event.type === 'click' && event.detail > 0)) return;
821
+ if (getNewSessionButton(event)) return;
822
+ const selectedTile = browserRef.current?.querySelector('.dwb-tile[data-dwb-kind="folder"][aria-pressed="true"]');
823
+ if (!event.composedPath().includes(selectedTile)) setSelectedFolder(null);
824
+ }
825
+ window.addEventListener('pointerdown', clearSelection, true);
826
+ window.addEventListener('click', clearSelection, true);
827
+ return () => {
828
+ window.removeEventListener('pointerdown', clearSelection, true);
829
+ window.removeEventListener('click', clearSelection, true);
830
+ };
831
+ }, [selectedFolder]);
832
+
833
+ const exists = key => key === null || key === ungrouped || byId.has(key);
834
+ const current = history.entries[history.index];
835
+ const folder = exists(current) ? current : null;
836
+ const parent = parents.get(folder) ?? null;
837
+ const activeSession = Object.values(sessions.byId).find(session => session.retainedBy?.mainView > 0);
838
+ const activeOwner = activeSession && workspaceState.items.find(item => item.sessionIds.includes(activeSession.id));
839
+ let guideFolder;
840
+ if (activeSession) {
841
+ for (let child = activeOwner?.workspaceId ?? ungrouped; child !== null && child !== folder; child = parents.get(child) ?? null) {
842
+ if ((parents.get(child) ?? null) !== folder) continue;
843
+ guideFolder = child;
844
+ break;
845
+ }
846
+ }
847
+ const onlyArchived = options.archivedFilter === 'only';
848
+ const foldersWithArchives = useMemo(() => {
849
+ const visible = new Set();
850
+ if (onlyArchived) for (const [key, rows] of byWorkspace) {
851
+ if (rows.length === 0) continue;
852
+ for (let item = key; item !== null && !visible.has(item); item = parents.get(item) ?? null) visible.add(item);
853
+ }
854
+ return visible;
855
+ }, [byWorkspace, onlyArchived, parents]);
856
+ const folders = (children.get(folder) ?? []).filter(item => !onlyArchived || foldersWithArchives.has(item.workspaceId));
857
+ const placement = placements?.[pageKey(folder)];
858
+ const rows = byWorkspace.get(folder) ?? [];
859
+ const rowIds = new Set(rows.map(row => row.id));
860
+ const shortcuts = (placement?.shortcuts ?? []).map(id => sessions.byId[id]).filter(session => session
861
+ && !rowIds.has(session.id) && (!session.blank || session.retainedBy?.mainView > 0)
862
+ && (options.archivedFilter === 'show' || onlyArchived === archived.has(session.id)));
863
+ const inside = new Set(notifications.byFolder.get(folder)?.map(entry => entry.sessionId));
864
+ for (const session of shortcuts) inside.add(session.id);
865
+ const outside = folder === null ? undefined : notifications.all.reduce((highest, entry) =>
866
+ !inside.has(entry.sessionId) && entry.priority > (highest?.priority ?? 0) ? entry : highest, undefined);
867
+ const workspaceLabel = workspace => workspace.title === 'default-workspace' ? nativeText('workspace.defaultName') : workspace.title;
868
+ const crumbs = [{ key: null, label: t('home') }];
869
+ if (folder === ungrouped) {
870
+ crumbs.push({ key: ungrouped, label: t('ungrouped') });
871
+ } else if (folder !== null) {
872
+ const trail = [];
873
+ for (let key = folder; key !== null; key = parents.get(key) ?? null) {
874
+ const workspace = byId.get(key);
875
+ trail.push({ key, label: workspaceLabel(workspace), path: workspace.path });
876
+ }
877
+ crumbs.push(...trail.reverse());
878
+ }
879
+
880
+ function visit(key) {
881
+ if (key === folder) return;
882
+ animatePage(() => {
883
+ setOpenError(null);
884
+ setSelectedFolder(null);
885
+ rememberFolder(key);
886
+ setHistory(previous => ({
887
+ entries: [...previous.entries.slice(0, previous.index + 1), key], index: previous.index + 1,
888
+ }));
889
+ });
890
+ }
891
+
892
+ function historyTarget(direction) {
893
+ let index = history.index + direction;
894
+ while (index >= 0 && index < history.entries.length) {
895
+ if (exists(history.entries[index])) return index;
896
+ index += direction;
897
+ }
898
+ return undefined;
899
+ }
900
+
901
+ function go(index) {
902
+ animatePage(() => {
903
+ setOpenError(null);
904
+ setSelectedFolder(null);
905
+ rememberFolder(history.entries[index]);
906
+ setHistory(previous => ({ ...previous, index }));
907
+ });
908
+ }
909
+
910
+ const back = historyTarget(-1);
911
+ const forward = historyTarget(1);
912
+ const gestureAction = useRef(null);
913
+ useLayoutEffect(() => {
914
+ gestureAction.current = direction => {
915
+ if (direction === 'up') { visit(parent); return; }
916
+ const index = direction === 'left' ? back : forward;
917
+ if (index !== undefined) go(index);
918
+ };
919
+ });
920
+ useEffect(() => installMouseGestures(
921
+ () => direction => gestureAction.current?.(direction),
922
+ () => {
923
+ const bounds = panel?.getBoundingClientRect();
924
+ if (bounds?.width >= 112 && bounds.height >= 112) return bounds;
925
+ },
926
+ target => Boolean(panel?.contains(target)) && !panel.closest('[inert]') && !toolbar.hidden,
927
+ direction => t({ left: 'back', right: 'forward', up: 'gestureUp', invalid: 'gestureInvalid' }[direction]),
928
+ ), [toolbar, panel, t]);
929
+ const hasUngrouped = folder === null && byWorkspace.get(ungrouped).length > 0;
930
+ const loading = workspaceState.state !== 'error' && (workspaceState.phase !== 'ready' || sessions.phase !== 'ready');
931
+ const entries = new Map([
932
+ ...folders.map(item => [folderKey(item.workspaceId), item]),
933
+ ...(hasUngrouped ? [[folderKey(ungrouped), null]] : []),
934
+ ...[...rows, ...shortcuts].map(session => [sessionKey(session.id), session]),
935
+ ]);
936
+ const keys = [...entries.keys()];
937
+ const activeKey = activeSession && sessionKey(activeSession.id);
938
+ const hasActiveTile = entries.has(activeKey);
939
+ const empty = keys.length === 0;
940
+
941
+ useLayoutEffect(() => {
942
+ function createSession(event) {
943
+ if (event.defaultPrevented || toolbar.hidden || !getNewSessionButton(event)) return;
944
+ const selected = entries.get(selectedFolder);
945
+ const inWorkspace = byId.has(folder);
946
+ const workspaceId = inWorkspace ? folder : selected?.workspaceId ?? activeOwner?.workspaceId;
947
+ if (!workspaceState.items.length) return;
948
+ event.preventDefault();
949
+ event.stopPropagation();
950
+ setSelectedFolder(null);
951
+ setOpenError(null);
952
+ startSession(workspaceId, sessionId => {
953
+ if (inWorkspace) return;
954
+ savePlacement(folder, (saved = {}) => {
955
+ const shortcuts = saved.shortcuts ?? [];
956
+ return { shortcuts: shortcuts.includes(sessionId) ? shortcuts : [...shortcuts, sessionId] };
957
+ });
958
+ }).catch(() => setOpenError('create'));
959
+ }
960
+
961
+ document.addEventListener('click', createSession, true);
962
+ return () => document.removeEventListener('click', createSession, true);
963
+ });
964
+
965
+ function locateCurrentSession() {
966
+ locate.current = activeSession.id;
967
+ if (!hasActiveTile && folder !== (activeOwner?.workspaceId ?? ungrouped) && !onlyArchived) {
968
+ visit(activeOwner?.workspaceId ?? ungrouped);
969
+ } else {
970
+ revealCurrentSession();
971
+ }
972
+ }
973
+
974
+ function revealCurrentSession() {
975
+ if (locate.current === null) return;
976
+ const item = browserRef.current.querySelector('[data-dwb-session-id="' + CSS.escape(locate.current) + '"] > button');
977
+ if (!item) { locate.current = null; return; }
978
+ locate.current = null;
979
+ item.focus({ preventScroll: true });
980
+ item.scrollIntoView({ block: 'nearest' });
981
+ }
982
+
983
+ useLayoutEffect(() => {
984
+ const crumbsElement = crumbsRef.current;
985
+ crumbsElement.scrollLeft = crumbsElement.scrollWidth;
986
+ const list = browserRef.current.closest('[data-dwb-grid]');
987
+ if (list) list.scrollTop = 0;
988
+ revealCurrentSession();
989
+ }, [folder, display]);
990
+
991
+ function tile({ key, label, title = label, icon, kind, activate, active, guided, pinned, archived, scheduled, menuTarget, dots, sessionId, runningText, runningCount, subagents }) {
992
+ const subagentLabel = subagents ? nativeText(subagents === 1 ? 'status.subagentsRunning.one' : 'status.subagentsRunning.other', { n: subagents }) : undefined;
993
+ const countBadge = display === 'icons' && runningCount > 0;
994
+ const description = [runningText, subagentLabel, scheduled && t('scheduled'), ...(dots ?? []).map(entry => nativeText(entry.label))].filter(Boolean).join(', ');
995
+ return h('li', { key, 'data-dwb-session-id': sessionId, ...dragProps(key) }, h(Button, {
996
+ className: 'dwb-tile', title, 'data-dwb-kind': kind,
997
+ 'aria-label': label,
998
+ 'aria-description': description || undefined,
999
+ 'aria-current': active ? 'true' : undefined,
1000
+ 'data-dwb-guide': guided ? '' : undefined,
1001
+ 'aria-pressed': kind === 'folder' ? selectedFolder === key : undefined,
1002
+ ...getTriggerProps(menuTarget),
1003
+ onClick: event => {
1004
+ if (kind === 'session' || event.detail === 0) activate();
1005
+ else setSelectedFolder(key);
1006
+ },
1007
+ onDoubleClick: kind === 'folder' ? activate : undefined,
1008
+ }, h('span', { className: 'dwb-tile-icon', 'aria-hidden': true }, h(icon, { size: display === 'list' ? 16 : 30 })),
1009
+ h('span', { className: 'dwb-label' }, label),
1010
+ h('span', { className: 'dwb-tile-status' },
1011
+ runningText && h('span', {
1012
+ className: 'dwb-running', 'data-dwb-running-count': countBadge ? '' : undefined, 'aria-hidden': true,
1013
+ }, countBadge ? runningCount : runningText),
1014
+ dots?.length > 0 && h(NotificationDots, { entries: dots, translate: nativeText, size: 22 }),
1015
+ (subagentLabel || scheduled || pinned || archived) && h('span', { className: 'dwb-status-marks' },
1016
+ subagentLabel && h('span', { className: 'dwb-row-mark', role: 'img', 'aria-label': subagentLabel, title: subagentLabel },
1017
+ h(StateDot, { state: 'ongoing' })),
1018
+ scheduled && h(IconClockOutlineRegular, { className: 'dwb-row-mark', size: 14, 'aria-label': t('scheduled'), role: 'img' }),
1019
+ pinned && h(IconPinFillRegular, { className: 'dwb-row-mark', size: 13, 'aria-label': nativeText('menu.unpin'), role: 'img' }),
1020
+ archived && h(IconArchiveOutlineRegular, { className: 'dwb-row-mark', size: 13, 'aria-label': t('archived'), role: 'img' })))));
1021
+ }
1022
+
1023
+ function folderTile(key, label, path) {
1024
+ const menuTarget = key === ungrouped ? undefined : { kind: 'workspace', value: { workspaceId: key, path, displayTitle: label } };
1025
+ const count = notifications.runningByFolder.get(key);
1026
+ const runningText = count ? t(count === 1 ? 'oneRunningSession' : 'runningSessions', { n: count }) : undefined;
1027
+ return tile({ key: folderKey(key), label, title: path ?? label, icon: FolderIcon, kind: 'folder',
1028
+ activate: () => visit(key), guided: sessionVisible && key === guideFolder, menuTarget, runningText, runningCount: count, dots: notifications.byFolder.get(key) });
1029
+ }
1030
+
1031
+ return h('section', { className: 'dwb-browser', 'aria-label': t('panel'), ref: browserRef },
1032
+ createPortal(h(react.Fragment, null, outside && h(NotificationDots, { entries: [outside], translate: nativeText, size: 22 }),
1033
+ h('span', { className: 'dwb-heading-name' }, folder === null ? nativeText('section.workspaces') : crumbs.at(-1).label)), heading),
1034
+ createPortal(h('div', { className: 'dwb-toolbar' },
1035
+ h(SidebarDivider, { label: t('resize'), toolbar, area, ratio: split, saveRatio: saveSplit }),
1036
+ h('div', { className: 'dwb-reveal-zone' }),
1037
+ h('div', { className: 'dwb-nav-buttons dwb-reveal-control' },
1038
+ h(NavButton, { icon: outside ? undefined : IconChevronLeftOutlineRegular, label: t('back'), disabled: back === undefined, onClick: () => go(back) }),
1039
+ h(NavButton, { icon: IconChevronRightOutlineRegular, label: t('forward'), disabled: forward === undefined, onClick: () => go(forward) }),
1040
+ h(NavButton, { icon: IconChevronUpOutlineRegular, label: t('up'), disabled: folder === null, onClick: () => visit(parent) }),
1041
+ h(NavButton, { icon: LocateIcon, label: t('locate'), disabled: !activeSession || (onlyArchived && !hasActiveTile),
1042
+ onClick: locateCurrentSession }))), toolbar),
1043
+ createPortal(h('nav', { className: 'dwb-path dwb-reveal-control', 'aria-label': t('path'), ref: crumbsRef },
1044
+ h(IconFolderOpenRegular, { size: 16, className: 'dwb-indicator', 'aria-hidden': true }),
1045
+ crumbs.map(({ key, label, path }, index) => h('span', { className: 'dwb-crumb', key: key === ungrouped ? 'ungrouped' : key ?? 'home' },
1046
+ index > 0 && h(IconChevronRightOutlineRegular, { size: 12, className: 'dwb-indicator', 'aria-hidden': true }),
1047
+ index === crumbs.length - 1
1048
+ ? h('span', { className: 'dwb-current', title: path, 'aria-current': 'location' }, label)
1049
+ : h(Button, { size: 'sm', title: path, onClick: () => visit(key) }, label)))), address),
1050
+ h('div', { 'aria-busy': loading },
1051
+ workspaceState.state === 'error' && h('p', { className: 'dwb-status', role: 'status' }, t('loadError')),
1052
+ openError && h('p', { className: 'dwb-status', role: 'alert' }, openError === 'archived'
1053
+ ? nativeText('toast.archivedNotOpenable') : t(openError === 'create' ? 'createError' : 'openError')),
1054
+ empty && workspaceState.state !== 'error' && h('p', { className: 'dwb-status', role: 'status' },
1055
+ t(loading ? 'loading' : onlyArchived ? 'noArchives' : folder === null ? 'emptyHome' : 'emptyFolder')),
1056
+ !empty && h('ul', { className: 'dwb-list', 'data-dwb-display': display, 'data-dwb-lifted': lifted ? 'true' : undefined },
1057
+ keys.map(key => {
1058
+ const item = entries.get(key);
1059
+ if (item === null) return folderTile(ungrouped, t('ungrouped'));
1060
+ if (key.startsWith('folder:')) return folderTile(item.workspaceId, workspaceLabel(item), item.path);
1061
+ const session = item;
1062
+ const label = session.blank ? nativeText('session.new') : session.title?.trim() || nativeText('session.untitled');
1063
+ const isArchived = archived.has(session.id);
1064
+ const activity = notifications.runningBySession.get(session.id);
1065
+ const active = sessionVisible && activeKey === key;
1066
+ return tile({ key, sessionId: session.id, label, title: isArchived ? `${label} · ${t('archived')}` : label,
1067
+ icon: SessionIcon, kind: 'session',
1068
+ pinned: !isArchived && pinned.has(session.id), archived: isArchived, scheduled: !isArchived && !session.blank && scheduledSessions.has(session.id), active,
1069
+ runningText: activity?.running ? t('running') : undefined, subagents: activity?.subagents,
1070
+ dots: notifications.bySession.has(session.id) ? [notifications.bySession.get(session.id)] : undefined,
1071
+ menuTarget: session.blank ? undefined : { kind: 'session', value: { sessionId: session.id, displayTitle: label } },
1072
+ activate: () => {
1073
+ setOpenError(isArchived ? 'archived' : null);
1074
+ if (!isArchived && !active) openSession(session.id, () => setOpenError('open'));
1075
+ },
1076
+ });
1077
+ }))));
1078
+ }
1079
+
1080
+ function SidebarExtension({ t, nativeText, workspaceSource, sessionSource, nativeEntry, openSession, startSession, insertBefore, useContextMenu, useSessionStatus, panelSource, scheduleSource, unreadSource }) {
1081
+ const [preference, setPreference] = useState(readPreference);
1082
+ const enabled = preference.enabled === true;
1083
+ const fade = usePageFade();
1084
+ const [actions] = useState(() => ({
1085
+ setEnabled: (enabled, list) => {
1086
+ const update = () => setPreference(previous => ({ ...previous, enabled }));
1087
+ if (list?.hasAttribute('data-dwb-grid') === enabled) return;
1088
+ fade(list, update);
1089
+ },
1090
+ rememberFolder: folder => setPreference(previous => ({ ...previous, folder })),
1091
+ setDisplay: display => setPreference(previous => ({ ...previous, display })),
1092
+ saveSplit: split => setPreference(previous => ({ ...previous, split })),
1093
+ savePlacement: (folder, update) => setPreference(previous => {
1094
+ const placements = previous.placements ?? emptyPlacements;
1095
+ const key = pageKey(folder);
1096
+ return { ...previous, placements: { ...placements, [key]: update(placements[key]) } };
1097
+ }),
1098
+ }));
1099
+ const { grid, list, toolbar, address, header, heading, nativeHeading, trigger, menu, menuMount, menuSeparator, menuLabel, searching, searchOpen, region, area, panel } = useSidebarMounts(nativeText);
1100
+ const display = preference.display === 'list' ? 'list' : 'icons';
1101
+ const entry = useSyncExternalStore(nativeEntry.subscribe, nativeEntry.getSnapshot);
1102
+ const view = useMemo(() => entry?.store?.create() ?? emptyView, [entry]);
1103
+ const animatePage = update => fade(list, update);
1104
+
1105
+ function openConversation(sessionId, onError) {
1106
+ const main = document.querySelector('[data-slot="main"]');
1107
+ fade(main?.parentElement, () => {
1108
+ try { openSession(sessionId); } catch { onError(); }
1109
+ });
1110
+ }
1111
+
1112
+ useEffect(() => { savePreference(preference); }, [preference]);
1113
+ useLayoutEffect(() => {
1114
+ if (!grid || !list || !header || !region) return;
1115
+ const show = enabled && Boolean(trigger);
1116
+ grid.hidden = !show || searching;
1117
+ toolbar.hidden = !show;
1118
+ address.hidden = !show;
1119
+ heading.hidden = !show;
1120
+ nativeHeading?.toggleAttribute('data-dwb-replaced-heading', show);
1121
+ region.toggleAttribute('data-dwb-layout', show);
1122
+ header.toggleAttribute('data-dwb-header', show);
1123
+ list.toggleAttribute('data-dwb-grid', show && !searching);
1124
+ return () => {
1125
+ region.removeAttribute('data-dwb-layout');
1126
+ header.removeAttribute('data-dwb-header');
1127
+ list.removeAttribute('data-dwb-grid');
1128
+ grid.hidden = true;
1129
+ toolbar.hidden = true;
1130
+ address.hidden = true;
1131
+ heading.hidden = true;
1132
+ nativeHeading?.removeAttribute('data-dwb-replaced-heading');
1133
+ };
1134
+ }, [grid, list, toolbar, address, header, heading, nativeHeading, enabled, trigger, searching, region]);
1135
+ useLayoutEffect(() => {
1136
+ region?.toggleAttribute('data-dwb-reveal-held', enabled && Boolean(searchOpen || menu));
1137
+ return () => region?.removeAttribute('data-dwb-reveal-held');
1138
+ }, [region, enabled, searchOpen, menu]);
1139
+ useLayoutEffect(() => {
1140
+ if (!enabled || !trigger || !header || !toolbar || !address || !region) return;
1141
+ const sidebar = panel ?? region;
1142
+ const divider = toolbar.querySelector('.dwb-divider');
1143
+ if (!divider) return;
1144
+ const clear = () => region.removeAttribute('data-dwb-reveal-hover');
1145
+ function update(event) {
1146
+ if (event.pointerType === 'touch') return;
1147
+ const { clientX: x, clientY: y } = event;
1148
+ const { left, right } = sidebar.getBoundingClientRect();
1149
+ const top = divider.getBoundingClientRect().bottom;
1150
+ const bottom = address.getBoundingClientRect().bottom;
1151
+ region.toggleAttribute('data-dwb-reveal-hover', x >= left && x < right && y >= top && y < bottom);
1152
+ }
1153
+ window.addEventListener('pointermove', update);
1154
+ sidebar.addEventListener('pointerleave', clear);
1155
+ window.addEventListener('blur', clear);
1156
+ return () => {
1157
+ window.removeEventListener('pointermove', update);
1158
+ sidebar.removeEventListener('pointerleave', clear);
1159
+ window.removeEventListener('blur', clear);
1160
+ clear();
1161
+ };
1162
+ }, [enabled, trigger, header, toolbar, address, region, panel]);
1163
+ useLayoutEffect(() => {
1164
+ if (!menu) return;
1165
+ menu.toggleAttribute('data-dwb-selected', enabled);
1166
+ return () => menu.removeAttribute('data-dwb-selected');
1167
+ }, [menu, enabled]);
1168
+
1169
+ useLayoutEffect(() => {
1170
+ if (!menu || !trigger || !view.actions) return;
1171
+ const { setGroupBy, setOrderBy, setArchivedFilter } = view.actions;
1172
+ const select = new Map([
1173
+ [nativeText('groupBy.workspace'), () => { actions.setEnabled(false, list); setGroupBy('workspace'); }],
1174
+ [nativeText('groupBy.workspaceTree'), () => { actions.setEnabled(false, list); setGroupBy('workspace-tree'); }],
1175
+ [nativeText('groupBy.flat'), () => { actions.setEnabled(false, list); setGroupBy('flat'); }],
1176
+ [nativeText('orderBy.manual'), () => setOrderBy('manual', displayedOrders(
1177
+ workspaceSource.getSnapshot(), sessionSource.getSnapshot(), view.getSnapshot()))],
1178
+ [nativeText('orderBy.updated'), () => setOrderBy('updated', {})],
1179
+ [nativeText('viewOptions.hideArchived'), () => setArchivedFilter('default')],
1180
+ [nativeText('viewOptions.showArchived'), () => setArchivedFilter('show')],
1181
+ [nativeText('viewOptions.onlyArchived'), () => setArchivedFilter('only')],
1182
+ ]);
1183
+ function selectNative(event) {
1184
+ const button = event.target instanceof Element && event.target.closest('button[role="menuitem"]');
1185
+ if (!button || menuMount.contains(button)) return;
1186
+ const apply = select.get(button.textContent.trim());
1187
+ if (!apply) return;
1188
+ event.preventDefault();
1189
+ event.stopPropagation();
1190
+ apply();
1191
+ }
1192
+ let closing = false;
1193
+ function dismissOutside(event) {
1194
+ if (closing || menu.contains(event.target) || trigger.contains(event.target)) return;
1195
+ closing = true;
1196
+ trigger.click();
1197
+ }
1198
+ menu.addEventListener('click', selectNative, true);
1199
+ document.addEventListener('wheel', dismissOutside, { capture: true, passive: true });
1200
+ document.addEventListener('contextmenu', dismissOutside, true);
1201
+ return () => {
1202
+ menu.removeEventListener('click', selectNative, true);
1203
+ document.removeEventListener('wheel', dismissOutside, true);
1204
+ document.removeEventListener('contextmenu', dismissOutside, true);
1205
+ };
1206
+ }, [menu, trigger, menuMount, view, actions, list, nativeText, workspaceSource, sessionSource]);
1207
+
1208
+ function menuItem(label, src, current, select) {
1209
+ const icon = h('img', { className: 'dwb-menu-icon', src, alt: '', width: 16, height: 16, draggable: false });
1210
+ return h(MenuItemButton, { current, icon, onSelect: select },
1211
+ h('span', { className: 'dwb-menu-label' }, t(label), current && h(IconCheckOutlineRegular, { size: 14, 'aria-hidden': true })));
1212
+ }
1213
+
1214
+ return h(react.Fragment, null,
1215
+ menu && createPortal(h(react.Fragment, null,
1216
+ menuItem('panel', menuFolderIcon, enabled, () => actions.setEnabled(true, list)),
1217
+ enabled && h(react.Fragment, null,
1218
+ h('div', { role: 'separator', className: menuSeparator?.className }),
1219
+ h('div', { role: 'presentation', className: menuLabel?.className }, t('display')),
1220
+ menuItem('icons', largeIconsMenuIcon, display === 'icons', () => {
1221
+ if (display !== 'icons') animatePage(() => actions.setDisplay('icons'));
1222
+ }),
1223
+ menuItem('list', listMenuIcon, display === 'list', () => {
1224
+ if (display !== 'list') animatePage(() => actions.setDisplay('list'));
1225
+ }),
1226
+ )), menuMount),
1227
+ enabled && grid && createPortal(h(Browser, {
1228
+ t, nativeText, workspaceSource, sessionSource, view, openSession: openConversation, insertBefore, toolbar, address, heading, area, panel, display, animatePage, useContextMenu, useSessionStatus,
1229
+ split: !trigger ? null : preference.split, saveSplit: actions.saveSplit,
1230
+ startSession, placements: preference.placements, savePlacement: actions.savePlacement, panelSource, scheduleSource, unreadSource,
1231
+ startFolder: typeof preference.folder === 'string' ? preference.folder : null, rememberFolder: actions.rememberFolder,
1232
+ }), grid));
1233
+ }
1234
+
1235
+ function apply(ctx) {
1236
+ const nativeText = ctx.locale.bind('workspace');
1237
+ const slots = ctx.slots;
1238
+ ctx.effect(() => ctx.locale.register(id, dictionaries));
1239
+ ctx.effect(() => {
1240
+ const style = document.createElement('style');
1241
+ style.textContent = css;
1242
+ document.head.append(style);
1243
+ return () => style.remove();
1244
+ });
1245
+ const workspaces = ctx.workspaces.list;
1246
+ const sessions = ctx.sessions.list;
1247
+ const navigation = ctx.uiWorkspace;
1248
+ const panel = ctx.layout.panelInfo;
1249
+ const panelSource = { subscribe: listener => panel.subscribe(listener), getSnapshot: () => panel.getSnapshot() };
1250
+ const workspaceSource = { subscribe: listener => workspaces.subscribe(listener), getSnapshot: () => workspaces.getSnapshot() };
1251
+ const sessionSource = { subscribe: listener => sessions.subscribe(listener), getSnapshot: () => sessions.getSnapshot() };
1252
+ const nativeEntry = {
1253
+ subscribe: listener => slots.subscribe('sidebar.workspaces', listener),
1254
+ getSnapshot: () => slots.entries('sidebar.workspaces').find(entry => entry.locale === 'workspace' && entry.store),
1255
+ };
1256
+ const scheduleSource = scheduleSourceFor(ctx);
1257
+ const unreadSource = completionSource(ctx);
1258
+ slots.inject('shell.overlay', () => slots.register({
1259
+ name: 'shell.overlay', id, locale: id,
1260
+ inject: () => ({
1261
+ nativeText, workspaceSource, sessionSource, nativeEntry, panelSource, scheduleSource, unreadSource,
1262
+ insertBefore: (workspaceId, beforeWorkspaceId) => ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId),
1263
+ openSession: sessionId => navigation.openSession(sessionId),
1264
+ startSession: (workspaceId, onCreated) => {
1265
+ const snapshot = sessions.getSnapshot();
1266
+ const target = workspaceId ?? workspaces.getSnapshot().items.reduce((recent, item) => {
1267
+ const latest = item.sessionIds.reduce((time, id) => Math.max(time, snapshot.byId[id]?.updatedAt ?? -Infinity), -Infinity);
1268
+ const activity = latest === -Infinity ? Date.parse(item.createdAt) : latest;
1269
+ return !recent || activity > recent.activity ? { workspaceId: item.workspaceId, activity } : recent;
1270
+ }, undefined)?.workspaceId;
1271
+ return target === undefined ? Promise.resolve() : navigation.openWorkspace(target, onCreated);
1272
+ },
1273
+ }),
1274
+ }, SidebarExtension));
1275
+ }