dsh-session-relocate 0.2.4 → 0.2.6

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
@@ -45,8 +45,9 @@ curl http://127.0.0.1:3080/api/dsh-session-relocate/status
45
45
  3. 点目标工作区。列表立刻刷新,这个对话出现在目标工作区下;
46
46
  4. 打开它继续聊:它现在就运行在新目录里。
47
47
 
48
- 想搬到一个**还不存在的工作区**:点 **其它目录…**,输入一个绝对路径 —— 目录会被创建,
49
- 并自动注册成一个新工作区。
48
+ 想搬到一个**还不存在的工作区**:点 **其它目录…**(composer chip 那条下拉里叫 **添加工作区…**)——
49
+ 会弹**系统目录选择器**(和官方「添加工作区」同一个:`uiWorkspace.pickDirectory()` / 桌面端 `__DSH_DIRECTORY_PICKER__`),
50
+ 选完目录就被创建并注册成新工作区,会话直接搬过去。本机没有目录选择器时才退回手输绝对路径。
50
51
 
51
52
  ### 方式二:直接拖
52
53
 
@@ -91,6 +92,8 @@ curl http://127.0.0.1:3080/api/dsh-session-relocate/status
91
92
 
92
93
  已开聊的会话,composer 上方会常驻一个工作区 chip(文件夹 + 工作区名,样式照官方 hero 那条做)。点它 → 选目标工作区 → 直接把这个会话搬过去(和侧栏菜单同一条 `/move` 路径;`applied: "attached"` 会显示「已补上归属」)。
93
94
 
95
+ 点它弹出的是**官方那套工作区下拉**(和 hero 页那条工作区胶囊一模一样:文件夹图标、当前工作区打勾、底部「添加工作区…」),选中目标就搬过去。
96
+
94
97
  **出现方式在插件设置页里三选一**:一直出现(默认)/ 悬浮才出现(鼠标移到那一行才显示,位置不变、不跳)/ 不出现(完全不渲染,预设胶囊自动回到右边)。
95
98
 
96
99
  **新会话(hero)页不渲染** —— 官方那条工作区胶囊还在,避免同一条 chip 出现两次;判定是 `session.blank`,再用 `[class*="heroWorkspaceRow"]` 兜底。它注册在官方槽 `conversation.input.dock`(和预设胶囊同一个槽),节点由 React 维护,不会被重渲染顶掉。
@@ -271,8 +274,13 @@ node --test
271
274
  菜单那条路始终不受影响,`dragMove: false` 可以一键全关。
272
275
  - **嵌套工作区**(工作区套工作区)时,父分组里若渲染了子分组,父分组的会话行不再算投放目标
273
276
  —— 这是保守取舍:宁可少接管,也不猜错工作区。
274
- - **正在跑活的那一轮不会换工作目录**:会话在内存里的 header 是 deep-frozen 的,改不了;
275
- 文件与归属都搬走了,但那一轮的工具仍然用旧目录,**下次打开**才真正在新目录里跑。
277
+ - **正在跑活的那一轮不会换工作目录**:那一轮手里的工具工作目录是启动时定下的;
278
+ 文件、归属、以及会话的 header 都已经搬到新目录,但**这一轮**的工具仍用旧目录,**下次打开**才真正在新目录里跑。
279
+ (修复后内存里那条 live 会话的 header 也会跟着换 —— 参见下一条。)
280
+ - **原地接管会同时换两处 header**:写句柄的 `header`(决定后续写入落到哪)和内存里
281
+ `Session.header`(`session-query` 会拿它跟磁盘 header 逐字段比对)。只换前者的话,
282
+ `/api/session/list` 会因 `session source headers conflict` 整体报错、侧栏全空,直到重启 DSH
283
+ (issue #1)。换不了内存 header 时插件**整体放弃**这次接管(`handoff-failed`),一个字节都不动。
276
284
  - **正在跑活的接管依赖私有内部结构**(`tracker.writers`、写句柄的 `header` 槽位、`enqueueChain`、
277
285
  以及注册表的 `entity.mutate`)。DSH 换 rc 版本时这些都可能变,所以每一处都 feature-detect:
278
286
  探测不到就整体放弃(`handoff-failed`),绝不半途而废。
package/docs/DESIGN.md CHANGED
@@ -132,6 +132,13 @@ C:\ -> --C--- (只剥前导,所以尾部留下分
132
132
 
133
133
  ## B. 就地接管:正在跑的会话怎么搬
134
134
 
135
+ > **两处 header 必须一起换**(issue #1):写句柄的 `handle.header` 决定后续写入落到哪;
136
+ > 内存里 `Session.header` 则是 `dsh-session-query` 的 `assertSessionHeadersCompatible()` 拿来
137
+ > 与磁盘 artifact header 逐字段比对的那一份(`id / createdAt / cwd / parentSession / isSeeded /
138
+ > delegationDepth`)。只换前者会让 `session/list` 抛 `SESSION_QUERY_SOURCE_CONFLICT`,
139
+ > 而 `dsh-api-session-controller` 的 `list()` 没有逐条兜错 → 整个列表失败、侧栏全空,重启才恢复。
140
+ > `Session.header` 是普通字段(不是 getter,实例没被冻),换引用即可;换不了就整体放弃(`handoff-failed`)。
141
+
135
142
  **为什么 attachSession 不行**:它读 header 时优先取内存里的活会话,而活会话的 header 被
136
143
  `validateSessionHeader` 末尾的 `return deepFreeze(record)` 冻住了 —— cwd 改不了,
137
144
  校验必然失败。所以接管这条路要绕开它,直接走注册表自己的写路径。
@@ -230,7 +237,17 @@ never 时容器加 `.dshsm-dock--hidden`(`justify-content:flex-end`),子
230
237
  自己还开了一个子槽 `session-relocate.dock`(list / scope=session),别人注册进来就排在 chip 右边;
231
238
  子槽必须用 renderer 给的 `SessionProvider` 包一层才能拿到会话。
232
239
  官方 hero 那一排(`heroWorkspaceRow`)在时**完全不渲染**(`session.blank` + DOM 兜底),
233
- 避免同一条 chip 出现两次。点 chip → `/describe` → 选目标 → `/move`。
240
+ 避免同一条 chip 出现两次。
241
+
242
+ 点 chip 弹的是**官方 `Menu`**(`dsh.client.inject` 里声明了 `@deepseek-ai/dsh-client-ui-primitives`):
243
+ `items` = 各工作区(`IconFolderCloseRegular` 图标),`selectedId` = 当前工作区(官方自己画勾),
244
+ `footer` = `[{ label: '添加工作区…', icon: IconPlusOutlineRegular }]`,`portal: true` + `getAnchorRect`
245
+ 指向 chip 本身 —— 位置、圆角、阴影、键盘导航都和 hero 那条工作区胶囊一致,不再自绘弹窗。
246
+ 同名工作区用末尾路径段区分(`withPathSuffix`)。取不到 primitives(老宿主)时退回原来的自绘面板。
247
+ 选中目标后 `/move`。选「添加工作区…」调**官方目录选择器**再 `/move { targetPath }`:
248
+ 优先 `globalThis.__DSH_DIRECTORY_PICKER__.pick()`(桌面端 preload),否则 `ctx.get('uiWorkspace').pickDirectory()` ——
249
+ `uiWorkspace` 是**服务**不是模块,`ctx.get` 是可选查找(动态插件 ctx 允许未声明的服务查询),
250
+ 所以这条不需要改 `dsh.client.inject`、也不需要重启。两者都没有才退回 `prompt` 手输。
234
251
 
235
252
  **连同子对话**:主机在搬完一条会话后,用 `sessionPersistence.list()` 的 header 关系找
236
253
  `origin === 'subagent' && parentSession === 本会话` 的后代(递归到孙),逐条走完整的
package/lib/client.js CHANGED
@@ -16,6 +16,10 @@ window.__ModuleLoader__.load({
16
16
  var module = { exports: {} };
17
17
  var exports = module.exports;
18
18
  var react = require('react');
19
+ // 官方 UI 基座:菜单(Menu)和图标。声明在 package.json 的 dsh.client.inject 里;
20
+ // 取不到(老宿主 / 没声明)时所有调用点都退回自绘面板,不影响其余功能。
21
+ var primitives = null;
22
+ try { primitives = require('@deepseek-ai/dsh-client-ui-primitives'); } catch (error) { primitives = null; }
19
23
 
20
24
  var STYLE_ID = 'dsh-session-relocate-styles';
21
25
  var CSS = [
@@ -104,6 +108,10 @@ window.__ModuleLoader__.load({
104
108
  '.dshsm-chip-label{text-overflow:ellipsis;white-space:nowrap;min-width:0;overflow:hidden}',
105
109
  '.dshsm-chip-chevron{color:var(--dsw-alias-label-caption,#a7b0bf);flex:none;display:inline-flex}',
106
110
  '.dshsm-chip-chevron svg{display:block}',
111
+ // 官方 Menu 里两行同名工作区时的「标题 + 末尾路径段」(照官方 WorkspacePicker 的样式)
112
+ '.dshsm-menu-disambig{display:flex;align-items:center;gap:4px;min-width:0}',
113
+ '.dshsm-menu-title{text-overflow:ellipsis;min-width:0;overflow:hidden}',
114
+ '.dshsm-menu-suffix{flex:none;max-width:75%;text-overflow:ellipsis;min-width:0;overflow:hidden;color:var(--dsw-alias-label-secondary,inherit)}',
107
115
  '.dshsm-chip[data-mode="hover"]{opacity:0;transition:opacity .12s ease}',
108
116
  '.dshsm-dock:hover .dshsm-chip[data-mode="hover"]{opacity:1}',
109
117
  '.dshsm-dock--hidden{justify-content:flex-end}',
@@ -152,6 +160,39 @@ window.__ModuleLoader__.load({
152
160
  return null;
153
161
  }
154
162
 
163
+ // 官方 uiWorkspace 服务(由 apply 里 ctx.get('uiWorkspace') 填)。它带 pickDirectory(),
164
+ // 也就是官方「添加工作区」用的那个目录选择器 —— 插件通过服务调用,不碰它的 UI。
165
+ var uiWorkspaceService = null;
166
+
167
+ /**
168
+ * 弹官方目录选择器(原生系统对话框)。
169
+ * @returns Promise<string|null|undefined>:路径 = 选了;null = 用户取消;undefined = 本机没有可用选择器。
170
+ */
171
+ function pickDirectoryNative() {
172
+ var desktop = globalThis.__DSH_DIRECTORY_PICKER__;
173
+ if (desktop !== null && typeof desktop === 'object' && typeof desktop.pick === 'function') {
174
+ return Promise.resolve().then(function () { return desktop.pick(); }).then(
175
+ function (path) { return typeof path === 'string' && path.length > 0 ? path : null; },
176
+ function () { return null; },
177
+ );
178
+ }
179
+ var service = uiWorkspaceService;
180
+ if (service !== null && service !== undefined && typeof service.pickDirectory === 'function') {
181
+ return Promise.resolve().then(function () { return service.pickDirectory(); }).then(
182
+ function (path) { return typeof path === 'string' && path.length > 0 ? path : null; },
183
+ function () { return null; },
184
+ );
185
+ }
186
+ return Promise.resolve(undefined);
187
+ }
188
+
189
+ /** 目录选择器是否可用(决定「添加工作区…」是弹系统对话框还是手输路径)。 */
190
+ function hasNativeDirectoryPicker() {
191
+ var desktop = globalThis.__DSH_DIRECTORY_PICKER__;
192
+ if (desktop !== null && typeof desktop === 'object' && typeof desktop.pick === 'function') return true;
193
+ return uiWorkspaceService !== null && uiWorkspaceService !== undefined && typeof uiWorkspaceService.pickDirectory === 'function';
194
+ }
195
+
155
196
  /** 桥接前缀由主机侧通过引导全局下发;取不到就用默认值。 */
156
197
  function bridgePrefix() {
157
198
  var boot = bootGlobal();
@@ -207,6 +248,7 @@ window.__ModuleLoader__.load({
207
248
  starPrompt: '顺手留颗 Star,作者能高兴一整天',
208
249
  starCta: '行,给你一颗 Star',
209
250
  chipPick: '移动这个对话到:',
251
+ chipAddWorkspace: '添加工作区…',
210
252
  chipMoved: '已移动到「{ws}」',
211
253
  chipAria: '当前工作区「{ws}」,点击移动',
212
254
  chipUnknown: '未分组',
@@ -252,6 +294,7 @@ window.__ModuleLoader__.load({
252
294
  starPrompt: 'Leave a star — it makes the author’s day',
253
295
  starCta: 'Give a star',
254
296
  chipPick: 'Move this conversation to:',
297
+ chipAddWorkspace: 'Add workspace…',
255
298
  chipMoved: 'Moved to “{ws}”',
256
299
  chipAria: 'Workspace “{ws}” — click to move',
257
300
  chipUnknown: 'Ungrouped',
@@ -557,9 +600,16 @@ window.__ModuleLoader__.load({
557
600
  }
558
601
 
559
602
  function chooseDirectory() {
560
- var picked = globalThis.prompt(strings.chooseDirPrompt, '');
561
- if (typeof picked !== 'string' || picked.trim().length === 0) return;
562
- run({ targetPath: picked.trim() });
603
+ pickDirectoryNative().then(function (picked) {
604
+ var path = picked;
605
+ if (path === undefined) {
606
+ var typed = globalThis.prompt(strings.chooseDirPrompt, '');
607
+ if (typeof typed !== 'string' || typed.trim().length === 0) return;
608
+ path = typed.trim();
609
+ }
610
+ if (typeof path !== 'string' || path.length === 0) return;
611
+ run({ targetPath: path });
612
+ }, function () { /* 选择器自己会报错 */ });
563
613
  }
564
614
 
565
615
  if (state.phase === 'idle') {
@@ -1015,6 +1065,26 @@ window.__ModuleLoader__.load({
1015
1065
  return workspaceId === null || workspaceId === undefined ? text().chipUnknown : null;
1016
1066
  }
1017
1067
 
1068
+ /**
1069
+ * 同名工作区用末尾路径段区分,免得菜单里两行一模一样。
1070
+ * 和官方 WorkspacePicker 的 distinguishingPathSuffixes 同一个思路,只是取最短尾部一段。
1071
+ */
1072
+ function withPathSuffix(rows) {
1073
+ var counts = {};
1074
+ var i;
1075
+ for (i = 0; i < rows.length; i += 1) {
1076
+ var name = rows[i].title;
1077
+ counts[name] = (counts[name] === undefined ? 0 : counts[name]) + 1;
1078
+ }
1079
+ for (i = 0; i < rows.length; i += 1) {
1080
+ if (counts[rows[i].title] > 1 && typeof rows[i].path === 'string') {
1081
+ var parts = rows[i].path.split(/[\\/]+/).filter(function (part) { return part.length > 0; });
1082
+ if (parts.length > 0) rows[i].suffix = parts[parts.length - 1];
1083
+ }
1084
+ }
1085
+ return rows;
1086
+ }
1087
+
1018
1088
  /** 从 composer chip 弹目标面板;取消返回 null。 */
1019
1089
  function pickMoveTarget(sessionId) {
1020
1090
  return new Promise(function (resolve) {
@@ -1109,6 +1179,29 @@ window.__ModuleLoader__.load({
1109
1179
  });
1110
1180
  }
1111
1181
 
1182
+ /** 按路径搬(菜单里的「添加工作区…」):目录不存在会由主机侧创建并注册成新工作区。 */
1183
+ function moveFromChipPath(sessionId, path, onMoved) {
1184
+ var strings = text();
1185
+ toast(strings.moving);
1186
+ var payload = { sessionId: sessionId, targetPath: path };
1187
+ if (wantChildren() === false) payload.includeChildren = false;
1188
+ post('/move', payload).then(function (result) {
1189
+ if (result !== null && typeof result === 'object' && result.ok === true) {
1190
+ var title = typeof result.targetTitle === 'string' && result.targetTitle.length > 0 ? result.targetTitle : path;
1191
+ toast(result.applied === 'attached'
1192
+ ? strings.attached.replace('{ws}', title)
1193
+ : strings.chipMoved.replace('{ws}', title));
1194
+ if (typeof onMoved === 'function') onMoved(title, result.targetWorkspaceId);
1195
+ refreshSidebar();
1196
+ return;
1197
+ }
1198
+ var message = result !== null && typeof result === 'object' && typeof result.message === 'string' ? result.message : '';
1199
+ toast(strings.dragFailed + message);
1200
+ }, function (error) {
1201
+ toast(strings.dragFailed + errorText(error));
1202
+ });
1203
+ }
1204
+
1112
1205
  /** 搬完通知 chip 换名字(回执里就有新工作区名)。 */
1113
1206
  function moveFromChip(sessionId, workspace, onMoved) {
1114
1207
  var strings = text();
@@ -1136,6 +1229,68 @@ window.__ModuleLoader__.load({
1136
1229
  * composer 里常驻的工作区 chip(注册进 conversation.input.dock)。
1137
1230
  * 外观逐项对齐官方 hero 那条:同一个文件夹图标 / 箭头 / 圆角 / 高度 / 字号 / hover。
1138
1231
  */
1232
+ /** 官方 Menu 可用吗(取不到就退回自绘面板)。 */
1233
+ function menuReady() {
1234
+ return primitives !== null && primitives !== undefined && typeof primitives.Menu === 'function';
1235
+ }
1236
+
1237
+ /** 菜单里的文件夹图标(官方 WorkspacePicker 用的是 IconFolderCloseRegular)。 */
1238
+ function chipFolderIcon() {
1239
+ if (primitives !== null && primitives !== undefined && primitives.IconFolderCloseRegular !== undefined) {
1240
+ return react.createElement(primitives.IconFolderCloseRegular, { size: 16 });
1241
+ }
1242
+ return undefined;
1243
+ }
1244
+
1245
+ /** 菜单里「添加工作区…」前面的加号图标。 */
1246
+ function chipPlusIcon() {
1247
+ if (primitives !== null && primitives !== undefined && primitives.IconPlusOutlineRegular !== undefined) {
1248
+ return react.createElement(primitives.IconPlusOutlineRegular, { size: 16 });
1249
+ }
1250
+ return undefined;
1251
+ }
1252
+
1253
+ var CHIP_ADD_WORKSPACE = '__dshsm-add-workspace';
1254
+ var CHIP_EMPTY_ID = '__dshsm-none';
1255
+
1256
+ /**
1257
+ * 把 /describe 的结果拼成官方 Menu 的 items / footer:
1258
+ * [📁 工作区 A ✓] [📁 工作区 B] ── [+ 添加工作区…]
1259
+ * 当前工作区由 selectedId 画勾(和官方工作区下拉一样)。
1260
+ */
1261
+ function chipMenuEntries(snapshot, strings) {
1262
+ var spaces = snapshot !== null && snapshot !== undefined && Array.isArray(snapshot.spaces) ? snapshot.spaces.slice() : [];
1263
+ if (snapshot === null || snapshot === undefined) {
1264
+ return { items: [{ id: CHIP_EMPTY_ID, label: strings.loading, disabled: true }], footer: [] };
1265
+ }
1266
+ var rows = withPathSuffix(spaces.map(function (space) {
1267
+ return {
1268
+ id: space.id,
1269
+ title: typeof space.title === 'string' && space.title.length > 0 ? space.title : String(space.id),
1270
+ path: space.path,
1271
+ };
1272
+ }));
1273
+ var items = [];
1274
+ for (var i = 0; i < rows.length; i += 1) {
1275
+ var label = rows[i].title;
1276
+ if (rows[i].suffix !== undefined) {
1277
+ label = react.createElement('span', { className: 'dshsm-menu-disambig', key: 'label', title: rows[i].path }, [
1278
+ react.createElement('span', { className: 'dshsm-menu-title', key: 'title' }, rows[i].title),
1279
+ ' ',
1280
+ react.createElement('span', { className: 'dshsm-menu-suffix', key: 'suffix' }, rows[i].suffix),
1281
+ ]);
1282
+ }
1283
+ items.push({ id: rows[i].id, label: label, icon: chipFolderIcon() });
1284
+ }
1285
+ if (items.length === 0) {
1286
+ return { items: [{ id: CHIP_EMPTY_ID, label: strings.noTargets, disabled: true }], footer: [] };
1287
+ }
1288
+ return {
1289
+ items: items,
1290
+ footer: [{ id: CHIP_ADD_WORKSPACE, label: strings.chipAddWorkspace, icon: chipPlusIcon() }],
1291
+ };
1292
+ }
1293
+
1139
1294
  function WorkspaceDockChip(props) {
1140
1295
  var strings = text();
1141
1296
  var sessionId = props !== null && props !== undefined
@@ -1159,22 +1314,51 @@ window.__ModuleLoader__.load({
1159
1314
 
1160
1315
  var useState = typeof react.useState === 'function' ? react.useState : function (initial) { return [initial, function () {}]; };
1161
1316
  var useEffect = typeof react.useEffect === 'function' ? react.useEffect : function () {};
1162
- var state = useState(strings.chipUnknown);
1163
- var title = state[0];
1164
- var setTitle = state[1];
1317
+ var useRef = typeof react.useRef === 'function' ? react.useRef : function () { return { current: null }; };
1318
+
1319
+ var titleState = useState(strings.chipUnknown);
1320
+ var title = titleState[0];
1321
+ var setTitle = titleState[1];
1322
+ // snapshot:最近一次 /describe 的结果(currentId + 工作区列表),菜单用它渲染。
1323
+ var snapshotState = useState(null);
1324
+ var snapshot = snapshotState[0];
1325
+ var setSnapshot = snapshotState[1];
1326
+ var openState = useState(false);
1327
+ var open = openState[0];
1328
+ var setOpen = openState[1];
1329
+ var anchorRef = useRef(null);
1165
1330
  var modeState = useState(chipMode());
1166
1331
  var mode = modeState[0];
1167
1332
  useEffect(function () {
1168
1333
  return subscribeChipMode(function (next) { modeState[1](next); });
1169
1334
  }, []);
1170
1335
 
1336
+ function applyDescribe(result) {
1337
+ var spaces = result !== null && typeof result === 'object' && Array.isArray(result.workspaces) ? result.workspaces : [];
1338
+ var described = result !== null && typeof result === 'object' ? result.session : null;
1339
+ var currentId = null;
1340
+ if (described !== null && described !== undefined && typeof described === 'object') {
1341
+ currentId = described.currentWorkspaceId !== undefined && described.currentWorkspaceId !== null
1342
+ ? described.currentWorkspaceId
1343
+ : (described.cwdMatchesWorkspaceId === undefined ? null : described.cwdMatchesWorkspaceId);
1344
+ }
1345
+ setSnapshot({ currentId: currentId, spaces: spaces });
1346
+ var next = titleFromDescribe(result);
1347
+ if (next !== null && next !== undefined) setTitle(next);
1348
+ }
1349
+
1350
+ function loadDescribe() {
1351
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return;
1352
+ post('/describe', { sessionId: sessionId }).then(function (result) {
1353
+ applyDescribe(result);
1354
+ }, function () { /* 读不到就保持上一次的显示 */ });
1355
+ }
1356
+
1171
1357
  useEffect(function () {
1172
1358
  if (heroPresent || typeof sessionId !== 'string' || sessionId.length === 0) return function () {};
1173
1359
  var alive = true;
1174
1360
  post('/describe', { sessionId: sessionId }).then(function (result) {
1175
- if (!alive) return;
1176
- var next = titleFromDescribe(result);
1177
- if (next !== null && next !== undefined) setTitle(next);
1361
+ if (alive) applyDescribe(result);
1178
1362
  }, function () { /* 读不到就保持上一次的显示 */ });
1179
1363
  return function () { alive = false; };
1180
1364
  }, [sessionId, heroPresent]);
@@ -1182,14 +1366,65 @@ window.__ModuleLoader__.load({
1182
1366
  // hooks 都调用过了,这里提前退出是安全的(顺序不变)。
1183
1367
  if (heroPresent) return null;
1184
1368
 
1185
- function onOpen() {
1369
+ function anchorRect() {
1370
+ var node = anchorRef.current;
1371
+ if (node === null || node === undefined || typeof node.getBoundingClientRect !== 'function') return null;
1372
+ return node.getBoundingClientRect();
1373
+ }
1374
+
1375
+ function onChipClick() {
1186
1376
  if (typeof sessionId !== 'string' || sessionId.length === 0) return;
1377
+ // 有官方 Menu 就弹官方那套下拉(和 hero 那条工作区胶囊一模一样);
1378
+ // 取不到就退回自绘面板。
1379
+ if (menuReady()) {
1380
+ if (open === true) { setOpen(false); return; }
1381
+ setOpen(true);
1382
+ if (snapshot === null) setSnapshot(null);
1383
+ loadDescribe();
1384
+ return;
1385
+ }
1187
1386
  pickMoveTarget(sessionId).then(function (workspace) {
1188
1387
  if (workspace === null) return;
1189
1388
  moveFromChip(sessionId, workspace, function (next) { setTitle(next); });
1190
1389
  }, function () { /* 面板自己会报错 */ });
1191
1390
  }
1192
1391
 
1392
+ function onChipSelect(id) {
1393
+ setOpen(false);
1394
+ if (id === CHIP_EMPTY_ID) return;
1395
+ if (id === CHIP_ADD_WORKSPACE) {
1396
+ // 和官方「添加工作区…」一样弹系统目录选择器;本机没有选择器才退回手输路径。
1397
+ pickDirectoryNative().then(function (picked) {
1398
+ var path = picked;
1399
+ if (path === undefined) {
1400
+ var typed = globalThis.prompt(strings.chooseDirPrompt, '');
1401
+ if (typeof typed !== 'string' || typed.trim().length === 0) return;
1402
+ path = typed.trim();
1403
+ }
1404
+ if (typeof path !== 'string' || path.length === 0) return; // 用户取消
1405
+ moveFromChipPath(sessionId, path, function (next, nextId) {
1406
+ setTitle(next);
1407
+ setSnapshot({
1408
+ currentId: typeof nextId === 'string' ? nextId : (snapshot !== null ? snapshot.currentId : null),
1409
+ spaces: snapshot !== null && Array.isArray(snapshot.spaces) ? snapshot.spaces : [],
1410
+ });
1411
+ });
1412
+ });
1413
+ return;
1414
+ }
1415
+ var spaces = snapshot !== null && Array.isArray(snapshot.spaces) ? snapshot.spaces : [];
1416
+ var target = null;
1417
+ for (var i = 0; i < spaces.length; i += 1) {
1418
+ if (spaces[i] !== null && spaces[i] !== undefined && spaces[i].id === id) target = spaces[i];
1419
+ }
1420
+ if (target === null) return;
1421
+ if (snapshot !== null && snapshot.currentId === id) return; // 已经是这个工作区了
1422
+ moveFromChip(sessionId, target, function (next) {
1423
+ setTitle(next);
1424
+ setSnapshot({ currentId: id, spaces: spaces });
1425
+ });
1426
+ }
1427
+
1193
1428
  var renderSlot = props !== null && props !== undefined && typeof props.renderSlot === 'function' ? props.renderSlot : null;
1194
1429
  var SessionProvider = props !== null && props !== undefined && typeof props.SessionProvider === 'function' ? props.SessionProvider : null;
1195
1430
  var tail = null;
@@ -1206,9 +1441,12 @@ window.__ModuleLoader__.load({
1206
1441
  type: 'button',
1207
1442
  className: 'dshsm-chip',
1208
1443
  'data-mode': mode,
1444
+ ref: anchorRef,
1209
1445
  'aria-label': strings.chipAria.replace('{ws}', label),
1210
1446
  title: strings.chipAria.replace('{ws}', label),
1211
- onClick: onOpen,
1447
+ 'aria-haspopup': menuReady() ? 'menu' : undefined,
1448
+ 'aria-expanded': menuReady() ? (open === true ? 'true' : 'false') : undefined,
1449
+ onClick: onChipClick,
1212
1450
  }, [
1213
1451
  react.createElement('span', { className: 'dshsm-chip-icon', key: 'icon' }, react.createElement('svg', {
1214
1452
  key: 'folder', width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none',
@@ -1223,8 +1461,29 @@ window.__ModuleLoader__.load({
1223
1461
  xmlns: 'http://www.w3.org/2000/svg', 'aria-hidden': 'true', strokeWidth: 1,
1224
1462
  }, react.createElement('path', { key: 'a', d: 'M4 6L7.29289 9.29289C7.68342 9.68342 8.31658 9.68342 8.70711 9.29289L12 6', stroke: 'currentColor' }))),
1225
1463
  ]);
1464
+
1465
+ var menuNode = null;
1466
+ if (open === true && menuReady()) {
1467
+ var entries = chipMenuEntries(snapshot, strings);
1468
+ menuNode = react.createElement(primitives.Menu, {
1469
+ key: 'chipmenu',
1470
+ open: true,
1471
+ anchor: null,
1472
+ items: entries.items,
1473
+ footer: entries.footer,
1474
+ selectedId: snapshot !== null && typeof snapshot.currentId === 'string' ? snapshot.currentId : '',
1475
+ onSelect: onChipSelect,
1476
+ onClose: function () { setOpen(false); },
1477
+ side: 'bottom',
1478
+ align: 'start',
1479
+ portal: true,
1480
+ getAnchorRect: anchorRect,
1481
+ });
1482
+ }
1483
+
1226
1484
  return react.createElement('div', { className: mode === 'never' ? 'dshsm-dock dshsm-dock--hidden' : 'dshsm-dock' }, [
1227
1485
  chipNode,
1486
+ menuNode,
1228
1487
  tail === null ? null : react.createElement('span', { className: 'dshsm-dock-slot', key: 'slot' }, tail),
1229
1488
  ]);
1230
1489
  }
@@ -1851,6 +2110,14 @@ window.__ModuleLoader__.load({
1851
2110
 
1852
2111
  function apply(ctx) {
1853
2112
  ensureStyles();
2113
+ // uiWorkspace 是**服务**不是模块:ctx.get 是可选查找,不需要在 inject 里声明,
2114
+ // 所以拿它不需要宿主重启。拿不到就退回手输路径。
2115
+ try {
2116
+ var workspaceService = typeof ctx.get === 'function' ? ctx.get('uiWorkspace') : null;
2117
+ uiWorkspaceService = workspaceService !== null && workspaceService !== undefined && typeof workspaceService === 'object' ? workspaceService : null;
2118
+ } catch (error) {
2119
+ uiWorkspaceService = null;
2120
+ }
1854
2121
  // 对外契约:dsh-delete-session 会检测这个全局,把「移动」放进它那根底栏。
1855
2122
  var boot = bootGlobal();
1856
2123
  var version = boot !== null && typeof boot === 'object' && typeof boot.version === 'string' ? boot.version : '0.0.0';
@@ -1979,6 +2246,8 @@ window.__ModuleLoader__.load({
1979
2246
  bulkSnapshot: bulkSnapshot,
1980
2247
  bulkUpdateBar: bulkUpdateBar,
1981
2248
  markSelecting: markSelecting,
2249
+ pickDirectoryNative: pickDirectoryNative,
2250
+ hasNativeDirectoryPicker: hasNativeDirectoryPicker,
1982
2251
  slotReady: function () { return bulkSlotReady; },
1983
2252
  enterBulk: enterBulk,
1984
2253
  exitBulk: exitBulk,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-session-relocate",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "跨工作区移动 DSH 对话:把某个 Session 的日志文件与工作区归属整体搬到另一个工作区(可自动注册新工作区)。带日志级崩溃恢复的安全事务,并且会先安全释放「已打开但空闲」的会话 —— 所以正在打开的对话也能直接搬,不需要重启 DSH。",
5
5
  "type": "module",
6
6
  "main": "src/plugin.js",
@@ -27,7 +27,8 @@
27
27
  "client": {
28
28
  "platform": "web",
29
29
  "inject": [
30
- "@deepseek-ai/dsh-client-ui-slots"
30
+ "@deepseek-ai/dsh-client-ui-slots",
31
+ "@deepseek-ai/dsh-client-ui-primitives"
31
32
  ]
32
33
  },
33
34
  "engines": {
package/scripts/e2e.mjs CHANGED
@@ -65,6 +65,35 @@ function seed() {
65
65
  process.stdout.write('seeded ' + SESSION_ID + ' -> ' + dir + '\n');
66
66
  }
67
67
 
68
+ /**
69
+ * 查一次 DSH 自己的 `session/list`(issue #1 的回归点)。
70
+ *
71
+ * dsh-session-query 会把**内存里 live Session 的 header** 和**磁盘 artifact 的 header**
72
+ * 逐字段比对;任何一处分叉都会让这个接口整体报 `SESSION_QUERY_SOURCE_CONFLICT`,
73
+ * 于是刷新后侧栏全空(重启才恢复)。这个 profile 没挂该接口时只提示、不判定失败。
74
+ */
75
+ async function assertSessionListHealthy(stage) {
76
+ const response = await fetch('http://127.0.0.1:' + PORT + '/api/session/list', {
77
+ method: 'POST',
78
+ headers: { 'content-type': 'application/json' },
79
+ body: JSON.stringify({
80
+ type: 'client-request',
81
+ rpcId: 'e2e-' + String(Date.now()),
82
+ method: 'session/list',
83
+ payload: { args: { _request: {} } },
84
+ }),
85
+ });
86
+ if (response.status === 404) {
87
+ process.stdout.write('list : 跳过(这个 profile 没挂 /api/session/list)\n');
88
+ return;
89
+ }
90
+ const payload = await response.json().catch(() => null);
91
+ if (payload === null || payload.ok === false) {
92
+ throw new Error('session/list 在「' + stage + '」之后不可用(header 分叉):' + JSON.stringify(payload === null ? response.status : payload.error));
93
+ }
94
+ process.stdout.write('list : 正常(' + stage + '之后)\n');
95
+ }
96
+
68
97
  async function post(path, body) {
69
98
  const response = await fetch(BASE + path, {
70
99
  method: 'POST',
@@ -182,6 +211,9 @@ async function live() {
182
211
  if (after.session?.live !== true) throw new Error('就地接管之后会话必须还活着');
183
212
  if (after.session?.unreadable === true) throw new Error('DSH 读不懂改写后的日志:' + String(after.session.message));
184
213
 
214
+ // issue #1 的回归点:迁移后 dsh 自己的会话列表必须还能用(header 内存/磁盘不许分叉)。
215
+ await assertSessionListHealthy('就地接管');
216
+
185
217
  const srcDir = join(HOME, 'sessions', projectKey(srcWs), encodeSegment(sessionId));
186
218
  const dstDir = join(HOME, 'sessions', projectKey(dstWs), encodeSegment(sessionId));
187
219
  if (existsSync(srcDir)) throw new Error('源目录还在:' + srcDir);
@@ -197,7 +229,7 @@ async function live() {
197
229
  process.stdout.write('drop : ' + JSON.stringify(dropped) + '\n');
198
230
  if (dropped.ok !== true) throw new Error('清理失败');
199
231
  if (existsSync(dstDir)) throw new Error('清理后目标目录还在');
200
- process.stdout.write('OK:就地接管(写链内搬 → 换 header → 释放锁 → 会话仍活 → 旧目录不复活 → 清理)全部正确\n');
232
+ process.stdout.write('OK:就地接管(写链内搬 → 换写句柄 + live Session 两处 header → 释放锁 → 会话仍活 → session/list 仍可用 → 旧目录不复活 → 清理)全部正确\n');
201
233
  }
202
234
 
203
235
 
package/src/plugin.js CHANGED
@@ -258,6 +258,37 @@ export function apply(ctx, config) {
258
258
  });
259
259
 
260
260
  /** 组装一次迁移需要的 DSH 运行时能力。 */
261
+ /**
262
+ * 内存里那条 live Session(SessionStore.get(id) 返回的就是 Session 本身)。
263
+ * 拿不到(老版本 / 没有 sessions 服务)就返回 undefined。
264
+ */
265
+ function liveSessionOf(sessionId) {
266
+ const sessions = ctx.get('sessions');
267
+ if (sessions === undefined || sessions === null || typeof sessions.get !== 'function') return undefined;
268
+ const session = sessions.get(sessionId);
269
+ return session === null || session === undefined ? undefined : session;
270
+ }
271
+
272
+ /**
273
+ * 把 Session.header 整体换成「同内容、只改 cwd」的新对象。
274
+ *
275
+ * 为什么必须做:dsh-session-query 的 assertSessionHeadersCompatible() 会逐字段比对
276
+ * **live Session 的 header** 与 **磁盘 artifact 的 header**(id / createdAt / cwd /
277
+ * parentSession / isSeeded / delegationDepth),不一致即抛 SESSION_QUERY_SOURCE_CONFLICT;
278
+ * 而 /api/session/list 没有逐条兜错,一条冲突就让整个列表报错(issues#1:刷新后侧栏全空)。
279
+ *
280
+ * 可行性:Session.header 是普通字段(`header;`),不是 getter,实例也没被冻;
281
+ * 被 deepFreeze 的是 header 那个对象本身。header 全是标量字段,
282
+ * 所以「新建对象 + 浅冻结」与深冻结等价。
283
+ */
284
+ function retargetSessionHeader(session, cwd) {
285
+ const previous = session.header;
286
+ if (previous === null || typeof previous !== 'object') throw new Error('live session 没有可用的 header');
287
+ const next = { ...previous, cwd };
288
+ session.header = Object.freeze(next);
289
+ return previous;
290
+ }
291
+
261
292
  function buildHost() {
262
293
  const registry = ctx.workspaceRegistry;
263
294
  return {
@@ -357,6 +388,16 @@ export function apply(ctx, config) {
357
388
  // 的坏状态(下一次写入就把旧目录重建出来)。整体放弃,让调用方改走释放路径。
358
389
  return { ok: false, code: 'no-writer', detail: '找不到这个会话的 live 写句柄' };
359
390
  }
391
+ // 内存里那条 live Session 的 header 必须能一起换:只换写句柄的话,磁盘 header
392
+ // 与内存 header 就分叉了,session/list 会整体报错(issues#1)。改不了就整体放弃,
393
+ // 绝不搬完文件再留一个「列表不可用」的状态。
394
+ const liveSession = liveSessionOf(sessionId);
395
+ if (liveSession === undefined) {
396
+ return { ok: false, code: 'no-live-session', detail: '拿不到内存里的 live Session,放弃接管(避免 session/list header 冲突)' };
397
+ }
398
+ if (liveSession.header === null || typeof liveSession.header !== 'object') {
399
+ return { ok: false, code: 'no-session-header', detail: 'live Session 没有 header,放弃接管(避免 session/list header 冲突)' };
400
+ }
360
401
  if (typeof handle.drainLive === 'function') await handle.drainLive();
361
402
  if (typeof handle.flush === 'function') await handle.flush();
362
403
 
@@ -365,20 +406,31 @@ export function apply(ctx, config) {
365
406
  const transaction = await handle.enqueueChain(async () => {
366
407
  if (typeof handle.ensureLease === 'function') await handle.ensureLease();
367
408
  const originalHeader = handle.header;
409
+ let originalSessionHeader;
368
410
  try {
369
411
  if (handle.lease !== undefined && handle.lease !== null && typeof handle.lease.release === 'function') {
370
412
  await handle.lease.release();
371
413
  }
372
414
  handle.lease = null;
373
415
  handle.header = { ...originalHeader, cwd: targetCwd };
416
+ // 内存 header 跟着换(否则 session-query 会认为磁盘与内存冲突)。
417
+ originalSessionHeader = retargetSessionHeader(liveSession, targetCwd);
374
418
  const result = await runTransaction();
375
- detail = '写链已接管:header.cwd -> ' + targetCwd;
419
+ detail = '写链已接管:header.cwd -> ' + targetCwd + '(写句柄 + live Session 同步)';
376
420
  result.writerRetargeted = true;
421
+ result.sessionHeaderRetargeted = true;
377
422
  return result;
378
423
  } catch (error) {
379
- // 回滚:恢复 header 与锁状态,让后续写入继续落在原路径。
424
+ // 回滚:恢复写句柄 header、内存 header 与锁状态,让后续写入继续落在原路径。
380
425
  handle.header = originalHeader;
381
426
  handle.lease = null;
427
+ if (originalSessionHeader !== undefined) {
428
+ try {
429
+ liveSession.header = originalSessionHeader;
430
+ } catch (rollbackError) {
431
+ log('warn', '回滚内存 header 失败:' + String(rollbackError && rollbackError.message));
432
+ }
433
+ }
382
434
  throw error;
383
435
  }
384
436
  });