dsh-session-relocate 0.2.1 → 0.2.2

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/README.md CHANGED
@@ -75,6 +75,12 @@ curl http://127.0.0.1:3080/api/dsh-session-relocate/status
75
75
  - 批量不是把 N 次单搬简单循环:文件事务逐条做(进度、失败隔离),**工作区归属最后一次性写入**。按实测的单条固定开销推算,3 条会话的总耗时从约 0.96 秒降到约 0.6 秒,条数越多差距越大。
76
76
  - 中途崩了也不怕:每条会话的迁移日志还在,下次启动(或下一次桥接调用)会按文件状态幂等补完归属。
77
77
 
78
+ ### 连同子对话(默认开)
79
+
80
+ 子智能体的会话(`origin: subagent`,侧边栏里是隐藏的)默认会**跟着父对话一起搬**:父搬到哪,它的子、孙会话也搬到哪里,`cwd` 和工作区归属一起改。每条子会话独立走事务,失败按条隔离,不会拖累父对话的回执。
81
+
82
+ 想只搬父对话:**Plugins → dsh-session-relocate → 配置** 里把「连同子对话一起移动」关掉(存在浏览器本地,默认开)。关掉后子会话留在旧工作区 —— 旧工作区先别删,子会话日志还在里面。
83
+
78
84
  ### 正在回答的对话也能搬
79
85
 
80
86
  **包括正在回答、正跑子代理、正跑后台任务的那个。** 插件会先拿到它的写所有权,再动文件:
package/docs/DESIGN.md CHANGED
@@ -206,6 +206,13 @@ header 是冻的,所以**那一轮的工具仍然用旧目录**;下次打开
206
206
  「将移动 M / 跳过 K」;M=0 的项置灰、不绑点击 —— 省掉纯 no-op 的 N 次请求,又不会在多选跨工作区时
207
207
  误删合法目标(例如 A 里 2 条、B 里 1 条,选 A 是合法的:搬 B 的 1 条、跳过 A 的 2 条)。
208
208
 
209
+ **连同子对话**:主机在搬完一条会话后,用 `sessionPersistence.list()` 的 header 关系找
210
+ `origin === 'subagent' && parentSession === 本会话` 的后代(递归到孙),逐条走完整的
211
+ `relocateSession`(文件 + 归属),`already-there` 记为跳过、其余失败按条隔离。开关在插件设置页
212
+ (`plugins.row.config` 槽),值存 localStorage,**默认开**;关掉时客户端在 `/move` 里显式传
213
+ `includeChildren: false`,主机就不找子会话。不搬子对话不会破坏父对话(子代理的产出事件本来就在
214
+ 父日志里),但子会话的日志/`cwd`/归属会留在旧工作区 —— 旧目录被删就一起没了。
215
+
209
216
  失效降级(分级,绝不错猜):分组结构读不到 → 退化成「只认文件夹行」(更早版本的老行为);
210
217
  连行属性也读不到 → 完全不介入(不会误伤官方拖动)。菜单那条路始终可用;
211
218
  `config.dragMove = false` 让客户端根本不挂这些监听。
package/lib/client.js CHANGED
@@ -63,6 +63,21 @@ window.__ModuleLoader__.load({
63
63
  '.dshsm-dark .dshsm-picker-btn:hover:not(:disabled){background:rgba(255,255,255,.08)}',
64
64
  '.dshsm-light .dshsm-picker-btn:hover:not(:disabled){background:rgba(0,0,0,.06)}',
65
65
  '.dshsm-picker-btn:disabled{opacity:.45;cursor:default}',
66
+ // 插件设置页:连同子对话开关
67
+ '.dshsm-setting{display:flex;align-items:flex-start;gap:16px;padding:12px 0;width:100%}',
68
+ '.dshsm-setting-text{flex:1;min-width:0}',
69
+ '.dshsm-setting-title{font-size:13px;font-weight:600;line-height:20px}',
70
+ '.dshsm-setting-desc{font-size:12px;line-height:18px;opacity:.7;margin-top:2px}',
71
+ '.dshsm-switch{position:relative;flex:none;width:38px;height:22px;border-radius:11px;border:0;padding:0;cursor:pointer;background:rgba(127,127,127,.4)}',
72
+ '.dshsm-switch[aria-checked="true"]{background:#4c8dff}',
73
+ '.dshsm-switch::after{content:"";position:absolute;top:2px;left:2px;width:18px;height:18px;border-radius:50%;background:#fff;transition:left .15s ease}',
74
+ '.dshsm-switch[aria-checked="true"]::after{left:18px}',
75
+ '.dshsm-card{display:flex;flex-direction:column;gap:10px;width:100%}',
76
+ '.dshsm-star{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:6px;padding:8px 10px;border-radius:8px;border:1px solid rgba(0,0,0,.08);background:rgba(255,196,0,.06);color:inherit;text-decoration:none;font-size:12px;line-height:1.4}',
77
+ '.dshsm-star:hover{background:rgba(255,196,0,.14)}',
78
+ '.dshsm-starIcon{font-size:14px;line-height:1}',
79
+ '.dshsm-starCta{margin-left:auto;color:#8a6d00;font-weight:600}',
80
+ '@media (prefers-color-scheme: dark){.dshsm-star{border-color:rgba(255,255,255,.12);background:rgba(255,196,0,.08)}.dshsm-starCta{color:#e8c15a}}',
66
81
  ].join('');
67
82
 
68
83
  function ensureStyles() {
@@ -133,6 +148,10 @@ window.__ModuleLoader__.load({
133
148
  bulkFailed: '批量移动失败:',
134
149
  noteReleaseRetries: '(释放重试 {n} 次)',
135
150
  noteSampled: '(大会话:抽样校验)',
151
+ childrenSettingTitle: '连同子对话一起移动',
152
+ childrenSettingDesc: '默认开。移动父对话时,它的子智能体会话(侧边栏里隐藏的 subagent 会话)一起搬到目标工作区;关掉后只搬父对话。',
153
+ starPrompt: '顺手留颗 Star,作者能高兴一整天',
154
+ starCta: '行,给你一颗 Star',
136
155
  };
137
156
  var EN = {
138
157
  open: 'Move to',
@@ -164,12 +183,73 @@ window.__ModuleLoader__.load({
164
183
  bulkFailed: 'Bulk move failed: ',
165
184
  noteReleaseRetries: ' (release retried {n}×)',
166
185
  noteSampled: ' (large session: sampled verify)',
186
+ childrenSettingTitle: 'Move child conversations too',
187
+ childrenSettingDesc: 'On by default. Moving a conversation also moves its hidden subagent sessions to the target workspace; turn it off to move only the parent conversation.',
188
+ starPrompt: 'Leave a star — it makes the author’s day',
189
+ starCta: 'Give a star',
167
190
  };
168
191
 
169
192
  function text() {
170
193
  return isChinese() ? ZH : EN;
171
194
  }
172
195
 
196
+ /** 「连同子对话」开关:插件设置页里改,存 localStorage,默认开。 */
197
+ function wantChildren() {
198
+ try {
199
+ if (typeof localStorage !== 'undefined' && localStorage !== null) {
200
+ return localStorage.getItem('dsh-session-relocate.includeChildren') !== 'false';
201
+ }
202
+ } catch (error) { /* 隐私模式读不了就按默认 */ }
203
+ return true;
204
+ }
205
+
206
+ function setWantChildren(value) {
207
+ try {
208
+ if (typeof localStorage !== 'undefined' && localStorage !== null) {
209
+ localStorage.setItem('dsh-session-relocate.includeChildren', value ? 'true' : 'false');
210
+ }
211
+ } catch (error) { /* 写不进去就算了,下次还是默认开 */ }
212
+ }
213
+
214
+ /** 插件设置页里的「连同子对话」开关(行配置页与包配置页共用)。 */
215
+ function ChildrenSetting() {
216
+ var strings = text();
217
+ var state = react.useState(wantChildren() ? 'on' : 'off');
218
+ var on = state[0] === 'on';
219
+ function toggle() {
220
+ var next = on !== true;
221
+ state[1](next ? 'on' : 'off');
222
+ setWantChildren(next);
223
+ }
224
+ return react.createElement('div', { className: 'dshsm-card' }, [
225
+ react.createElement('div', { className: 'dshsm-setting', key: 'setting' }, [
226
+ react.createElement('div', { className: 'dshsm-setting-text', key: 'text' }, [
227
+ react.createElement('div', { className: 'dshsm-setting-title', key: 'title' }, strings.childrenSettingTitle),
228
+ react.createElement('div', { className: 'dshsm-setting-desc', key: 'desc' }, strings.childrenSettingDesc),
229
+ ]),
230
+ react.createElement('button', {
231
+ key: 'switch',
232
+ type: 'button',
233
+ role: 'switch',
234
+ 'aria-checked': on === true ? 'true' : 'false',
235
+ className: 'dshsm-switch',
236
+ onClick: toggle,
237
+ }),
238
+ ]),
239
+ react.createElement('a', {
240
+ key: 'star',
241
+ className: 'dshsm-star',
242
+ href: 'https://github.com/DDDMUC/dsh-session-relocate',
243
+ target: '_blank',
244
+ rel: 'noopener noreferrer',
245
+ }, [
246
+ react.createElement('span', { className: 'dshsm-starIcon', key: 'icon' }, '⭐'),
247
+ react.createElement('span', { key: 'prompt' }, strings.starPrompt),
248
+ react.createElement('span', { className: 'dshsm-starCta', key: 'cta' }, strings.starCta),
249
+ ]),
250
+ ]);
251
+ }
252
+
173
253
  function post(path, body) {
174
254
  var options = { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body !== undefined ? body : {}) };
175
255
  return fetch(bridgePrefix() + path, options).then(function (response) {
@@ -559,7 +639,9 @@ window.__ModuleLoader__.load({
559
639
  function moveByDrag(sessionId, targetWorkspaceId, hostSelected) {
560
640
  var strings = text();
561
641
  toast(strings.moving);
562
- post('/move', { sessionId: sessionId, targetWorkspaceId: targetWorkspaceId }).then(function (result) {
642
+ var payload = { sessionId: sessionId, targetWorkspaceId: targetWorkspaceId };
643
+ if (wantChildren() === false) payload.includeChildren = false;
644
+ post('/move', payload).then(function (result) {
563
645
  if (result !== null && result !== undefined && result.ok === true) {
564
646
  var title = result.targetTitle;
565
647
  var label = typeof title === 'string' && title.length > 0 ? title : targetWorkspaceId;
@@ -789,7 +871,9 @@ window.__ModuleLoader__.load({
789
871
  function step(index) {
790
872
  if (index >= ids.length) return twoPhase && deferred.length > 0 ? commit(deferred) : Promise.resolve(finish());
791
873
  var sessionId = ids[index];
792
- var done = post('/move', { sessionId: sessionId, targetWorkspaceId: targetWorkspaceId, deferRegistry: twoPhase }).then(function (result) {
874
+ var payload = { sessionId: sessionId, targetWorkspaceId: targetWorkspaceId, deferRegistry: twoPhase };
875
+ if (wantChildren() === false) payload.includeChildren = false;
876
+ var done = post('/move', payload).then(function (result) {
793
877
  if (result !== null && typeof result === 'object' && result.ok === true) {
794
878
  if (result.verification === 'sampled') sampled = true;
795
879
  if (Number.isSafeInteger(result.releaseAttempts) && result.releaseAttempts > releaseRetries) releaseRetries = result.releaseAttempts;
@@ -1242,29 +1326,70 @@ window.__ModuleLoader__.load({
1242
1326
  } else {
1243
1327
  installDrag();
1244
1328
  }
1245
- return ctx.slots.inject('sidebar.workspaces.session.menu.item', function () {
1246
- var disposers = [];
1329
+ var disposers = [];
1330
+ // 插件设置页(Plugins → 本插件):把「连同子对话」开关挂到这一行的配置页。
1331
+ // 槽的 renderSlot 用 options.key 过滤,所以这里把「行 id 的两种可能写法」都登记上,
1332
+ // 行页和包页各一条,匹配不上的那条不会渲染。
1333
+ if (typeof ctx.slots.inject === 'function') {
1334
+ disposers.push(ctx.slots.inject('plugins.row.config', function () {
1335
+ var keys = ['dsh-session-relocate#session-relocate', 'dsh-session-relocate#dsh-session-relocate'];
1336
+ var entries = [];
1337
+ for (var i = 0; i < keys.length; i += 1) {
1338
+ entries.push(ctx.slots.register(
1339
+ { name: 'plugins.row.config', key: keys[i], id: 'session-relocate-children-row-' + i, order: 100 },
1340
+ ChildrenSetting,
1341
+ ));
1342
+ }
1343
+ return function () {
1344
+ for (var j = 0; j < entries.length; j += 1) {
1345
+ if (typeof entries[j] === 'function') {
1346
+ try { entries[j](); } catch (error) { /* ignore */ }
1347
+ }
1348
+ }
1349
+ };
1350
+ }));
1351
+ disposers.push(ctx.slots.inject('plugins.bundle.config', function () {
1352
+ return ctx.slots.register(
1353
+ { name: 'plugins.bundle.config', key: 'dsh-session-relocate', id: 'session-relocate-children-bundle', order: 100 },
1354
+ ChildrenSetting,
1355
+ );
1356
+ }));
1357
+ }
1358
+ disposers.push(ctx.slots.inject('sidebar.workspaces.session.menu.item', function () {
1359
+ var items = [];
1247
1360
  // 「多选」入口:dsh-delete-session 支持批量动作时该组件渲染 null(入口交给它那根底栏)。
1248
- disposers.push(ctx.slots.register(
1361
+ items.push(ctx.slots.register(
1249
1362
  { name: 'sidebar.workspaces.session.menu.item', id: 'session-relocate-bulk', order: 351 },
1250
1363
  BulkEntry,
1251
1364
  ));
1252
- disposers.push(ctx.slots.register(
1365
+ items.push(ctx.slots.register(
1253
1366
  { name: 'sidebar.workspaces.session.menu.item', id: 'session-relocate', order: 350 },
1254
1367
  Entry,
1255
1368
  ));
1256
1369
  return function () {
1257
- for (var i = 0; i < disposers.length; i += 1) {
1258
- if (typeof disposers[i] === 'function') {
1259
- try { disposers[i](); } catch (error) { /* ignore */ }
1370
+ for (var i = 0; i < items.length; i += 1) {
1371
+ if (typeof items[i] === 'function') {
1372
+ try { items[i](); } catch (error) { /* ignore */ }
1260
1373
  }
1261
1374
  }
1262
1375
  };
1263
- });
1376
+ }));
1377
+ return function () {
1378
+ for (var i = 0; i < disposers.length; i += 1) {
1379
+ if (typeof disposers[i] === 'function') {
1380
+ try { disposers[i](); } catch (error) { /* ignore */ }
1381
+ }
1382
+ }
1383
+ };
1264
1384
  }
1265
1385
 
1266
1386
  exports.apply = apply;
1267
1387
  exports.__ui = { pageIsDark: pageIsDark, themeClass: themeClass };
1388
+ exports.__settings = {
1389
+ ChildrenSetting: ChildrenSetting,
1390
+ wantChildren: wantChildren,
1391
+ setWantChildren: setWantChildren,
1392
+ };
1268
1393
  exports.inject = inject;
1269
1394
  exports.__entry = Entry;
1270
1395
  exports.__bulkEntry = BulkEntry;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-session-relocate",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "跨工作区移动 DSH 对话:把某个 Session 的日志文件与工作区归属整体搬到另一个工作区(可自动注册新工作区)。带日志级崩溃恢复的安全事务,并且会先安全释放「已打开但空闲」的会话 —— 所以正在打开的对话也能直接搬,不需要重启 DSH。",
5
5
  "type": "module",
6
6
  "main": "src/plugin.js",
package/src/plugin.js CHANGED
@@ -114,6 +114,37 @@ function failure(error) {
114
114
  return { ok: false, code: 'internal', message: String(error && error.message ? error.message : error) };
115
115
  }
116
116
 
117
+ /**
118
+ * 从全部会话快照里找出 rootId 的**所有后代**(按 header.parentSession 递归)。
119
+ * 子代理会话在侧边栏是隐藏的,只能靠 header 关系找;孤儿(父不存在)自然找不到。
120
+ *
121
+ * @param snapshots - `sessionPersistence.list()` 的返回(每项至少带 `header`)。
122
+ * @param rootId - 父会话 id。
123
+ * @returns 后代 id(不含 root),按层序。
124
+ */
125
+ export function descendantIdsOf(snapshots, rootId) {
126
+ const out = [];
127
+ const seen = new Set([rootId]);
128
+ let frontier = [rootId];
129
+ const all = Array.isArray(snapshots) ? snapshots : [];
130
+ while (frontier.length > 0) {
131
+ const next = [];
132
+ for (const snapshot of all) {
133
+ const header = snapshot !== null && typeof snapshot === 'object' ? snapshot.header : null;
134
+ if (header === null || header === undefined || typeof header !== 'object') continue;
135
+ if (typeof header.parentSession !== 'string' || frontier.indexOf(header.parentSession) < 0) continue;
136
+ // 只认子代理会话(与 DSH 自己 sessionVisible 的过滤一致);分支/分叉是可见会话,不跟着搬。
137
+ if (header.origin !== 'subagent') continue;
138
+ if (typeof header.id !== 'string' || seen.has(header.id)) continue;
139
+ seen.add(header.id);
140
+ out.push(header.id);
141
+ next.push(header.id);
142
+ }
143
+ frontier = next;
144
+ }
145
+ return out;
146
+ }
147
+
117
148
  /**
118
149
  * 挂载插件。
119
150
  *
@@ -233,6 +264,21 @@ export function apply(ctx, config) {
233
264
  async statSession(sessionId) {
234
265
  return await ctx.sessionPersistence.stat(sessionId);
235
266
  },
267
+ /**
268
+ * 全部会话快照(含隐藏的子代理会话)—— 用来找 `parentSession` 后代。
269
+ * 后端不支持或读失败时返回空数组:父会话照常搬,只是不带子。
270
+ */
271
+ async listSessions() {
272
+ const persistence = ctx.sessionPersistence;
273
+ if (persistence === undefined || persistence === null || typeof persistence.list !== 'function') return [];
274
+ try {
275
+ const snapshots = await persistence.list();
276
+ return Array.isArray(snapshots) ? snapshots : [];
277
+ } catch (error) {
278
+ log('warn', '列会话失败,按没有子对话继续:' + String(error && error.message));
279
+ return [];
280
+ }
281
+ },
236
282
  getWorkspace(workspaceId) {
237
283
  return registry.get(workspaceId);
238
284
  },
@@ -611,7 +657,8 @@ export function apply(ctx, config) {
611
657
  const targetWorkspaceId = typeof body.targetWorkspaceId === 'string' ? body.targetWorkspaceId : '';
612
658
  const targetPath = typeof body.targetPath === 'string' ? body.targetPath.trim() : '';
613
659
  try {
614
- const receipt = await relocateSession(buildHost(), store, {
660
+ const host = buildHost();
661
+ const receipt = await relocateSession(host, store, {
615
662
  sessionId,
616
663
  targetWorkspaceId,
617
664
  targetPath,
@@ -620,13 +667,63 @@ export function apply(ctx, config) {
620
667
  // 批量搬移时客户端逐条 defer:文件事务各自做完,注册表最后一次性写。
621
668
  deferRegistry: body.deferRegistry === true,
622
669
  });
623
- return { ok: true, ...receipt };
670
+ // 「连同子对话」默认开;客户端在用户关掉开关时会显式传 false。
671
+ // 子会话走**完整**事务(文件 + 归属),每条失败按条隔离,不拖累父回执。
672
+ let children;
673
+ if (body.includeChildren !== false) {
674
+ const snapshots = await host.listSessions();
675
+ const childIds = descendantIdsOf(snapshots, sessionId);
676
+ if (childIds.length > 0) children = await moveChildren(host, childIds, body);
677
+ }
678
+ return children === undefined ? { ok: true, ...receipt } : { ok: true, ...receipt, children };
624
679
  } catch (error) {
625
680
  log('warn', '迁移失败:' + String(error && error.message));
626
681
  return failure(error);
627
682
  }
628
683
  }
629
684
 
685
+ /**
686
+ * 把父会话的全部后代(子代理会话)搬到同一个目标。
687
+ * 每个子会话走完整事务(文件 + 归属);失败按条隔离,父会话的成功回执不受影响。
688
+ */
689
+ async function moveChildren(host, ids, body) {
690
+ const results = [];
691
+ let moved = 0;
692
+ let failed = 0;
693
+ let skipped = 0;
694
+ for (const id of ids) {
695
+ try {
696
+ await relocateSession(host, store, {
697
+ sessionId: id,
698
+ targetWorkspaceId: body.targetWorkspaceId,
699
+ targetPath: body.targetPath,
700
+ releaseLive,
701
+ moveLive,
702
+ // 子会话不参与两段式:条数少,直接落归属,避免 commit 回执里混进子 id。
703
+ deferRegistry: false,
704
+ });
705
+ moved += 1;
706
+ results.push({ sessionId: id, status: 'moved' });
707
+ } catch (error) {
708
+ if (error !== null && typeof error === 'object' && error.code === 'already-there') {
709
+ skipped += 1;
710
+ results.push({ sessionId: id, status: 'skipped', message: String(error.message) });
711
+ } else {
712
+ failed += 1;
713
+ results.push({
714
+ sessionId: id,
715
+ status: 'failed',
716
+ code: error !== null && typeof error === 'object' && typeof error.code === 'string' ? error.code : 'failed',
717
+ message: String(error !== null && typeof error === 'object' && typeof error.message === 'string'
718
+ ? error.message
719
+ : error),
720
+ });
721
+ }
722
+ }
723
+ }
724
+ return { total: ids.length, moved, failed, skipped, results };
725
+ }
726
+
630
727
  /** 批量收尾:把一串 defer 过的迁移的归属一次性写进注册表。 */
631
728
  async function moveCommit(body) {
632
729
  const ids = Array.isArray(body.sessionIds)