dsh-mop 0.2.0 → 0.2.1

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 CHANGED
@@ -16,7 +16,7 @@ window.__ModuleLoader__.load({
16
16
  factory(require) {
17
17
  const React = require('react');
18
18
  const { HoverCard, HoverCardGroup, StateDot, Button, Input, SegmentedTabs, Toast, Modal } = require('@deepseek-ai/dsh-client-ui-primitives');
19
- const { useState, useEffect, useCallback } = React;
19
+ const { useState, useEffect, useCallback, useMemo } = React;
20
20
  const h = React.createElement;
21
21
 
22
22
  const NS = 'dsh-mop';
@@ -41,10 +41,12 @@ window.__ModuleLoader__.load({
41
41
  'residue.ghostRegistry': '无对应会话的注册',
42
42
  'residue.sessionDirectory': '未识别会话目录',
43
43
  'residue.emptyProject': '空会话目录',
44
+ 'residue.memoryResident': '已删除会话仍在内存,重启后自动消散',
44
45
  'confirm.tasks.description': '所选任务及其保存的运行记录将被删除',
45
46
  'error.schedule_changed': '任务已变化,请刷新后重试',
46
- 'error.session_resident': '会话仍加载在本 DSH 实例中;重启 DSH 后可删除',
47
+ 'error.session_resident': '会话仍加载在本 DSH,重启后可删除',
47
48
  'error.purge_busy': '会话正在清理,请稍后重试',
49
+ 'error.cleanup_partial': '清理被中断',
48
50
  'error.workspace_unavailable': '无法检查工作区注册',
49
51
  'error.workspace_filtered': '工作区含其他隐藏注册,无法单独移除',
50
52
  'error.unsupported_storage': '无法确认会话日志位置',
@@ -65,7 +67,11 @@ window.__ModuleLoader__.load({
65
67
  'error.purge_failed': '操作失败,请重试',
66
68
  'error.residue_failed': '操作失败,请重试',
67
69
  'empty.residue': '暂无结果',
68
- 'notice.failed': '失败 {count}',
70
+ 'notice.purgeFailed': '删除失败:{reasons}',
71
+ 'notice.restoreFailed': '取消归档失败:{reasons}',
72
+ 'notice.archiveFailed': '归档失败:{reasons}',
73
+ 'notice.cleanFailed': '清理失败:{reasons}',
74
+ 'notice.listSeparator': ';',
69
75
  'selection.selectAll': '全选',
70
76
  'selection.deselectAll': '取消全选',
71
77
  'confirm.purge.title': '删除 {provider}?',
@@ -170,10 +176,12 @@ window.__ModuleLoader__.load({
170
176
  'residue.ghostRegistry': 'ghost registration',
171
177
  'residue.sessionDirectory': 'shell dir',
172
178
  'residue.emptyProject': 'empty project dir',
179
+ 'residue.memoryResident': 'deleted session still in memory, clears on restart',
173
180
  'confirm.tasks.description': 'Selected tasks and their saved run history will be deleted',
174
181
  'error.schedule_changed': 'Task changed; refresh and try again',
175
- 'error.session_resident': 'The session is still loaded in this DSH instance; restart DSH to delete it',
182
+ 'error.session_resident': 'Still loaded in this DSH, restart to delete',
176
183
  'error.purge_busy': 'Session cleanup is in progress; try again later',
184
+ 'error.cleanup_partial': 'Cleanup was interrupted',
177
185
  'error.workspace_unavailable': 'Cannot check workspace registrations',
178
186
  'error.workspace_filtered': 'Workspace has other hidden registrations; cannot remove this one separately',
179
187
  'error.unsupported_storage': 'Cannot identify the session log location',
@@ -194,7 +202,11 @@ window.__ModuleLoader__.load({
194
202
  'error.purge_failed': 'Could not complete the action. Try again.',
195
203
  'error.residue_failed': 'Could not complete the action. Try again.',
196
204
  'empty.residue': 'No results',
197
- 'notice.failed': 'Failed {count}',
205
+ 'notice.purgeFailed': 'Delete failed: {reasons}',
206
+ 'notice.restoreFailed': 'Unarchive failed: {reasons}',
207
+ 'notice.archiveFailed': 'Archive failed: {reasons}',
208
+ 'notice.cleanFailed': 'Cleanup failed: {reasons}',
209
+ 'notice.listSeparator': '; ',
198
210
  'selection.selectAll': 'Select all',
199
211
  'selection.deselectAll': 'Deselect all',
200
212
  'confirm.purge.title': 'Delete {provider}?',
@@ -299,10 +311,12 @@ window.__ModuleLoader__.load({
299
311
  'residue.ghostRegistry': '幽霊登録',
300
312
  'residue.sessionDirectory': '殻ディレクトリ',
301
313
  'residue.emptyProject': '空プロジェクト',
314
+ 'residue.memoryResident': '削除済みセッションがメモリに残存、再起動で消滅',
302
315
  'confirm.tasks.description': '選択したタスクと保存された実行履歴が削除されます',
303
316
  'error.schedule_changed': 'タスクが変更されました。更新して再試行してください',
304
- 'error.session_resident': 'このセッションはこの DSH インスタンスに読み込まれたままです。DSH を再起動すると削除できます',
317
+ 'error.session_resident': 'この DSH に読み込まれたままです。再起動後に削除できます',
305
318
  'error.purge_busy': 'セッションのクリーンアップ中です。後でもう一度お試しください',
319
+ 'error.cleanup_partial': 'クリーンアップが中断されました',
306
320
  'error.workspace_unavailable': 'ワークスペース登録を確認できません',
307
321
  'error.workspace_filtered': '他の非表示の登録があるため個別に削除できません',
308
322
  'error.unsupported_storage': 'セッションログの場所を確認できません',
@@ -323,7 +337,11 @@ window.__ModuleLoader__.load({
323
337
  'error.purge_failed': '操作に失敗しました。再試行してください。',
324
338
  'error.residue_failed': '操作に失敗しました。再試行してください。',
325
339
  'empty.residue': '結果なし',
326
- 'notice.failed': '失敗 {count}',
340
+ 'notice.purgeFailed': '削除に失敗しました:{reasons}',
341
+ 'notice.restoreFailed': 'アーカイブ解除に失敗しました:{reasons}',
342
+ 'notice.archiveFailed': 'アーカイブに失敗しました:{reasons}',
343
+ 'notice.cleanFailed': 'クリーンアップに失敗しました:{reasons}',
344
+ 'notice.listSeparator': '。',
327
345
  'selection.selectAll': 'すべて選択',
328
346
  'selection.deselectAll': 'すべて解除',
329
347
  'confirm.purge.title': '{provider}を削除しますか?',
@@ -428,10 +446,12 @@ window.__ModuleLoader__.load({
428
446
  'residue.ghostRegistry': 'registro fantasma',
429
447
  'residue.sessionDirectory': 'directorio casca',
430
448
  'residue.emptyProject': 'directorio de proyecto vacío',
449
+ 'residue.memoryResident': 'sesión eliminada aún en memoria, desaparece al reiniciar',
431
450
  'confirm.tasks.description': 'Se eliminarán las tareas seleccionadas y su historial guardado',
432
451
  'error.schedule_changed': 'La tarea cambió; actualiza e inténtalo de nuevo',
433
- 'error.session_resident': 'La sesión sigue cargada en esta instancia de DSH; reinicia DSH para eliminarla',
452
+ 'error.session_resident': 'Sigue cargada en este DSH, reinicia para eliminarla',
434
453
  'error.purge_busy': 'Se está limpiando la sesión; inténtalo más tarde',
454
+ 'error.cleanup_partial': 'Se interrumpió la limpieza',
435
455
  'error.workspace_unavailable': 'No se pueden comprobar los registros del espacio de trabajo',
436
456
  'error.workspace_filtered': 'Otros registros ocultos impiden eliminar este por separado',
437
457
  'error.unsupported_storage': 'No se puede identificar la ubicación del registro',
@@ -452,7 +472,11 @@ window.__ModuleLoader__.load({
452
472
  'error.purge_failed': 'No se pudo completar la acción. Inténtelo de nuevo.',
453
473
  'error.residue_failed': 'No se pudo completar la acción. Inténtelo de nuevo.',
454
474
  'empty.residue': 'Sin resultados',
455
- 'notice.failed': 'Error {count}',
475
+ 'notice.purgeFailed': 'Error al eliminar: {reasons}',
476
+ 'notice.restoreFailed': 'Error al desarchivar: {reasons}',
477
+ 'notice.archiveFailed': 'Error al archivar: {reasons}',
478
+ 'notice.cleanFailed': 'Error al limpiar: {reasons}',
479
+ 'notice.listSeparator': '; ',
456
480
  'selection.selectAll': 'Seleccionar todo',
457
481
  'selection.deselectAll': 'Deseleccionar todo',
458
482
  'confirm.purge.title': '¿Eliminar {provider}?',
@@ -557,10 +581,12 @@ window.__ModuleLoader__.load({
557
581
  'residue.ghostRegistry': 'entrée fantôme',
558
582
  'residue.sessionDirectory': 'répertoire coquille',
559
583
  'residue.emptyProject': 'répertoire de projet vide',
584
+ 'residue.memoryResident': 'session supprimée encore en mémoire, disparaît au redémarrage',
560
585
  'confirm.tasks.description': 'Les tâches sélectionnées et leur historique enregistré seront supprimés',
561
586
  'error.schedule_changed': 'La tâche a changé ; actualisez et réessayez',
562
- 'error.session_resident': 'La session est toujours chargée dans cette instance de DSH ; redémarrez DSH pour la supprimer',
587
+ 'error.session_resident': 'Toujours chargée dans ce DSH, redémarrez pour la supprimer',
563
588
  'error.purge_busy': 'Nettoyage de la session en cours ; réessayez plus tard',
589
+ 'error.cleanup_partial': 'Le nettoyage a été interrompu',
564
590
  'error.workspace_unavailable': 'Impossible de vérifier les inscriptions de l’espace de travail',
565
591
  'error.workspace_filtered': 'D’autres inscriptions masquées empêchent la suppression individuelle',
566
592
  'error.unsupported_storage': 'Impossible de localiser le journal de session',
@@ -581,7 +607,11 @@ window.__ModuleLoader__.load({
581
607
  'error.purge_failed': 'Impossible de terminer l’action. Réessayez.',
582
608
  'error.residue_failed': 'Impossible de terminer l’action. Réessayez.',
583
609
  'empty.residue': 'Aucun résultat',
584
- 'notice.failed': 'Échec du {count}',
610
+ 'notice.purgeFailed': 'Échec de la suppression : {reasons}',
611
+ 'notice.restoreFailed': 'Échec de la restauration : {reasons}',
612
+ 'notice.archiveFailed': 'Échec de l’archivage : {reasons}',
613
+ 'notice.cleanFailed': 'Échec du nettoyage : {reasons}',
614
+ 'notice.listSeparator': ' ; ',
585
615
  'selection.selectAll': 'Tout sélectionner',
586
616
  'selection.deselectAll': 'Tout désélectionner',
587
617
  'confirm.purge.title': 'Supprimer {provider} ?',
@@ -686,10 +716,12 @@ window.__ModuleLoader__.load({
686
716
  'residue.ghostRegistry': 'Geister-Eintrag',
687
717
  'residue.sessionDirectory': 'Hüllen-Verzeichnis',
688
718
  'residue.emptyProject': 'leeres Projektverzeichnis',
719
+ 'residue.memoryResident': 'gelöschte Sitzung noch im Speicher, verschwindet nach Neustart',
689
720
  'confirm.tasks.description': 'Ausgewählte Aufgaben und gespeicherte Ausführungen werden gelöscht',
690
721
  'error.schedule_changed': 'Aufgabe geändert; aktualisieren und erneut versuchen',
691
- 'error.session_resident': 'Die Sitzung ist noch in dieser DSH-Instanz geladen; starten Sie DSH neu, um sie zu löschen',
722
+ 'error.session_resident': 'Noch in dieser DSH geladen, nach Neustart löschen',
692
723
  'error.purge_busy': 'Sitzung wird bereinigt; später erneut versuchen',
724
+ 'error.cleanup_partial': 'Die Bereinigung wurde unterbrochen',
693
725
  'error.workspace_unavailable': 'Arbeitsbereichseinträge können nicht geprüft werden',
694
726
  'error.workspace_filtered': 'Andere verborgene Einträge verhindern das einzelne Entfernen',
695
727
  'error.unsupported_storage': 'Speicherort des Sitzungsprotokolls nicht ermittelbar',
@@ -710,7 +742,11 @@ window.__ModuleLoader__.load({
710
742
  'error.purge_failed': 'Die Aktion konnte nicht abgeschlossen werden. Versuchen Sie es erneut.',
711
743
  'error.residue_failed': 'Die Aktion konnte nicht abgeschlossen werden. Versuchen Sie es erneut.',
712
744
  'empty.residue': 'Keine Ergebnisse',
713
- 'notice.failed': 'Fehlgeschlagen {count}',
745
+ 'notice.purgeFailed': 'Löschen fehlgeschlagen: {reasons}',
746
+ 'notice.restoreFailed': 'Dearchivieren fehlgeschlagen: {reasons}',
747
+ 'notice.archiveFailed': 'Archivieren fehlgeschlagen: {reasons}',
748
+ 'notice.cleanFailed': 'Bereinigung fehlgeschlagen: {reasons}',
749
+ 'notice.listSeparator': '; ',
714
750
  'selection.selectAll': 'Alles auswählen',
715
751
  'selection.deselectAll': 'Alle abwählen',
716
752
  'confirm.purge.title': '{provider} löschen?',
@@ -815,10 +851,12 @@ window.__ModuleLoader__.load({
815
851
  'residue.ghostRegistry': 'запись-призрак',
816
852
  'residue.sessionDirectory': 'каталог-оболочка',
817
853
  'residue.emptyProject': 'пустой каталог проекта',
854
+ 'residue.memoryResident': 'удалённый сеанс ещё в памяти, исчезнет после перезапуска',
818
855
  'confirm.tasks.description': 'Выбранные задачи и сохранённая история будут удалены',
819
856
  'error.schedule_changed': 'Задача изменилась; обновите данные и повторите попытку',
820
- 'error.session_resident': 'Сеанс всё ещё загружен в этом экземпляре DSH; перезапустите DSH, чтобы удалить его',
857
+ 'error.session_resident': 'Всё ещё загружен в этом DSH, перезапустите для удаления',
821
858
  'error.purge_busy': 'Идёт очистка сеанса; повторите попытку позже',
859
+ 'error.cleanup_partial': 'Очистка была прервана',
822
860
  'error.workspace_unavailable': 'Не удалось проверить записи рабочего пространства',
823
861
  'error.workspace_filtered': 'Другие скрытые записи мешают удалить эту запись отдельно',
824
862
  'error.unsupported_storage': 'Не удалось определить расположение журнала сеанса',
@@ -839,7 +877,11 @@ window.__ModuleLoader__.load({
839
877
  'error.purge_failed': 'Не удалось выполнить действие. Повторите попытку.',
840
878
  'error.residue_failed': 'Не удалось выполнить действие. Повторите попытку.',
841
879
  'empty.residue': 'Нет результатов',
842
- 'notice.failed': 'Ошибка {count}',
880
+ 'notice.purgeFailed': 'Не удалось удалить: {reasons}',
881
+ 'notice.restoreFailed': 'Не удалось разархивировать: {reasons}',
882
+ 'notice.archiveFailed': 'Не удалось архивировать: {reasons}',
883
+ 'notice.cleanFailed': 'Не удалось очистить: {reasons}',
884
+ 'notice.listSeparator': '; ',
843
885
  'selection.selectAll': 'Выбрать все',
844
886
  'selection.deselectAll': 'Отменить выбор всех',
845
887
  'confirm.purge.title': 'Удалить {provider}?',
@@ -944,10 +986,12 @@ window.__ModuleLoader__.load({
944
986
  'residue.ghostRegistry': 'registro fantasma',
945
987
  'residue.sessionDirectory': 'diretório casca',
946
988
  'residue.emptyProject': 'diretório de projeto vazio',
989
+ 'residue.memoryResident': 'sessão excluída ainda na memória, some ao reiniciar',
947
990
  'confirm.tasks.description': 'As tarefas selecionadas e seu histórico salvo serão excluídos',
948
991
  'error.schedule_changed': 'A tarefa mudou; atualize e tente novamente',
949
- 'error.session_resident': 'A sessão ainda está carregada nesta instância do DSH; reinicie o DSH para excluí-la',
992
+ 'error.session_resident': 'Ainda carregada neste DSH, reinicie para excluí-la',
950
993
  'error.purge_busy': 'Limpeza da sessão em andamento; tente novamente mais tarde',
994
+ 'error.cleanup_partial': 'A limpeza foi interrompida',
951
995
  'error.workspace_unavailable': 'Não foi possível verificar os registros do espaço de trabalho',
952
996
  'error.workspace_filtered': 'Outros registros ocultos impedem a remoção individual',
953
997
  'error.unsupported_storage': 'Não foi possível identificar a localização do log',
@@ -968,7 +1012,11 @@ window.__ModuleLoader__.load({
968
1012
  'error.purge_failed': 'Não foi possível concluir a ação. Tente novamente.',
969
1013
  'error.residue_failed': 'Não foi possível concluir a ação. Tente novamente.',
970
1014
  'empty.residue': 'Nenhum resultado',
971
- 'notice.failed': 'Falha {count}',
1015
+ 'notice.purgeFailed': 'Falha ao excluir: {reasons}',
1016
+ 'notice.restoreFailed': 'Falha ao restaurar: {reasons}',
1017
+ 'notice.archiveFailed': 'Falha ao arquivar: {reasons}',
1018
+ 'notice.cleanFailed': 'Falha na limpeza: {reasons}',
1019
+ 'notice.listSeparator': '; ',
972
1020
  'selection.selectAll': 'Selecionar tudo',
973
1021
  'selection.deselectAll': 'Desmarcar tudo',
974
1022
  'confirm.purge.title': 'Excluir {provider}?',
@@ -1058,8 +1106,6 @@ window.__ModuleLoader__.load({
1058
1106
  },
1059
1107
  };
1060
1108
 
1061
- const fill = (template, params) => String(template ?? '').replace(/\{(\w+)\}/g, (_, k) => String(params?.[k] ?? ''));
1062
-
1063
1109
  const ERROR_KEYS = { session_not_archived: 'error.notArchived',
1064
1110
  session_not_found: 'error.sessionNotFound', protected_workspace: 'error.workspaceProtected', schedule_reference: 'reference.schedule',
1065
1111
  reference_check_failed: 'error.referenceCheck' };
@@ -1078,13 +1124,41 @@ window.__ModuleLoader__.load({
1078
1124
  return reason + count + detail;
1079
1125
  }
1080
1126
 
1081
- function resultText(t, completed, successText, failures, detail) {
1127
+ /** 官方失败模板句(toast.createFailed 同款):「{动作}失败:{reasons}」,
1128
+ * 冒号烘焙在 locale 模板里;原因去重、以分句符号相连。无原因时去掉
1129
+ * 尾随冒号即短句(toast.pinFailed 同款)。哪个条目失败看列表里保持
1130
+ * 勾选的行,toast 不计数。 */
1131
+ function resultText(t, completed, successText, failureKey, detail) {
1082
1132
  const parts = [];
1083
- if (completed > 0 || failures === 0) parts.push(successText);
1084
- if (failures > 0) parts.push(`${fill(t('notice.failed', { n: failures, count: failures }), { n: failures, count: failures })}${detail ? `: ${detail}` : ''}`);
1133
+ if (completed > 0 || !failureKey) parts.push(successText);
1134
+ if (failureKey) {
1135
+ const reasons = [...new Set((Array.isArray(detail) ? detail : detail ? [detail] : []).filter(Boolean))]
1136
+ .join(t('notice.listSeparator'));
1137
+ const text = t(failureKey, { reasons });
1138
+ parts.push(reasons ? text : text.replace(/[::]\s*$/, ''));
1139
+ }
1085
1140
  return parts.join(' · ');
1086
1141
  }
1087
1142
 
1143
+ /** 搜索匹配:会话与残留条目共用的字段集(空白词 = 全匹配)。 */
1144
+ function matchesTerm(item, term) {
1145
+ return !term || [item.id, item.title, item.workspaceTitle, item.workspacePath, item.label, item.hint, item.targetSessionId]
1146
+ .some((value) => String(value ?? '').toLocaleLowerCase().includes(term));
1147
+ }
1148
+
1149
+ /** 按工作区归桶(两个列表共用);items 须已按展示时间排序。 */
1150
+ function groupedByWorkspace(items, t) {
1151
+ const byWorkspace = new Map();
1152
+ for (const item of items) {
1153
+ const key = item.workspacePath || item.workspaceTitle || '';
1154
+ if (!byWorkspace.has(key)) byWorkspace.set(key, {
1155
+ title: item.workspaceTitle || item.workspacePath || t('group.ungrouped'), path: item.workspacePath, createdAt: item.workspaceCreatedAt, list: [],
1156
+ });
1157
+ byWorkspace.get(key).list.push(item);
1158
+ }
1159
+ return byWorkspace;
1160
+ }
1161
+
1088
1162
  /** Use the same theme-managed sprite symbols as DSH's product icons. */
1089
1163
  function officialIcon(glyph, size, className) {
1090
1164
  const id = `dsw-icon-${glyph}-regular`;
@@ -1170,8 +1244,8 @@ window.__ModuleLoader__.load({
1170
1244
  ...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',
1171
1245
  disabled: !task.id, onClick: (event) => { event.stopPropagation(); return onOpenTask?.(task.id); },
1172
1246
  onKeyDown: (event) => { event.stopPropagation(); } },
1173
- h(React.Fragment, null, officialIcon('clock-outline', 14), h('span', null, task.title || task.id),
1174
- task.showStatus || task.status === 'paused' || task.status === 'ended' ? h('span', null, t(`status.${task.status}`)) : null))),
1247
+ officialIcon('clock-outline', 14), h('span', null, task.title || task.id),
1248
+ task.showStatus || task.status === 'paused' || task.status === 'ended' ? h('span', null, t(`status.${task.status}`)) : null)),
1175
1249
  active.length > 2 ? h('div', { className: 'dsh-mop-hover-time' }, t('hover.more', { count: active.length - 2 })) : null,
1176
1250
  ...(statuses ?? []).map((entry) => h('div', { key: entry.key, className: 'dsh-mop-hover-status' },
1177
1251
  h(StateDot, { state: entry.state }), h('span', null, t(entry.key, entry.params)))),
@@ -1273,8 +1347,8 @@ window.__ModuleLoader__.load({
1273
1347
  // plugin's own Host route, over official services; refresh on every action.
1274
1348
  const sessionItems = overview?.sessions ?? [];
1275
1349
  const archivedItems = overview?.recycled ?? [];
1276
- const tabItems = () => (tab === 'sessions' ? sessionItems : archivedItems);
1277
- const selectableIds = new Set(tabItems().filter((item) => !item.protected).map((item) => item.id));
1350
+ const selectableIds = useMemo(() => new Set((tab === 'sessions' ? sessionItems : archivedItems)
1351
+ .filter((item) => !item.protected).map((item) => item.id)), [overview, tab]);
1278
1352
  const selectedSessionIds = [...checked].filter((id) => selectableIds.has(id));
1279
1353
 
1280
1354
  useEffect(() => {
@@ -1344,34 +1418,54 @@ window.__ModuleLoader__.load({
1344
1418
  void refresh();
1345
1419
  }, [refresh, showNotice]);
1346
1420
 
1421
+ // 切换标签的公共状态重置(调用方可再叠加 setNotice/setDialog)。
1422
+ const switchTab = (next) => {
1423
+ setChecked(new Set()); setQuery(''); setSearchCollapsed(new Set()); setTab(next);
1424
+ };
1425
+
1426
+ // 批量取消归档:优先官方 uiWorkspace 动作,缺失时走本插件 Host 路由;
1427
+ // 两个入口都收敛为 {done, failed} 形状(撤销 toast 与还原按钮共用)。
1428
+ const unarchiveIds = useCallback(async (ids, { busy = true } = {}) => {
1429
+ if (!workspaceActions) return post('unarchive', { sessionIds: ids });
1430
+ const done = [], failed = [];
1431
+ const run = async () => {
1432
+ for (const id of ids) {
1433
+ try { await workspaceActions.unarchiveSession(id); done.push(id); }
1434
+ catch (error) { failed.push({ id, message: errorText(error, t) }); }
1435
+ }
1436
+ };
1437
+ try { if (busy) setBusy(true); await run(); } finally { if (busy) setBusy(false); }
1438
+ return { done, failed };
1439
+ }, [post, t, workspaceActions]);
1440
+
1441
+ /** 批量动作收尾的公共尾部:默认保留失败行的勾选,构造去重原因的
1442
+ * 失败 toast(无失败则空文本→清除提示),并刷新。 */
1443
+ const reportFailures = useCallback((r, keyOf, failureKey, actions, { retain = true } = {}) => {
1444
+ if (retain) setChecked(new Set(r.failed.map(keyOf)));
1445
+ const detail = r.failed.map((item) => errorText(item, t)).filter(Boolean);
1446
+ report(r.failed.length ? resultText(t, 0, '', failureKey, detail) : '', r.failed.length > 0, actions);
1447
+ }, [report, t]);
1448
+
1347
1449
  const reportArchived = async (done, failed = [], stopped = false) => {
1348
- const detail = failed.map((item) => errorText(item, t)).filter(Boolean).join('; ');
1450
+ const detail = failed.map((item) => errorText(item, t)).filter(Boolean);
1349
1451
  const single = done.length === 1 && failed.length === 0;
1350
1452
  const notices = archiveNotice ? await Promise.all(done.map(async (id) => {
1351
1453
  try { return await archiveNotice(id); } catch { return undefined; }
1352
1454
  })) : [];
1353
1455
  const extra = notices.filter((notice) => notice?.text);
1354
1456
  const text = single ? extra[0]?.text ?? t(stopped ? 'toast.stoppedAndArchived' : 'toast.archived')
1355
- : resultText(t, done.length, fill(t('notice.archived'), { n: done.length }), failed.length, detail);
1457
+ : resultText(t, done.length, t('notice.archived', { n: done.length }), failed.length ? 'notice.archiveFailed' : '', detail);
1356
1458
  const actions = done.length ? [{
1357
1459
  label: t('toast.archivedUndo'), ...(single ? {} : { prefix: t('toast.archivedOr') }), onClick: async () => {
1358
1460
  try {
1359
1461
  setNotice(null);
1360
- let result;
1361
- if (workspaceActions) {
1362
- const errors = [];
1363
- for (const id of done) {
1364
- try { await workspaceActions.unarchiveSession(id); }
1365
- catch (error) { errors.push({ id, message: errorText(error, t) }); }
1366
- }
1367
- result = { failed: errors };
1368
- } else result = await post('unarchive', { sessionIds: done });
1369
- const detail = result.failed.map((failure) => errorText(failure, t)).filter(Boolean).join('; ');
1370
- report(result.failed.length ? resultText(t, 0, '', result.failed.length, detail) : '', result.failed.length > 0);
1462
+ // 撤销不占用主区 busy(toast 即时反馈),也不改勾选(原行为)。
1463
+ reportFailures(await unarchiveIds(done, { busy: false }), (item) => item.id, 'notice.restoreFailed',
1464
+ undefined, { retain: false });
1371
1465
  } catch (error) { showNotice(errorText(error, t), true); }
1372
1466
  },
1373
1467
  }, { prefix: t('toast.archivedOr'), label: t('delete'), onClick: () => {
1374
- setNotice(null); setChecked(new Set()); setQuery(''); setSearchCollapsed(new Set()); setTab('recycled');
1468
+ setNotice(null); switchTab('recycled');
1375
1469
  } }] : undefined;
1376
1470
  report(single || !extra.length ? text : `${text} · ${extra.map((notice) => notice.text).join(' · ')}`,
1377
1471
  failed.length > 0 || extra.some((notice) => notice.tone === 'warning'), actions);
@@ -1435,57 +1529,35 @@ window.__ModuleLoader__.load({
1435
1529
  if (selectedSessionIds.length === 0) return;
1436
1530
  const r = await post('purge', { sessionIds: selectedSessionIds });
1437
1531
  await syncSessionList();
1438
- setChecked(new Set(r.failed.map((item) => item.id)));
1439
- const detail = [...new Set(r.failed.map((item) => {
1440
- const reason = errorText(item, t);
1441
- const shown = archivedItems.find((entry) => entry.id === item.id);
1442
- return reason ? `${(shown && displayTitle(shown)) || (item.title === 'default-workspace' ? t('workspace.defaultName') : item.title) || item.id}: ${reason}` : '';
1443
- }).filter(Boolean))].join(' ');
1444
- report(r.failed.length ? resultText(t, 0, '', r.failed.length, detail) : '', r.failed.length > 0);
1532
+ // 原因去重后进 toast;哪个会话失败看列表里保持勾选的行。
1533
+ // 夹层失败的主场景:剩余的锁壳目录会落在「残留」栏,给一个直达入口。
1534
+ const partial = r.failed.some((item) => item.code === 'cleanup_partial');
1535
+ reportFailures(r, (item) => item.id, 'notice.purgeFailed', partial ? [{ label: t('tabs.residue'), onClick: () => {
1536
+ setNotice(null); switchTab('residue');
1537
+ } }] : undefined);
1445
1538
  } catch (error) {
1446
1539
  showNotice(errorText(error, t), true);
1447
1540
  }
1448
- }, [checked, tab, overview, post, report, showNotice, t, syncSessionList]);
1541
+ }, [checked, tab, overview, post, reportFailures, showNotice, t, syncSessionList]);
1449
1542
 
1450
1543
  const runRestore = useCallback(async () => {
1451
1544
  try {
1452
1545
  if (selectedSessionIds.length === 0) return;
1453
- let r;
1454
- if (workspaceActions) {
1455
- const done = [], failed = [];
1456
- setBusy(true);
1457
- try {
1458
- for (const id of selectedSessionIds) {
1459
- try { await workspaceActions.unarchiveSession(id); done.push(id); }
1460
- catch (error) { failed.push({ id, message: errorText(error, t) }); }
1461
- }
1462
- r = { done, failed };
1463
- } finally { setBusy(false); }
1464
- } else r = await post('unarchive', { sessionIds: selectedSessionIds });
1465
- setChecked(new Set(r.failed.map((item) => item.id)));
1466
- const detail = r.failed.map((item) => errorText(item, t)).filter(Boolean).join('; ');
1467
- report(r.failed.length ? resultText(t, 0, '', r.failed.length, detail) : '', r.failed.length > 0);
1546
+ reportFailures(await unarchiveIds(selectedSessionIds), (item) => item.id, 'notice.restoreFailed');
1468
1547
  } catch (error) {
1469
1548
  showNotice(errorText(error, t), true);
1470
1549
  }
1471
- }, [checked, tab, overview, post, report, showNotice, t, workspaceActions]);
1550
+ }, [checked, tab, overview, reportFailures, showNotice, t, unarchiveIds]);
1472
1551
 
1473
1552
  const runClean = useCallback(async (confirmedTasks = {}) => {
1474
1553
  try {
1475
1554
  const r = await post('residue', { keys: [...checked], confirmedTasks });
1476
1555
  await syncSessionList();
1477
- setChecked(new Set(r.failed.map((item) => item.key)));
1478
- const detail = r.failed.map((item) => {
1479
- const reason = errorText(item, t);
1480
- const entry = overview?.residue?.items?.find((row) => row.key === item.key);
1481
- const name = entry?.label || item.id || item.key;
1482
- return reason ? `${name ? `${name}: ` : ''}${reason}` : '';
1483
- }).filter(Boolean).join('; ');
1484
- report(r.failed.length ? resultText(t, 0, '', r.failed.length, detail) : '', r.failed.length > 0);
1556
+ reportFailures(r, (item) => item.key, 'notice.cleanFailed');
1485
1557
  } catch (error) {
1486
1558
  showNotice(errorText(error, t), true);
1487
1559
  }
1488
- }, [checked, overview, post, report, showNotice, t, syncSessionList]);
1560
+ }, [checked, overview, post, reportFailures, showNotice, t, syncSessionList]);
1489
1561
 
1490
1562
  const ui = {
1491
1563
  checked,
@@ -1514,25 +1586,29 @@ window.__ModuleLoader__.load({
1514
1586
  }),
1515
1587
  };
1516
1588
 
1589
+ // 派生列表(本地化标题、搜索过滤、分组排序)只在数据源变化时重算;
1590
+ // 勾选、toast 等交互不触发。
1517
1591
  const term = query.trim().toLocaleLowerCase();
1518
- const matches = (item) => !term || [item.id, item.title, item.workspaceTitle, item.workspacePath, item.label, item.hint, item.targetSessionId]
1519
- .some((value) => String(value ?? '').toLocaleLowerCase().includes(term));
1520
- const displayItems = tabItems().map((item) => ({ ...item,
1521
- title: displayTitle(item),
1522
- workspaceTitle: workspaceName(item),
1523
- }));
1524
- const visibleItems = displayItems.filter(matches);
1592
+ const displayItems = useMemo(() => sortByDisplayedTime((tab === 'sessions' ? sessionItems : archivedItems)
1593
+ .map((item) => ({ ...item,
1594
+ title: displayTitle(item),
1595
+ workspaceTitle: workspaceName(item),
1596
+ })), sessionTime), [overview, tab, t]);
1597
+ const visibleItems = useMemo(() => displayItems.filter((item) => matchesTerm(item, term)), [displayItems, term]);
1525
1598
  const ready = !!overview && !busy;
1526
1599
  const kindLabels = { 'orphan-cache': 'residue.orphanCache', 'orphan-task': 'residue.orphanTask', 'ghost-registry': 'residue.ghostRegistry',
1527
- 'shell-dir': 'residue.sessionDirectory', 'empty-project': 'residue.emptyProject' };
1528
- const allResidue = overview?.residue?.items ?? [];
1529
- const registeredIds = new Set(allResidue.filter((item) => item.kind === 'ghost-registry').map((item) => item.id));
1530
- const residueItems = allResidue.map((item) => ({ ...item,
1531
- workspaceTitle: workspaceName(item),
1532
- hint: t(kindLabels[item.kind]),
1533
- relatedRegistration: item.kind === 'orphan-cache' && registeredIds.has(item.id) }));
1534
- const visibleResidue = residueItems.filter(matches);
1535
- const allKeys = tab === 'residue' ? visibleResidue.map((x) => x.key)
1600
+ 'shell-dir': 'residue.sessionDirectory', 'empty-project': 'residue.emptyProject', 'memory-resident': 'residue.memoryResident' };
1601
+ const residueItems = useMemo(() => {
1602
+ const allResidue = overview?.residue?.items ?? [];
1603
+ const registeredIds = new Set(allResidue.filter((item) => item.kind === 'ghost-registry').map((item) => item.id));
1604
+ return sortByDisplayedTime(allResidue.map((item) => ({ ...item,
1605
+ workspaceTitle: workspaceName(item),
1606
+ hint: t(kindLabels[item.kind]),
1607
+ relatedRegistration: item.kind === 'orphan-cache' && registeredIds.has(item.id) })), residueTime);
1608
+ }, [overview, t]);
1609
+ const visibleResidue = useMemo(() => residueItems.filter((item) => matchesTerm(item, term)), [residueItems, term]);
1610
+ // 内存常驻行不可清理(数据已删净,仅剩进程内条目),不进入选择集。
1611
+ const allKeys = tab === 'residue' ? visibleResidue.filter((x) => x.kind !== 'memory-resident').map((x) => x.key)
1536
1612
  : visibleItems.filter((x) => selectableIds.has(x.id)).map((x) => x.id);
1537
1613
  const allSelected = allKeys.length > 0 && allKeys.every((k) => checked.has(k));
1538
1614
  const toggleVisible = () => setChecked((prev) => {
@@ -1541,7 +1617,7 @@ window.__ModuleLoader__.load({
1541
1617
  return next;
1542
1618
  });
1543
1619
  const selectedItems = tab === 'residue' ? residueItems.filter((x) => checked.has(x.key))
1544
- : tabItems().filter((x) => checked.has(x.id));
1620
+ : displayItems.filter((x) => checked.has(x.id));
1545
1621
  const measuredItems = selectedItems.filter((x) => typeof x.sizeBytes === 'number' && Number.isFinite(x.sizeBytes));
1546
1622
  const selectedBytes = measuredItems.length ? measuredItems.reduce((sum, x) => sum + x.sizeBytes, 0) : null;
1547
1623
  const tabLabels = { sessions: t('section.sessions'), recycled: t('tabs.archived'), residue: t('tabs.residue') };
@@ -1560,7 +1636,7 @@ window.__ModuleLoader__.load({
1560
1636
  className: 'dsh-mop-tabs', size: 'sm', label: t('actions.archive'), value: tab,
1561
1637
  items: [['sessions', tabLabels.sessions], ['recycled', tabLabels.recycled], ['residue', tabLabels.residue]]
1562
1638
  .map(([value, label]) => ({ value, label, id: `dsh-mop-tab-${value}`, panelId: `dsh-mop-panel-${value}` })),
1563
- onChange: (key) => { if (busy) return; setTab(key); setChecked(new Set()); setQuery(''); setSearchCollapsed(new Set()); setDialog(null); },
1639
+ onChange: (key) => { if (busy) return; switchTab(key); setDialog(null); },
1564
1640
  }),
1565
1641
  h('div', { className: 'dsh-mop-search' },
1566
1642
  h(Input, { className: 'dsh-mop-search-input', icon: officialIcon('search-outline', 16),
@@ -1622,7 +1698,7 @@ window.__ModuleLoader__.load({
1622
1698
  h('span', { className: 'dsh-mop-foot-info' },
1623
1699
  selectedBytes === null
1624
1700
  ? t('selection.summaryCount', { n: checked.size })
1625
- : fill(t('selection.summary'), { n: checked.size, size: formatBytes(selectedBytes) })),
1701
+ : t('selection.summary', { n: checked.size, size: formatBytes(selectedBytes) })),
1626
1702
  tab === 'sessions' ? h(Button, { variant: 'outline', disabled: !ready || selectedSessionIds.length === 0,
1627
1703
  onClick: runArchive }, t('actions.archive')) : null,
1628
1704
  tab === 'recycled' ? [
@@ -1635,23 +1711,21 @@ window.__ModuleLoader__.load({
1635
1711
  onClick: confirmResidue }, t('delete')) : null)));
1636
1712
  }
1637
1713
 
1638
- /** 会话行:状态/选择框 + 标题 + 右侧元信息。 */
1714
+ /** 会话行的子节点:状态/选择框 + 标题 + 右侧元信息。 */
1639
1715
  function sessionCard(x, t, checkNode) {
1640
1716
  const timestamp = sessionTime(x);
1641
1717
  const time = timestamp > 0 ? relativeTime(timestamp, t) : '';
1642
1718
  const status = sessionStatus(x);
1643
- return {
1644
- main: [
1645
- x.protected ? h('span', { className: 'dsh-mop-lead', 'aria-label': t('protection.label') }, officialIcon('shield-outline', 14)) : checkNode,
1646
- ...(x.live && !x.protected ? [h('span', { className: 'dsh-mop-lead', 'aria-label': t(status.key, status.params) }, h(StateDot, { state: status.state }))] : []),
1647
- h('span', { className: 'dsh-mop-title' }, x.blank === true ? t('session.new') : x.title),
1648
- h('span', { className: 'dsh-mop-row-side has-columns' },
1649
- h('span', { className: 'dsh-mop-marker', ...(x.purgeBlock && !x.protected ? { 'aria-label': t(x.purgeBlock === 'schedule_reference' ? 'reference.schedule' : 'error.referenceCheck') } : { 'aria-hidden': true }) },
1650
- x.purgeBlock && !x.protected ? officialIcon('shield-outline', 14) : null),
1651
- h('span', { className: 'dsh-mop-size' }, typeof x.sizeBytes === 'number' ? formatBytes(x.sizeBytes) : ''),
1652
- h('span', { className: 'dsh-mop-time' }, time)),
1653
- ],
1654
- };
1719
+ return [
1720
+ x.protected ? h('span', { className: 'dsh-mop-lead', 'aria-label': t('protection.label') }, officialIcon('shield-outline', 14)) : checkNode,
1721
+ ...(x.live && !x.protected ? [h('span', { className: 'dsh-mop-lead', 'aria-label': t(status.key, status.params) }, h(StateDot, { state: status.state }))] : []),
1722
+ h('span', { className: 'dsh-mop-title' }, x.blank === true ? t('session.new') : x.title),
1723
+ h('span', { className: 'dsh-mop-row-side has-columns' },
1724
+ h('span', { className: 'dsh-mop-marker', ...(x.purgeBlock && !x.protected ? { 'aria-label': t(x.purgeBlock === 'schedule_reference' ? 'reference.schedule' : 'error.referenceCheck') } : { 'aria-hidden': true }) },
1725
+ x.purgeBlock && !x.protected ? officialIcon('shield-outline', 14) : null),
1726
+ h('span', { className: 'dsh-mop-size' }, typeof x.sizeBytes === 'number' ? formatBytes(x.sizeBytes) : ''),
1727
+ h('span', { className: 'dsh-mop-time' }, time)),
1728
+ ];
1655
1729
  }
1656
1730
 
1657
1731
  // Mirrors the official workspace row's status precedence over the facts the
@@ -1678,14 +1752,10 @@ window.__ModuleLoader__.load({
1678
1752
  : button);
1679
1753
  }
1680
1754
 
1681
- /** 按工作区分组的行;ui = {checked, onSelect(key), collapsed, onToggleCollapse(key)}。 */
1755
+ /** 按工作区分组的行(items 须已按展示时间排序);
1756
+ * ui = {checked, onSelect(key), collapsed, onToggleCollapse(key)}。 */
1682
1757
  function renderGroups(items, cardOf, ui, t) {
1683
- const byWs = new Map();
1684
- for (const it of sortByDisplayedTime(items, sessionTime)) {
1685
- const key = it.workspacePath || it.workspaceTitle || '';
1686
- if (!byWs.has(key)) byWs.set(key, { title: it.workspaceTitle || it.workspacePath || t('group.ungrouped'), path: it.workspacePath, createdAt: it.workspaceCreatedAt, list: [] });
1687
- byWs.get(key).list.push(it);
1688
- }
1758
+ const byWs = groupedByWorkspace(items, t);
1689
1759
  return [...byWs.entries()].map(([wsKey, group]) => {
1690
1760
  const isCollapsed = ui.collapsed.has(wsKey);
1691
1761
  return h('div', { key: wsKey, className: 'dsh-mop-group' },
@@ -1698,7 +1768,7 @@ window.__ModuleLoader__.load({
1698
1768
  }));
1699
1769
  const row = h('label', { className: `dsh-mop-row${blocked ? ' is-static' : ''}${x.archived ? ' is-archived' : ''}${ui.checked.has(x.id) ? ' is-selected' : ''}`,
1700
1770
  onPointerEnter: titleEnter, onPointerLeave: titleLeave },
1701
- h('div', { className: 'dsh-mop-row-main' }, ...card.main));
1771
+ h('div', { className: 'dsh-mop-row-main' }, ...card));
1702
1772
  const timestamp = sessionTime(x);
1703
1773
  return rowWithHover(x.id, row, cardContent({ title: x.title, path: displayPath(x.cwd || x.workspacePath, ui.home),
1704
1774
  time: x.blank ? '' : hoverTime(timestamp, t),
@@ -1711,27 +1781,22 @@ window.__ModuleLoader__.load({
1711
1781
  });
1712
1782
  }
1713
1783
 
1714
- /** 按可核实的工作区分组。 */
1784
+ /** 按可核实的工作区分组(items 须已按展示时间排序)。 */
1715
1785
  function renderResidueGroups(items, ui, t) {
1716
- const byWorkspace = new Map();
1717
- for (const item of sortByDisplayedTime(items, residueTime)) {
1718
- const workspaceKey = item.workspacePath || '';
1719
- if (!byWorkspace.has(workspaceKey)) byWorkspace.set(workspaceKey, {
1720
- title: item.workspaceTitle || item.workspacePath || t('group.ungrouped'), path: item.workspacePath, createdAt: item.workspaceCreatedAt, entries: [],
1721
- });
1722
- byWorkspace.get(workspaceKey).entries.push(item);
1723
- }
1786
+ const byWorkspace = groupedByWorkspace(items, t);
1724
1787
  return [...byWorkspace].map(([workspaceKey, group]) => {
1725
1788
  const key = `residue:workspace:${workspaceKey}`;
1726
1789
  const isCollapsed = ui.collapsed.has(key);
1727
1790
  return h('div', { key, className: 'dsh-mop-group' },
1728
1791
  groupHeading(key, group.title, isCollapsed, ui, group.path, group.createdAt, t),
1729
- isCollapsed ? null : group.entries.map((item) => {
1730
- const reason = item.kind === 'orphan-task' ? t('residue.orphanTask') : item.relatedRegistration ? t('residue.registeredCache') : '';
1792
+ isCollapsed ? null : group.list.map((item) => {
1793
+ const memory = item.kind === 'memory-resident';
1794
+ const reason = item.kind === 'orphan-task' ? t('residue.orphanTask') : item.relatedRegistration ? t('residue.registeredCache')
1795
+ : memory ? t('residue.memoryResident') : '';
1731
1796
  const row = h('label', { onPointerEnter: titleEnter, onPointerLeave: titleLeave,
1732
- className: `dsh-mop-row${ui.checked.has(item.key) ? ' is-selected' : ''}` },
1797
+ className: `dsh-mop-row${memory ? ' is-static' : ''}${ui.checked.has(item.key) ? ' is-selected' : ''}` },
1733
1798
  h('div', { className: 'dsh-mop-row-main' },
1734
- h('input', { type: 'checkbox', className: 'dsh-mop-check', checked: ui.checked.has(item.key),
1799
+ memory ? h('span', { className: 'dsh-mop-lead', 'aria-label': t('residue.memoryResident') }, '·') : h('input', { type: 'checkbox', className: 'dsh-mop-check', checked: ui.checked.has(item.key),
1735
1800
  onChange: () => ui.onSelect(item.key, !ui.checked.has(item.key)), 'aria-label': item.label }),
1736
1801
  h('span', { className: 'dsh-mop-title' }, item.label),
1737
1802
  h('span', { className: 'dsh-mop-row-side has-columns' },