dsh-mop 0.0.0-stage → 0.1.4

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/client.js ADDED
@@ -0,0 +1,997 @@
1
+ /**
2
+ * dsh-mop 浏览器半边:设置 → 归档会话。
3
+ * 查看会话和 DSH 官方归档,支持清理与还原。
4
+ */
5
+ window.__ModuleLoader__.load({
6
+ id: 'dsh-mop',
7
+ factory(require) {
8
+ const React = require('react');
9
+ const { HoverCard, HoverCardGroup, StateDot, Button, Input, SegmentedTabs, Toast, Modal } = require('@deepseek-ai/dsh-client-ui-primitives');
10
+ const { useState, useEffect, useLayoutEffect, useRef, useCallback, useSyncExternalStore } = React;
11
+ const h = React.createElement;
12
+
13
+ const NS = 'dsh-mop';
14
+
15
+ // 界面文案按语言放在同目录的 client.<语言>.js,由 DSH 按需下发,在 apply() 里载入。
16
+ const LANGUAGE_FILES = ['zh', 'en', 'de', 'es', 'fr', 'ja', 'pt', 'ru'];
17
+ let LOCALES = {};
18
+
19
+ // 复用的 DSH 官方词条:插件的键 → 官方词典的命名空间、键和参数名。插件语言包里不要再定义这些键。
20
+ const OFFICIAL_COPY = {
21
+ 'host.updateRequired': { namespace: 'pluginManager', key: 'restartNotice', params: { reason: '' } },
22
+ 'action.archiveCleanup': { namespace: 'common', key: 'delete' },
23
+ 'tabs.archived': { namespace: 'workspace', key: 'row.archived' },
24
+ 'selection.selectAll': { namespace: 'settings.models', key: 'fetchSelectAll' },
25
+ 'selection.deselectAll': { namespace: 'settings.models', key: 'fetchDeselectAll' },
26
+ 'confirm.purge.title': { namespace: 'settings.models', key: 'deleteTitle' },
27
+ 'confirm.residue.title': { namespace: 'settings.models', key: 'deleteTitle' },
28
+ 'action.purge': { namespace: 'common', key: 'delete' },
29
+ 'action.clean': { namespace: 'common', key: 'delete' },
30
+ 'notice.archived': { namespace: 'workspace', key: 'row.archived' },
31
+ 'empty.residue': { namespace: 'conversation', key: 'detail.empty' },
32
+ 'error.sessionNotFound': { namespace: 'conversation', key: 'placeholder.unavailable' },
33
+ 'error.referenceCheck': { namespace: 'schedule.manager', key: 'list.error' },
34
+ 'notice.failed': { namespace: 'workflowRun', key: 'statusCount.failed', params: { count: ['n', 'count'] } },
35
+ 'residue.orphanTask': { namespace: 'schedule.manager', key: 'detail.sessionUnavailable' },
36
+ 'error.schedule_delete_failed': { namespace: 'schedule.manager', key: 'toast.deleteFailed' },
37
+ 'error.residue_unavailable': { namespace: 'contextMenu', key: 'failed' },
38
+ 'error.purge_failed': { namespace: 'contextMenu', key: 'failed' },
39
+ 'error.residue_failed': { namespace: 'contextMenu', key: 'failed' },
40
+ };
41
+
42
+ const fill = (template, params) => String(template ?? '').replace(/\{(\w+)\}/g, (_, k) => String(params?.[k] ?? ''));
43
+
44
+ // Use the live official dictionaries first. Official keys have no plugin
45
+ // copy (client.<language>.js must not define them), so an absent official
46
+ // namespace leaves only the host's missing-key rendering.
47
+ function officialTranslator(locale) {
48
+ const own = locale.bind(NS);
49
+ const translators = new Map();
50
+ return (key, params) => {
51
+ const entry = OFFICIAL_COPY[key];
52
+ if (!entry) return own(key, params);
53
+ const { namespace, key: officialKey, params: paramMap } = entry;
54
+ if (!translators.has(namespace)) translators.set(namespace, locale.bind(namespace));
55
+ const mapped = paramMap && Object.fromEntries(Object.entries(paramMap).map(([name, source]) => [
56
+ name, Array.isArray(source) ? source.map((part) => params?.[part]).find((value) => value !== undefined) : source,
57
+ ]));
58
+ const value = translators.get(namespace)(officialKey, mapped ?? params);
59
+ if (typeof value === 'string' && value !== officialKey) return key === 'host.updateRequired' ? value.trimEnd() : value;
60
+ // Generic actions have no plugin translation: the official label is their only source.
61
+ return ['action.archiveCleanup', 'action.purge', 'action.clean'].includes(key) ? value : own(key, params);
62
+ };
63
+ }
64
+
65
+ const ERROR_KEYS = { session_not_archived: 'error.notArchived',
66
+ session_not_found: 'error.sessionNotFound', protected_workspace: 'error.workspaceProtected', schedule_reference: 'reference.schedule',
67
+ reference_check_failed: 'error.referenceCheck' };
68
+ function errorText(error, t, workspaceT = t) {
69
+ const message = String(error?.message ?? error ?? '');
70
+ const embedded = /dsh-mop:([a-z_]+)/.exec(message);
71
+ const code = embedded?.[1] || error?.code;
72
+ const errorKey = `error.${code}`;
73
+ const key = ERROR_KEYS[code] || (Object.hasOwn(LOCALES.en, errorKey) || Object.hasOwn(OFFICIAL_COPY, errorKey) ? errorKey : null);
74
+ const reason = code === 'already_archived' ? workspaceT('row.archived') : key ? t(key) : message;
75
+ // Preserve diagnostics supplied by the host for failures without a
76
+ // plugin-defined code, while translating the actionable heading.
77
+ const diagnostic = ['purge_failed', 'residue_failed'].includes(code) ? error?.message : error?.detail;
78
+ const detail = diagnostic ? `: ${diagnostic}` : '';
79
+ const count = code === 'workspace_filtered' && Number.isInteger(error?.blockedCount) ? ` (${error.blockedCount})` : '';
80
+ return reason + count + detail;
81
+ }
82
+
83
+ function resultText(t, completed, successText, failures, detail) {
84
+ const parts = [];
85
+ if (completed > 0 || failures === 0) parts.push(successText);
86
+ if (failures > 0) parts.push(`${fill(t('notice.failed', { n: failures, count: failures }), { n: failures, count: failures })}${detail ? `: ${detail}` : ''}`);
87
+ return parts.join(' · ');
88
+ }
89
+
90
+ /** Use the same theme-managed sprite symbols as DSH's product icons. */
91
+ function officialIcon(glyph, size, className) {
92
+ const id = `dsw-icon-${glyph}-regular`;
93
+ return h('svg', { width: size, height: size, className, 'data-icon': id, 'aria-hidden': true },
94
+ h('use', { href: `#${id}` }));
95
+ }
96
+
97
+ function formatBytes(bytes) {
98
+ if (typeof bytes !== 'number' || !Number.isFinite(bytes)) return '—';
99
+ if (bytes < 1024) return `${bytes} B`;
100
+ const units = ['KB', 'MB', 'GB', 'TB'];
101
+ let v = bytes / 1024, u = 0;
102
+ while (v >= 1024 && u < units.length - 1) { v /= 1024; u += 1; }
103
+ return `${v >= 100 ? Math.round(v) : v.toFixed(1)} ${units[u]}`;
104
+ }
105
+
106
+ // Match the official workspace sidebar's compact time buckets and translations.
107
+ function relativeTime(ms, t) {
108
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return '';
109
+ const diff = Math.max(0, Date.now() - ms);
110
+ if (diff < 60000) return t('time.now');
111
+ const [unit, interval] = diff < 3600000 ? ['minutes', 60000]
112
+ : diff < 86400000 ? ['hours', 3600000]
113
+ : diff < 30 * 86400000 ? ['days', 86400000]
114
+ : diff < 365 * 86400000 ? ['months', 30 * 86400000]
115
+ : ['years', 365 * 86400000];
116
+ return t(`time.${unit}`, { n: Math.floor(diff / interval) });
117
+ }
118
+
119
+ function hoverTime(ms, t) {
120
+ if (!(ms > 0)) return '';
121
+ const time = relativeTime(ms, t);
122
+ return Math.max(0, Date.now() - ms) < 60000 ? time : t('time.ago', { t: time });
123
+ }
124
+
125
+ // Sort by the same timestamp shown in each row. A blank session has no
126
+ // displayed time, even if its backing record has a timestamp.
127
+ function sessionTime(item) {
128
+ if (item.blank === true) return 0;
129
+ if (Number.isFinite(item.updatedAt) && item.updatedAt > 0) return item.updatedAt;
130
+ return Number.isFinite(item.mtimeMs) && item.mtimeMs > 0 ? item.mtimeMs : 0;
131
+ }
132
+
133
+ function residueTime(item) {
134
+ return Number.isFinite(item.mtimeMs) && item.mtimeMs > 0 ? item.mtimeMs : 0;
135
+ }
136
+
137
+ function sortByDisplayedTime(items, timeOf) {
138
+ return [...items].sort((a, b) => {
139
+ const left = timeOf(a), right = timeOf(b);
140
+ if (!left || !right) return left ? 1 : right ? -1 : 0;
141
+ return right - left;
142
+ });
143
+ }
144
+
145
+ function workspaceCreatedLabel(createdAt, t) {
146
+ const d = new Date(createdAt);
147
+ if (createdAt == null || !Number.isFinite(d.getTime())) return '';
148
+ const date = t('date.ymd', { y: d.getFullYear(), m: d.getMonth() + 1, d: d.getDate() });
149
+ const pad = (n) => String(n).padStart(2, '0');
150
+ return t('hover.created', { time: `${date} ${pad(d.getHours())}:${pad(d.getMinutes())}` });
151
+ }
152
+
153
+ // Same display-only POSIX home abbreviation used by DSH workspace rows.
154
+ function displayPath(path, home) {
155
+ if (!path || !home || /^[A-Za-z]:[/\\]|^\\\\/.test(path) || /^[A-Za-z]:[/\\]|^\\\\/.test(home)) return path;
156
+ const root = home.replace(/\/+$/, '');
157
+ if (!root) return path;
158
+ if (path.replace(/\/+$/, '') === root) return '~';
159
+ return path.startsWith(`${root}/`) ? `~${path.slice(root.length)}` : path;
160
+ }
161
+
162
+ /** Keep the 24px content inset and 1px outside gap; flip when needed. */
163
+ function HoverPlacement({ anchorRef }) {
164
+ const marker = useRef(null);
165
+ useLayoutEffect(() => {
166
+ const card = marker.current?.closest('.dsh-mop-hover-content')?.parentElement;
167
+ const portal = card?.parentElement;
168
+ const anchor = anchorRef.current;
169
+ const panel = anchor?.closest('[data-shortcut-modal="settings"]');
170
+ if (!card || !portal || !panel) return;
171
+ // The official component temporarily replaces card content after copy.
172
+ // Keep placement on its portal, which survives the feedback state.
173
+ portal.dataset.dshMopPositioned = '';
174
+ const place = () => {
175
+ const width = card.getBoundingClientRect().width;
176
+ const anchorBounds = anchor.getBoundingClientRect();
177
+ const right = anchorBounds.right + 24 + 1;
178
+ const left = anchorBounds.left - width - 1;
179
+ const x = right + width <= window.innerWidth - 8 ? right : Math.max(8, left);
180
+ portal.style.setProperty('--dsh-mop-card-left', `${x}px`);
181
+ };
182
+ place();
183
+ window.addEventListener('resize', place);
184
+ window.addEventListener('scroll', place, true);
185
+ return () => { window.removeEventListener('resize', place); window.removeEventListener('scroll', place, true); };
186
+ }, [anchorRef]);
187
+ return h('span', { ref: marker, hidden: true });
188
+ }
189
+
190
+ function cardContent({ title, path, time, statuses, archived, reason, tasks = [], anchorRef, onOpenTask, officialSchedule, scheduleSnapshot, catalogT, scheduleT }, t) {
191
+ const active = tasks.filter((task) => task.status === 'active').sort((a, b) => {
192
+ const next = (task) => Math.max(Date.parse(task.record?.scheduledAt) || 0, Date.parse(task.record?.deliveryFloorEndsAt) || 0);
193
+ return next(a) - next(b);
194
+ });
195
+ const visibleTasks = [...active.slice(0, 2), ...tasks.filter((task) => task.status !== 'active')];
196
+ return h('div', { className: 'dsh-mop-hover-content' },
197
+ h(HoverPlacement, { anchorRef }), h('div', { className: 'dsh-mop-hover-title' }, title),
198
+ path ? h('div', { className: 'dsh-mop-hover-path' }, path) : null,
199
+ time ? h('div', { className: 'dsh-mop-hover-time' }, time) : null,
200
+ ...visibleTasks.map((task, index) => h('button', { key: task.id || index, type: 'button', className: 'dsh-mop-hover-status dsh-mop-hover-archived dsh-mop-hover-task-button',
201
+ disabled: !task.id, onClick: (event) => { event.stopPropagation(); return onOpenTask?.(task.id); },
202
+ onKeyDown: (event) => { event.stopPropagation(); } },
203
+ task.status === 'active' && task.officialVisible && officialSchedule && scheduleSnapshot?.settled
204
+ ? h(officialSchedule, { sessionId: task.sessionId, t: catalogT,
205
+ useCatalog: (selector) => selector({ ...scheduleSnapshot, records: [task.record] }) })
206
+ : h(React.Fragment, null, officialIcon('clock-outline', 14), h('span', null, task.title || task.id),
207
+ task.showStatus || task.status === 'paused' || task.status === 'ended' ? h('span', null, scheduleT?.(`status.${task.status}`)) : null))),
208
+ active.length > 2 ? h('div', { className: 'dsh-mop-hover-time' }, catalogT?.('hover.more', { count: active.length - 2 })) : null,
209
+ ...(statuses ?? []).map((entry) => h('div', { key: entry.key, className: 'dsh-mop-hover-status' },
210
+ h(StateDot, { state: entry.state }), h('span', null, t(entry.key, entry.params)))),
211
+ archived ? h('div', { className: 'dsh-mop-hover-status dsh-mop-hover-archived' },
212
+ officialIcon('archive-outline', 14), h('span', null, t('row.archived'))) : null,
213
+ reason ? h('div', { className: 'dsh-mop-hover-status' },
214
+ officialIcon('shield-outline', 14), h('span', null, reason)) : null);
215
+ }
216
+
217
+ function rowWithHover(key, row, content, t, copyText) {
218
+ return h(HoverCard, {
219
+ key, anchor: row, content, openDelayMs: 800, grouped: true,
220
+ ...(copyText ? { copyText, copyLabel: t('copy'), copiedLabel: t('hover.copied') } : {}),
221
+ });
222
+ }
223
+
224
+ // Mirrors the official sidebar: reveal only overflows > 8px at 0.03px/ms.
225
+ const titleFrames = new WeakMap();
226
+ function titleEnter(event) {
227
+ if (event.pointerType === 'touch') return;
228
+ const element = event.currentTarget.querySelector('.dsh-mop-title');
229
+ if (!element || titleFrames.has(element)) return;
230
+ const range = element.scrollWidth - element.clientWidth;
231
+ if (range <= 8) return;
232
+ const place = (left) => {
233
+ element.scrollLeft = left;
234
+ if (left > 0) element.dataset.scrolled = ''; else delete element.dataset.scrolled;
235
+ if (left < range) element.dataset.clipped = ''; else delete element.dataset.clipped;
236
+ };
237
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { place(range); return; }
238
+ let previous, position = 0;
239
+ const step = (now) => {
240
+ if (!element.isConnected) { titleFrames.delete(element); return; }
241
+ position += previous === undefined ? 0 : (now - previous) * 0.03;
242
+ previous = now;
243
+ place(Math.min(position, range));
244
+ if (position < range) titleFrames.set(element, requestAnimationFrame(step));
245
+ else titleFrames.delete(element);
246
+ };
247
+ titleFrames.set(element, requestAnimationFrame(step));
248
+ }
249
+ function titleLeave(event) {
250
+ const element = event.currentTarget.querySelector('.dsh-mop-title');
251
+ if (!element) return;
252
+ if (titleFrames.has(element)) cancelAnimationFrame(titleFrames.get(element));
253
+ titleFrames.delete(element);
254
+ element.scrollLeft = 0;
255
+ delete element.dataset.scrolled;
256
+ delete element.dataset.clipped;
257
+ }
258
+
259
+ /** Join DSH's authoritative session-list flags without inferring from titles. */
260
+ function mergeSessionSummaries(data, summary, rpcId) {
261
+ if (summary.rpcId !== rpcId || !summary.result?.ok || !Array.isArray(summary.result.value?.items)) {
262
+ throw new Error('session/list unavailable');
263
+ }
264
+ const byId = new Map(summary.result.value.items.map((item) => [item.sessionId, item]));
265
+ const merge = (item) => {
266
+ const current = byId.get(item.id);
267
+ return current ? { ...item, blank: current.blank,
268
+ updatedAt: Number.isFinite(current.updatedAt) && current.updatedAt > 0 ? current.updatedAt : item.mtimeMs,
269
+ running: current.running,
270
+ live: typeof current.running === 'boolean' ? current.running : item.live } : item;
271
+ };
272
+ return { ...data, sessions: (data.sessions ?? []).map(merge), recycled: (data.recycled ?? []).map(merge) };
273
+ }
274
+
275
+ /** Read the same root hooks used by the official workspace sidebar. */
276
+ function LiveSection(props) {
277
+ const liveSessions = props.useSessions((value) => value);
278
+ const liveStatuses = props.useSessionStatus((value) => value);
279
+ return h(SectionContent, { ...props, liveSessions, liveStatuses });
280
+ }
281
+
282
+ function SessionSection(props) {
283
+ return typeof props.useSessions === 'function' && typeof props.useSessionStatus === 'function'
284
+ ? h(LiveSection, props) : h(SectionContent, props);
285
+ }
286
+
287
+ function ScheduleSection(props) {
288
+ const scheduleSnapshot = useSyncExternalStore(props.scheduleSource.subscribe, props.scheduleSource.getSnapshot, props.scheduleSource.getSnapshot);
289
+ return h(SessionSection, { ...props, scheduleSnapshot });
290
+ }
291
+
292
+ function Section(props) {
293
+ return props.scheduleSource && typeof useSyncExternalStore === 'function'
294
+ ? h(ScheduleSection, props) : h(SessionSection, props);
295
+ }
296
+
297
+ function withSchedule(item, snapshot) {
298
+ if (!snapshot?.settled || !Array.isArray(snapshot.records)) return item;
299
+ const records = snapshot.records.filter((task) => (task.involvedSessionIds ?? []).includes(item.id)
300
+ || (task.target?.kind !== 'new' && task.target?.sessionId === item.id)
301
+ || task.lastDelivery?.targetSessionId === item.id);
302
+ return { ...item,
303
+ purgeBlock: item.purgeBlock === 'reference_check_failed' ? item.purgeBlock : records.length ? 'schedule_reference' : null,
304
+ scheduleTasks: records.map((task) => ({ id: task.id, title: task.title || task.id, status: task.status, sessionId: item.id, record: task,
305
+ officialVisible: (task.involvedSessionIds ?? []).includes(item.id) || (task.target?.kind !== 'new' && task.target?.sessionId === item.id) })) };
306
+ }
307
+
308
+ /** Overlay the authoritative live state without changing the persisted overview. */
309
+ function liveItem(item, liveSessions, liveStatuses) {
310
+ const current = liveSessions?.byId?.[item.id];
311
+ const status = liveStatuses?.get?.(item.id);
312
+ const running = status?.running ?? current?.running ?? item.running ?? item.live;
313
+ const pending = ['approval', 'plan-review', 'question'].includes(status?.pendingInteraction?.kind)
314
+ ? status.pendingInteraction.kind : undefined;
315
+ const children = liveSessions?.projectionsBySession?.[item.id]?.values?.subagentCatalog;
316
+ const runningChildren = Array.isArray(children) ? children.reduce((count, child) =>
317
+ count + ((liveStatuses?.get?.(child.id)?.running ?? liveSessions?.byId?.[child.id]?.running) === true ? 1 : 0), 0) : 0;
318
+ return { ...item,
319
+ title: typeof current?.title === 'string' && current.title ? current.title : item.title,
320
+ blank: typeof current?.blank === 'boolean' ? current.blank : item.blank,
321
+ updatedAt: Number.isFinite(current?.updatedAt) && current.updatedAt > 0 ? current.updatedAt : item.updatedAt,
322
+ running: running === true, pending, runningChildren,
323
+ completed: status?.completionUnread === true,
324
+ live: running === true || pending !== undefined || runningChildren > 0,
325
+ };
326
+ }
327
+
328
+ // Mirrors the official workspace row's status precedence.
329
+ function sessionStatuses(item) {
330
+ const labels = { approval: 'status.waitingApproval', 'plan-review': 'status.planReview', question: 'status.waitingAnswer' };
331
+ const child = item.runningChildren > 0 ? { state: 'ongoing',
332
+ key: item.runningChildren === 1 ? 'status.subagentsRunning.one' : 'status.subagentsRunning.other',
333
+ params: { n: item.runningChildren } } : null;
334
+ let primary;
335
+ if (labels[item.pending]) primary = { state: 'warning', key: labels[item.pending] };
336
+ else if (item.running ?? item.live) primary = { state: 'ongoing', key: 'status.running' };
337
+ else if (child) return [child];
338
+ else if (item.completed) primary = { state: 'done', key: 'status.completed' };
339
+ else primary = { state: 'idle', key: 'status.idle' };
340
+ return child ? [primary, child] : [primary];
341
+ }
342
+
343
+ function archiveActivityLine(entry, t) {
344
+ const items = Array.isArray(entry.items) ? entry.items : [];
345
+ const n = items.length;
346
+ const names = items.map((item) => item.label ?? item.id).join(t('archive.confirm.listSeparator'));
347
+ const plural = n === 1 ? 'one' : 'other';
348
+ if (entry.kind === 'turn') return t('archive.confirm.turn');
349
+ const namesByKind = { subagent: 'subagents', job: 'jobs', schedule: 'schedules' };
350
+ const kind = namesByKind[entry.kind];
351
+ return kind ? t(`archive.confirm.${kind}.${plural}`, { n, names })
352
+ : t(`archive.confirm.other.${plural}`, { kind: entry.kind, n });
353
+ }
354
+
355
+ function taskRule(task, t) {
356
+ if (task.kind === 'at' || task.kind === 'after') return t('frequency.once');
357
+ if (task.kind === 'every' && Number.isFinite(task.everySeconds)) {
358
+ const units = [['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]];
359
+ const [unit, seconds] = units.find(([, size]) => task.everySeconds % size === 0) ?? units[3];
360
+ const value = task.everySeconds / seconds;
361
+ return t('frequency.every', { value, unit: t(`unit.${unit}.${value === 1 ? 'one' : 'other'}`, { count: value }) });
362
+ }
363
+ if (task.kind === 'daily') return t('frequency.daily', { time: task.time, timeZone: task.timeZone });
364
+ if (task.kind === 'weekly') return t('frequency.weekly', { time: task.time, timeZone: task.timeZone,
365
+ weekdays: (task.weekdays ?? []).map((day) => t(`frequency.weekday.${day}`)).join(t('frequency.weekday.join')) });
366
+ if (task.kind === 'cron') return [task.expression, task.timeZone].filter(Boolean).join(' · ');
367
+ if (task.kind === 'rrule') return task.rrule || t('frequency.hostCustom');
368
+ return t('frequency.hostCustom');
369
+ }
370
+
371
+ function SectionContent({ t, workspaceT = t, scheduleT = t, catalogT = scheduleT, liveSessions, liveStatuses, scheduleSnapshot, officialSchedule, workspaceActions, sessionsService, archiveNotice }) {
372
+ const [tab, setTab] = useState('sessions');
373
+ const [query, setQuery] = useState('');
374
+ const [overview, setOverview] = useState(null);
375
+ const [checked, setChecked] = useState(() => new Set());
376
+ const [busy, setBusy] = useState(false);
377
+ const [dialog, setDialog] = useState(null); // {text, run}
378
+ const [notice, setNotice] = useState(null); // {text, warning, seq}
379
+ const [loadError, setLoadError] = useState(false);
380
+ const [collapsed, setCollapsed] = useState(() => new Set());
381
+ const [searchCollapsed, setSearchCollapsed] = useState(() => new Set());
382
+
383
+ const workspaceName = (item) => {
384
+ const title = item.workspaceTitle || item.workspacePath;
385
+ return title === 'default-workspace' ? t('workspace.defaultName') : title || workspaceT('group.ungrouped');
386
+ };
387
+ const displayTitle = (item) => item.blank === true ? workspaceT('session.new')
388
+ : item.title === 'default-workspace' ? t('workspace.defaultName') : item.title;
389
+ const sessionItems = (overview?.sessions ?? []).map((item) => withSchedule(liveItem(item, liveSessions, liveStatuses), scheduleSnapshot));
390
+ const archivedItems = (overview?.recycled ?? []).map((item) => withSchedule(liveItem(item, liveSessions, liveStatuses), scheduleSnapshot));
391
+ const tabItems = () => (tab === 'sessions' ? sessionItems : archivedItems);
392
+ const selectableIds = new Set(tabItems().filter((item) => !item.protected).map((item) => item.id));
393
+ const selectedSessionIds = [...checked].filter((id) => selectableIds.has(id));
394
+
395
+ useEffect(() => {
396
+ if (tab === 'residue' || !overview) return;
397
+ setChecked((current) => {
398
+ const next = new Set([...current].filter((id) => selectableIds.has(id)));
399
+ return next.size === current.size ? current : next;
400
+ });
401
+ }, [tab, overview, liveSessions, liveStatuses]);
402
+
403
+ const refresh = useCallback(async () => {
404
+ setBusy(true);
405
+ try {
406
+ const response = await fetch('api/dsh-mop.overview');
407
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
408
+ const raw = await response.json();
409
+ if (raw?.error) throw new Error(raw.error);
410
+ if (raw?.apiVersion !== 3) {
411
+ setOverview(null);
412
+ setLoadError('host-version');
413
+ return;
414
+ }
415
+ if (!Array.isArray(raw?.residue?.items)) throw new Error('invalid residue response');
416
+ const data = raw;
417
+ // DSH 的 session/list 含官方 blank 标志;标题不等于空白状态。
418
+ try {
419
+ const rpcId = globalThis.crypto?.randomUUID?.() ?? `dsh-mop-${Date.now()}-${Math.random()}`;
420
+ const summaryResponse = await fetch('api/session/list', {
421
+ method: 'POST', headers: { 'content-type': 'application/json' },
422
+ body: JSON.stringify({ type: 'client-request', rpcId, method: 'session/list', payload: { args: { _request: {} } } }),
423
+ });
424
+ if (!summaryResponse.ok) throw new Error(`HTTP ${summaryResponse.status}`);
425
+ const summary = await summaryResponse.json();
426
+ Object.assign(data, mergeSessionSummaries(data, summary, rpcId));
427
+ } catch (error) {
428
+ // 无法取得标记时仍展示清单;不要根据标题猜测空白状态。
429
+ console.warn('dsh-mop: session status unavailable', error);
430
+ }
431
+ setOverview(data);
432
+ setLoadError(false);
433
+ } catch {
434
+ setLoadError(true);
435
+ } finally {
436
+ setBusy(false);
437
+ }
438
+ }, []);
439
+
440
+ useEffect(() => { void refresh(); }, [refresh]);
441
+
442
+ // Disk maintenance has no official session/disposed event. Re-read the
443
+ // host catalog through the same service that supplies the DSH sidebar.
444
+ const syncSessionList = useCallback(async () => {
445
+ if (typeof sessionsService?.refresh !== 'function') return;
446
+ try { await sessionsService.refresh(); }
447
+ catch (error) { console.warn('dsh-mop: session list refresh failed', error); }
448
+ }, [sessionsService]);
449
+ useEffect(() => { void syncSessionList(); }, [syncSessionList]);
450
+
451
+ const post = useCallback(async (action, body) => {
452
+ setBusy(true);
453
+ try {
454
+ const response = await fetch(`api/dsh-mop.${action}`, {
455
+ method: 'POST',
456
+ headers: { 'content-type': 'application/json' },
457
+ body: JSON.stringify(body ?? {}),
458
+ });
459
+ const result = await response.json();
460
+ if (!response.ok || result?.error) throw new Error(result?.error || `HTTP ${response.status}`);
461
+ return result;
462
+ } finally {
463
+ setBusy(false);
464
+ }
465
+ }, []);
466
+
467
+ const showNotice = useCallback((text, warning = false, actions) => {
468
+ setNotice((previous) => ({ text, warning, actions, seq: (previous?.seq ?? 0) + 1 }));
469
+ }, []);
470
+
471
+ const report = useCallback((text, warning = false, actions) => {
472
+ if (warning || actions) showNotice(text, warning, actions);
473
+ else setNotice(null);
474
+ void refresh();
475
+ }, [refresh, showNotice]);
476
+
477
+ const reportArchived = async (done, failed = [], stopped = false) => {
478
+ const detail = failed.map((item) => errorText(item, t, workspaceT)).filter(Boolean).join('; ');
479
+ const single = done.length === 1 && failed.length === 0;
480
+ const notices = archiveNotice ? await Promise.all(done.map(async (id) => {
481
+ try { return await archiveNotice(id); } catch { return undefined; }
482
+ })) : [];
483
+ const extra = notices.filter((notice) => notice?.text);
484
+ const text = single ? extra[0]?.text ?? workspaceT(stopped ? 'toast.stoppedAndArchived' : 'toast.archived')
485
+ : resultText(t, done.length, fill(t('notice.archived'), { n: done.length }), failed.length, detail);
486
+ const actions = done.length ? [{
487
+ label: workspaceT('toast.archivedUndo'), ...(single ? {} : { prefix: ' · ' }),
488
+ onClick: async () => {
489
+ try {
490
+ setNotice(null);
491
+ let result;
492
+ if (workspaceActions) {
493
+ const errors = [];
494
+ for (const id of done) {
495
+ try { await workspaceActions.unarchiveSession(id); }
496
+ catch (error) { errors.push({ id, message: errorText(error, t) }); }
497
+ }
498
+ result = { failed: errors };
499
+ } else result = await post('unarchive', { sessionIds: done });
500
+ const detail = result.failed.map((failure) => errorText(failure, t, workspaceT)).filter(Boolean).join('; ');
501
+ report(result.failed.length ? resultText(t, 0, '', result.failed.length, detail) : '', result.failed.length > 0);
502
+ } catch (error) { showNotice(errorText(error, t), true); }
503
+ },
504
+ }, { prefix: workspaceT('toast.archivedOr'), label: t('action.archiveCleanup'), onClick: () => {
505
+ setNotice(null); setChecked(new Set()); setQuery(''); setSearchCollapsed(new Set()); setTab('recycled');
506
+ } }] : undefined;
507
+ report(single || !extra.length ? text : `${text} · ${extra.map((notice) => notice.text).join(' · ')}`,
508
+ failed.length > 0 || extra.some((notice) => notice.tone === 'warning'), actions);
509
+ };
510
+
511
+ const archiveSessions = async (ids, stopActivity = false) => {
512
+ if (!workspaceActions) return post('archive', { sessionIds: ids, ...(stopActivity ? { stopActivity: true } : {}) });
513
+ setBusy(true);
514
+ const done = [], failed = [];
515
+ try {
516
+ for (const id of ids) {
517
+ try {
518
+ await workspaceActions.archiveSession(id, stopActivity ? { stopActivity: true } : {});
519
+ done.push(id);
520
+ } catch (error) {
521
+ const rpc = error?.rpcError;
522
+ if (rpc?.code === 'workspace/session-active' && Array.isArray(rpc.details?.activity)) {
523
+ failed.push({ id, title: sessionItems.find((item) => item.id === id)?.title || id, code: 'session_active', activity: rpc.details.activity });
524
+ } else failed.push({ id, message: errorText(error, t) });
525
+ }
526
+ }
527
+ return { done, failed };
528
+ } finally { setBusy(false); }
529
+ };
530
+
531
+ const runArchive = useCallback(async () => {
532
+ try {
533
+ if (selectedSessionIds.length === 0) return;
534
+ const result = await archiveSessions(selectedSessionIds);
535
+ setChecked(new Set(result.failed.map((item) => item.id)));
536
+ const active = result.failed.filter((item) => item.code === 'session_active');
537
+ const failures = result.failed.filter((item) => item.code !== 'session_active');
538
+ if (result.done.length || failures.length) {
539
+ await reportArchived(result.done, failures);
540
+ }
541
+ const showNext = (index) => {
542
+ const item = active[index];
543
+ if (!item) { setDialog(null); return; }
544
+ const next = () => showNext(index + 1);
545
+ setDialog({ kind: 'archiveActive', item, next, run: async () => {
546
+ try {
547
+ const retry = await archiveSessions([item.id], true);
548
+ if (retry.done.includes(item.id)) {
549
+ setChecked((current) => { const updated = new Set(current); updated.delete(item.id); return updated; });
550
+ await reportArchived(retry.done, [], true);
551
+ next();
552
+ } else {
553
+ showNotice(retry.failed.map((failure) => errorText(failure, t, workspaceT) || t('load.failed')).join('; '), true);
554
+ }
555
+ } catch (error) { showNotice(errorText(error, t), true); }
556
+ } });
557
+ };
558
+ if (active.length) showNext(0);
559
+ } catch (error) {
560
+ showNotice(errorText(error, t), true);
561
+ }
562
+ }, [checked, tab, overview, liveSessions, liveStatuses, post, report, showNotice, t, workspaceT, workspaceActions, archiveNotice]);
563
+
564
+ const runPurge = useCallback(async () => {
565
+ try {
566
+ if (selectedSessionIds.length === 0) return;
567
+ const r = await post('purge', { sessionIds: selectedSessionIds });
568
+ await syncSessionList();
569
+ setChecked(new Set(r.failed.map((item) => item.id)));
570
+ const detail = [...new Set(r.failed.map((item) => {
571
+ const reason = errorText(item, t);
572
+ const shown = archivedItems.find((entry) => entry.id === item.id);
573
+ return reason ? `${(shown && displayTitle(shown)) || (item.title === 'default-workspace' ? t('workspace.defaultName') : item.title) || item.id}: ${reason}` : '';
574
+ }).filter(Boolean))].join(' ');
575
+ report(r.failed.length ? resultText(t, 0, '', r.failed.length, detail) : '', r.failed.length > 0);
576
+ } catch (error) {
577
+ showNotice(errorText(error, t), true);
578
+ }
579
+ }, [checked, tab, overview, liveSessions, liveStatuses, scheduleSnapshot, post, report, showNotice, t, workspaceT, workspaceActions, syncSessionList]);
580
+
581
+ const runRestore = useCallback(async () => {
582
+ try {
583
+ if (selectedSessionIds.length === 0) return;
584
+ let r;
585
+ if (workspaceActions) {
586
+ const done = [], failed = [];
587
+ setBusy(true);
588
+ try {
589
+ for (const id of selectedSessionIds) {
590
+ try { await workspaceActions.unarchiveSession(id); done.push(id); }
591
+ catch (error) { failed.push({ id, message: errorText(error, t) }); }
592
+ }
593
+ r = { done, failed };
594
+ } finally { setBusy(false); }
595
+ } else r = await post('unarchive', { sessionIds: selectedSessionIds });
596
+ setChecked(new Set(r.failed.map((item) => item.id)));
597
+ const detail = r.failed.map((item) => errorText(item, t, workspaceT)).filter(Boolean).join('; ');
598
+ report(r.failed.length ? resultText(t, 0, '', r.failed.length, detail) : '', r.failed.length > 0);
599
+ } catch (error) {
600
+ showNotice(errorText(error, t), true);
601
+ }
602
+ }, [checked, tab, overview, liveSessions, liveStatuses, post, report, showNotice, t, workspaceActions]);
603
+
604
+ const runClean = useCallback(async (confirmedTasks = {}) => {
605
+ try {
606
+ const r = await post('residue', { keys: [...checked], confirmedTasks });
607
+ await syncSessionList();
608
+ setChecked(new Set(r.failed.map((item) => item.key)));
609
+ const detail = r.failed.map((item) => {
610
+ const reason = errorText(item, t);
611
+ const entry = overview?.residue?.items?.find((row) => row.key === item.key);
612
+ const name = entry?.label || item.id || item.key;
613
+ return reason ? `${name ? `${name}: ` : ''}${reason}` : '';
614
+ }).filter(Boolean).join('; ');
615
+ report(r.failed.length ? resultText(t, 0, '', r.failed.length, detail) : '', r.failed.length > 0);
616
+ } catch (error) {
617
+ showNotice(errorText(error, t), true);
618
+ }
619
+ }, [checked, overview, post, report, showNotice, t, syncSessionList]);
620
+
621
+ const ui = {
622
+ checked,
623
+ home: overview?.home,
624
+ officialSchedule, scheduleSnapshot, catalogT, scheduleT,
625
+ onOpenTask: async (sessionId, taskId) => {
626
+ try {
627
+ const result = await post('task', { sessionId, id: taskId });
628
+ if (!result.task) throw new Error(scheduleT('detail.missing'));
629
+ setDialog({ kind: 'taskDetail', task: result.task });
630
+ } catch (error) {
631
+ const message = String(error?.message ?? error);
632
+ showNotice(message.includes('dsh-mop:task_not_found') ? scheduleT('detail.missing')
633
+ : message.includes('dsh-mop:task_unavailable') ? scheduleT('list.error') : errorText(error, t), true);
634
+ }
635
+ },
636
+ onSelect: (key, on) => setChecked((prev) => {
637
+ const next = new Set(prev);
638
+ if (on) next.add(key); else next.delete(key);
639
+ return next;
640
+ }),
641
+ collapsed: query.trim() ? searchCollapsed : collapsed,
642
+ onToggleCollapse: (key) => (query.trim() ? setSearchCollapsed : setCollapsed)((prev) => {
643
+ const next = new Set(prev);
644
+ if (next.has(key)) next.delete(key); else next.add(key);
645
+ return next;
646
+ }),
647
+ };
648
+
649
+ const term = query.trim().toLocaleLowerCase();
650
+ const matches = (item) => !term || [item.id, item.title, item.workspaceTitle, item.workspacePath, item.label, item.hint, item.targetSessionId]
651
+ .some((value) => String(value ?? '').toLocaleLowerCase().includes(term));
652
+ const displayItems = tabItems().map((item) => ({ ...item,
653
+ title: displayTitle(item),
654
+ workspaceTitle: workspaceName(item),
655
+ }));
656
+ const visibleItems = displayItems.filter(matches);
657
+ const ready = !!overview && !busy;
658
+ const kindLabels = { 'orphan-cache': 'residue.orphanCache', 'orphan-task': 'residue.orphanTask', 'ghost-registry': 'residue.ghostRegistry',
659
+ 'shell-dir': 'residue.sessionDirectory', 'empty-project': 'residue.emptyProject' };
660
+ const allResidue = overview?.residue?.items ?? [];
661
+ const registeredIds = new Set(allResidue.filter((item) => item.kind === 'ghost-registry').map((item) => item.id));
662
+ const residueItems = allResidue.map((item) => ({ ...item,
663
+ workspaceTitle: workspaceName(item),
664
+ hint: t(kindLabels[item.kind]),
665
+ relatedRegistration: item.kind === 'orphan-cache' && registeredIds.has(item.id) }));
666
+ const visibleResidue = residueItems.filter(matches);
667
+ const allKeys = tab === 'residue' ? visibleResidue.map((x) => x.key)
668
+ : visibleItems.filter((x) => selectableIds.has(x.id)).map((x) => x.id);
669
+ const allSelected = allKeys.length > 0 && allKeys.every((k) => checked.has(k));
670
+ const toggleVisible = () => setChecked((prev) => {
671
+ const next = new Set(prev);
672
+ for (const key of allKeys) { if (allSelected) next.delete(key); else next.add(key); }
673
+ return next;
674
+ });
675
+ const selectedItems = tab === 'residue' ? residueItems.filter((x) => checked.has(x.key))
676
+ : tabItems().filter((x) => checked.has(x.id));
677
+ const measuredItems = selectedItems.filter((x) => typeof x.sizeBytes === 'number' && Number.isFinite(x.sizeBytes));
678
+ const selectedBytes = measuredItems.length ? measuredItems.reduce((sum, x) => sum + x.sizeBytes, 0) : null;
679
+ const tabLabels = { sessions: workspaceT('section.sessions'), recycled: t('tabs.archived'), residue: t('tabs.residue') };
680
+ const searchPlaceholder = t('search.placeholder', { section: tabLabels[tab] });
681
+ const confirmResidue = () => {
682
+ const tasks = selectedItems.filter((item) => item.kind === 'orphan-task');
683
+ const confirmedTasks = Object.fromEntries(tasks.map((item) => [item.id,
684
+ { targetSessionId: item.targetSessionId, updatedAt: item.updatedAt ?? null }]));
685
+ setDialog({ text: t('confirm.residue.title', { provider: t('tabs.residue') }), kind: 'clean', taskNames: tasks.map((item) => item.label),
686
+ run: () => runClean(confirmedTasks) });
687
+ };
688
+
689
+ return h('div', { className: 'dsh-mop' },
690
+ h(Style, null),
691
+ h('div', { className: 'dsh-mop-header' }, h(SegmentedTabs, {
692
+ className: 'dsh-mop-tabs', size: 'sm', label: workspaceT('actions.archive'), value: tab,
693
+ items: [['sessions', tabLabels.sessions], ['recycled', tabLabels.recycled], ['residue', tabLabels.residue]]
694
+ .map(([value, label]) => ({ value, label, id: `dsh-mop-tab-${value}`, panelId: `dsh-mop-panel-${value}` })),
695
+ onChange: (key) => { if (busy) return; setTab(key); setChecked(new Set()); setQuery(''); setSearchCollapsed(new Set()); setDialog(null); },
696
+ }),
697
+ h('div', { className: 'dsh-mop-search' },
698
+ h(Input, { className: 'dsh-mop-search-input', icon: officialIcon('search-outline', 16),
699
+ type: 'search', value: query, placeholder: searchPlaceholder, 'aria-label': searchPlaceholder,
700
+ onChange: (event) => { setQuery(event.target.value); setSearchCollapsed(new Set()); } }),
701
+ h(Button, { variant: 'ghost', size: 'sm', disabled: !ready || allKeys.length === 0,
702
+ onClick: toggleVisible }, allSelected ? t('selection.deselectAll') : t('selection.selectAll')))),
703
+ !overview ? h('div', { className: 'dsh-mop-body dsh-mop-state' },
704
+ loadError ? [t(loadError === 'host-version' ? 'host.updateRequired' : 'load.failed'), ' ', h(Button, { variant: 'outline', size: 'sm', onClick: () => { setLoadError(false); void refresh(); } }, t('retry'))] : t('loading')) : null,
705
+ overview && tab !== 'residue' ? h('div', { className: 'dsh-mop-body', role: 'tabpanel', id: `dsh-mop-panel-${tab}`, 'aria-labelledby': `dsh-mop-tab-${tab}` },
706
+ visibleItems.length === 0 ? h('p', { className: 'dsh-mop-state' }, query.trim() ? workspaceT('empty.noMatches')
707
+ : (tab === 'sessions' ? workspaceT('empty.none') : workspaceT('empty.noneArchived'))) :
708
+ h(HoverCardGroup, null, ...renderGroups(visibleItems, (x, check) => sessionCard(x, t, check, workspaceT), ui,
709
+ { t, workspaceT }))) : null,
710
+ overview && tab === 'residue' ? h('div', { className: 'dsh-mop-body', role: 'tabpanel', id: `dsh-mop-panel-${tab}`, 'aria-labelledby': `dsh-mop-tab-${tab}` },
711
+ visibleResidue.length === 0 ? h('p', { className: 'dsh-mop-state' }, query.trim() ? workspaceT('empty.noMatches') : t('empty.residue')) :
712
+ h(HoverCardGroup, null, ...renderResidueGroups(visibleResidue, ui, t, workspaceT))) : null,
713
+ h('div', { className: 'dsh-mop-foot' },
714
+ dialog?.kind === 'taskDetail' ? h(Modal, {
715
+ open: true, onClose: () => setDialog(null), closeLabel: scheduleT('detail.close'), className: 'dsh-mop-dialog',
716
+ title: scheduleT('detail.label'),
717
+ footer: h(Button, { variant: 'outline', onClick: () => setDialog(null) }, workspaceT('close')),
718
+ }, h('dl', { className: 'dsh-mop-task-detail' },
719
+ ...[
720
+ [scheduleT('detail.name'), dialog.task.title],
721
+ [scheduleT('detail.instruction'), dialog.task.prompt],
722
+ [scheduleT('statusFilter.label'), scheduleT(`status.${dialog.task.status}`)],
723
+ [scheduleT('rule.repeat'), taskRule(dialog.task, scheduleT)],
724
+ ...(dialog.task.status === 'active' && dialog.task.scheduledAt && Number.isFinite(Date.parse(dialog.task.scheduledAt))
725
+ ? [[scheduleT('detail.nextRun'), new Date(dialog.task.scheduledAt).toLocaleString()]] : []),
726
+ [scheduleT('host.target'), scheduleT(dialog.task.target?.kind === 'session' ? 'host.currentConversation'
727
+ : dialog.task.target?.kind === 'new_once' ? 'host.targetNewOnce' : 'host.targetNew')],
728
+ ].flatMap(([label, value], index) => [h('dt', { key: `label-${index}` }, label), h('dd', { key: `value-${index}` }, value)])))
729
+ : dialog?.kind === 'archiveActive' ? h(Modal, {
730
+ open: true, onClose: () => { if (!busy) dialog.next(); }, closeLabel: workspaceT('close'), className: 'dsh-mop-dialog',
731
+ title: workspaceT('archive.confirm.title'),
732
+ description: workspaceT('archive.confirm.desc', { title: dialog.item.title || dialog.item.id }),
733
+ footer: h(React.Fragment, null,
734
+ h(Button, { variant: 'outline', disabled: busy, onClick: dialog.next, 'data-modal-autofocus': '' }, workspaceT('cancel')),
735
+ h(Button, { variant: 'outline', className: 'dsh-mop-danger', disabled: busy, onClick: dialog.run },
736
+ workspaceT(busy ? 'archive.confirm.pending' : 'archive.confirm.action'))),
737
+ }, h('ul', { 'aria-label': workspaceT('archive.confirm.activity') },
738
+ ...dialog.item.activity.map((entry, index) => h('li', { key: index }, archiveActivityLine(entry, workspaceT)))),
739
+ dialog.item.activity.some((entry) => entry.kind === 'schedule') ? h('p', { role: 'note' }, t('archive.scheduleDeletion')) : null)
740
+ : dialog ? h(Modal, {
741
+ open: true, className: 'dsh-mop-dialog', title: dialog.text,
742
+ description: dialog.kind === 'purge' ? t('confirm.purge.description') : dialog.taskNames?.length ? t('confirm.tasks.description') : undefined,
743
+ closeLabel: workspaceT('close'), onClose: () => setDialog(null),
744
+ footer: h('div', { className: 'dsh-mop-confirm-actions' },
745
+ h(Button, { variant: 'outline', onClick: () => setDialog(null), 'data-modal-autofocus': '' }, scheduleT('delete.cancel')),
746
+ h(Button, { variant: 'outline', className: 'dsh-mop-danger',
747
+ onClick: async () => { const d = dialog; setDialog(null); await d.run(); } }, scheduleT(dialog.kind === 'purge' ? 'delete.confirm' : 'clear.confirm'))),
748
+ }, dialog.taskNames?.length ? h('div', { className: 'dsh-mop-confirm-tasks' },
749
+ h('ul', null, ...dialog.taskNames.map((name, index) => h('li', { key: index }, name)))) : null)
750
+ : null,
751
+ notice ? h(Toast, { key: notice.seq, text: notice.text, actions: notice.actions,
752
+ ...(notice.warning ? { icon: officialIcon('warning-outline', 16), holdMs: 8000 } : { tone: 'success', ...(notice.actions ? { holdMs: 6000 } : {}) }),
753
+ onDone: () => setNotice((current) => current?.seq === notice.seq ? null : current) }) : null,
754
+ h(React.Fragment, null,
755
+ h('span', { className: 'dsh-mop-foot-info' },
756
+ fill(t('selection.summary'), { n: checked.size, size: formatBytes(selectedBytes) })),
757
+ tab === 'sessions' ? h(Button, { variant: 'outline', disabled: !ready || selectedSessionIds.length === 0,
758
+ onClick: runArchive }, workspaceT('actions.archive')) : null,
759
+ tab === 'recycled' ? [
760
+ h(Button, { key: 'restore', variant: 'outline', disabled: !ready || selectedSessionIds.length === 0,
761
+ onClick: runRestore }, workspaceT('actions.unarchive')),
762
+ h(Button, { key: 'action.purge', variant: 'outline', className: 'dsh-mop-danger', disabled: !ready || selectedSessionIds.length === 0,
763
+ onClick: () => setDialog({ kind: 'purge', text: t('confirm.purge.title', { provider: t('tabs.archived') }), run: runPurge }) }, t('action.purge')),
764
+ ] : null,
765
+ tab === 'residue' ? h(Button, { variant: 'outline', className: 'dsh-mop-danger', disabled: !ready || checked.size === 0,
766
+ onClick: confirmResidue }, t('action.clean')) : null)));
767
+ }
768
+
769
+ /** 会话行:状态/选择框 + 标题 + 右侧元信息。 */
770
+ function sessionCard(x, t, checkNode, workspaceT = t) {
771
+ const timestamp = sessionTime(x);
772
+ const time = timestamp > 0 ? relativeTime(timestamp, workspaceT) : '';
773
+ const status = sessionStatuses(x)[0];
774
+ return {
775
+ main: [
776
+ x.protected ? h('span', { className: 'dsh-mop-lead', 'aria-label': t('protection.label') }, officialIcon('shield-outline', 14)) : checkNode,
777
+ ...(x.live && !x.protected ? [h('span', { className: 'dsh-mop-lead', 'aria-label': workspaceT(status.key, status.params) }, h(StateDot, { state: status.state }))] : []),
778
+ h('span', { className: 'dsh-mop-title' }, x.blank === true ? workspaceT('session.new') : x.title),
779
+ h('span', { className: 'dsh-mop-row-side has-columns' },
780
+ h('span', { className: 'dsh-mop-marker', ...(x.purgeBlock && !x.protected ? { 'aria-label': t(x.purgeBlock === 'schedule_reference' ? 'reference.schedule' : 'error.referenceCheck') } : { 'aria-hidden': true }) },
781
+ x.purgeBlock && !x.protected ? officialIcon('shield-outline', 14) : null),
782
+ h('span', { className: 'dsh-mop-size' }, typeof x.sizeBytes === 'number' ? formatBytes(x.sizeBytes) : ''),
783
+ h('span', { className: 'dsh-mop-time' }, time)),
784
+ ],
785
+ };
786
+ }
787
+
788
+ /** DSH theme's shared icon sprite, used by the official workspace rows. */
789
+ function groupHeading(key, title, isCollapsed, ui, path, createdAt, workspaceT) {
790
+ const anchorRef = { current: null };
791
+ const button = h('button', {
792
+ ref: anchorRef,
793
+ type: 'button', className: 'dsh-mop-group-name',
794
+ onClick: () => ui.onToggleCollapse(key), 'aria-expanded': !isCollapsed,
795
+ },
796
+ h('span', { className: 'dsh-mop-group-icon', 'aria-hidden': true },
797
+ officialIcon(`folder-${isCollapsed ? 'close' : 'open'}`, 16, 'dsh-mop-folder'),
798
+ officialIcon('triangle-right-fill', 14, `dsh-mop-chevron${isCollapsed ? '' : ' is-open'}`)),
799
+ h('span', { className: 'dsh-mop-group-label' }, title));
800
+ return h('div', { className: 'dsh-mop-group-title' }, path && createdAt != null && Number.isFinite(new Date(createdAt).getTime())
801
+ ? rowWithHover(`workspace:${key}`, button, cardContent({ anchorRef, title, path: displayPath(path, ui.home),
802
+ time: workspaceCreatedLabel(createdAt, workspaceT) }, workspaceT), workspaceT, path)
803
+ : button);
804
+ }
805
+
806
+ /** 按工作区分组的行;ui = {checked, onSelect(key), collapsed, onToggleCollapse(key)}。 */
807
+ function renderGroups(items, cardOf, ui, { t, workspaceT }) {
808
+ const byWs = new Map();
809
+ for (const it of sortByDisplayedTime(items, sessionTime)) {
810
+ const key = it.workspacePath || it.workspaceTitle || '';
811
+ if (!byWs.has(key)) byWs.set(key, { title: it.workspaceTitle || it.workspacePath || workspaceT('group.ungrouped'), path: it.workspacePath, createdAt: it.workspaceCreatedAt, list: [] });
812
+ byWs.get(key).list.push(it);
813
+ }
814
+ return [...byWs.entries()].map(([wsKey, group]) => {
815
+ const isCollapsed = ui.collapsed.has(wsKey);
816
+ return h('div', { key: wsKey, className: 'dsh-mop-group' },
817
+ groupHeading(wsKey, group.title, isCollapsed, ui, group.path, group.createdAt, workspaceT),
818
+ isCollapsed ? null : group.list.map((x) => {
819
+ const anchorRef = { current: null };
820
+ const blocked = x.protected;
821
+ const card = cardOf(x, blocked ? h('span', { className: 'dsh-mop-lead' }, '·') : h('input', {
822
+ type: 'checkbox', className: 'dsh-mop-check', checked: ui.checked.has(x.id),
823
+ onChange: () => ui.onSelect(x.id, !ui.checked.has(x.id)), 'aria-label': x.title,
824
+ }));
825
+ const row = h('label', { ref: anchorRef, className: `dsh-mop-row${blocked ? ' is-static' : ''}${x.archived ? ' is-archived' : ''}${ui.checked.has(x.id) ? ' is-selected' : ''}`,
826
+ onPointerEnter: titleEnter, onPointerLeave: titleLeave },
827
+ h('div', { className: 'dsh-mop-row-main' }, ...card.main));
828
+ const timestamp = sessionTime(x);
829
+ return rowWithHover(x.id, row, cardContent({ anchorRef, title: x.title, path: displayPath(x.cwd || x.workspacePath, ui.home),
830
+ time: x.blank ? '' : hoverTime(timestamp, workspaceT),
831
+ statuses: sessionStatuses(x).filter((status) => !x.archived || !['idle', 'done'].includes(status.state)),
832
+ archived: x.archived, tasks: x.purgeBlock === 'schedule_reference' ? x.scheduleTasks ?? [] : [],
833
+ officialSchedule: ui.officialSchedule, scheduleSnapshot: ui.scheduleSnapshot, catalogT: ui.catalogT, scheduleT: ui.scheduleT,
834
+ onOpenTask: (taskId) => ui.onOpenTask?.(x.id, taskId),
835
+ reason: x.protected ? t('protection.label') : x.purgeBlock === 'reference_check_failed' ? t('error.referenceCheck') : x.purgeBlock === 'schedule_reference' && !x.scheduleTasks?.length ? t('reference.schedule') : '' }, workspaceT),
836
+ workspaceT, x.blank ? undefined : x.title);
837
+ }));
838
+ });
839
+ }
840
+
841
+ /** 按可核实的工作区分组。 */
842
+ function renderResidueGroups(items, ui, t, workspaceT) {
843
+ const byWorkspace = new Map();
844
+ for (const item of sortByDisplayedTime(items, residueTime)) {
845
+ const workspaceKey = item.workspacePath || '';
846
+ if (!byWorkspace.has(workspaceKey)) byWorkspace.set(workspaceKey, {
847
+ title: item.workspaceTitle || item.workspacePath || workspaceT('group.ungrouped'), path: item.workspacePath, createdAt: item.workspaceCreatedAt, entries: [],
848
+ });
849
+ byWorkspace.get(workspaceKey).entries.push(item);
850
+ }
851
+ return [...byWorkspace].map(([workspaceKey, group]) => {
852
+ const key = `residue:workspace:${workspaceKey}`;
853
+ const isCollapsed = ui.collapsed.has(key);
854
+ return h('div', { key, className: 'dsh-mop-group' },
855
+ groupHeading(key, group.title, isCollapsed, ui, group.path, group.createdAt, workspaceT),
856
+ isCollapsed ? null : group.entries.map((item) => {
857
+ const anchorRef = { current: null };
858
+ const reason = item.kind === 'orphan-task' ? t('residue.orphanTask') : item.relatedRegistration ? t('residue.registeredCache') : '';
859
+ const row = h('label', { ref: anchorRef, onPointerEnter: titleEnter, onPointerLeave: titleLeave,
860
+ className: `dsh-mop-row${ui.checked.has(item.key) ? ' is-selected' : ''}` },
861
+ h('div', { className: 'dsh-mop-row-main' },
862
+ h('input', { type: 'checkbox', className: 'dsh-mop-check', checked: ui.checked.has(item.key),
863
+ onChange: () => ui.onSelect(item.key, !ui.checked.has(item.key)), 'aria-label': item.label }),
864
+ h('span', { className: 'dsh-mop-title' }, item.label),
865
+ h('span', { className: 'dsh-mop-row-side has-columns' },
866
+ h('span', { className: 'dsh-mop-marker', 'aria-hidden': true }, item.kind === 'orphan-task' ? officialIcon('clock-outline', 14) : null),
867
+ h('span', { className: 'dsh-mop-size' }, typeof item.sizeBytes === 'number' ? formatBytes(item.sizeBytes) : ''),
868
+ h('span', { className: 'dsh-mop-time' }, residueTime(item) > 0 ? relativeTime(residueTime(item), workspaceT) : ''))));
869
+ return rowWithHover(item.key, row, cardContent({ anchorRef, title: item.label,
870
+ path: displayPath(item.kind === 'orphan-task' ? item.targetSessionId : item.workspacePath || (item.id !== item.label ? item.id : ''), ui.home),
871
+ time: hoverTime(residueTime(item), workspaceT), reason,
872
+ tasks: item.kind === 'orphan-task' ? [{ id: item.id, title: item.label, status: item.status, showStatus: true }] : [],
873
+ scheduleT: ui.scheduleT, onOpenTask: (taskId) => ui.onOpenTask?.(item.targetSessionId, taskId) }, workspaceT),
874
+ workspaceT, item.label);
875
+ }));
876
+ });
877
+ }
878
+
879
+ /** 组件内样式:随组件卸载移除,仅用官方主题令牌。 */
880
+ function Style() {
881
+ return h('style', null, `
882
+ .dsh-mop { display: flex; flex-direction: column; height: 100%; min-height: 0; min-width: 0; font-family: var(--dsw-font-family, inherit); font-size: var(--dsh-content-font-size, 14px); line-height: 1.5; color: var(--dsw-alias-label-primary); }
883
+ .dsh-mop *, .dsh-mop *::before, .dsh-mop *::after { box-sizing: border-box; }
884
+ .dsh-mop button, .dsh-mop input { font-family: inherit; }
885
+ .dsh-mop-body { flex: 1 1 0; min-width: 0; min-height: 0; overflow-y: auto; overflow-x: hidden; }
886
+ .dsh-mop-header { flex: none; min-width: 0; padding-top: 8px; }
887
+ .dsh-mop-state { padding: 32px 0; text-align: center; color: var(--dsw-alias-label-secondary); }
888
+ .dsh-mop-search { display: flex; align-items: center; gap: 8px; margin: 14px 0 8px; min-width: 0; }
889
+ .dsh-mop-search-input { flex: 1 1 240px; min-width: 0; }
890
+ .dsh-mop-tabs { align-self: flex-start; max-width: 100%; }
891
+ .dsh-mop-group + .dsh-mop-group { margin-top: 4px; }
892
+ .dsh-mop-group > * + * { margin-top: 2px; }
893
+ .dsh-mop-group-title { display: flex; align-items: center; width: 100%; }
894
+ .dsh-mop-group-title > span:has(> .dsh-mop-group-name) { display: block; width: 100%; }
895
+ .dsh-mop-group-name { display: flex; align-items: center; gap: 6px; width: 100%; min-width: 0; height: 32px; padding: 0 8px; border: 0; border-radius: var(--dsw-radius-md, 8px); background: transparent; color: var(--dsw-alias-label-primary); font-size: 14px; line-height: 20px; cursor: pointer; text-align: left; }
896
+ .dsh-mop-group-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
897
+ /* Official compact card is portaled above the settings panel. */
898
+ span[data-dsh-mop-positioned] > div { z-index: 1001; max-width: calc(100vw - 16px); left: var(--dsh-mop-card-left) !important; }
899
+ .dsh-mop-hover-content { display: flex; flex-direction: column; gap: 8px; }
900
+ .dsh-mop-hover-title { color: var(--dsw-alias-hovercard-label-primary); font-size: 14px; line-height: 20px; overflow-wrap: break-word; }
901
+ .dsh-mop-hover-path { color: var(--dsw-alias-hovercard-label-secondary); font-size: 12px; line-height: 16px; word-break: break-all; }
902
+ .dsh-mop-hover-time { color: var(--dsw-alias-hovercard-label-secondary); font-size: 12px; line-height: 16px; }
903
+ .dsh-mop-hover-status { display: flex; align-items: center; gap: 8px; color: var(--dsw-alias-hovercard-label-tertiary); font-size: 12px; line-height: 20px; }
904
+ .dsh-mop-hover-status span { min-width: 0; overflow-wrap: break-word; }
905
+ .dsh-mop-hover-archived > svg { flex-shrink: 0; margin: 0 -4px; }
906
+ .dsh-mop-hover-task-button { width: 100%; padding: 0; border: 0; background: transparent; font-family: inherit; text-align: left; cursor: pointer; }
907
+ .dsh-mop-hover-task-button:hover { color: var(--dsw-alias-hovercard-label-primary); }
908
+ .dsh-mop-hover-task-button:focus-visible { outline: var(--dsw-focus-ring-width, 2px) solid var(--dsw-focus-ring-color, currentColor); outline-offset: 2px; }
909
+ .dsh-mop-hover-task-button:disabled { cursor: default; }
910
+ .dsh-mop-group-icon { flex: 0 0 16px; width: 16px; height: 20px; display: inline-flex; align-items: center; justify-content: center; color: var(--dsw-alias-label-tertiary); }
911
+ .dsh-mop-folder { width: 16px; height: 16px; }
912
+ .dsh-mop-chevron { width: 14px; height: 14px; }
913
+ .dsh-mop-chevron { display: none; color: var(--dsw-alias-label-caption); transition: transform 150ms var(--ds-ease-in-out, ease-in-out); }
914
+ .dsh-mop-chevron.is-open { transform: rotate(90deg); }
915
+ @media (hover: hover) { .dsh-mop-group-name:hover { background: var(--dsw-alias-interactive-bg-hover, var(--dsw-alias-bg-layer-2)); } .dsh-mop-group-name:hover .dsh-mop-folder { display: none; } .dsh-mop-group-name:hover .dsh-mop-chevron { display: block; } }
916
+ @media (prefers-reduced-motion: reduce) { .dsh-mop-chevron { transition: none; } }
917
+ .dsh-mop-row { display: flex; align-items: center; height: 32px; padding: 0 8px 0 24px; border-radius: var(--dsw-radius-md, 8px); cursor: pointer; }
918
+ .dsh-mop-row:hover, .dsh-mop-row.is-selected { background: var(--dsw-alias-interactive-bg-hover, var(--dsw-alias-bg-layer-2)); }
919
+ .dsh-mop-row.is-static { cursor: default; }
920
+ .dsh-mop-row.is-static:hover { background: transparent; }
921
+ .dsh-mop-row-main { display: flex; align-items: center; gap: 6px; min-width: 0; flex: 1; }
922
+ .dsh-mop-row-side { margin-left: auto; color: var(--dsw-alias-label-tertiary); font-size: 10px; line-height: 16px; white-space: nowrap; }
923
+ .dsh-mop-row-side.has-columns { flex: 0 0 min(136px, 50%); min-width: 0; display: grid; grid-template-columns: 16px minmax(0, 1fr) minmax(0, 1fr); column-gap: 6px; align-items: center; text-align: right; }
924
+ .dsh-mop-marker { width: 16px; height: 20px; display: inline-flex; align-items: center; justify-content: center; }
925
+ .dsh-mop-size, .dsh-mop-time { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
926
+ .dsh-mop-check { flex: 0 0 auto; width: 16px; height: 16px; margin: 0; accent-color: var(--dsw-alias-brand-primary); }
927
+ .dsh-mop-check:focus-visible { outline: var(--dsw-focus-ring-width, 2px) solid var(--dsw-focus-ring-color, var(--dsw-alias-brand-primary)); outline-offset: 2px; }
928
+ .dsh-mop-lead { flex: 0 0 16px; display: inline-flex; align-items: center; justify-content: center; color: var(--dsw-alias-label-secondary); }
929
+ .dsh-mop-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 14px; line-height: 20px; }
930
+ .dsh-mop-row.is-archived .dsh-mop-title { color: var(--dsw-alias-label-caption); }
931
+ @media (hover: hover) { .dsh-mop-row:hover .dsh-mop-title { text-overflow: clip; } }
932
+ .dsh-mop-title[data-scrolled] { mask-image: linear-gradient(to right, transparent, #000 12px); }
933
+ .dsh-mop-title[data-clipped] { mask-image: linear-gradient(to left, transparent, #000 12px); }
934
+ .dsh-mop-title[data-scrolled][data-clipped] { mask-image: linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent); }
935
+ .dsh-mop-foot { flex: none; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 12px 0 0; border-top: 0.5px solid var(--dsw-alias-border-l2); }
936
+ .dsh-mop-foot-info { flex: 1 1 100px; color: var(--dsw-alias-label-secondary); font-size: .86em; }
937
+ .dsh-mop-group-name:focus-visible { outline: var(--dsw-focus-ring-width, 2px) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: 2px; }
938
+ .dsh-mop-danger { color: var(--dsw-alias-state-error-primary); --dsh-button-outline-color: var(--dsw-alias-state-error-primary); }
939
+ .dsh-mop-confirm-actions { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; }
940
+ .dsh-mop-confirm-tasks { min-width: 0; }
941
+ .dsh-mop-confirm-tasks ul { margin: 4px 0 0; padding-left: 20px; }
942
+ div:has(> .dsh-mop-dialog) { z-index: 1002; }
943
+ .dsh-mop-task-detail { display: grid; gap: 6px; margin: 0; font-size: 14px; }
944
+ .dsh-mop-task-detail dt { color: var(--dsw-alias-label-secondary); }
945
+ .dsh-mop-task-detail dd { margin: 0 0 10px; white-space: pre-wrap; overflow-wrap: anywhere; }
946
+ `);
947
+ }
948
+
949
+ /** 设置导航图标跟随 DSH 主题的 archive-outline 图标。 */
950
+ function NavIcon({ size = 16 }) {
951
+ return officialIcon('archive-outline', size);
952
+ }
953
+
954
+ return {
955
+ inject: ['slots', 'locale'],
956
+ async apply(ctx) {
957
+ // 语言包是包内 chunk:宿主按需下发,地址带版本号,之后走浏览器缓存。
958
+ // 单个语言载入失败只让该语言回退英文;英文不可用则无法显示界面。
959
+ const loaded = await Promise.allSettled(LANGUAGE_FILES.map(async (language) =>
960
+ [language, (await require.async(`./client.${language}.js`)).messages]));
961
+ for (const [index, item] of loaded.entries()) {
962
+ if (item.status === 'rejected') console.warn(`dsh-mop: ${LANGUAGE_FILES[index]} UI text unavailable`, item.reason);
963
+ }
964
+ LOCALES = Object.fromEntries(loaded.filter((item) => item.status === 'fulfilled').map((item) => item.value));
965
+ if (!LOCALES.en) throw new Error('dsh-mop: English UI text could not be loaded');
966
+ ctx.effect(() => ctx.locale.register(NS, LOCALES));
967
+ const t = officialTranslator(ctx.locale);
968
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
969
+ name: 'settings.section',
970
+ id: 'dsh-mop',
971
+ order: 60,
972
+ label: () => ctx.locale.bind('workspace')('actions.archive'),
973
+ locale: NS,
974
+ inject: () => {
975
+ const workspace = ctx.get?.('uiWorkspace');
976
+ const sessionsService = ctx.get?.('sessions');
977
+ const entries = ctx.slots.entriesOfSlot?.('sidebar.session.row.hover') ?? ctx.slots.entries?.('sidebar.session.row.hover') ?? [];
978
+ const entry = entries.find((item) => item.options?.id === 'schedule-tasks');
979
+ let scheduleSource;
980
+ try { scheduleSource = entry?.inject?.()?.hooks?.catalog; } catch { /* optional official task view */ }
981
+ return { t, workspaceT: ctx.locale.bind('workspace'), scheduleT: ctx.locale.bind('schedule.manager'),
982
+ catalogT: ctx.locale.bind('schedule.catalog'),
983
+ ...(typeof ctx.waterfall === 'function' ? { archiveNotice: (id) => ctx.waterfall('workspace/archive-notice', id, () => Promise.resolve(undefined)) } : {}),
984
+ ...(workspace && typeof workspace.archiveSession === 'function' && typeof workspace.unarchiveSession === 'function' ? { workspaceActions: workspace } : {}),
985
+ ...(sessionsService && typeof sessionsService.refresh === 'function' ? { sessionsService } : {}),
986
+ ...(entry?.component && typeof scheduleSource?.subscribe === 'function' && typeof scheduleSource?.getSnapshot === 'function'
987
+ ? { officialSchedule: entry.component, scheduleSource } : {}) };
988
+ },
989
+ }, Section));
990
+ ctx.slots.inject('settings.section.icon', () => ctx.slots.register({
991
+ name: 'settings.section.icon',
992
+ id: 'dsh-mop',
993
+ }, NavIcon));
994
+ },
995
+ };
996
+ },
997
+ });