dsh-session-relocate 0.2.1 → 0.2.3

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,18 @@ 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
+
84
+ ### 目录已经在目标里、但没归属(未分组)
85
+
86
+ 如果会话的 `cwd` 已经在某个工作区的目录下,但注册表里没有它的归属(侧栏显示「未分组」),
87
+ 「移动」不会再返回 `already-there` —— 插件会把归属补写进目标工作区(回执 `applied: "attached"`),
88
+ 文件一个字节都不动。菜单也不会再把这种会话当成「已经在目标里」,目标列表会正常给出那个工作区。
89
+
78
90
  ### 正在回答的对话也能搬
79
91
 
80
92
  **包括正在回答、正跑子代理、正跑后台任务的那个。** 插件会先拿到它的写所有权,再动文件:
package/docs/DESIGN.md CHANGED
@@ -89,6 +89,13 @@ C:\ -> --C--- (只剥前导,所以尾部留下分
89
89
  因此本插件在 attach 前调用私有的 `replaceHeaderIndex(listStoredHeaders())`(feature-detect,
90
90
  拿不到就降级为「下次启动补齐归属」)。
91
91
 
92
+ **already-there 的判定**:目录相同(`cwd == target.path`)**不等于**已在目标工作区 —— DSH 的分组
93
+ 依据是 `workspace.json` 的 `sessionIds`。目录在、归属不在(孤儿/未分组)时,`relocateSession` 走
94
+ `attachExisting`:优先 `host.adoptSession`,老宿主退回 `adoptSessions + detachSessions`,补写归属后
95
+ 返回 `applied: "attached"`,不动文件、不写迁移日志。`/describe` 的 `currentWorkspaceId` 也**只认归属**,
96
+ 并额外返回 `memberOfWorkspaceId` / `cwdMatchesWorkspaceId`,避免 UI 把孤儿会话当成「已在目标工作区」
97
+ 而不给补归属的入口。
98
+
92
99
  ## Zstandard 容器
93
100
 
94
101
  - 日志是**一串彼此独立的 Zstandard 帧**:第一帧**恰好只有 header 一行**,后续每批一帧。
@@ -206,6 +213,13 @@ header 是冻的,所以**那一轮的工具仍然用旧目录**;下次打开
206
213
  「将移动 M / 跳过 K」;M=0 的项置灰、不绑点击 —— 省掉纯 no-op 的 N 次请求,又不会在多选跨工作区时
207
214
  误删合法目标(例如 A 里 2 条、B 里 1 条,选 A 是合法的:搬 B 的 1 条、跳过 A 的 2 条)。
208
215
 
216
+ **连同子对话**:主机在搬完一条会话后,用 `sessionPersistence.list()` 的 header 关系找
217
+ `origin === 'subagent' && parentSession === 本会话` 的后代(递归到孙),逐条走完整的
218
+ `relocateSession`(文件 + 归属),`already-there` 记为跳过、其余失败按条隔离。开关在插件设置页
219
+ (`plugins.row.config` 槽),值存 localStorage,**默认开**;关掉时客户端在 `/move` 里显式传
220
+ `includeChildren: false`,主机就不找子会话。不搬子对话不会破坏父对话(子代理的产出事件本来就在
221
+ 父日志里),但子会话的日志/`cwd`/归属会留在旧工作区 —— 旧目录被删就一起没了。
222
+
209
223
  失效降级(分级,绝不错猜):分组结构读不到 → 退化成「只认文件夹行」(更早版本的老行为);
210
224
  连行属性也读不到 → 完全不介入(不会误伤官方拖动)。菜单那条路始终可用;
211
225
  `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() {
@@ -113,6 +128,7 @@ window.__ModuleLoader__.load({
113
128
  moving: '正在移动…',
114
129
  done: '已移动',
115
130
  pending: '文件已搬移;工作区归属会在下次启动 DSH 时自动补齐',
131
+ attached: '已补上「{ws}」的工作区归属',
116
132
  cannot: '这个对话无法移动',
117
133
  failed: '移动失败',
118
134
  needsReload: '(刷新页面后生效)',
@@ -133,6 +149,10 @@ window.__ModuleLoader__.load({
133
149
  bulkFailed: '批量移动失败:',
134
150
  noteReleaseRetries: '(释放重试 {n} 次)',
135
151
  noteSampled: '(大会话:抽样校验)',
152
+ childrenSettingTitle: '连同子对话一起移动',
153
+ childrenSettingDesc: '默认开。移动父对话时,它的子智能体会话(侧边栏里隐藏的 subagent 会话)一起搬到目标工作区;关掉后只搬父对话。',
154
+ starPrompt: '顺手留颗 Star,作者能高兴一整天',
155
+ starCta: '行,给你一颗 Star',
136
156
  };
137
157
  var EN = {
138
158
  open: 'Move to',
@@ -144,6 +164,7 @@ window.__ModuleLoader__.load({
144
164
  moving: 'Moving…',
145
165
  done: 'Moved',
146
166
  pending: 'Files moved; the workspace accounting is completed on the next DSH start',
167
+ attached: 'Workspace membership restored for “{ws}”',
147
168
  cannot: 'This conversation cannot be moved',
148
169
  failed: 'Move failed',
149
170
  needsReload: ' (reload the page to apply)',
@@ -164,12 +185,73 @@ window.__ModuleLoader__.load({
164
185
  bulkFailed: 'Bulk move failed: ',
165
186
  noteReleaseRetries: ' (release retried {n}×)',
166
187
  noteSampled: ' (large session: sampled verify)',
188
+ childrenSettingTitle: 'Move child conversations too',
189
+ 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.',
190
+ starPrompt: 'Leave a star — it makes the author’s day',
191
+ starCta: 'Give a star',
167
192
  };
168
193
 
169
194
  function text() {
170
195
  return isChinese() ? ZH : EN;
171
196
  }
172
197
 
198
+ /** 「连同子对话」开关:插件设置页里改,存 localStorage,默认开。 */
199
+ function wantChildren() {
200
+ try {
201
+ if (typeof localStorage !== 'undefined' && localStorage !== null) {
202
+ return localStorage.getItem('dsh-session-relocate.includeChildren') !== 'false';
203
+ }
204
+ } catch (error) { /* 隐私模式读不了就按默认 */ }
205
+ return true;
206
+ }
207
+
208
+ function setWantChildren(value) {
209
+ try {
210
+ if (typeof localStorage !== 'undefined' && localStorage !== null) {
211
+ localStorage.setItem('dsh-session-relocate.includeChildren', value ? 'true' : 'false');
212
+ }
213
+ } catch (error) { /* 写不进去就算了,下次还是默认开 */ }
214
+ }
215
+
216
+ /** 插件设置页里的「连同子对话」开关(行配置页与包配置页共用)。 */
217
+ function ChildrenSetting() {
218
+ var strings = text();
219
+ var state = react.useState(wantChildren() ? 'on' : 'off');
220
+ var on = state[0] === 'on';
221
+ function toggle() {
222
+ var next = on !== true;
223
+ state[1](next ? 'on' : 'off');
224
+ setWantChildren(next);
225
+ }
226
+ return react.createElement('div', { className: 'dshsm-card' }, [
227
+ react.createElement('div', { className: 'dshsm-setting', key: 'setting' }, [
228
+ react.createElement('div', { className: 'dshsm-setting-text', key: 'text' }, [
229
+ react.createElement('div', { className: 'dshsm-setting-title', key: 'title' }, strings.childrenSettingTitle),
230
+ react.createElement('div', { className: 'dshsm-setting-desc', key: 'desc' }, strings.childrenSettingDesc),
231
+ ]),
232
+ react.createElement('button', {
233
+ key: 'switch',
234
+ type: 'button',
235
+ role: 'switch',
236
+ 'aria-checked': on === true ? 'true' : 'false',
237
+ className: 'dshsm-switch',
238
+ onClick: toggle,
239
+ }),
240
+ ]),
241
+ react.createElement('a', {
242
+ key: 'star',
243
+ className: 'dshsm-star',
244
+ href: 'https://github.com/DDDMUC/dsh-session-relocate',
245
+ target: '_blank',
246
+ rel: 'noopener noreferrer',
247
+ }, [
248
+ react.createElement('span', { className: 'dshsm-starIcon', key: 'icon' }, '⭐'),
249
+ react.createElement('span', { key: 'prompt' }, strings.starPrompt),
250
+ react.createElement('span', { className: 'dshsm-starCta', key: 'cta' }, strings.starCta),
251
+ ]),
252
+ ]);
253
+ }
254
+
173
255
  function post(path, body) {
174
256
  var options = { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body !== undefined ? body : {}) };
175
257
  return fetch(bridgePrefix() + path, options).then(function (response) {
@@ -298,9 +380,14 @@ window.__ModuleLoader__.load({
298
380
  return button('error', strings.failed + ':' + state.message, { disabled: true, className: 'dshsm-item dshsm-bad' });
299
381
  }
300
382
  if (state.phase === 'done') {
301
- var suffix = state.applied === 'pending' ? strings.pending : (state.applied === 'live' ? '' : strings.needsReload);
383
+ var doneText = state.applied === 'attached'
384
+ ? strings.attached.replace('{ws}', String(state.title))
385
+ : strings.done + ' ' + String(state.title);
386
+ var suffix = state.applied === 'pending'
387
+ ? strings.pending
388
+ : (state.applied === 'live' || state.applied === 'attached' ? '' : strings.needsReload);
302
389
  var note = typeof state.note === 'string' ? state.note : '';
303
- return button('done', strings.done + ' ' + String(state.title) + note + (suffix.length > 0 ? ';' + suffix : ''), { disabled: true });
390
+ return button('done', doneText + note + (suffix.length > 0 ? ';' + suffix : ''), { disabled: true });
304
391
  }
305
392
  // picking
306
393
  var nodes = [button('caption', strings.pick + (state.targets.length === 0 ? ' ' + strings.noTargets : ''), { disabled: true })];
@@ -559,11 +646,16 @@ window.__ModuleLoader__.load({
559
646
  function moveByDrag(sessionId, targetWorkspaceId, hostSelected) {
560
647
  var strings = text();
561
648
  toast(strings.moving);
562
- post('/move', { sessionId: sessionId, targetWorkspaceId: targetWorkspaceId }).then(function (result) {
649
+ var payload = { sessionId: sessionId, targetWorkspaceId: targetWorkspaceId };
650
+ if (wantChildren() === false) payload.includeChildren = false;
651
+ post('/move', payload).then(function (result) {
563
652
  if (result !== null && result !== undefined && result.ok === true) {
564
653
  var title = result.targetTitle;
565
654
  var label = typeof title === 'string' && title.length > 0 ? title : targetWorkspaceId;
566
- toast(strings.dragMoved.replace('{ws}', label) + receiptNotes(result));
655
+ var summary = result.applied === 'attached'
656
+ ? strings.attached.replace('{ws}', label)
657
+ : strings.dragMoved.replace('{ws}', label);
658
+ toast(summary + receiptNotes(result));
567
659
  if (bulkState.selecting === true) exitBulk();
568
660
  else if (hostSelected === true) dismissHostSelection();
569
661
  return;
@@ -789,12 +881,19 @@ window.__ModuleLoader__.load({
789
881
  function step(index) {
790
882
  if (index >= ids.length) return twoPhase && deferred.length > 0 ? commit(deferred) : Promise.resolve(finish());
791
883
  var sessionId = ids[index];
792
- var done = post('/move', { sessionId: sessionId, targetWorkspaceId: targetWorkspaceId, deferRegistry: twoPhase }).then(function (result) {
884
+ var payload = { sessionId: sessionId, targetWorkspaceId: targetWorkspaceId, deferRegistry: twoPhase };
885
+ if (wantChildren() === false) payload.includeChildren = false;
886
+ var done = post('/move', payload).then(function (result) {
793
887
  if (result !== null && typeof result === 'object' && result.ok === true) {
794
888
  if (result.verification === 'sampled') sampled = true;
795
889
  if (Number.isSafeInteger(result.releaseAttempts) && result.releaseAttempts > releaseRetries) releaseRetries = result.releaseAttempts;
796
- if (twoPhase) deferred.push(sessionId);
797
- else {
890
+ if (result.applied === 'attached') {
891
+ // 目录本来就在目标、只补了归属:没有可提交的文件事务,直接算已搬。
892
+ moved += 1;
893
+ record({ sessionId: sessionId, status: 'moved', targetWorkspaceId: targetWorkspaceId, applied: 'attached' });
894
+ } else if (twoPhase) {
895
+ deferred.push(sessionId);
896
+ } else {
798
897
  moved += 1;
799
898
  record({ sessionId: sessionId, status: 'moved', targetWorkspaceId: targetWorkspaceId });
800
899
  }
@@ -1242,29 +1341,70 @@ window.__ModuleLoader__.load({
1242
1341
  } else {
1243
1342
  installDrag();
1244
1343
  }
1245
- return ctx.slots.inject('sidebar.workspaces.session.menu.item', function () {
1246
- var disposers = [];
1344
+ var disposers = [];
1345
+ // 插件设置页(Plugins → 本插件):把「连同子对话」开关挂到这一行的配置页。
1346
+ // 槽的 renderSlot 用 options.key 过滤,所以这里把「行 id 的两种可能写法」都登记上,
1347
+ // 行页和包页各一条,匹配不上的那条不会渲染。
1348
+ if (typeof ctx.slots.inject === 'function') {
1349
+ disposers.push(ctx.slots.inject('plugins.row.config', function () {
1350
+ var keys = ['dsh-session-relocate#session-relocate', 'dsh-session-relocate#dsh-session-relocate'];
1351
+ var entries = [];
1352
+ for (var i = 0; i < keys.length; i += 1) {
1353
+ entries.push(ctx.slots.register(
1354
+ { name: 'plugins.row.config', key: keys[i], id: 'session-relocate-children-row-' + i, order: 100 },
1355
+ ChildrenSetting,
1356
+ ));
1357
+ }
1358
+ return function () {
1359
+ for (var j = 0; j < entries.length; j += 1) {
1360
+ if (typeof entries[j] === 'function') {
1361
+ try { entries[j](); } catch (error) { /* ignore */ }
1362
+ }
1363
+ }
1364
+ };
1365
+ }));
1366
+ disposers.push(ctx.slots.inject('plugins.bundle.config', function () {
1367
+ return ctx.slots.register(
1368
+ { name: 'plugins.bundle.config', key: 'dsh-session-relocate', id: 'session-relocate-children-bundle', order: 100 },
1369
+ ChildrenSetting,
1370
+ );
1371
+ }));
1372
+ }
1373
+ disposers.push(ctx.slots.inject('sidebar.workspaces.session.menu.item', function () {
1374
+ var items = [];
1247
1375
  // 「多选」入口:dsh-delete-session 支持批量动作时该组件渲染 null(入口交给它那根底栏)。
1248
- disposers.push(ctx.slots.register(
1376
+ items.push(ctx.slots.register(
1249
1377
  { name: 'sidebar.workspaces.session.menu.item', id: 'session-relocate-bulk', order: 351 },
1250
1378
  BulkEntry,
1251
1379
  ));
1252
- disposers.push(ctx.slots.register(
1380
+ items.push(ctx.slots.register(
1253
1381
  { name: 'sidebar.workspaces.session.menu.item', id: 'session-relocate', order: 350 },
1254
1382
  Entry,
1255
1383
  ));
1256
1384
  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 */ }
1385
+ for (var i = 0; i < items.length; i += 1) {
1386
+ if (typeof items[i] === 'function') {
1387
+ try { items[i](); } catch (error) { /* ignore */ }
1260
1388
  }
1261
1389
  }
1262
1390
  };
1263
- });
1391
+ }));
1392
+ return function () {
1393
+ for (var i = 0; i < disposers.length; i += 1) {
1394
+ if (typeof disposers[i] === 'function') {
1395
+ try { disposers[i](); } catch (error) { /* ignore */ }
1396
+ }
1397
+ }
1398
+ };
1264
1399
  }
1265
1400
 
1266
1401
  exports.apply = apply;
1267
1402
  exports.__ui = { pageIsDark: pageIsDark, themeClass: themeClass };
1403
+ exports.__settings = {
1404
+ ChildrenSetting: ChildrenSetting,
1405
+ wantChildren: wantChildren,
1406
+ setWantChildren: setWantChildren,
1407
+ };
1268
1408
  exports.inject = inject;
1269
1409
  exports.__entry = Entry;
1270
1410
  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.3",
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
  },
@@ -536,7 +582,8 @@ export function apply(ctx, config) {
536
582
  /** 描述当前状态:可选带一个 sessionId,用来告诉界面「能不能搬、为什么不能」。 */
537
583
  async function describe(body) {
538
584
  const registry = ctx.workspaceRegistry;
539
- const workspaces = registry.list().map((entity) => ({ id: entity.id, title: entity.title, path: entity.path }));
585
+ const entities = registry.list();
586
+ const workspaces = entities.map((entity) => ({ id: entity.id, title: entity.title, path: entity.path }));
540
587
  const payload = {
541
588
  ok: true,
542
589
  version: PLUGIN_VERSION,
@@ -570,9 +617,12 @@ export function apply(ctx, config) {
570
617
  canonical = undefined;
571
618
  }
572
619
  }
573
- const current = canonical === undefined
574
- ? undefined
575
- : workspaces.find((workspace) => samePath(workspace.path, canonical));
620
+ // 「当前工作区」只认注册表归属;cwd 相同但没归属的孤儿,必须留在目标列表里(补归属入口)。
621
+ const member = entities.find((entity) => Array.isArray(entity.sessionIds) && entity.sessionIds.indexOf(sessionId) >= 0);
622
+ const cwdMatch = canonical === undefined ? undefined : entities.find((entity) => samePath(entity.path, canonical));
623
+ const memberId = member === undefined ? null : member.id;
624
+ const cwdMatchId = cwdMatch === undefined ? null : cwdMatch.id;
625
+ const currentId = memberId;
576
626
  const activity = await host.listActivity(sessionId);
577
627
  const live = host.isSessionLive(sessionId);
578
628
  // 就地接管可用时,连「正在跑活」都能搬(换掉 live 写句柄的 header,turn 不断)。
@@ -588,7 +638,10 @@ export function apply(ctx, config) {
588
638
  id: sessionId,
589
639
  cwd: cwd ?? null,
590
640
  canonicalCwd: canonical ?? null,
591
- currentWorkspaceId: current === undefined ? null : current.id,
641
+ currentWorkspaceId: currentId,
642
+ memberOfWorkspaceId: memberId,
643
+ cwdMatchesWorkspaceId: cwdMatchId,
644
+ currentWorkspaceBy: member !== undefined ? 'membership' : null,
592
645
  live,
593
646
  willHandoff: handoffAvailable && reason === null,
594
647
  willRelease: live && !handoffAvailable && reason === null,
@@ -599,7 +652,9 @@ export function apply(ctx, config) {
599
652
  };
600
653
  payload.workspaces = workspaces.map((workspace) => ({
601
654
  ...workspace,
602
- current: workspace.id === payload.session.currentWorkspaceId,
655
+ current: workspace.id === currentId,
656
+ member: workspace.id === memberId,
657
+ cwdMatches: workspace.id === cwdMatchId,
603
658
  }));
604
659
  return payload;
605
660
  }
@@ -611,7 +666,8 @@ export function apply(ctx, config) {
611
666
  const targetWorkspaceId = typeof body.targetWorkspaceId === 'string' ? body.targetWorkspaceId : '';
612
667
  const targetPath = typeof body.targetPath === 'string' ? body.targetPath.trim() : '';
613
668
  try {
614
- const receipt = await relocateSession(buildHost(), store, {
669
+ const host = buildHost();
670
+ const receipt = await relocateSession(host, store, {
615
671
  sessionId,
616
672
  targetWorkspaceId,
617
673
  targetPath,
@@ -620,13 +676,63 @@ export function apply(ctx, config) {
620
676
  // 批量搬移时客户端逐条 defer:文件事务各自做完,注册表最后一次性写。
621
677
  deferRegistry: body.deferRegistry === true,
622
678
  });
623
- return { ok: true, ...receipt };
679
+ // 「连同子对话」默认开;客户端在用户关掉开关时会显式传 false。
680
+ // 子会话走**完整**事务(文件 + 归属),每条失败按条隔离,不拖累父回执。
681
+ let children;
682
+ if (body.includeChildren !== false) {
683
+ const snapshots = await host.listSessions();
684
+ const childIds = descendantIdsOf(snapshots, sessionId);
685
+ if (childIds.length > 0) children = await moveChildren(host, childIds, body);
686
+ }
687
+ return children === undefined ? { ok: true, ...receipt } : { ok: true, ...receipt, children };
624
688
  } catch (error) {
625
689
  log('warn', '迁移失败:' + String(error && error.message));
626
690
  return failure(error);
627
691
  }
628
692
  }
629
693
 
694
+ /**
695
+ * 把父会话的全部后代(子代理会话)搬到同一个目标。
696
+ * 每个子会话走完整事务(文件 + 归属);失败按条隔离,父会话的成功回执不受影响。
697
+ */
698
+ async function moveChildren(host, ids, body) {
699
+ const results = [];
700
+ let moved = 0;
701
+ let failed = 0;
702
+ let skipped = 0;
703
+ for (const id of ids) {
704
+ try {
705
+ await relocateSession(host, store, {
706
+ sessionId: id,
707
+ targetWorkspaceId: body.targetWorkspaceId,
708
+ targetPath: body.targetPath,
709
+ releaseLive,
710
+ moveLive,
711
+ // 子会话不参与两段式:条数少,直接落归属,避免 commit 回执里混进子 id。
712
+ deferRegistry: false,
713
+ });
714
+ moved += 1;
715
+ results.push({ sessionId: id, status: 'moved' });
716
+ } catch (error) {
717
+ if (error !== null && typeof error === 'object' && error.code === 'already-there') {
718
+ skipped += 1;
719
+ results.push({ sessionId: id, status: 'skipped', message: String(error.message) });
720
+ } else {
721
+ failed += 1;
722
+ results.push({
723
+ sessionId: id,
724
+ status: 'failed',
725
+ code: error !== null && typeof error === 'object' && typeof error.code === 'string' ? error.code : 'failed',
726
+ message: String(error !== null && typeof error === 'object' && typeof error.message === 'string'
727
+ ? error.message
728
+ : error),
729
+ });
730
+ }
731
+ }
732
+ }
733
+ return { total: ids.length, moved, failed, skipped, results };
734
+ }
735
+
630
736
  /** 批量收尾:把一串 defer 过的迁移的归属一次性写进注册表。 */
631
737
  async function moveCommit(body) {
632
738
  const ids = Array.isArray(body.sessionIds)
package/src/relocate.js CHANGED
@@ -347,6 +347,28 @@ export function newOpId() {
347
347
  * ``releaseLive`` 为 false 时恢复旧行为(打开中的会话直接拒绝)。
348
348
  * @returns 迁移回执。
349
349
  */
350
+ /**
351
+ * 会话目录已经在目标工作区的 path 上、但注册表里没有这条归属时,补写归属(不动文件)。
352
+ *
353
+ * 「cwd 相同」不等于「已在目标工作区」:DSH 的分组依据是 workspace.json 的 sessionIds,
354
+ * 两者可以不一致(本次的孤儿/未分组会话)。优先走 host.adoptSession(live/frozen header
355
+ * 的旁路),老宿主退回 adoptSessions + detachSessions。
356
+ */
357
+ async function attachExisting(host, sessionId, target, source) {
358
+ if (typeof host.adoptSession === 'function') {
359
+ return await host.adoptSession(sessionId, target, source, target.path);
360
+ }
361
+ if (typeof host.adoptSessions === 'function') {
362
+ const adopted = await host.adoptSessions([sessionId], target, target.path);
363
+ if (adopted !== null && adopted !== undefined && adopted.applied === true
364
+ && source !== undefined && source.id !== target.id && typeof host.detachSessions === 'function') {
365
+ await host.detachSessions([sessionId], source);
366
+ }
367
+ return adopted;
368
+ }
369
+ return { applied: false, reason: '宿主没有提供补写归属的接口' };
370
+ }
371
+
350
372
  export async function relocateSession(host, store, request) {
351
373
  const sessionId = request.sessionId;
352
374
  if (typeof sessionId !== 'string' || sessionId.length === 0) {
@@ -383,7 +405,33 @@ export async function relocateSession(host, store, request) {
383
405
  throw new MoveError('source-cwd-unresolved', '这个对话记录的目录已不存在:' + header.cwd + ',无法安全迁移。');
384
406
  }
385
407
  if (samePath(sourceCanonical, target.path)) {
386
- throw new MoveError('already-there', '这个对话已经在「' + target.title + '」里了。');
408
+ // 目录相同 ≠ 已在目标工作区:DSH 的分组依据是注册表 sessionIds。
409
+ // 目录在、归属不在(孤儿/未分组)时这是一次**可修复**的状态,不能当成终态。
410
+ const member = Array.isArray(target.sessionIds) && target.sessionIds.indexOf(sessionId) >= 0;
411
+ if (member) throw new MoveError('already-there', '这个对话已经在「' + target.title + '」里了。');
412
+ const source = host.findWorkspaceByPath(sourceCanonical);
413
+ const attached = await attachExisting(host, sessionId, target, source);
414
+ if (attached !== null && attached !== undefined && attached.applied === true) {
415
+ if (typeof host.invalidateProjection === 'function') await host.invalidateProjection(sessionId);
416
+ return {
417
+ ok: true,
418
+ sessionId,
419
+ from: sourceCanonical,
420
+ to: target.path,
421
+ targetWorkspaceId: target.id,
422
+ targetTitle: target.title,
423
+ applied: 'attached',
424
+ released: false,
425
+ handedOff: false,
426
+ verification: 'full',
427
+ };
428
+ }
429
+ throw new MoveError(
430
+ 'attach-failed',
431
+ '这个对话的目录已经在「' + target.title + '」里,但补写工作区归属失败:'
432
+ + String(attached !== null && attached !== undefined && attached.reason !== undefined ? attached.reason : '未知原因')
433
+ + '。请重启 DSH 后再试。',
434
+ );
387
435
  }
388
436
 
389
437
  // 三种情况: