dsh-nested-workspaces 1.0.0 → 2.0.0

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
@@ -42,11 +42,12 @@ window.__ModuleLoader__.load({
42
42
  'dialog.rename.title': '重命名工作区',
43
43
  'dialog.delete.title': '删除工作区',
44
44
  'dialog.delete.description': '将把「{name}」从侧边栏移除,磁盘上的文件不会被删除。',
45
+ 'dialog.deleteGroup.description': '将把子工作区分组「{name}」及其下级分组从侧边栏删除;其中的会话会回到它们真正所属的工作区。',
45
46
  'renamed': '已重命名',
46
47
  'deleted': '已删除工作区',
47
48
  'dialog.addChild.title': '添加子工作区',
48
49
  'dialog.addWorkspace.title': '添加工作区',
49
- 'dialog.addChild.description': '将在 {parent} 下创建新的子工作区目录。',
50
+ 'dialog.addChild.description': '会在 {parent} 下新建一个子工作区分组;只在侧栏里记录,不会在磁盘上创建文件夹。',
50
51
  'dialog.addWorkspace.description': '填写工作区目录的绝对路径;留空则打开目录选择器。',
51
52
  'field.name': '子工作区名称',
52
53
  'field.path': '工作区路径(留空可选择)',
@@ -61,6 +62,7 @@ window.__ModuleLoader__.load({
61
62
  'actions.hideArchived': '隐藏已归档会话',
62
63
  'created': '已创建工作区',
63
64
  'createdChild': '已创建子工作区',
65
+ 'virtual.hint': '分组,会话在',
64
66
  'moved': '已移动会话',
65
67
  'rail.search': '搜索',
66
68
  'expandGroup': '展开分组',
@@ -70,6 +72,25 @@ window.__ModuleLoader__.load({
70
72
  'ungrouped': '未分组',
71
73
  'empty': '暂无会话',
72
74
  'search.empty': '没有匹配结果',
75
+ 'time.now': '刚刚',
76
+ 'time.minutes': '{n}分钟',
77
+ 'time.hours': '{n}小时',
78
+ 'time.days': '{n}天',
79
+ 'time.months': '{n}个月',
80
+ 'time.years': '{n}年',
81
+ 'time.ago': '{t}前',
82
+ 'actions.pin': '置顶',
83
+ 'actions.unpin': '取消置顶',
84
+ 'row.pinned': '已置顶',
85
+ 'errors.pinFailed': '置顶状态更新失败',
86
+ 'status.running': '正在工作',
87
+ 'status.subagentsRunning': '{n}个子代理正在运行',
88
+ 'status.completed': '已完成',
89
+ 'status.waitingApproval': '等待批准',
90
+ 'status.planReview': '等待确认计划',
91
+ 'status.waitingAnswer': '等待回答',
92
+ 'errors.reorderFailed': '工作区排序更新失败',
93
+ 'errors.unreadable': 'The new directory could not be read.',
73
94
  },
74
95
  en: {
75
96
  'heading.default': 'Workspaces',
@@ -88,11 +109,12 @@ window.__ModuleLoader__.load({
88
109
  'dialog.rename.title': 'Rename workspace',
89
110
  'dialog.delete.title': 'Delete workspace',
90
111
  'dialog.delete.description': 'This removes "{name}" from the sidebar. Files on disk are kept.',
112
+ 'dialog.deleteGroup.description': 'This removes the child workspace group "{name}" and its nested groups from the sidebar. Sessions it showed return to the workspace that owns them.',
91
113
  'renamed': 'Renamed',
92
114
  'deleted': 'Workspace deleted',
93
115
  'dialog.addChild.title': 'Add child workspace',
94
116
  'dialog.addWorkspace.title': 'Add workspace',
95
- 'dialog.addChild.description': 'A new child workspace directory will be created under {parent}.',
117
+ 'dialog.addChild.description': 'Adds a child workspace group under {parent}. It is only recorded in the sidebar — no folder is created on disk.',
96
118
  'dialog.addWorkspace.description': 'Enter the absolute path of the workspace directory, or leave it empty to pick a folder.',
97
119
  'field.name': 'Child workspace name',
98
120
  'field.path': 'Workspace path (empty to pick)',
@@ -107,6 +129,7 @@ window.__ModuleLoader__.load({
107
129
  'actions.hideArchived': 'Hide archived sessions',
108
130
  'created': 'Workspace created',
109
131
  'createdChild': 'Child workspace created',
132
+ 'virtual.hint': 'group, sessions run in',
110
133
  'moved': 'Session moved',
111
134
  'rail.search': 'Search',
112
135
  'expandGroup': 'Expand group',
@@ -116,6 +139,25 @@ window.__ModuleLoader__.load({
116
139
  'ungrouped': 'Ungrouped',
117
140
  'empty': 'No sessions',
118
141
  'search.empty': 'No matches',
142
+ 'time.now': 'now',
143
+ 'time.minutes': '{n}min',
144
+ 'time.hours': '{n}h',
145
+ 'time.days': '{n}d',
146
+ 'time.months': '{n}mo',
147
+ 'time.years': '{n}y',
148
+ 'time.ago': '{t} ago',
149
+ 'actions.pin': 'Pin',
150
+ 'actions.unpin': 'Unpin',
151
+ 'row.pinned': 'Pinned',
152
+ 'errors.pinFailed': 'Could not update the pin',
153
+ 'status.running': 'Working',
154
+ 'status.subagentsRunning': '{n} subagents running',
155
+ 'status.completed': 'Completed',
156
+ 'status.waitingApproval': 'Waiting for approval',
157
+ 'status.planReview': 'Waiting for plan review',
158
+ 'status.waitingAnswer': 'Waiting for an answer',
159
+ 'errors.reorderFailed': 'Could not reorder the workspace',
160
+ 'errors.unreadable': 'The new directory could not be read.',
119
161
  },
120
162
  ja: {
121
163
  'heading.default': 'ワークスペース',
@@ -134,11 +176,12 @@ window.__ModuleLoader__.load({
134
176
  'dialog.rename.title': 'ワークスペース名を変更',
135
177
  'dialog.delete.title': 'ワークスペースを削除',
136
178
  'dialog.delete.description': '「{name}」をサイドバーから削除します。ディスク上のファイルは残ります。',
179
+ 'dialog.deleteGroup.description': '子ワークスペースのグループ「{name}」とその下位グループをサイドバーから削除します。そこに表示されていたセッションは本来のワークスペースに戻ります。',
137
180
  'renamed': '名前を変更しました',
138
181
  'deleted': 'ワークスペースを削除しました',
139
182
  'dialog.addChild.title': '子ワークスペースを追加',
140
183
  'dialog.addWorkspace.title': 'ワークスペースを追加',
141
- 'dialog.addChild.description': '{parent} の下に子ワークスペースを作成します。',
184
+ 'dialog.addChild.description': '{parent} の下に子ワークスペースのグループを追加します。サイドバーに記録するだけで、ディスク上にフォルダーは作成しません。',
142
185
  'dialog.addWorkspace.description': 'ワークスペースの絶対パスを入力するか、空欄のままフォルダを選択してください。',
143
186
  'field.name': '子ワークスペース名',
144
187
  'field.path': 'ワークスペースのパス(空欄で選択)',
@@ -153,6 +196,7 @@ window.__ModuleLoader__.load({
153
196
  'actions.hideArchived': 'アーカイブ済みを隠す',
154
197
  'created': 'ワークスペースを作成しました',
155
198
  'createdChild': '子ワークスペースを作成しました',
199
+ 'virtual.hint': 'グループ、セッションの実行先は',
156
200
  'moved': 'セッションを移動しました',
157
201
  'rail.search': '検索',
158
202
  'expandGroup': 'グループを開く',
@@ -162,6 +206,25 @@ window.__ModuleLoader__.load({
162
206
  'ungrouped': '未分類',
163
207
  'empty': 'セッションはありません',
164
208
  'search.empty': '一致する項目はありません',
209
+ 'time.now': '今',
210
+ 'time.minutes': '{n}分',
211
+ 'time.hours': '{n}時間',
212
+ 'time.days': '{n}日',
213
+ 'time.months': '{n}か月',
214
+ 'time.years': '{n}年',
215
+ 'time.ago': '{t}前',
216
+ 'actions.pin': 'ピン留め',
217
+ 'actions.unpin': 'ピン留めを解除',
218
+ 'row.pinned': 'ピン留め済み',
219
+ 'errors.pinFailed': 'ピン留めを更新できませんでした',
220
+ 'status.running': '実行中',
221
+ 'status.subagentsRunning': '{n}件のサブエージェントが実行中',
222
+ 'status.completed': '完了',
223
+ 'status.waitingApproval': '承認待ち',
224
+ 'status.planReview': 'プラン確認待ち',
225
+ 'status.waitingAnswer': '回答待ち',
226
+ 'errors.reorderFailed': 'ワークスペースの並び順を更新できませんでした',
227
+ 'errors.unreadable': '作成したディレクトリを読み取れませんでした。',
165
228
  },
166
229
  }
167
230
 
@@ -204,9 +267,26 @@ window.__ModuleLoader__.load({
204
267
  .dnw-rowArchived .dnw-title{color:var(--dsw-alias-label-caption)}
205
268
  .dnw-actions{flex:none;display:none;align-items:center;gap:13px}
206
269
  .dnw-row:hover .dnw-actions,.dnw-actionsOpen{display:flex}
207
- @media (hover:none){.dnw-actions{display:flex}}
208
- .dnw-dot{width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-state-business-primary);flex:none}
209
- .dnw-dotIdle{background:var(--dsw-alias-label-caption);opacity:.5}
270
+ .dnw-resting{flex:none;display:inline-flex;align-items:center;gap:6px}
271
+ .dnw-time{flex:none;font-size:10px;line-height:16px;color:var(--dsw-alias-label-tertiary);margin-inline-end:-1px}
272
+ .dnw-pinIndicator{display:inline-flex;flex:none;width:16px;height:20px;align-items:center;justify-content:center;color:var(--dsw-alias-label-caption)}
273
+ @media (hover:hover){.dnw-row:hover .dnw-resting,html[data-input-modality='keyboard'] .dnw-row:focus-within .dnw-resting{display:none}}
274
+ .dnw-row:has(.dnw-actionsOpen) .dnw-resting{display:none}
275
+ @media (hover:none){.dnw-actions{display:flex}.dnw-resting{display:none}}
276
+ .dnw-stateDot{position:relative;display:inline-block;flex:none;border-radius:50%}
277
+ .dnw-stateDot::after{content:"";position:absolute;inset:20%;border-radius:50%;background:currentColor}
278
+ .dnw-stateDot[data-state=done]{color:var(--dsw-alias-state-success-primary)}
279
+ .dnw-stateDot[data-state=warning]{color:var(--dsw-alias-state-warn-primary)}
280
+ .dnw-stateDot[data-state=error]{color:var(--dsw-alias-state-error-primary)}
281
+ .dnw-spinner{flex:none;color:var(--dsw-alias-label-tertiary)}
282
+ .dnw-spinnerMotion{transform-origin:center;animation:dnw-state-dot-spin 1.5s linear infinite}
283
+ .dnw-spinnerTrack,.dnw-spinnerArc{fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round}
284
+ .dnw-spinnerTrack{opacity:.25}
285
+ .dnw-spinnerArc{stroke-dasharray:12 150;animation:dnw-state-dot-dash 1.5s ease-in-out infinite}
286
+ @keyframes dnw-state-dot-spin{to{transform:rotate(360deg)}}
287
+ @keyframes dnw-state-dot-dash{0%{stroke-dasharray:12 150;stroke-dashoffset:0}50%{stroke-dasharray:24 150;stroke-dashoffset:-6}to{stroke-dasharray:12 150;stroke-dashoffset:0}}
288
+ @media (prefers-reduced-motion:reduce){.dnw-spinnerMotion,.dnw-spinnerArc{animation:none}.dnw-spinnerArc{stroke-dasharray:18 150;stroke-dashoffset:-3}}
289
+ .dnw-visuallyHidden{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
210
290
  .dnw-empty{padding:2px 8px 4px;padding-inline-start:calc(var(--dsh-sidebar-row-padding,12px) + 22px + var(--dnw-indent,0px));font-size:13px;line-height:20px;color:var(--dsw-alias-label-caption)}
211
291
  .dnw-dropBefore::before,.dnw-dropAfter::after{content:"";position:absolute;left:calc(-1 * var(--dsh-sidebar-paint-inset,3px));right:calc(4px - var(--dsh-sidebar-paint-inset,3px));height:2px;border-radius:1px;background:var(--dsw-alias-state-business-primary)}
212
292
  .dnw-dropBefore::before{top:-8px}
@@ -296,11 +376,100 @@ window.__ModuleLoader__.load({
296
376
  h('path', { key: 'b', d: 'M4.8 8.5v6.2h10.4V8.5' }),
297
377
  h('path', { key: 'c', d: 'M10 13.4V9.9M8.4 11.5L10 9.9l1.6 1.6' }),
298
378
  ])
379
+ /* A pushed-in pin, drawn solid so it reads at 14px in a 16px cell. */
380
+ const IconPin = () =>
381
+ svg(
382
+ [
383
+ h('path', { key: 'a', d: 'M7.2 3h5.6l-.7 4.1 2.4 2.1-.5 1.3H5.9l-.5-1.3 2.4-2.1z', fill: 'currentColor', stroke: 'none' }),
384
+ h('path', { key: 'b', d: 'M10 10.5V17' }),
385
+ ],
386
+ { strokeWidth: 1.4 },
387
+ )
388
+ const IconPinOutline = () =>
389
+ svg([
390
+ h('path', { key: 'a', d: 'M7.2 3h5.6l-.7 4.1 2.4 2.1-.5 1.3H5.9l-.5-1.3 2.4-2.1z' }),
391
+ h('path', { key: 'b', d: 'M10 10.5V17' }),
392
+ ])
299
393
 
300
394
  /* ---------------------------------------------------------------- utilities */
301
395
 
302
396
  const cls = (...parts) => parts.filter(Boolean).join(' ')
303
397
 
398
+ const MINUTE_MS = 60 * 1000
399
+ const HOUR_MS = 60 * MINUTE_MS
400
+ const DAY_MS = 24 * HOUR_MS
401
+ const MONTH_MS = 30 * DAY_MS
402
+ const YEAR_MS = 365 * DAY_MS
403
+
404
+ /**
405
+ * Coarse age bucket of one timestamp, mirroring the shipped row labels.
406
+ * @returns {{unit: 'now'|'minutes'|'hours'|'days'|'months'|'years', n: number}}
407
+ */
408
+ function relativeTime(updatedAt, now) {
409
+ /* `updatedAt` is epoch milliseconds on a live SessionSummary; a fixture or
410
+ * a future shape may hand us something else, and a "NaN分钟" label is
411
+ * worse than no label at all. */
412
+ const stamp = typeof updatedAt === 'number' ? updatedAt : typeof updatedAt === 'string' ? Date.parse(updatedAt) : Number(updatedAt)
413
+ if (!Number.isFinite(stamp) || !Number.isFinite(now)) return { unit: 'now', n: 0 }
414
+ const age = Math.max(0, now - stamp)
415
+ if (age < MINUTE_MS) return { unit: 'now', n: 0 }
416
+ if (age < HOUR_MS) return { unit: 'minutes', n: Math.floor(age / MINUTE_MS) }
417
+ if (age < DAY_MS) return { unit: 'hours', n: Math.floor(age / HOUR_MS) }
418
+ if (age < MONTH_MS) return { unit: 'days', n: Math.floor(age / DAY_MS) }
419
+ if (age < YEAR_MS) return { unit: 'months', n: Math.floor(age / MONTH_MS) }
420
+ return { unit: 'years', n: Math.floor(age / YEAR_MS) }
421
+ }
422
+
423
+ /** Compact resting label: 刚刚 / 12分钟 / 3小时 / 2天 … */
424
+ function timeLabel(updatedAt, now, t) {
425
+ const { unit, n } = relativeTime(updatedAt, now)
426
+ return unit === 'now' ? t('time.now') : t('time.' + unit, { n })
427
+ }
428
+
429
+ /** Full sentence for the tooltip: 刚才 / 12分钟前 … */
430
+ function hoverTimeLabel(updatedAt, now, t) {
431
+ const { unit, n } = relativeTime(updatedAt, now)
432
+ return unit === 'now' ? t('time.now') : t('time.ago', { t: t('time.' + unit, { n }) })
433
+ }
434
+
435
+ /** Shipped runningChildCount: sessions in this one's subagent catalog still running. */
436
+ function runningSubagentCount(list, parentId, statuses) {
437
+ const entry = list !== null && list !== undefined && list.projectionsBySession !== undefined ? list.projectionsBySession[parentId] : undefined
438
+ const catalog = entry !== undefined && entry !== null && entry.values !== undefined ? entry.values.subagentCatalog : undefined
439
+ if (!Array.isArray(catalog)) return 0
440
+ let count = 0
441
+ for (const child of catalog) {
442
+ const childStatus = statuses.get(child.id)
443
+ const running = childStatus === undefined ? list.byId[child.id] !== undefined && list.byId[child.id].running === true : childStatus.running === true
444
+ if (running) count += 1
445
+ }
446
+ return count
447
+ }
448
+
449
+ /* The shipped browser's working indicator: a 14px stroked arc that spins
450
+ * while the stroke length breathes. Both keyframes and the reduced-motion
451
+ * fallback live in the stylesheet below. */
452
+ function StatusSpinner() {
453
+ return h(
454
+ 'svg',
455
+ {
456
+ className: 'dnw-spinner',
457
+ 'data-state': 'ongoing',
458
+ width: '14',
459
+ height: '14',
460
+ viewBox: '0 0 24 24',
461
+ 'aria-hidden': 'true',
462
+ focusable: 'false',
463
+ },
464
+ h(
465
+ 'g',
466
+ { className: 'dnw-spinnerMotion' },
467
+ h('circle', { className: 'dnw-spinnerTrack', cx: '12', cy: '12', r: '9.5' }),
468
+ h('circle', { className: 'dnw-spinnerArc', cx: '12', cy: '12', r: '9.5' }),
469
+ ),
470
+ )
471
+ }
472
+
304
473
  function isRecord(value) {
305
474
  return typeof value === 'object' && value !== null && !Array.isArray(value)
306
475
  }
@@ -348,9 +517,42 @@ window.__ModuleLoader__.load({
348
517
  }
349
518
  }
350
519
 
520
+ /** A child workspace is a record in this store, never a directory. */
521
+ function normalizeChildren(value) {
522
+ if (!Array.isArray(value)) return []
523
+ const seen = new Set()
524
+ const children = []
525
+ for (const entry of value) {
526
+ if (!isRecord(entry)) continue
527
+ const id = typeof entry.id === 'string' ? entry.id.trim() : ''
528
+ const parentId = typeof entry.parentId === 'string' ? entry.parentId.trim() : ''
529
+ const title = typeof entry.title === 'string' ? entry.title.trim() : ''
530
+ if (id === '' || parentId === '' || title === '') continue
531
+ if (seen.has(id)) continue
532
+ seen.add(id)
533
+ children.push({ id, parentId, title })
534
+ }
535
+ return children
536
+ }
537
+
538
+ function newChildId() {
539
+ return 'vk-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8)
540
+ }
541
+
542
+ /** Move one child record before another (or to the end of its parent run). */
543
+ function moveChildRecord(children, id, anchorId) {
544
+ const record = children.find(entry => entry.id === id)
545
+ if (record === undefined) return children
546
+ const rest = children.filter(entry => entry.id !== id)
547
+ if (anchorId === undefined || anchorId === null) return [...rest, record]
548
+ const at = rest.findIndex(entry => entry.id === anchorId)
549
+ if (at === -1) return [...rest, record]
550
+ return [...rest.slice(0, at), record, ...rest.slice(at)]
551
+ }
552
+
351
553
  function createStore() {
352
554
  const read = () => {
353
- const empty = { title: null, assign: {}, order: {}, collapsed: {} }
555
+ const empty = { title: null, assign: {}, order: {}, collapsed: {}, children: [] }
354
556
  if (typeof localStorage === 'undefined') return empty
355
557
  try {
356
558
  const raw = localStorage.getItem(STORAGE_KEY)
@@ -362,6 +564,7 @@ window.__ModuleLoader__.load({
362
564
  assign: isRecord(parsed.assign) ? parsed.assign : {},
363
565
  order: isRecord(parsed.order) ? parsed.order : {},
364
566
  collapsed: isRecord(parsed.collapsed) ? parsed.collapsed : {},
567
+ children: normalizeChildren(parsed.children),
365
568
  }
366
569
  } catch {
367
570
  return empty
@@ -408,6 +611,7 @@ window.__ModuleLoader__.load({
408
611
  known.add(item.workspaceId)
409
612
  if (realOwner === null && item.sessionIds.includes(sessionId)) realOwner = item.workspaceId
410
613
  }
614
+ for (const id of current.children) known.add(id.id)
411
615
  const assigned = current.assign[sessionId]
412
616
  const previousKey =
413
617
  typeof assigned === 'string' && known.has(assigned)
@@ -478,7 +682,7 @@ window.__ModuleLoader__.load({
478
682
  run: () => {
479
683
  addChildRequest.set({
480
684
  parentId: target.workspaceId,
481
- parentPath: target.path,
685
+ parentPath: null,
482
686
  parentTitle: target.displayTitle,
483
687
  })
484
688
  },
@@ -520,6 +724,18 @@ window.__ModuleLoader__.load({
520
724
  notify(ctx.locale.bind(NS)('moved'), true)
521
725
  },
522
726
  }))
727
+ /* Virtual child groups are this plugin's own records, so they are
728
+ * listed from the store rather than from the workspace list. */
729
+ for (const record of store.get().children) {
730
+ children.push({
731
+ id: 'move:' + record.id,
732
+ label: record.title,
733
+ run: () => {
734
+ assignSessionIn(store, items, sessionId, record.id, undefined)
735
+ notify(ctx.locale.bind(NS)('moved'), true)
736
+ },
737
+ })
738
+ }
523
739
  children.push({
524
740
  id: 'move:ungrouped',
525
741
  label: ctx.locale.bind(NS)('ungrouped'),
@@ -541,11 +757,18 @@ window.__ModuleLoader__.load({
541
757
  'dsh-nested-workspaces: move-to menu',
542
758
  )
543
759
 
760
+ /* Pin/unpin is NOT registered here. ui-workspace already contributes
761
+ * `session.pin` at order 100 (guarding archived rows and the pin/unpin
762
+ * capability), and a second contribution would show the toggle twice in
763
+ * the same menu. The plugin's value-add is the row button below. */
764
+
544
765
  /* --------------------------------------------------------------- dialog */
545
766
 
546
767
  function NewWorkspaceDialog(props) {
547
768
  const request = props.request
548
- const isChild = typeof request.parentPath === 'string'
769
+ /* A request carries `parentId` for a child group; a top-level "add
770
+ * workspace" leaves it null and asks for a real directory instead. */
771
+ const isChild = typeof request.parentId === 'string' && request.parentId !== ''
549
772
  const [value, setValue] = useState('')
550
773
  const [busy, setBusy] = useState(false)
551
774
  const [error, setError] = useState(null)
@@ -568,6 +791,9 @@ window.__ModuleLoader__.load({
568
791
  if (code === 'directory-picker/exists' || message.includes('directory-exists') || message.includes('already exists')) {
569
792
  return t('errors.exists')
570
793
  }
794
+ /* The Host answers these two with a stable code and an English OS
795
+ * string; show the localized wording instead of the raw message. */
796
+ if (code === 'directory-picker/unreadable') return t('errors.unreadable')
571
797
  return t('errors.createFailed', { message })
572
798
  }
573
799
 
@@ -585,10 +811,24 @@ window.__ModuleLoader__.load({
585
811
  setBusy(true)
586
812
  setError(null)
587
813
  try {
588
- let path = trimmed
814
+ /* A child workspace is a record in this plugin's store — no folder,
815
+ * no Host registration. Its sessions run in the nearest real
816
+ * ancestor, which is why nothing needs to be created on disk. */
589
817
  if (isChild) {
590
- path = await uiWorkspace.createDirectory(request.parentPath, trimmed)
591
- } else if (path === '') {
818
+ const id = newChildId()
819
+ store.update(state => ({
820
+ ...state,
821
+ /* Prepend: a freshly added child sits at the top of its
822
+ * siblings, the same place the shipped browser puts one. */
823
+ children: [{ id, parentId: request.parentId, title: trimmed }, ...state.children],
824
+ collapsed: { ...state.collapsed, [request.parentId]: false },
825
+ }))
826
+ notify(t('createdChild'), true)
827
+ props.onClose()
828
+ return
829
+ }
830
+ let path = trimmed
831
+ if (path === '') {
592
832
  /* No typed path: ask the host's directory picker, which is the
593
833
  * same flow the shipped picker uses. */
594
834
  const picked = await uiWorkspace.pickDirectory()
@@ -599,15 +839,7 @@ window.__ModuleLoader__.load({
599
839
  setBusy(true)
600
840
  }
601
841
  await workspaces.create({ path })
602
- if (isChild) {
603
- store.update(state => ({
604
- ...state,
605
- collapsed: { ...state.collapsed, [request.parentId]: false },
606
- }))
607
- notify(t('createdChild'), true)
608
- } else {
609
- notify(t('created'), true)
610
- }
842
+ notify(t('created'), true)
611
843
  props.onClose()
612
844
  } catch (failure) {
613
845
  setError(describe(failure))
@@ -621,7 +853,7 @@ window.__ModuleLoader__.load({
621
853
  {
622
854
  title: isChild ? t('dialog.addChild.title') : t('dialog.addWorkspace.title'),
623
855
  description: isChild
624
- ? t('dialog.addChild.description', { parent: request.parentPath })
856
+ ? t('dialog.addChild.description', { parent: request.parentTitle })
625
857
  : t('dialog.addWorkspace.description'),
626
858
  error,
627
859
  busy,
@@ -925,6 +1157,18 @@ window.__ModuleLoader__.load({
925
1157
  setBusy(true)
926
1158
  setError(null)
927
1159
  try {
1160
+ /* A virtual group has no Host record; its title lives here. */
1161
+ if (workspace.virtual) {
1162
+ store.update(current => ({
1163
+ ...current,
1164
+ children: current.children.map(entry =>
1165
+ entry.id === workspace.workspaceId ? { ...entry, title: trimmed } : entry,
1166
+ ),
1167
+ }))
1168
+ notify(t('renamed'), true)
1169
+ onClose()
1170
+ return
1171
+ }
928
1172
  await workspaces.rename(workspace.workspaceId, trimmed)
929
1173
  notify(t('renamed'), true)
930
1174
  onClose()
@@ -978,7 +1222,62 @@ window.__ModuleLoader__.load({
978
1222
  setBusy(true)
979
1223
  setError(null)
980
1224
  try {
1225
+ if (workspace.virtual) {
1226
+ /* Drop the record and its subtree; sessions filed under it fall
1227
+ * back to their real workspace because their assignment is gone. */
1228
+ const doomed = new Set([workspace.workspaceId])
1229
+ let grew = true
1230
+ while (grew) {
1231
+ grew = false
1232
+ for (const entry of store.get().children) {
1233
+ if (doomed.has(entry.parentId) && !doomed.has(entry.id)) {
1234
+ doomed.add(entry.id)
1235
+ grew = true
1236
+ }
1237
+ }
1238
+ }
1239
+ store.update(current => {
1240
+ const assign = { ...current.assign }
1241
+ for (const [sessionId, groupKey] of Object.entries(assign)) {
1242
+ if (doomed.has(groupKey)) delete assign[sessionId]
1243
+ }
1244
+ return {
1245
+ ...current,
1246
+ children: current.children.filter(entry => !doomed.has(entry.id)),
1247
+ assign,
1248
+ }
1249
+ })
1250
+ notify(t('deleted'), true)
1251
+ onClose()
1252
+ return
1253
+ }
981
1254
  await workspaces.delete(workspace.workspaceId)
1255
+ /* Its child groups can no longer be reached through the tree, so
1256
+ * drop the records instead of leaving them orphaned in storage. */
1257
+ const orphans = new Set([workspace.workspaceId])
1258
+ let spread = true
1259
+ while (spread) {
1260
+ spread = false
1261
+ for (const entry of store.get().children) {
1262
+ if (orphans.has(entry.parentId) && !orphans.has(entry.id)) {
1263
+ orphans.add(entry.id)
1264
+ spread = true
1265
+ }
1266
+ }
1267
+ }
1268
+ if (orphans.size > 1) {
1269
+ store.update(current => {
1270
+ const assign = { ...current.assign }
1271
+ for (const [sessionId, groupKey] of Object.entries(assign)) {
1272
+ if (orphans.has(groupKey)) delete assign[sessionId]
1273
+ }
1274
+ return {
1275
+ ...current,
1276
+ children: current.children.filter(entry => !orphans.has(entry.id)),
1277
+ assign,
1278
+ }
1279
+ })
1280
+ }
982
1281
  notify(t('deleted'), true)
983
1282
  onClose()
984
1283
  } catch (failure) {
@@ -990,7 +1289,9 @@ window.__ModuleLoader__.load({
990
1289
 
991
1290
  return h(DialogShell, {
992
1291
  title: t('dialog.delete.title'),
993
- description: t('dialog.delete.description', { name: workspace.title }),
1292
+ description: workspace.virtual === true
1293
+ ? t('dialog.deleteGroup.description', { name: workspace.title })
1294
+ : t('dialog.delete.description', { name: workspace.title }),
994
1295
  error,
995
1296
  busy,
996
1297
  danger: true,
@@ -1012,18 +1313,71 @@ window.__ModuleLoader__.load({
1012
1313
  */
1013
1314
  function SessionRow(props) {
1014
1315
  const { session, groupKey, index, bucket, env } = props
1015
- const { view, statuses, t, uiWorkspace, useSessionAccess, openMenu, assignSession, dragIdRef, draggingId, dropTarget, setDropTarget, setDraggingId } = env
1316
+ const { view, statuses, t, uiWorkspace, list, useSessionAccess, openMenu, assignSession, dragIdRef, draggingId, dropTarget, setDropTarget, setDraggingId, now } = env
1016
1317
  const isArchived = view.archived.has(session.id)
1318
+ const isPinned = view.pinned.has(session.id) && !isArchived
1017
1319
  const label = session.blank ? (session.id === view.currentId ? t('session.new') : t('session.untitled')) : sessionTitle(session)
1018
1320
  const title = label === '' ? t('session.untitled') : label
1019
1321
  const status = statuses.get(session.id)
1020
1322
  const running = status !== undefined && status.running === true
1323
+ /* Shipped precedence (ui-workspace Rows.tsx sessionStatuses): a pending
1324
+ * interaction wins, then running, then running subagents, then an unread
1325
+ * completion, and otherwise the row is idle and draws no glyph. */
1326
+ const pendingKind = status === undefined ? undefined : status.pendingInteraction === undefined ? undefined : status.pendingInteraction.kind
1327
+ const runningChildren = runningSubagentCount(list, session.id, statuses)
1328
+ const statusState =
1329
+ session.blank || isArchived
1330
+ ? 'idle'
1331
+ : pendingKind !== undefined && pendingKind !== null
1332
+ ? 'warning'
1333
+ : running
1334
+ ? 'ongoing'
1335
+ : runningChildren > 0
1336
+ ? 'ongoing'
1337
+ : status !== undefined && status.completionUnread === true
1338
+ ? 'done'
1339
+ : 'idle'
1340
+ const statusLabel =
1341
+ statusState === 'idle'
1342
+ ? null
1343
+ : statusState === 'warning'
1344
+ ? t(pendingKind === 'approval' ? 'status.waitingApproval' : pendingKind === 'plan-review' ? 'status.planReview' : 'status.waitingAnswer')
1345
+ : statusState === 'ongoing'
1346
+ ? running
1347
+ ? t('status.running')
1348
+ : t('status.subagentsRunning', { n: runningChildren })
1349
+ : t('status.completed')
1021
1350
  const selected = session.id === view.currentId
1022
1351
  const canUnarchive = useSessionAccess(session.id, 'workspace/unarchiveSession')
1023
1352
  const canMove = useSessionAccess(session.id, 'workspace/insertSessionBefore')
1353
+ const canPin = useSessionAccess(session.id, isPinned ? 'workspace/unpinSession' : 'workspace/pinSession')
1024
1354
  const canDrag = !session.blank && !isArchived && canMove
1025
1355
  const rowDropPosition = dropTarget !== null && dropTarget.sessionId === session.id ? dropTarget.position : null
1026
1356
  const actions = []
1357
+ const menuOpen = env.menuOpenSessionId === session.id
1358
+ if (!session.blank && !isArchived && canPin) {
1359
+ actions.push(
1360
+ h(
1361
+ 'button',
1362
+ {
1363
+ type: 'button',
1364
+ key: 'pin',
1365
+ className: cls('dnw-iconButton', isPinned && 'dnw-iconButtonOn'),
1366
+ title: t(isPinned ? 'actions.unpin' : 'actions.pin'),
1367
+ 'aria-label': t(isPinned ? 'actions.unpin' : 'actions.pin') + ' ' + title,
1368
+ 'aria-pressed': isPinned,
1369
+ onClick: event => {
1370
+ event.stopPropagation()
1371
+ const task = isPinned ? uiWorkspace.unpinSession(session.id) : uiWorkspace.pinSession(session.id)
1372
+ if (task !== null && typeof task === 'object' && typeof task.catch === 'function') {
1373
+ task.catch(() => notify(t('errors.pinFailed'), false))
1374
+ }
1375
+ },
1376
+ },
1377
+ h(isPinned ? IconPin : IconPinOutline, null),
1378
+ ),
1379
+ )
1380
+ }
1027
1381
  if (!session.blank && !isArchived) {
1028
1382
  actions.push(
1029
1383
  openMenu(
@@ -1135,19 +1489,54 @@ window.__ModuleLoader__.load({
1135
1489
  },
1136
1490
  onClick: activate,
1137
1491
  },
1492
+ /* Leading cell, matching the shipped browser: an idle session shows
1493
+ * nothing at all, a running one shows the rotating spinner, and a
1494
+ * pending interaction or unread completion shows a state dot. */
1138
1495
  h(
1139
1496
  'span',
1140
1497
  { className: 'dnw-slot' },
1141
- running ? h('span', { className: 'dnw-dot' }) : h('span', { className: cls('dnw-dot', 'dnw-dotIdle') }),
1498
+ statusState === 'ongoing' ? h(StatusSpinner, null) : null,
1499
+ statusState !== 'ongoing' && statusState !== 'idle'
1500
+ ? h('span', { className: 'dnw-stateDot', 'data-state': statusState, style: { width: '10px', height: '10px' }, 'aria-hidden': 'true' })
1501
+ : null,
1502
+ statusLabel === null ? null : h('span', { className: 'dnw-visuallyHidden' }, statusLabel),
1142
1503
  ),
1143
1504
  h('span', { className: cls('dnw-title', (session.blank || isArchived) && 'dnw-titleMuted') }, title),
1144
- actions.length === 0 ? null : h('span', { className: 'dnw-actions' }, ...actions),
1505
+ /* Resting cell: the last-used time and, when pinned, the pin glyph —
1506
+ * the shipped browser swaps this cell for the action buttons on
1507
+ * hover, and so does this one. */
1508
+ session.blank
1509
+ ? null
1510
+ : h(
1511
+ 'span',
1512
+ { className: 'dnw-resting' },
1513
+ h(
1514
+ 'span',
1515
+ { className: 'dnw-time', title: hoverTimeLabel(session.updatedAt, now, t) },
1516
+ timeLabel(session.updatedAt, now, t),
1517
+ ),
1518
+ isPinned
1519
+ ? h(
1520
+ 'span',
1521
+ {
1522
+ className: 'dnw-pinIndicator',
1523
+ role: 'img',
1524
+ 'aria-label': t('row.pinned'),
1525
+ title: t('row.pinned'),
1526
+ },
1527
+ h(IconPin, null),
1528
+ )
1529
+ : null,
1530
+ ),
1531
+ actions.length === 0
1532
+ ? null
1533
+ : h('span', { className: cls('dnw-actions', menuOpen && 'dnw-actionsOpen') }, ...actions),
1145
1534
  )
1146
1535
  }
1147
1536
 
1148
1537
  function WorkspaceGroup(props) {
1149
1538
  const { workspace, depth, env } = props
1150
- const { view, state, t, uiWorkspace, useWorkspaceAccess, openMenu, openWorkspaceMenu, assignSession, setExpanded, setRenaming, menu, dragIdRef, draggingId, dropTarget, setDropTarget, setDraggingId } = env
1539
+ const { view, state, t, uiWorkspace, useWorkspaceAccess, openMenu, openWorkspaceMenu, assignSession, startSessionInGroup, setExpanded, setRenaming, menu, dragIdRef, draggingId, dropTarget, setDropTarget, setDraggingId, workspaceDrag, draggingWorkspaceId, beginWorkspaceDrag, endWorkspaceDrag, hoverWorkspaceDrag, workspaceClickBlockRef } = env
1151
1540
  const workspaceId = workspace.workspaceId
1152
1541
  const collapsed = state.collapsed[workspaceId] === true
1153
1542
  const members = view.members.get(workspaceId) || []
@@ -1159,19 +1548,52 @@ window.__ModuleLoader__.load({
1159
1548
  const isDropTarget =
1160
1549
  dropTarget !== null && dropTarget.workspaceId === workspaceId && dropTarget.sessionId === undefined
1161
1550
  const indent = { '--dnw-indent': depth * INDENT_PX + 'px' }
1162
- const canCreateSession = useWorkspaceAccess(workspaceId, 'session/create')
1551
+ /* A virtual group has no directory of its own: access and new sessions
1552
+ * belong to the nearest real ancestor, which is where it runs. */
1553
+ const realId = view.realOf.get(workspaceId)
1554
+ const accessId = realId === undefined ? workspaceId : realId
1555
+ const canCreateSession = useWorkspaceAccess(accessId, 'session/create')
1163
1556
  const collapsible = children.length > 0 || hasSessions
1557
+ /* A workspace drag is legal only between rows that share a parent, so a
1558
+ * child can be reordered among its siblings but never leave its root. */
1559
+ const parentId = view.parentOf.get(workspaceId)
1560
+ const workspaceSibling =
1561
+ workspaceDrag !== null &&
1562
+ workspaceDrag.workspaceId !== workspaceId &&
1563
+ view.parentOf.get(workspaceDrag.workspaceId) === parentId
1564
+ const workspaceDropHalf =
1565
+ workspaceSibling && workspaceDrag.over !== null && workspaceDrag.over.id === workspaceId
1566
+ ? workspaceDrag.over.half
1567
+ : null
1164
1568
  const row = h(
1165
1569
  'div',
1166
1570
  {
1167
1571
  key: 'w:' + workspaceId,
1168
- className: cls('dnw-row', 'dnw-workspaceRow', isDropTarget && 'dnw-dropOn'),
1572
+ className: cls(
1573
+ 'dnw-row',
1574
+ 'dnw-workspaceRow',
1575
+ isDropTarget && 'dnw-dropOn',
1576
+ workspaceDropHalf === 'before' && 'dnw-dropBefore',
1577
+ workspaceDropHalf === 'after' && 'dnw-dropAfter',
1578
+ draggingWorkspaceId === workspaceId && 'dnw-rowDragging',
1579
+ ),
1169
1580
  role: 'treeitem',
1170
1581
  tabIndex: 0,
1582
+ draggable: true,
1171
1583
  'aria-expanded': !collapsed,
1172
- 'aria-label': workspace.title + ' — ' + workspace.path,
1584
+ 'aria-label': workspace.virtual
1585
+ ? workspace.title + ' — ' + t('virtual.hint') + ' ' + workspace.path
1586
+ : workspace.title + ' — ' + workspace.path,
1173
1587
  style: indent,
1174
- onClick: () => setExpanded(workspaceId, collapsed),
1588
+ onClick: () => {
1589
+ /* A drag ends with a click; expanding on it would undo the drop. */
1590
+ if (draggingWorkspaceId !== null) return
1591
+ if (workspaceClickBlockRef.current) {
1592
+ workspaceClickBlockRef.current = false
1593
+ return
1594
+ }
1595
+ setExpanded(workspaceId, collapsed)
1596
+ },
1175
1597
  onKeyDown: event => {
1176
1598
  if (event.target !== event.currentTarget) return
1177
1599
  if (event.key !== 'Enter' && event.key !== ' ') return
@@ -1179,7 +1601,50 @@ window.__ModuleLoader__.load({
1179
1601
  setExpanded(workspaceId, collapsed)
1180
1602
  },
1181
1603
  onContextMenu: event => openWorkspaceMenu(event, workspace),
1604
+ onDragStart: event => {
1605
+ /* `draggable` lives on the row, so the target is normally the row
1606
+ * itself; a drag started on the action buttons must not reorder. */
1607
+ const fromActions =
1608
+ event.target !== event.currentTarget &&
1609
+ typeof Element !== 'undefined' &&
1610
+ event.target instanceof Element &&
1611
+ event.target.closest('.dnw-actions') !== null
1612
+ if (fromActions) {
1613
+ event.preventDefault()
1614
+ return
1615
+ }
1616
+ event.stopPropagation()
1617
+ try {
1618
+ event.dataTransfer.effectAllowed = 'move'
1619
+ event.dataTransfer.setData('text/plain', workspaceId)
1620
+ } catch {
1621
+ /* ignore */
1622
+ }
1623
+ beginWorkspaceDrag(workspaceId)
1624
+ },
1625
+ onDragEnd: () => {
1626
+ endWorkspaceDrag()
1627
+ },
1182
1628
  onDragOver: event => {
1629
+ if (workspaceDrag !== null) {
1630
+ /* Workspace reorder: sibling rows only, chosen by row midpoint. */
1631
+ if (!workspaceSibling) {
1632
+ /* Keep swallowing the event so the session path below cannot
1633
+ * mistake a workspace drag for a session drop. */
1634
+ return
1635
+ }
1636
+ event.preventDefault()
1637
+ event.stopPropagation()
1638
+ try {
1639
+ event.dataTransfer.dropEffect = 'move'
1640
+ } catch {
1641
+ /* ignore */
1642
+ }
1643
+ const rect = event.currentTarget.getBoundingClientRect()
1644
+ const half = event.clientY < rect.top + rect.height / 2 ? 'before' : 'after'
1645
+ if (workspaceDropHalf !== half) hoverWorkspaceDrag(workspaceId, half)
1646
+ return
1647
+ }
1183
1648
  if (dragIdRef.current === null) return
1184
1649
  event.preventDefault()
1185
1650
  event.stopPropagation()
@@ -1197,9 +1662,10 @@ window.__ModuleLoader__.load({
1197
1662
  if (isDropTarget) setDropTarget(null)
1198
1663
  },
1199
1664
  onDrop: event => {
1200
- const id = dragIdRef.current || event.dataTransfer.getData('text/plain')
1201
1665
  event.preventDefault()
1202
1666
  event.stopPropagation()
1667
+ if (workspaceDrag !== null) return
1668
+ const id = dragIdRef.current || event.dataTransfer.getData('text/plain')
1203
1669
  setDropTarget(null)
1204
1670
  setDraggingId(null)
1205
1671
  dragIdRef.current = null
@@ -1265,7 +1731,7 @@ window.__ModuleLoader__.load({
1265
1731
  'aria-label': t('actions.newSession') + ' ' + workspace.title,
1266
1732
  onClick: event => {
1267
1733
  event.stopPropagation()
1268
- uiWorkspace.startSession(workspaceId)
1734
+ startSessionInGroup(workspaceId, accessId)
1269
1735
  },
1270
1736
  },
1271
1737
  h(IconPlus, null),
@@ -1275,10 +1741,14 @@ window.__ModuleLoader__.load({
1275
1741
  )
1276
1742
 
1277
1743
  const body = []
1278
- if (visible && hasSessions) body.push(h('div', { key: 'g:' + workspaceId, role: 'group' }, members.map((session, index) => h(SessionRow, { key: 's:' + session.id, session, groupKey: workspaceId, index, bucket: members, env }))))
1744
+ /* Shipped section order: the workspace header, then its child
1745
+ * workspaces, then the workspace's own session rows. A newly created
1746
+ * child therefore sits directly under its parent instead of at the
1747
+ * bottom of the section. */
1279
1748
  if (visible) {
1280
1749
  for (const child of children) body.push(h(WorkspaceGroup, { key: 'grp:' + child.workspaceId, workspace: child, depth: depth + 1, env }))
1281
1750
  }
1751
+ if (visible && hasSessions) body.push(h('div', { key: 'g:' + workspaceId, role: 'group', style: indent }, members.map((session, index) => h(SessionRow, { key: 's:' + session.id, session, groupKey: workspaceId, index, bucket: members, env }))))
1282
1752
  return h(Fragment, { key: 'grp:' + workspaceId }, row, ...body)
1283
1753
  }
1284
1754
 
@@ -1290,6 +1760,18 @@ window.__ModuleLoader__.load({
1290
1760
  const useSessionAccess = typeof props.useSessionAccess === 'function' ? props.useSessionAccess : () => true
1291
1761
  const state = useSyncExternalStore(store.subscribe, store.get, store.get)
1292
1762
  const request = useSyncExternalStore(addChildRequest.subscribe, addChildRequest.get, addChildRequest.get)
1763
+ /* The shared context menu portals out of the row, so neither :hover nor
1764
+ * :focus-within holds while a row's menu is open. Track the menu's
1765
+ * active target instead, exactly like the shipped `.sessionRow.menuOpen`. */
1766
+ const menuTarget = useSyncExternalStore(
1767
+ contextMenus.active.subscribe,
1768
+ contextMenus.active.getSnapshot,
1769
+ contextMenus.active.getSnapshot,
1770
+ )
1771
+ const menuOpenSessionId =
1772
+ menuTarget !== null && menuTarget !== undefined && menuTarget.kind === 'session'
1773
+ ? menuTarget.value.sessionId
1774
+ : null
1293
1775
  const list = useSessions(snapshot => snapshot)
1294
1776
  const workspaceSnapshot = useWorkspaces(snapshot => snapshot)
1295
1777
  const statuses = useSessionStatus(snapshot => snapshot)
@@ -1303,6 +1785,11 @@ window.__ModuleLoader__.load({
1303
1785
  const [query, setQuery] = useState('')
1304
1786
  const [draggingId, setDraggingId] = useState(null)
1305
1787
  const [dropTarget, setDropTarget] = useState(null)
1788
+ const [workspaceDrag, setWorkspaceDrag] = useState(null)
1789
+ const workspaceDragRef = useRef(null)
1790
+ /* Some browsers still deliver a click after a drag ends; that click must
1791
+ * not also toggle the group open/closed. */
1792
+ const workspaceClickBlockRef = useRef(false)
1306
1793
  const [menu, setMenu] = useState(null)
1307
1794
  const [renaming, setRenaming] = useState(null)
1308
1795
  const [deleting, setDeleting] = useState(null)
@@ -1324,41 +1811,109 @@ window.__ModuleLoader__.load({
1324
1811
  const byId = new Map(items.map(item => [item.workspaceId, item]))
1325
1812
  const byPath = new Map(items.map(item => [item.path, item.workspaceId]))
1326
1813
  const paths = items.map(item => item.path)
1327
- const parentOf = new Map()
1814
+
1815
+ /* Real workspaces nest by path ancestry. */
1816
+ const realParentOf = new Map()
1328
1817
  for (const item of items) {
1329
1818
  const parentPath = owningParentPath(item.path, paths)
1330
1819
  if (parentPath === null) continue
1331
1820
  const parentId = byPath.get(parentPath)
1332
- if (parentId !== undefined) parentOf.set(item.workspaceId, parentId)
1821
+ if (parentId !== undefined) realParentOf.set(item.workspaceId, parentId)
1333
1822
  }
1823
+
1824
+ const realOf = new Map()
1825
+ const realIdOf = parentId => {
1826
+ let cursor = parentId
1827
+ for (let guard = 0; cursor !== undefined && guard < 64; guard += 1) {
1828
+ const real = realOf.get(cursor)
1829
+ if (real !== undefined) return real
1830
+ cursor = parentOf.get(cursor)
1831
+ }
1832
+ return undefined
1833
+ }
1834
+
1835
+ const parentOf = new Map(realParentOf)
1836
+ const nodesById = new Map()
1837
+ for (const item of items) {
1838
+ nodesById.set(item.workspaceId, {
1839
+ workspaceId: item.workspaceId,
1840
+ title: item.title,
1841
+ path: item.path,
1842
+ virtual: false,
1843
+ parentId: realParentOf.get(item.workspaceId),
1844
+ })
1845
+ realOf.set(item.workspaceId, item.workspaceId)
1846
+ }
1847
+
1848
+ /* Virtual children: records only. Their `path` is the nearest real
1849
+ * ancestor's directory, because that is where a session started
1850
+ * from them actually runs. Records are stored flat, so resolve them
1851
+ * to a fixpoint: a record whose parent is another record only lands
1852
+ * once that parent is known. */
1853
+ let pending = state.children.slice()
1854
+ for (let pass = 0; pass < 64 && pending.length > 0; pass += 1) {
1855
+ const deferred = []
1856
+ let placed = 0
1857
+ for (const record of pending) {
1858
+ const parent = nodesById.get(record.parentId)
1859
+ if (parent === undefined) {
1860
+ deferred.push(record)
1861
+ continue
1862
+ }
1863
+ placed += 1
1864
+ parentOf.set(record.id, record.parentId)
1865
+ const realId = parent.virtual ? realIdOf(record.parentId) : parent.workspaceId
1866
+ nodesById.set(record.id, {
1867
+ workspaceId: record.id,
1868
+ title: record.title,
1869
+ path: realId === undefined ? parent.path : (byId.get(realId) || parent).path,
1870
+ virtual: true,
1871
+ parentId: record.parentId,
1872
+ })
1873
+ if (realId !== undefined) realOf.set(record.id, realId)
1874
+ }
1875
+ pending = deferred
1876
+ if (placed === 0) break
1877
+ }
1878
+
1334
1879
  const childrenOf = new Map()
1335
1880
  const roots = []
1336
1881
  for (const item of items) {
1337
- const parentId = parentOf.get(item.workspaceId)
1882
+ const parentId = realParentOf.get(item.workspaceId)
1338
1883
  if (parentId === undefined) {
1339
- roots.push(item)
1884
+ roots.push(nodesById.get(item.workspaceId))
1340
1885
  continue
1341
1886
  }
1342
1887
  const bucket = childrenOf.get(parentId)
1343
- if (bucket === undefined) childrenOf.set(parentId, [item])
1344
- else bucket.push(item)
1888
+ if (bucket === undefined) childrenOf.set(parentId, [nodesById.get(item.workspaceId)])
1889
+ else bucket.push(nodesById.get(item.workspaceId))
1890
+ }
1891
+ for (const record of state.children) {
1892
+ const node = nodesById.get(record.id)
1893
+ if (node === undefined) continue
1894
+ const bucket = childrenOf.get(record.parentId)
1895
+ if (bucket === undefined) childrenOf.set(record.parentId, [node])
1896
+ else bucket.push(node)
1345
1897
  }
1346
1898
 
1347
1899
  const archived = new Set(workspaceSnapshot.archivedSessionIds)
1900
+ const pinned = new Set(workspaceSnapshot.pinnedSessionIds)
1348
1901
  const realOwner = new Map()
1349
1902
  for (const item of items) for (const id of item.sessionIds) realOwner.set(id, item.workspaceId)
1350
1903
  const currentId = list.ids.find(id => ((list.byId[id] && list.byId[id].retainedBy.mainView) || 0) > 0) || null
1351
1904
 
1352
1905
  const ownerOf = id => {
1353
1906
  const assigned = state.assign[id]
1354
- if (typeof assigned === 'string' && byId.has(assigned)) return assigned
1907
+ if (typeof assigned === 'string' && nodesById.has(assigned)) return assigned
1355
1908
  const real = realOwner.get(id)
1356
- return real === undefined ? UNGROUPED : real
1909
+ if (real === undefined) return UNGROUPED
1910
+ /* A session whose real workspace is not visible belongs to no group */
1911
+ return nodesById.has(real) ? real : UNGROUPED
1357
1912
  }
1358
1913
 
1359
1914
  const members = new Map()
1360
1915
  members.set(UNGROUPED, [])
1361
- for (const item of items) members.set(item.workspaceId, [])
1916
+ for (const nodeId of nodesById.keys()) members.set(nodeId, [])
1362
1917
 
1363
1918
  const needle = query.trim().toLowerCase()
1364
1919
  const matches = text => needle === '' || String(text || '').toLowerCase().includes(needle)
@@ -1384,27 +1939,38 @@ window.__ModuleLoader__.load({
1384
1939
  const saved = state.order[key]
1385
1940
  if (!Array.isArray(saved) || saved.length === 0) {
1386
1941
  bucket.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0))
1387
- continue
1942
+ } else {
1943
+ const rank = new Map()
1944
+ for (let index = 0; index < saved.length; index += 1) rank.set(saved[index], index)
1945
+ const known = []
1946
+ const rest = []
1947
+ for (const session of bucket) {
1948
+ if (rank.has(session.id)) known.push(session)
1949
+ else rest.push(session)
1950
+ }
1951
+ known.sort((a, b) => rank.get(a.id) - rank.get(b.id))
1952
+ rest.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0))
1953
+ bucket.splice(0, bucket.length, ...known, ...rest)
1388
1954
  }
1389
- const rank = new Map()
1390
- for (let index = 0; index < saved.length; index += 1) rank.set(saved[index], index)
1391
- const known = []
1392
- const rest = []
1955
+ /* Shipped section order: the blank row, then pinned rows, then the
1956
+ * rest. Sorting after the manual order keeps both intact. */
1957
+ const leading = []
1958
+ const pinnedRows = []
1959
+ const trailing = []
1393
1960
  for (const session of bucket) {
1394
- if (rank.has(session.id)) known.push(session)
1395
- else rest.push(session)
1961
+ if (session.blank) leading.push(session)
1962
+ else if (pinned.has(session.id) && !archived.has(session.id)) pinnedRows.push(session)
1963
+ else trailing.push(session)
1396
1964
  }
1397
- known.sort((a, b) => rank.get(a.id) - rank.get(b.id))
1398
- rest.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0))
1399
- members.set(key, known.concat(rest))
1965
+ bucket.splice(0, bucket.length, ...leading, ...pinnedRows, ...trailing)
1400
1966
  }
1401
1967
 
1402
1968
  const filtering = needle !== ''
1403
1969
  let visibleCount = 0
1404
1970
  for (const bucket of members.values()) visibleCount += bucket.length
1405
1971
 
1406
- return { byId, parentOf, childrenOf, roots, members, currentId, ownerOf, realOwner, archived, filtering, visibleCount }
1407
- }, [items, list, state.order, state.assign, workspaceSnapshot.archivedSessionIds, query, showArchived])
1972
+ return { byId, nodesById, parentOf, childrenOf, roots, members, currentId, ownerOf, realOwner, realOf, archived, pinned, filtering, visibleCount }
1973
+ }, [items, list, state.order, state.assign, state.children, workspaceSnapshot.archivedSessionIds, workspaceSnapshot.pinnedSessionIds, query, showArchived])
1408
1974
 
1409
1975
  const setExpanded = useCallback((workspaceId, expanded) => {
1410
1976
  store.update(current => ({
@@ -1413,9 +1979,84 @@ window.__ModuleLoader__.load({
1413
1979
  }))
1414
1980
  }, [])
1415
1981
 
1982
+ /* Workspace reorder. Mirrors the shipped `commitWorkspaceDrag`: the drop
1983
+ * anchor is the next row after the target, and a move that would leave
1984
+ * the order unchanged is dropped instead of being written.
1985
+ * A virtual group is ordered in this plugin's own store, a real
1986
+ * workspace in the Host registry, so the two are never mixed. */
1987
+ const commitWorkspaceDrag = useCallback(
1988
+ (drag, over) => {
1989
+ if (drag === null || over === null) return
1990
+ const dragged = view.nodesById.get(drag.workspaceId)
1991
+ const target = view.nodesById.get(over.id)
1992
+ if (dragged === undefined || target === undefined) return
1993
+ const owner = view.parentOf.get(drag.workspaceId)
1994
+ if (view.parentOf.get(over.id) !== owner) return
1995
+ /* Mixing the plugin order with the Host order would need a position
1996
+ * neither store can express, so a cross-kind drop is refused. */
1997
+ if (dragged.virtual !== target.virtual) return
1998
+ const siblings =
1999
+ owner === undefined ? view.roots.slice() : (view.childrenOf.get(owner) || []).slice()
2000
+ const rowIndex = siblings.findIndex(node => node.workspaceId === over.id)
2001
+ if (rowIndex === -1) return
2002
+ const anchor = over.half === 'before' ? over.id : (siblings[rowIndex + 1] || {}).workspaceId
2003
+ if (anchor === drag.workspaceId) return
2004
+ const sourceIndex = siblings.findIndex(node => node.workspaceId === drag.workspaceId)
2005
+ const anchorIndex =
2006
+ anchor === undefined ? siblings.length : siblings.findIndex(node => node.workspaceId === anchor)
2007
+ if (sourceIndex !== -1 && (anchorIndex === sourceIndex || anchorIndex === sourceIndex + 1)) return
2008
+ if (dragged.virtual) {
2009
+ store.update(current => ({ ...current, children: moveChildRecord(current.children, drag.workspaceId, anchor) }))
2010
+ return
2011
+ }
2012
+ workspaces.insertBefore(drag.workspaceId, anchor).catch(() => {
2013
+ notify(t('errors.reorderFailed'), false)
2014
+ })
2015
+ },
2016
+ [items, view, workspaces, notify, t],
2017
+ )
2018
+
2019
+ const beginWorkspaceDrag = useCallback(workspaceId => {
2020
+ const next = { workspaceId, over: null }
2021
+ workspaceDragRef.current = next
2022
+ workspaceClickBlockRef.current = true
2023
+ setWorkspaceDrag(next)
2024
+ }, [])
2025
+
2026
+ const hoverWorkspaceDrag = useCallback((id, half) => {
2027
+ const current = workspaceDragRef.current
2028
+ if (current === null) return
2029
+ if (current.over !== null && current.over.id === id && current.over.half === half) return
2030
+ const next = { ...current, over: { id, half } }
2031
+ workspaceDragRef.current = next
2032
+ setWorkspaceDrag(next)
2033
+ }, [])
2034
+
2035
+ const endWorkspaceDrag = useCallback(() => {
2036
+ const current = workspaceDragRef.current
2037
+ workspaceDragRef.current = null
2038
+ setWorkspaceDrag(null)
2039
+ if (current !== null && current.over !== null) commitWorkspaceDrag(current, current.over)
2040
+ /* The click that follows a drop arrives after `dragend`; keep the
2041
+ * block for one task so it is swallowed, then re-arm the row. */
2042
+ window.setTimeout(() => {
2043
+ workspaceClickBlockRef.current = false
2044
+ }, 0)
2045
+ }, [commitWorkspaceDrag])
2046
+
1416
2047
  const assignSession = useCallback(
1417
2048
  (sessionId, groupKey, beforeSessionId) => {
1418
2049
  if (typeof sessionId !== 'string' || sessionId === '') return
2050
+ /* The display bucket is re-partitioned blank → pinned → rest after a
2051
+ * drop index is derived, so a drop that crosses the pinned boundary
2052
+ * would land somewhere other than the marker promised. Refuse it. */
2053
+ if (
2054
+ beforeSessionId !== undefined &&
2055
+ beforeSessionId !== null &&
2056
+ view.pinned.has(sessionId) !== view.pinned.has(beforeSessionId)
2057
+ ) {
2058
+ return
2059
+ }
1419
2060
  store.update(current => {
1420
2061
  const realOwner = view.realOwner.get(sessionId)
1421
2062
  const previousKey = view.ownerOf(sessionId)
@@ -1438,6 +2079,35 @@ window.__ModuleLoader__.load({
1438
2079
  [view],
1439
2080
  )
1440
2081
 
2082
+ /**
2083
+ * New session for a row. A real workspace opens its own blank. A
2084
+ * virtual group has no directory, so the session is created in the
2085
+ * nearest real ancestor and then filed into the group — the same
2086
+ * display assignment a drag writes, only done right after creation.
2087
+ */
2088
+ const startSessionInGroup = useCallback(
2089
+ (groupId, realId) => {
2090
+ const node = view.nodesById.get(groupId)
2091
+ if (node === undefined || node.virtual !== true) {
2092
+ uiWorkspace.startSession(realId === undefined ? groupId : realId)
2093
+ return
2094
+ }
2095
+ if (realId === undefined) {
2096
+ uiWorkspace.startSession()
2097
+ return
2098
+ }
2099
+ void uiWorkspace
2100
+ .openWorkspace(realId, sessionId => {
2101
+ assignSession(sessionId, groupId, undefined)
2102
+ })
2103
+ .catch(failure => {
2104
+ const message = failure && failure.message ? String(failure.message) : String(failure)
2105
+ notify(t('errors.createFailed', { message }), false)
2106
+ })
2107
+ },
2108
+ [view, uiWorkspace, assignSession, notify, t],
2109
+ )
2110
+
1441
2111
  const openMenu = (target, label) => {
1442
2112
  if (typeof renderFactorySlot !== 'function') return null
1443
2113
  const node = renderFactorySlot('contextMenu.button', { target, label, className: 'dnw-iconButton' })
@@ -1458,11 +2128,12 @@ window.__ModuleLoader__.load({
1458
2128
  })
1459
2129
  }
1460
2130
 
1461
- const menuWorkspace =
1462
- menu === null ? null : items.find(item => item.workspaceId === menu.workspaceId) || null
2131
+ const menuWorkspace = menu === null ? null : view.nodesById.get(menu.workspaceId) || null
1463
2132
 
1464
2133
  const menuItems = useMemo(() => {
1465
2134
  if (menuWorkspace === null) return []
2135
+ const groupId = menuWorkspace.workspaceId
2136
+ const realId = view.realOf.get(groupId)
1466
2137
  return [
1467
2138
  {
1468
2139
  id: 'addChild',
@@ -1470,8 +2141,8 @@ window.__ModuleLoader__.load({
1470
2141
  icon: IconFolderPlus,
1471
2142
  onSelect: () =>
1472
2143
  addChildRequest.set({
1473
- parentId: menuWorkspace.workspaceId,
1474
- parentPath: menuWorkspace.path,
2144
+ parentId: groupId,
2145
+ parentPath: null,
1475
2146
  parentTitle: menuWorkspace.title,
1476
2147
  }),
1477
2148
  },
@@ -1479,7 +2150,7 @@ window.__ModuleLoader__.load({
1479
2150
  id: 'newSession',
1480
2151
  label: t('actions.newSession'),
1481
2152
  icon: IconPlus,
1482
- onSelect: () => uiWorkspace.startSession(menuWorkspace.workspaceId),
2153
+ onSelect: () => startSessionInGroup(groupId, realId),
1483
2154
  },
1484
2155
  {
1485
2156
  id: 'rename',
@@ -1496,7 +2167,7 @@ window.__ModuleLoader__.load({
1496
2167
  onSelect: () => setDeleting(menuWorkspace),
1497
2168
  },
1498
2169
  ]
1499
- }, [menuWorkspace, t, uiWorkspace])
2170
+ }, [menuWorkspace, t, view, startSessionInGroup])
1500
2171
 
1501
2172
  const commitTitle = () => {
1502
2173
  /* Escape sets the cancel flag first; the input then unmounts and its
@@ -1547,10 +2218,13 @@ window.__ModuleLoader__.load({
1547
2218
 
1548
2219
  /* One bag of closures for the row components; rebuilt each render. */
1549
2220
  const env = {
1550
- view, state, statuses, t, uiWorkspace,
2221
+ view, state, statuses, t, uiWorkspace, list,
1551
2222
  useSessionAccess, useWorkspaceAccess,
1552
- openMenu, openWorkspaceMenu, assignSession, setExpanded, setRenaming,
1553
- menu, draggingId, dropTarget, dragIdRef, setDraggingId, setDropTarget,
2223
+ openMenu, openWorkspaceMenu, assignSession, startSessionInGroup, setExpanded, setRenaming,
2224
+ menu, menuOpenSessionId, draggingId, dropTarget, dragIdRef, setDraggingId, setDropTarget,
2225
+ workspaceDrag, draggingWorkspaceId: workspaceDrag === null ? null : workspaceDrag.workspaceId,
2226
+ beginWorkspaceDrag, hoverWorkspaceDrag, endWorkspaceDrag, workspaceClickBlockRef,
2227
+ now: Date.now(),
1554
2228
  }
1555
2229
 
1556
2230
  const tree = []
@@ -1579,6 +2253,7 @@ window.__ModuleLoader__.load({
1579
2253
  setExpanded(UNGROUPED, ungroupedCollapsed)
1580
2254
  },
1581
2255
  onDragOver: event => {
2256
+ if (workspaceDrag !== null) return
1582
2257
  if (dragIdRef.current === null) return
1583
2258
  event.preventDefault()
1584
2259
  event.stopPropagation()
@@ -1589,9 +2264,12 @@ window.__ModuleLoader__.load({
1589
2264
  if (isUngroupedDrop) setDropTarget(null)
1590
2265
  },
1591
2266
  onDrop: event => {
1592
- const id = dragIdRef.current || event.dataTransfer.getData('text/plain')
1593
2267
  event.preventDefault()
1594
2268
  event.stopPropagation()
2269
+ /* The ungrouped bucket is not a real workspace: it accepts
2270
+ * sessions but must never take part in a workspace reorder. */
2271
+ if (workspaceDrag !== null) return
2272
+ const id = dragIdRef.current || event.dataTransfer.getData('text/plain')
1595
2273
  setDropTarget(null)
1596
2274
  setDraggingId(null)
1597
2275
  dragIdRef.current = null