@cooper-zhuang/dsh-workspace-sort 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
@@ -1,6 +1,6 @@
1
1
  # @cooper-zhuang/dsh-workspace-sort
2
2
 
3
- DSH(DeepSeek Harness)Web 插件:给左侧「工作区」那一层补排序能力——按最近一次人工提问自动排、置顶几个常驻、运行中的排前面,并提供一个只看排序的小面板。
3
+ DSH(DeepSeek Harness)Web 插件:给左侧「工作区」那一层补排序能力——按最近一次人工提问自动排、正在等你输入的排最前、置顶几个常驻、运行中的排前面,并提供一个只看排序的小面板。
4
4
 
5
5
  官方侧栏的「视图选项 → 最近更新」排的是**每个工作区内部的会话**,从不排工作区本身;工作区顺序只由宿主保存的拖拽顺序决定。所以那个选项看起来「没生效」——它本来就不管工作区。
6
6
 
@@ -9,18 +9,20 @@ DSH(DeepSeek Harness)Web 插件:给左侧「工作区」那一层补排序
9
9
  ## 功能
10
10
 
11
11
  - **按最近提问自动排序**:每个工作区取最新一条「你发出的提问」的时间(会话摘要的 `updatedAt`)。打开会话、助手回复、后台任务跑完都不算活动,不会让顺序跳动。
12
+ - **等你输入优先**:工作区里有会话正等你回答(审批、计划审阅、提问三种)就排到未置顶区最前,压过「运行中」。判据是内核的 `ctx.uiSession.pendingInteractions`,与侧栏自己显示等待标记的规则一致;其他 kind 不算。
12
13
  - **容器目录按子树汇总**:`~/Documents/Code/Mubea` 这类只用来分组的目录自己没有会话,按整个子树的最新活动参与排序,否则这个分组会沉到底部。
13
14
  - **置顶**:把几个常驻工作区钉在列表最前,按你钉的顺序排列,不参与活动排序。
14
15
  - **运行中的排前面**:可选。某个工作区里有会话正在跑,就排在未置顶区的前面,长任务不会沉出视野。
15
- - **面板**(插件页里本组合包页面的卡片上点「打开排序面板」;侧栏不放图标):列出全部工作区,显示会话数、运行中会话数、最近活动相对时间;支持按名称筛选、点图钉置顶、开关上面两条规则、点「立即整理」立刻重排一次。
16
- - **手动拖拽优先**:你用鼠标拖过之后,插件停手,直到下一次提问或你点「立即整理」。
16
+ - **面板**(插件页里本组合包页面的卡片上点「打开排序面板」;侧栏不放图标):列出全部工作区,显示会话数、等待输入数、运行中会话数、最近活动相对时间;支持按名称筛选、点图钉置顶、开关上面两条规则、点「立即整理」立刻重排一次。
17
+ - **手动拖拽优先**:你用鼠标拖过之后,插件停手,直到下一次提问、某个会话开始等你输入,或你点「立即整理」。
17
18
  - **无变化不写盘**:算出来的顺序和当前一致时,一个字节都不写。
18
19
 
19
20
  ## 实现要点
20
21
 
21
22
  - 顺序只通过官方 `workspaces.insertBefore` 写入(与拖拽同一个命令),落在 `$DSH_HOME/storages/workspace.json` 的持久顺序里,刷新、换窗口、重启都保留。
22
23
  - 置顶与两个开关存在宿主侧 `$DSH_HOME/workspace-sort/prefs.json`(原子写:tmp 后 rename)。**不用 localStorage**:桌面端 Web 服务绑定的是随机端口(`port: 0`),页面 origin 每次重启都变,localStorage 会跟着丢。
23
- - 宿主半边只有两条回环路由:`GET /dsh-workspace-sort/api/state`(配置 + 位置 + 最后一次重排决策)和 `POST /dsh-workspace-sort/api/prefs`(保存置顶与开关)。没有文件系统操作、没有子进程、没有会话操作。
24
+ - 三个配置键是宿主 `Config` 上的 `.volatile()` 字段:宿主拿到活的 `{ get() }` 引用,浏览器半边拿到同一份值的 `SyncedConfig` 引用。改配置即时生效,不重启、不重载页面;启动时也不再 GET 配置,宿主路由不可达只影响置顶的持久化,不会把排序整个关掉。
25
+ - 宿主半边只有两条回环路由:`GET /dsh-workspace-sort/api/state`(置顶 + 最后一次重排决策,`config` 段仅用于 curl 诊断)和 `POST /dsh-workspace-sort/api/prefs`(保存置顶与开关)。没有文件系统操作、没有子进程、没有会话操作。
24
26
  - 面板与入口都用官方 Slot:`plugins.bundle.config`(插件页本组合包的卡片)和 `shell.overlay`(面板),不查 DOM 类名;侧栏不占任何位置。
25
27
 
26
28
  ## 安装
@@ -31,17 +33,23 @@ dsh plugin --profile desktop add /path/to/packages/dsh-workspace-sort
31
33
 
32
34
  生效条件:
33
35
 
34
- - 第一次安装 / 改了 `index.js`(宿主半边):重启一次宿主。
35
- - 只改了浏览器半边:菜单「DSH Desktop Beta → 重新加载界面」重载页面即可。
36
+ - 第一次安装 / 改了 `index.js` 或 `lib/client.js`(插件代码):重启一次宿主。
37
+ - 改配置(插件页的配置卡片,或 `cordis.patch.yml` 的 `config` 块):即时生效,不重启、不重载页面。
38
+ - 只重载界面:菜单「DSH Desktop Beta → 重新加载界面」。
39
+
40
+ ## 内核要求
41
+
42
+ - 配置即时生效需要 DSH **0.2.2-rc.3+**:该版本起 Host 的 `.volatile()` Config 字段会同步给浏览器半边,`apply(ctx, config)` 收到 `SyncedConfig` 引用;插件页的 `plugins.bundle.config` 槽位也要求同一条版本线。
43
+ - 更老的内核(`engines.dsh` 仍允许的 0.2.1):配置退回内置默认值,改配置要重启宿主;`ctx.uiSession` 不存在时插件退化为纯活动排序,不显示等待徽标。
36
44
 
37
45
  ## 配置
38
46
 
39
- 配置在插件的 load 行(profile 的 `cordis.patch.yml`)里:
47
+ 配置在插件的 load 行(profile 的 `cordis.patch.yml`)里,也可以直接在插件页本行的配置卡片里改;两边都即时生效:
40
48
 
41
49
  ```yaml
42
50
  - id: workspace-sort
43
51
  config:
44
- enabled: true # false = 宿主半边不挂路由,浏览器半边静默,顺序不动
52
+ enabled: true # false = 浏览器半边停手,顺序不动;宿主路由仍在,置顶照常读写
45
53
  aggregate: true # false = 容器目录只按自己的会话算(不含子树)
46
54
  initialSort: true # false = 页面加载时不排,等下一次提问或手动整理
47
55
  ```
@@ -51,8 +59,8 @@ dsh plugin --profile desktop add /path/to/packages/dsh-workspace-sort
51
59
  ## 数据与副作用
52
60
 
53
61
  - 顺序是**宿主持久状态**,写在 `$DSH_HOME/storages/workspace.json` 的 `global.workspaceIds`,和其他窗口一致。
54
- - 活动来自会话列表的 `updatedAt`(持久化的最后一条人类提问时间);空白新会话(草稿)与子代理会话不计入。
55
- - 每次实际重排宿主写一行日志;`GET /dsh-workspace-sort/api/state` 返回最后一次重排的 `current` / `desired` / `moves` / `newest`。
62
+ - 活动来自会话列表的 `updatedAt`(持久化的最后一条人类提问时间);空白新会话(草稿)与子代理会话不计入。等待状态来自 `ctx.uiSession.pendingInteractions`,不落盘。
63
+ - 每次实际重排宿主写一行日志;`GET /dsh-workspace-sort/api/state` 返回最后一次重排的 `current` / `desired` / `moves` / `newest` / `waiting`。
56
64
  - 不联网(除了本机回环路由),不读写你的项目文件。
57
65
 
58
66
  ## 与社区插件的差别
@@ -68,18 +76,19 @@ dsh plugin --profile desktop add /path/to/packages/dsh-workspace-sort
68
76
  ## 已知限制
69
77
 
70
78
  - 置顶存在本机 `prefs.json`,不随 DSH 跨机同步。
71
- - 「按工作区」(非树形)分组下,容器空行会浮在它最活跃的子项目上方;不想要就把 `aggregate` 设成 `false`。
72
- - 依赖客户端服务的内部形状(`ctx.workspaces.list`、`ctx.sessions.list.byId` 的 `updatedAt` / `running` / `blank`)。DSH 改这两处时插件要跟着改,`engines.dsh` 只声明到 0.2.x 就是这个意思。
79
+ - 「按工作区」(非树形)分组下,容器空行会浮在它最活跃的子项目上方;不想要就把 `aggregate` 设成 `false`(这一项同时决定子会话「等你输入」会不会抬起容器)。
80
+ - 「等你输入」只认 `approval` / `plan-review` / `question` 三种 kind,与内核侧栏的可见等待标记一致;其他 kind 不排前。
81
+ - 依赖客户端服务的内部形状(`ctx.workspaces.list`、`ctx.sessions.list.byId` 的 `updatedAt` / `running` / `blank`、`ctx.uiSession.pendingInteractions`)。DSH 改这些时插件要跟着改,`engines.dsh` 只声明到 0.2.x 就是这个意思。
73
82
  - 顺序写进宿主,是全局行为,不是某个窗口的视图偏好。
74
83
 
75
84
  ## 开发
76
85
 
77
86
  ```sh
78
87
  npm run build # src/sort.js 内联进 src/client.js → lib/client.js
79
- npm test # node --test:父级推导、活动聚合、置顶、运行中优先、目标顺序、move 计划(11 例)
88
+ npm test # node --test:纯规则 13 例 + 浏览器半边等待排序 5 例
80
89
  ```
81
90
 
82
- `src/sort.js` 是纯函数(可测);`src/client.js` 是浏览器半边(引擎 + 两个 Slot 组件);`index.js` 是宿主半边(配置、prefs 文件、两条路由、日志)。没有打包器。
91
+ `src/sort.js` 是纯函数(可测);`src/client.js` 是浏览器半边(引擎 + 两个 Slot 组件);`index.js` 是宿主半边(Config、prefs 文件、两条路由、日志)。没有打包器。`lib/client.js` 是跟踪的构建产物,改 `src/client.js` 或 `src/sort.js` 后要重建再提交。
83
92
 
84
93
  ## 许可
85
94
 
package/cordis.patch.yml CHANGED
@@ -1,19 +1,25 @@
1
1
  # The dsh-workspace-sort bundle patch: one row over the profile root.
2
2
  #
3
- # The row carries both halves. The Host half serves config, the stored pins and
4
- # the last reorder report on `/dsh-workspace-sort/api/state`, and persists pins
5
- # plus the two rule switches on `/dsh-workspace-sort/api/prefs` into
3
+ # The row carries both halves. The Host half persists the pins plus the two rule
4
+ # switches on `/dsh-workspace-sort/api/prefs` into
6
5
  # `$DSH_HOME/workspace-sort/prefs.json` (never localStorage: the desktop Web
7
- # server binds an ephemeral port, so the page origin changes on every restart).
6
+ # server binds an ephemeral port, so the page origin changes on every restart),
7
+ # and keeps the last reorder report on `/dsh-workspace-sort/api/state` for
8
+ # `curl` diagnostics.
9
+ #
8
10
  # The browser half
9
11
  # (`dsh.client.platform: web`) sorts the sidebar Workspaces by their newest
10
- # human prompt and writes that order through the official
11
- # `workspaces.insertBefore` command, so the order is Host-durable exactly like a
12
- # drag.
12
+ # human prompt, puts a Workspace that is waiting for the user's input first, and
13
+ # writes that order through the official `workspaces.insertBefore` command, so
14
+ # the order is Host-durable exactly like a drag.
13
15
  #
14
- # Every knob is optional and lives here, not in the browser bundle:
15
- # enabled false mounts the Host half inert (no route), so the page stays
16
- # silent and the workspace order is left exactly as it was.
16
+ # Every knob is optional and lives here, not in the browser bundle. All three
17
+ # are `.volatile()` Host Config fields: the Host reads them through live
18
+ # `{ get() }` references and the browser half through `SyncedConfig` refs, so a
19
+ # change applies without a restart or a page reload.
20
+ # enabled false stops the browser half from sorting; the order is left
21
+ # exactly as it is. Both Host routes stay mounted, so the pins keep
22
+ # working and the switch can be turned back on live.
17
23
  # aggregate true (default) ranks a container Workspace by its whole subtree;
18
24
  # false ranks it by its own Sessions only, which makes container
19
25
  # folders such as Code/Mubea sink to the bottom.
package/index.js CHANGED
@@ -4,11 +4,9 @@
4
4
  * The ordering itself is a Client job: only the browser holds both the
5
5
  * Workspace order (`ctx.workspaces.list`) and the Session summaries whose
6
6
  * `updatedAt` is the last human prompt, and only the browser can call the
7
- * durable `workspaces.insertBefore`. The Host owes the browser three things and
7
+ * durable `workspaces.insertBefore`. The Host owes the browser two things and
8
8
  * nothing else:
9
9
  *
10
- * * the resolved knobs (`GET /dsh-workspace-sort/api/state`), so defaults live
11
- * in the profile instead of the bundle;
12
10
  * * the user's pins and rule switches, persisted as plain JSON under
13
11
  * `$DSH_HOME/workspace-sort/prefs.json` (`GET` on the state route,
14
12
  * `POST /dsh-workspace-sort/api/prefs` to write). They are stored here
@@ -18,15 +16,25 @@
18
16
  * * an audit trail: the last reorder decision is kept in memory for `GET`, and
19
17
  * every applied reorder logs one line.
20
18
  *
19
+ * The sorting knobs are not a route: they are this package's {@link Config},
20
+ * whose fields are all `.volatile()`. The Loader hands `apply` live `{ get() }`
21
+ * references and gives the browser face the same values as `SyncedConfig` refs,
22
+ * so a change made in the plugin page applies without a restart or a reload.
23
+ * The state route still echoes the resolved knobs for `curl` diagnostics, but
24
+ * the browser never depends on it for configuration.
25
+ *
21
26
  * Deliberately absent: file moves, directory renames, Workspace removal,
22
27
  * session migration, process spawning. This plugin changes ordering state only.
23
28
  *
24
- * `enabled: false` mounts this half inert: no route is registered, so the
25
- * browser half stays silent rather than inventing its own defaults.
29
+ * `enabled: false` leaves the order untouched: the browser half stops sorting.
30
+ * Both routes stay mounted, so the pins remain readable and writable while the
31
+ * switch is off and toggling it back on is itself a live config change.
26
32
  *
27
33
  * @module dsh-workspace-sort
28
34
  */
29
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
35
+ import z from '@deepseek-ai/schemastery'
36
+ import { randomUUID } from 'node:crypto'
37
+ import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
30
38
  import { homedir } from 'node:os'
31
39
  import { dirname, join } from 'node:path'
32
40
 
@@ -34,6 +42,30 @@ import { dirname, join } from 'node:path'
34
42
  export const STATE_ROUTE = '/dsh-workspace-sort/api/state'
35
43
  export const PREFS_ROUTE = '/dsh-workspace-sort/api/prefs'
36
44
 
45
+ /**
46
+ * Plugin config, edited live in the plugin page.
47
+ *
48
+ * Every field is `.volatile()` on purpose: the Loader then keeps the running
49
+ * references stable and commits new values in place, so changing a knob neither
50
+ * remounts this half nor reloads the page. Descriptions are the form labels.
51
+ */
52
+ export const Config = z.object({
53
+ /** Sort at all; false stops the browser half and leaves the Host order exactly as it is. */
54
+ enabled: z.boolean().default(true).description('启用排序。关掉后浏览器半边停手,工作区顺序保持原样。').volatile(),
55
+ /** Rank a container Workspace by its whole subtree instead of its own Sessions. */
56
+ aggregate: z
57
+ .boolean()
58
+ .default(true)
59
+ .description('容器目录按整个子树汇总(默认开);关掉后只按目录自己的会话算。')
60
+ .volatile(),
61
+ /** Apply the order as soon as a page loads instead of waiting for the next prompt. */
62
+ initialSort: z
63
+ .boolean()
64
+ .default(true)
65
+ .description('页面加载时立即排序(默认开);关掉后等下一次提问或手动整理。')
66
+ .volatile(),
67
+ })
68
+
37
69
  /** A reorder report or a pin set is small; anything larger is not this request. */
38
70
  const MAX_BODY_BYTES = 64 * 1024
39
71
 
@@ -46,10 +78,16 @@ const DEFAULT_PREFS = { auto: true, runningFirst: false, pins: [] }
46
78
  /**
47
79
  * The part of the profile row's `config` block this plugin reads.
48
80
  *
81
+ * A `.volatile()` field arrives as a live `{ get() }` reference; a plain
82
+ * boolean is also accepted, see {@link readFlag}.
83
+ *
84
+ * @typedef {object} VolatileFlag
85
+ * @property {() => boolean | undefined} get - the current value.
86
+ *
49
87
  * @typedef {object} WorkspaceSortConfig
50
- * @property {boolean} [enabled] Mount the plugin at all (false leaves the order untouched).
51
- * @property {boolean} [aggregate] Rank a container by its whole subtree (default true).
52
- * @property {boolean} [initialSort] Apply the order as soon as a page loads (default true).
88
+ * @property {VolatileFlag | boolean} [enabled] Sort at all; false leaves the order untouched.
89
+ * @property {VolatileFlag | boolean} [aggregate] Rank a container by its whole subtree (default true).
90
+ * @property {VolatileFlag | boolean} [initialSort] Apply the order as soon as a page loads (default true).
53
91
  */
54
92
 
55
93
  /**
@@ -72,16 +110,21 @@ const DEFAULT_PREFS = { auto: true, runningFirst: false, pins: [] }
72
110
 
73
111
  /**
74
112
  * @param {HostContext} ctx - the plugin's Cordis context.
75
- * @param {WorkspaceSortConfig} [config] - the profile row's `config` block.
113
+ * @param {WorkspaceSortConfig} [config] - the row's `config` block; volatile
114
+ * fields arrive as live `{ get() }` references.
76
115
  */
77
116
  export function apply(ctx, config = {}) {
78
117
  if (config === null || typeof config !== 'object') config = {}
79
- if (config.enabled === false) return
80
- const resolved = {
81
- enabled: true,
82
- aggregate: config.aggregate !== false,
83
- initialSort: config.initialSort !== false,
84
- }
118
+ /**
119
+ * The knobs as they are right now. Read on every use instead of once at
120
+ * mount: with `.volatile()` fields the Loader commits new values into the
121
+ * same references, so a cached copy would go stale.
122
+ */
123
+ const resolvedConfig = () => ({
124
+ enabled: readFlag(config.enabled, true),
125
+ aggregate: readFlag(config.aggregate, true),
126
+ initialSort: readFlag(config.initialSort, true),
127
+ })
85
128
 
86
129
  let prefs = { ...DEFAULT_PREFS }
87
130
  let lastReport
@@ -92,6 +135,8 @@ export function apply(ctx, config = {}) {
92
135
 
93
136
  /**
94
137
  * Answer one request on the state route: knobs, prefs, and the last decision.
138
+ * The knobs are echoed for diagnostics only; the browser half gets them from
139
+ * its `SyncedConfig`.
95
140
  *
96
141
  * @param {import('node:http').IncomingMessage} request - the route request.
97
142
  * @param {import('node:http').ServerResponse} response - the route response.
@@ -103,7 +148,7 @@ export function apply(ctx, config = {}) {
103
148
  }
104
149
  if (request.method === 'GET' || request.method === 'HEAD') {
105
150
  await ready
106
- sendJson(response, 200, { ok: true, config: resolved, prefs, lastReport })
151
+ sendJson(response, 200, { ok: true, config: resolvedConfig(), prefs, lastReport }, {}, request.method === 'HEAD')
107
152
  return
108
153
  }
109
154
  if (request.method !== 'POST') {
@@ -125,7 +170,8 @@ export function apply(ctx, config = {}) {
125
170
  if (body.hello === true) {
126
171
  const options = body.options !== null && typeof body.options === 'object' ? body.options : {}
127
172
  ctx.logger?.info?.(
128
- 'dsh-workspace-sort: client attached (aggregate=%s, initialSort=%s)',
173
+ 'dsh-workspace-sort: client attached (enabled=%s, aggregate=%s, initialSort=%s)',
174
+ options.enabled !== false,
129
175
  options.aggregate !== false,
130
176
  options.initialSort !== false,
131
177
  )
@@ -134,10 +180,11 @@ export function apply(ctx, config = {}) {
134
180
  }
135
181
  const moves = Array.isArray(body.moves) ? body.moves : []
136
182
  ctx.logger?.info?.(
137
- 'dsh-workspace-sort: reordered %d workspace(s), newest activity %s%s',
183
+ 'dsh-workspace-sort: reordered %d workspace(s), newest activity %s%s, %d waiting on you',
138
184
  moves.length,
139
185
  typeof body.newest === 'number' && body.newest > 0 ? new Date(body.newest).toISOString() : 'none',
140
186
  body.manual === true ? ' (manual)' : '',
187
+ typeof body.waiting === 'number' && body.waiting > 0 ? body.waiting : 0,
141
188
  )
142
189
  sendJson(response, 200, { ok: true })
143
190
  }
@@ -167,6 +214,7 @@ export function apply(ctx, config = {}) {
167
214
  }
168
215
  const next = sanitizePrefs(body)
169
216
  try {
217
+ await ready
170
218
  await writeStoredPrefs(next)
171
219
  } catch (error) {
172
220
  ctx.logger?.warn?.('dsh-workspace-sort: could not persist prefs: %o', error)
@@ -189,6 +237,29 @@ export function apply(ctx, config = {}) {
189
237
  })
190
238
  }
191
239
 
240
+ /**
241
+ * Read one config field.
242
+ *
243
+ * A `.volatile()` field is handed to `apply` as a live `{ get() }` reference
244
+ * whose value may still be absent; a plain boolean is accepted too so a direct
245
+ * `apply(ctx, {...})` (a test, or a Host that does not mark it volatile) reads
246
+ * the same way. Anything unusable falls back to the field default.
247
+ *
248
+ * @param field - the config field as received.
249
+ * @param fallback - the documented default.
250
+ * @returns the effective boolean.
251
+ */
252
+ function readFlag(field, fallback) {
253
+ if (field === undefined || field === null) return fallback
254
+ let value
255
+ try {
256
+ value = typeof field.get === 'function' ? field.get() : field
257
+ } catch {
258
+ return fallback
259
+ }
260
+ return typeof value === 'boolean' ? value : fallback
261
+ }
262
+
192
263
  /**
193
264
  * Where this plugin keeps its own small state file.
194
265
  *
@@ -235,18 +306,30 @@ async function readStoredPrefs(logger) {
235
306
  }
236
307
  }
237
308
 
309
+ let writeQueue = Promise.resolve()
310
+
238
311
  /**
239
- * Write the prefs atomically (tmp file then rename).
312
+ * Write the prefs atomically (serialized unique tmp file then rename).
240
313
  *
241
314
  * @param prefs - the value to store.
242
315
  * @returns a promise that settles once the rename is durable.
243
316
  */
244
- async function writeStoredPrefs(prefs) {
245
- const file = prefsFile()
246
- await mkdir(dirname(file), { recursive: true })
247
- const tmp = `${file}.tmp`
248
- await writeFile(tmp, `${JSON.stringify(prefs, null, 1)}\n`, 'utf8')
249
- await rename(tmp, file)
317
+ function writeStoredPrefs(prefs) {
318
+ const run = async () => {
319
+ const file = prefsFile()
320
+ await mkdir(dirname(file), { recursive: true })
321
+ const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`
322
+ try {
323
+ await writeFile(tmp, `${JSON.stringify(prefs, null, 1)}\n`, 'utf8')
324
+ await rename(tmp, file)
325
+ } catch (error) {
326
+ await unlink(tmp).catch(() => undefined)
327
+ throw error
328
+ }
329
+ }
330
+ const queued = writeQueue.then(run, run)
331
+ writeQueue = queued.catch(() => undefined)
332
+ return queued
250
333
  }
251
334
 
252
335
  /**
@@ -291,7 +374,7 @@ async function readJsonBody(request) {
291
374
  * @param {unknown} payload - JSON-serializable body.
292
375
  * @param {Record<string, string | string[]>} [headers] - extra headers.
293
376
  */
294
- function sendJson(response, status, payload, headers = {}) {
377
+ function sendJson(response, status, payload, headers = {}, headOnly = false) {
295
378
  const body = Buffer.from(JSON.stringify(payload), 'utf8')
296
379
  response.writeHead(status, {
297
380
  'content-type': 'application/json; charset=utf-8',
@@ -299,7 +382,7 @@ function sendJson(response, status, payload, headers = {}) {
299
382
  'cache-control': 'no-store',
300
383
  ...headers,
301
384
  })
302
- response.end(body)
385
+ response.end(headOnly ? undefined : body)
303
386
  }
304
387
 
305
388
  /**
package/lib/client.js CHANGED
@@ -8,11 +8,12 @@
8
8
  * every filesystem and destructive operation out of scope:
9
9
  *
10
10
  * * automatic order by each Workspace's newest human prompt (`updatedAt` on a
11
- * non-blank Session), optionally with running Workspaces first;
11
+ * non-blank Session), with a Workspace waiting for your input ahead of the
12
+ * rest and — optionally — running Workspaces next;
12
13
  * * pins that keep chosen Workspaces at the front, in pin order;
13
14
  * * a card on this bundle's page in the Plugins view that opens a panel with
14
- * session/running counts, the last activity, a name filter, the two rule
15
- * switches and a "tidy now" button (the sidebar itself gets no icon);
15
+ * session/running/waiting counts, the last activity, a name filter, the two
16
+ * rule switches and a "tidy now" button (the sidebar itself gets no icon);
16
17
  * * every write goes through `ctx.workspaces.insertBefore`, the same durable
17
18
  * command a Workspace drag uses.
18
19
  *
@@ -23,10 +24,11 @@
23
24
  * Guard rails:
24
25
  *
25
26
  * * only a human prompt (or an explicit button) starts a pass;
26
- * * a manual drag wins until the next prompt;
27
+ * * a manual drag wins until the next prompt or a Session starts waiting;
27
28
  * * one pass at a time, and a pass that finds the order in place writes nothing;
28
- * * the Host half answers the knobs on its own route; a page that cannot read
29
- * that route stays inert instead of guessing.
29
+ * * the knobs arrive as Host-synced `SyncedConfig` refs and are re-read live,
30
+ * so a config change stops or restarts the engine without a page reload;
31
+ * * `ctx.uiSession.pendingInteractions` is the authority for "waiting on you".
30
32
  *
31
33
  * `src/sort.js` (inlined by `scripts/build-client.mjs`) holds the pure rules.
32
34
  */
@@ -54,6 +56,10 @@ window.__ModuleLoader__.load({
54
56
  * * a Session summary carries `updatedAt` = the persisted last *human* prompt
55
57
  * time (opening a Session or an assistant reply never advances it) and
56
58
  * `blank` = the unsent New Session draft, which is not activity;
59
+ * * a Session can be **waiting for you**: `ctx.uiSession.pendingInteractions`
60
+ * reports the highest-precedence request (approval, plan review, question)
61
+ * that only a human can answer. A waiting Workspace outranks a running one,
62
+ * because it is the one that stops making progress until you look;
57
63
  * * under **Group by → Workspace tree** the sidebar nests a Workspace below
58
64
  * its nearest registered ancestor path and nothing else — nesting is
59
65
  * derived from paths, so reordering the flat Host order reorders siblings.
@@ -75,14 +81,30 @@ window.__ModuleLoader__.load({
75
81
  * @param paths - absolute directories of every registered Workspace.
76
82
  * @returns the ancestor's registered path, or `undefined` for a root.
77
83
  */
84
+ function normalizePathForMatch(p) {
85
+ let out = p.replace(/\\/gu, '/')
86
+ if (/^[A-Za-z]:\//u.test(out)) out = out[0].toLowerCase() + out.slice(1)
87
+ if (out.length > 1 && out !== '/' && !/^[a-z]:\/$/u.test(out)) {
88
+ out = out.replace(/\/+$/u, '')
89
+ }
90
+ return out
91
+ }
92
+
78
93
  function owningParent(path, paths) {
79
94
  if (typeof path !== 'string' || path.length === 0) return undefined
95
+ const normPath = normalizePathForMatch(path)
80
96
  let best
97
+ let bestLen = -1
81
98
  for (const candidate of paths) {
82
- if (typeof candidate !== 'string' || candidate === path) continue
83
- const prefix = candidate.endsWith('/') ? candidate : `${candidate}/`
84
- if (!path.startsWith(prefix)) continue
85
- if (best === undefined || candidate.length > best.length) best = candidate
99
+ if (typeof candidate !== 'string' || candidate.length === 0) continue
100
+ const normCand = normalizePathForMatch(candidate)
101
+ if (normCand === normPath) continue
102
+ const prefix = normCand.endsWith('/') ? normCand : `${normCand}/`
103
+ if (!normPath.startsWith(prefix)) continue
104
+ if (normCand.length > bestLen) {
105
+ best = candidate
106
+ bestLen = normCand.length
107
+ }
86
108
  }
87
109
  return best
88
110
  }
@@ -118,10 +140,28 @@ function ownActivity(workspace, byId) {
118
140
  * @returns Workspace id to activity timestamp; every input Workspace is present.
119
141
  */
120
142
  function activityByWorkspace(workspaces, byId, options = {}) {
121
- const aggregate = options.aggregate !== false
122
- const activity = new Map()
123
- for (const workspace of workspaces) activity.set(workspace.workspaceId, ownActivity(workspace, byId))
124
- if (!aggregate) return activity
143
+ return bySubtree(workspaces, (workspace) => ownActivity(workspace, byId), Math.max, 0, options)
144
+ }
145
+
146
+ /**
147
+ * Fold one per-Workspace value over the Workspace's whole subtree.
148
+ *
149
+ * This is the shared shape behind both sort keys: activity takes the newest
150
+ * stamp of the subtree, waiting takes the number of waiting Sessions. With
151
+ * `aggregate: false` a container keeps its own value, so a descendant never
152
+ * lifts it.
153
+ *
154
+ * @param workspaces - Workspaces in Host order.
155
+ * @param own - the Workspace's own value.
156
+ * @param merge - combines a folded value with one child's folded value.
157
+ * @param empty - the accumulator before any value is merged.
158
+ * @param options - `aggregate: false` disables the subtree fold.
159
+ * @returns Workspace id to folded value; every input Workspace is present.
160
+ */
161
+ function bySubtree(workspaces, own, merge, empty, options = {}) {
162
+ const values = new Map()
163
+ for (const workspace of workspaces) values.set(workspace.workspaceId, own(workspace))
164
+ if (options.aggregate === false) return values
125
165
 
126
166
  const paths = workspaces.map((workspace) => workspace.path)
127
167
  const children = new Map()
@@ -137,13 +177,13 @@ function activityByWorkspace(workspaces, byId, options = {}) {
137
177
  const cached = memo.get(workspace.workspaceId)
138
178
  if (cached !== undefined) return cached
139
179
  // No cycle is possible: a parent path is strictly shorter than its child's.
140
- let best = activity.get(workspace.workspaceId) ?? 0
141
- for (const child of children.get(workspace.path) ?? []) best = Math.max(best, subtree(child))
142
- memo.set(workspace.workspaceId, best)
143
- return best
180
+ let value = values.get(workspace.workspaceId) ?? empty
181
+ for (const child of children.get(workspace.path) ?? []) value = merge(value, subtree(child))
182
+ memo.set(workspace.workspaceId, value)
183
+ return value
144
184
  }
145
- for (const workspace of workspaces) activity.set(workspace.workspaceId, subtree(workspace))
146
- return activity
185
+ for (const workspace of workspaces) values.set(workspace.workspaceId, subtree(workspace))
186
+ return values
147
187
  }
148
188
 
149
189
  /**
@@ -159,24 +199,92 @@ function isRunning(workspace, byId) {
159
199
  return false
160
200
  }
161
201
 
202
+ /**
203
+ * Pending-interaction kinds that mean "this Session is waiting for your input".
204
+ *
205
+ * Mirrors the shipped sidebar's `visiblePendingKind`: only these three kinds get
206
+ * a visible waiting marker. A domain may publish other kinds, such as a plan
207
+ * that is still being generated, which are not the user's turn to act on.
208
+ */
209
+ const WAITING_KINDS = Object.freeze(['approval', 'plan-review', 'question'])
210
+
211
+ /**
212
+ * Whether one pending-interaction kind is the user's turn to act.
213
+ *
214
+ * @param kind - the domain-owned `kind` string.
215
+ * @returns true for {@link WAITING_KINDS}.
216
+ */
217
+ function isWaitingKind(kind) {
218
+ return typeof kind === 'string' && WAITING_KINDS.includes(kind)
219
+ }
220
+
221
+ /**
222
+ * The pending interaction for one Session, accepting the Map the Client publishes
223
+ * and a plain object for callers that do not have a Map.
224
+ *
225
+ * @param pending - `ctx.uiSession.pendingInteractions` snapshot.
226
+ * @param sessionId - the Session id to look up.
227
+ * @returns the interaction, or undefined.
228
+ */
229
+ function pendingOf(pending, sessionId) {
230
+ if (pending === undefined || pending === null) return undefined
231
+ if (typeof pending.get === 'function') return pending.get(sessionId)
232
+ return pending[sessionId]
233
+ }
234
+
235
+ /**
236
+ * How many of this Workspace's own Sessions are waiting for the user.
237
+ *
238
+ * @param workspace - the Workspace row.
239
+ * @param pending - `ctx.uiSession.pendingInteractions` snapshot.
240
+ * @returns the number of member Sessions whose pending kind is visible.
241
+ */
242
+ function ownWaitingCount(workspace, pending) {
243
+ const ids = Array.isArray(workspace?.sessionIds) ? workspace.sessionIds : []
244
+ let count = 0
245
+ for (const id of ids) if (isWaitingKind(pendingOf(pending, id)?.kind)) count += 1
246
+ return count
247
+ }
248
+
249
+ /**
250
+ * Waiting Sessions per Workspace, optionally aggregated over descendants.
251
+ *
252
+ * A container folder that holds a waiting Session lifts with its subtree, for
253
+ * the same reason activity does: it is the group a user would look under. With
254
+ * `aggregate: false` only a Workspace's own Sessions count.
255
+ *
256
+ * @param workspaces - Workspaces in Host order.
257
+ * @param pending - `ctx.uiSession.pendingInteractions` snapshot.
258
+ * @param options - `aggregate: false` disables the subtree fold.
259
+ * @returns Workspace id to waiting count; every input Workspace is present.
260
+ */
261
+ function waitingByWorkspace(workspaces, pending, options = {}) {
262
+ return bySubtree(workspaces, (workspace) => ownWaitingCount(workspace, pending), (left, right) => left + right, 0, options)
263
+ }
264
+
162
265
  /**
163
266
  * The Workspace ids in display order.
164
267
  *
165
- * Pinned Workspaces keep their pin order at the front; the rest follow activity.
166
- * With `runningFirst` a Workspace holding a running Session leads the unpinned
167
- * partition, so a long agent run does not sink out of sight. Ties keep the
168
- * current relative order, which is what keeps an untouched Workspace from
169
- * wandering between two runs.
268
+ * Pinned Workspaces keep their pin order at the front. The unpinned remainder is
269
+ * ranked by, in order: a Session waiting for the user, a running Session (only
270
+ * with `runningFirst`), the newest prompt, then the current index. A waiting
271
+ * Workspace therefore outranks a merely busy one: an approval prompt is the
272
+ * thing that actually needs a click. `waitingFirst: false` disables the first
273
+ * key. Ties keep the current relative order, which is what keeps an untouched
274
+ * Workspace from wandering between two runs.
170
275
  *
171
276
  * @param workspaces - Workspaces in Host order.
172
277
  * @param byId - Session summaries keyed by Session id.
173
- * @param options - `aggregate` (forwarded), `pins` in pin order, `runningFirst`.
278
+ * @param options - `aggregate` (forwarded), `pins` in pin order, `runningFirst`,
279
+ * `waitingFirst`, `pending`.
174
280
  * @returns Workspace ids sorted for display.
175
281
  */
176
282
  function desiredOrder(workspaces, byId, options = {}) {
177
283
  const activity = activityByWorkspace(workspaces, byId, options)
284
+ const waiting = waitingByWorkspace(workspaces, options.pending, options)
178
285
  const pins = Array.isArray(options.pins) ? options.pins : []
179
286
  const runningFirst = options.runningFirst === true
287
+ const waitingFirst = options.waitingFirst !== false
180
288
  const known = new Map(workspaces.map((workspace) => [workspace.workspaceId, workspace]))
181
289
  const pinnedRows = pins.map((id) => known.get(id)).filter((workspace) => workspace !== undefined)
182
290
  const pinnedIds = new Set(pinnedRows.map((workspace) => workspace.workspaceId))
@@ -185,12 +293,16 @@ function desiredOrder(workspaces, byId, options = {}) {
185
293
  workspace,
186
294
  index,
187
295
  score: activity.get(workspace.workspaceId) ?? 0,
296
+ waiting: waitingFirst && (waiting.get(workspace.workspaceId) ?? 0) > 0,
188
297
  running: runningFirst && isRunning(workspace, byId),
189
298
  }))
190
299
  .filter((row) => !pinnedIds.has(row.workspace.workspaceId))
191
300
  .sort(
192
301
  (left, right) =>
193
- Number(right.running) - Number(left.running) || right.score - left.score || left.index - right.index,
302
+ Number(right.waiting) - Number(left.waiting) ||
303
+ Number(right.running) - Number(left.running) ||
304
+ right.score - left.score ||
305
+ left.index - right.index,
194
306
  )
195
307
  return [...pinnedRows.map((workspace) => workspace.workspaceId), ...rest.map((row) => row.workspace.workspaceId)]
196
308
  }
@@ -272,6 +384,69 @@ function newestActivity(activity) {
272
384
 
273
385
  const DEFAULT_PREFS = { auto: true, runningFirst: false, pins: [] }
274
386
 
387
+ /**
388
+ * One Host-synced config field, as `@deepseek-ai/dsh-client-config` defines
389
+ * it: the plugin may read it at any time, the value may still be absent, and
390
+ * the Host never remounts the plugin to change it. Declared locally so this
391
+ * bundle carries no extra dependency.
392
+ *
393
+ * @template T
394
+ * @typedef {object} SyncedConfigRef
395
+ * @property {() => T | undefined} get - the current frozen value.
396
+ * @property {((listener: () => void) => () => void)} [subscribe] - change observer.
397
+ *
398
+ * @typedef {object} SyncedConfig
399
+ * @property {SyncedConfigRef<boolean>} [enabled]
400
+ * @property {SyncedConfigRef<boolean>} [aggregate]
401
+ * @property {SyncedConfigRef<boolean>} [initialSort]
402
+ */
403
+
404
+ /** Stand-in when the shell did not mount `uiSession` (nothing can be waiting). */
405
+ const EMPTY_PENDING = new Map()
406
+ const NO_PENDING = Object.freeze({
407
+ getSnapshot: () => EMPTY_PENDING,
408
+ subscribe: () => () => {},
409
+ })
410
+
411
+ /**
412
+ * Read one config field, falling back when the Host sent no value.
413
+ *
414
+ * @param {SyncedConfigRef<boolean> | boolean | undefined} ref - the field.
415
+ * @param {boolean} fallback - the bundle default.
416
+ * @returns {boolean} the effective knob.
417
+ */
418
+ function readConfigFlag(ref, fallback) {
419
+ if (ref === undefined || ref === null) return fallback
420
+ try {
421
+ const value = typeof ref.get === 'function' ? ref.get() : ref
422
+ return typeof value === 'boolean' ? value : fallback
423
+ } catch {
424
+ return fallback
425
+ }
426
+ }
427
+
428
+ /**
429
+ * The knobs as the Host has them right now.
430
+ *
431
+ * @param {SyncedConfig | undefined} config - the second `apply` argument.
432
+ * @returns {{enabled: boolean, aggregate: boolean, initialSort: boolean}} the knobs.
433
+ */
434
+ function readOptions(config) {
435
+ return {
436
+ enabled: readConfigFlag(config?.enabled, DEFAULTS.enabled),
437
+ aggregate: readConfigFlag(config?.aggregate, DEFAULTS.aggregate),
438
+ initialSort: readConfigFlag(config?.initialSort, DEFAULTS.initialSort),
439
+ }
440
+ }
441
+
442
+ /** Whether the pending-interaction snapshot holds a kind that needs the user. */
443
+ function hasWaiting(pending) {
444
+ if (pending === undefined || pending === null) return false
445
+ const values = typeof pending.values === 'function' ? pending.values() : Object.values(pending)
446
+ for (const interaction of values) if (isWaitingKind(interaction?.kind)) return true
447
+ return false
448
+ }
449
+
275
450
  const DICT = {
276
451
  zh: {
277
452
  button: '工作区排序',
@@ -287,6 +462,7 @@ function newestActivity(activity) {
287
462
  pinnedTag: '置顶',
288
463
  sessions: '{n} 会话',
289
464
  running: '{n} 运行中',
465
+ waiting: '{n} 等你输入',
290
466
  idle: '无会话',
291
467
  never: '从没用过',
292
468
  minutes: '{n} 分钟前',
@@ -316,6 +492,7 @@ function newestActivity(activity) {
316
492
  pinnedTag: 'Pinned',
317
493
  sessions: '{n} sessions',
318
494
  running: '{n} running',
495
+ waiting: '{n} waiting on you',
319
496
  idle: 'No sessions',
320
497
  never: 'Never used',
321
498
  minutes: '{n} min ago',
@@ -482,9 +659,12 @@ function newestActivity(activity) {
482
659
  }
483
660
 
484
661
  return {
485
- inject: ['workspaces', 'sessions', 'locale', 'slots'],
486
- apply(ctx) {
487
- let options = { ...DEFAULTS }
662
+ inject: ['workspaces', 'sessions', 'locale', 'slots', 'uiSession'],
663
+ /**
664
+ * @param ctx - the Client Cordis context.
665
+ * @param {SyncedConfig} [config] - the Host-synced knobs; one ref per field.
666
+ */
667
+ apply(ctx, config) {
488
668
  let timer
489
669
  let disposed = false
490
670
  /** Timestamp of our own last durable write, to recognise its echo. */
@@ -503,13 +683,41 @@ function newestActivity(activity) {
503
683
  let busy = false
504
684
  /** The Workspace ids of the previous store emission (to see drags apart from add/remove). */
505
685
  let knownIds = []
686
+ /** True while loading initial prefs from the Host, so `prefs.subscribe` doesn't force a pass. */
687
+ let hydrating = false
688
+ /** True while `prunePins` updates prefs inside `pass()`, to avoid re-entrant `request(true)`. */
689
+ let pruningPins = false
690
+ /** Whether `start()` completed (or confirmed Host unreachable) before pruning persisted pins. */
691
+ let hydrated = false
692
+ /** Consecutive `insertBefore` failures; caps infinite retry spam when order cannot be written. */
693
+ let consecutiveFailures = 0
506
694
 
507
695
  const prefs = createStore({ ...DEFAULT_PREFS })
696
+ /**
697
+ * The live knobs. A Host-synced config field is a reference that mutates
698
+ * in place, so this store is what makes React re-render after a change
699
+ * and what `pass()` reads at operation time.
700
+ */
701
+ const settings = createStore(readOptions(config))
508
702
  /** Whether this Host half exposes the prefs route; an older build does not. */
509
703
  const capabilities = createStore({ persist: false })
510
704
  const panel = createStore({ open: false })
511
705
  const t = () => ctx.locale.bind(NS)
512
706
 
707
+ /**
708
+ * The pending-interaction snapshot, or an empty one when the shell did
709
+ * not mount `uiSession`.
710
+ *
711
+ * @returns {ReadonlyMap<string, {kind?: string}>} the snapshot.
712
+ */
713
+ const readPending = () => {
714
+ try {
715
+ return ctx.uiSession?.pendingInteractions?.getSnapshot?.() ?? NO_PENDING.getSnapshot()
716
+ } catch {
717
+ return NO_PENDING.getSnapshot()
718
+ }
719
+ }
720
+
513
721
  const readItems = () => {
514
722
  try {
515
723
  const snapshot = ctx.workspaces?.list?.getSnapshot?.()
@@ -568,9 +776,17 @@ function newestActivity(activity) {
568
776
  * @param workspaceIds - the ids the Host currently reports.
569
777
  */
570
778
  const prunePins = (workspaceIds) => {
779
+ if (!hydrated || workspaceIds.length === 0) return
571
780
  const pins = prefs.get().pins
572
781
  const next = pins.filter((id) => workspaceIds.indexOf(id) !== -1)
573
- if (next.length !== pins.length) updatePrefs({ pins: next })
782
+ if (next.length !== pins.length) {
783
+ pruningPins = true
784
+ try {
785
+ updatePrefs({ pins: next })
786
+ } finally {
787
+ pruningPins = false
788
+ }
789
+ }
574
790
  }
575
791
 
576
792
  /**
@@ -628,7 +844,8 @@ function newestActivity(activity) {
628
844
  * @returns true when this pass wrote a durable order.
629
845
  */
630
846
  const pass = async (manual) => {
631
- if (disposed || options.enabled === false) return false
847
+ const options = settings.get()
848
+ if (disposed || (!manual && options.enabled === false)) return false
632
849
  const items = readItems()
633
850
  if (items.length < 2) return false
634
851
  const byId = readSummaries()
@@ -636,16 +853,23 @@ function newestActivity(activity) {
636
853
  const state = prefs.get()
637
854
  if (!manual && !state.auto) return false
638
855
 
856
+ const pending = readPending()
639
857
  const shared = {
640
858
  aggregate: options.aggregate !== false,
641
859
  pins: state.pins,
642
860
  runningFirst: state.runningFirst,
861
+ pending,
643
862
  }
644
863
  const current = items.map((workspace) => workspace.workspaceId)
645
864
  prunePins(current)
646
865
  const desired = desiredOrder(items, byId, shared)
647
866
  const newest = newestActivity(activityByWorkspace(items, byId, shared))
648
- if (newest === 0) {
867
+ // Waiting Workspaces have no activity of their own to report: a Session
868
+ // that asks for approval may never have prompted at all, or only did so
869
+ // long ago, so the waiting count has to keep the pass alive here.
870
+ let waiting = 0
871
+ for (const count of waitingByWorkspace(items, pending, shared).values()) waiting += count
872
+ if (newest === 0 && waiting === 0) {
649
873
  // Before the baseline pass the summary store may still be filling in;
650
874
  // an all-zero ranking would only reproduce the current index order.
651
875
  return false
@@ -653,6 +877,7 @@ function newestActivity(activity) {
653
877
  if (sameOrder(current, desired)) {
654
878
  sorted = true
655
879
  manualHold = false
880
+ consecutiveFailures = 0
656
881
  return false
657
882
  }
658
883
  if (!manual && sorted && manualHold) return false
@@ -660,15 +885,25 @@ function newestActivity(activity) {
660
885
  const moves = planMoves(current, desired)
661
886
  if (moves.length === 0) {
662
887
  sorted = true
888
+ consecutiveFailures = 0
663
889
  return false
664
890
  }
665
891
  for (const move of moves) {
892
+ // A config change can stop the engine mid-pass; do not keep writing.
893
+ if (disposed || (!manual && settings.get().enabled === false)) return false
894
+ // Re-verify both ids still exist before each await in case a workspace was removed mid-pass.
895
+ const liveIds = new Set(readItems().map((workspace) => workspace.workspaceId))
896
+ if (!liveIds.has(move.id) || (move.before !== undefined && !liveIds.has(move.before))) {
897
+ schedule(SETTLE_MS)
898
+ return false
899
+ }
666
900
  selfWriteAt = Date.now()
667
901
  await ctx.workspaces.insertBefore(move.id, move.before)
668
902
  }
669
903
  sorted = true
670
904
  manualHold = false
671
- report({ current, desired, moves, newest, manual: manual === true })
905
+ consecutiveFailures = 0
906
+ report({ current, desired, moves, newest, waiting, manual: manual === true })
672
907
  return true
673
908
  }
674
909
 
@@ -687,6 +922,7 @@ function newestActivity(activity) {
687
922
  if (!wanted) break
688
923
  }
689
924
  } catch (error) {
925
+ consecutiveFailures += 1
690
926
  warn('reorder failed', error)
691
927
  } finally {
692
928
  busy = false
@@ -709,12 +945,21 @@ function newestActivity(activity) {
709
945
  * @param manual - true for a button press.
710
946
  */
711
947
  const request = (manual) => {
712
- if (manual) forced = true
948
+ if (manual) {
949
+ consecutiveFailures = 0
950
+ forced = true
951
+ }
713
952
  schedule(0)
714
953
  }
715
954
 
716
955
  /**
717
- * Read this bundle's knobs from the Host half before sorting at all.
956
+ * Read the persisted prefs from the Host half.
957
+ *
958
+ * The knobs do NOT come from this route any more: they arrive as
959
+ * `SyncedConfig` refs in `apply`. A Host that cannot be reached costs the
960
+ * persisted pins, not the sorting itself — the bundle keeps its defaults
961
+ * and in-memory prefs instead of going inert, which is what the old
962
+ * startup handshake did.
718
963
  */
719
964
  const start = async () => {
720
965
  let body
@@ -722,25 +967,27 @@ function newestActivity(activity) {
722
967
  const response = await fetch(STATE_ROUTE, { headers: { accept: 'application/json' } })
723
968
  body = response.ok ? await response.json() : undefined
724
969
  } catch (error) {
725
- warn('host half unreachable; leaving the workspace order untouched', error)
726
- options = { ...options, enabled: false }
970
+ hydrated = true
971
+ warn('host half unreachable; keeping pins in memory', error)
727
972
  return
728
973
  }
729
- if (body === undefined || body === null || body.ok !== true || typeof body.config !== 'object' || body.config === null) {
730
- warn('host half did not answer; leaving the workspace order untouched')
731
- options = { ...options, enabled: false }
974
+ if (body === undefined || body === null || body.ok !== true) {
975
+ hydrated = true
976
+ warn('host half did not answer; keeping pins in memory')
732
977
  return
733
978
  }
734
- options = { ...DEFAULTS, ...body.config }
735
- if (disposed || options.enabled === false) return
736
- // An older Host half answers without `prefs`; keep pins in memory then,
737
- // instead of posting to a route that does not exist yet.
738
979
  if (body.prefs !== undefined && body.prefs !== null) {
739
- prefs.set(sanitizePrefs(body.prefs))
980
+ hydrating = true
981
+ try {
982
+ prefs.set(sanitizePrefs(body.prefs))
983
+ } finally {
984
+ hydrating = false
985
+ }
740
986
  capabilities.set({ persist: true })
741
987
  }
742
- report({ hello: true, options })
743
- if (options.initialSort !== false) schedule(0)
988
+ hydrated = true
989
+ report({ hello: true, options: settings.get() })
990
+ if (settings.get().enabled && settings.get().initialSort && prefs.get().auto) schedule(0)
744
991
  }
745
992
 
746
993
  // ------------------------------------------------------------ styles
@@ -761,7 +1008,7 @@ function newestActivity(activity) {
761
1008
  ctx.effect(
762
1009
  () =>
763
1010
  prefs.subscribe(() => {
764
- if (capabilities.get().persist) savePrefs(prefs.get())
1011
+ if (!hydrating && capabilities.get().persist) savePrefs(prefs.get())
765
1012
  }),
766
1013
  'dsh-workspace-sort: prefs',
767
1014
  )
@@ -779,6 +1026,7 @@ function newestActivity(activity) {
779
1026
  const ids = readItems().map((workspace) => workspace.workspaceId)
780
1027
  const membershipChanged = ids.length !== knownIds.length || ids.some((id) => knownIds.indexOf(id) === -1)
781
1028
  const orderChanged = !membershipChanged && ids.some((id, index) => id !== knownIds[index])
1029
+ if (membershipChanged) consecutiveFailures = 0
782
1030
  if (orderChanged && sorted && Date.now() - selfWriteAt > SELF_WRITE_MS) manualHold = true
783
1031
  knownIds = ids
784
1032
  }),
@@ -790,11 +1038,53 @@ function newestActivity(activity) {
790
1038
  ctx.sessions.list.subscribe(() => {
791
1039
  const advanced = noteActivity()
792
1040
  if (advanced) manualHold = false
1041
+ if (consecutiveFailures >= 3) return
793
1042
  if (advanced || (!sorted && prefs.get().auto)) schedule()
794
1043
  }),
795
1044
  )
796
1045
  // A pin or a rule toggle changes the target order: re-sort at once.
797
- offs.push(prefs.subscribe(() => request(true)))
1046
+ offs.push(
1047
+ prefs.subscribe(() => {
1048
+ if (hydrating || pruningPins) return
1049
+ request(true)
1050
+ }),
1051
+ )
1052
+ // The authoritative "waiting on you" source. Both entering and
1053
+ // leaving the state re-sort; the debounce absorbs a request being
1054
+ // replaced by the next one. A waiting Session outranks the user's
1055
+ // last manual drag, so that hold is released on entry.
1056
+ if (typeof ctx.uiSession?.pendingInteractions?.subscribe === 'function') {
1057
+ offs.push(
1058
+ ctx.uiSession.pendingInteractions.subscribe(() => {
1059
+ if (hasWaiting(readPending())) manualHold = false
1060
+ schedule()
1061
+ }),
1062
+ )
1063
+ }
1064
+ // Host-synced knobs change live: a disable stops the engine, any
1065
+ // other change re-runs the pass. No remount or page reload.
1066
+ for (const field of ['enabled', 'aggregate', 'initialSort']) {
1067
+ const ref = config?.[field]
1068
+ if (ref === undefined || ref === null || typeof ref.subscribe !== 'function') continue
1069
+ offs.push(
1070
+ ref.subscribe(() => {
1071
+ const before = settings.get()
1072
+ const next = readOptions(config)
1073
+ settings.set(next)
1074
+ if (next.enabled === false) {
1075
+ wanted = false
1076
+ forced = false
1077
+ if (timer !== undefined) clearTimeout(timer)
1078
+ timer = undefined
1079
+ return
1080
+ }
1081
+ if (!before.enabled || before.aggregate !== next.aggregate) {
1082
+ manualHold = false
1083
+ schedule()
1084
+ }
1085
+ }),
1086
+ )
1087
+ }
798
1088
  } catch (error) {
799
1089
  warn('could not follow the sidebar stores', error)
800
1090
  }
@@ -817,10 +1107,10 @@ function newestActivity(activity) {
817
1107
  /**
818
1108
  * One Workspace row: pin toggle, name, and its activity summary.
819
1109
  *
820
- * @param props - `{workspace, byId, pinned}` plus the resolved `t`.
1110
+ * @param props - `{workspace, byId, pending, pinned}` plus the resolved `t`.
821
1111
  * @returns the row element.
822
1112
  */
823
- function Row({ workspace, byId, pinned, tr }) {
1113
+ function Row({ workspace, byId, pending, pinned, tr }) {
824
1114
  const members = Array.isArray(workspace.sessionIds) ? workspace.sessionIds : []
825
1115
  let running = 0
826
1116
  let last = 0
@@ -830,6 +1120,7 @@ function newestActivity(activity) {
830
1120
  if (summary.running === true) running += 1
831
1121
  if (summary.blank !== true && typeof summary.updatedAt === 'number' && summary.updatedAt > last) last = summary.updatedAt
832
1122
  }
1123
+ const waiting = ownWaitingCount(workspace, pending)
833
1124
  const meta = members.length === 0 ? tr('idle') : tr('sessions', { n: members.length })
834
1125
  const when = last === 0 ? tr('never') : relativeTime(last, tr)
835
1126
  return h(
@@ -854,31 +1145,31 @@ function newestActivity(activity) {
854
1145
  h(PinIcon, { pinned }),
855
1146
  ),
856
1147
  h('span', { className: 'wss-name', title: workspace.path }, workspace.title || workspace.path),
1148
+ waiting > 0 ? h('span', { className: 'wss-tag' }, tr('waiting', { n: waiting })) : null,
857
1149
  running > 0 ? h('span', { className: 'wss-tag' }, tr('running', { n: running })) : null,
858
1150
  h('span', { className: 'wss-meta', title: when }, `${meta} · ${when}`),
859
1151
  )
860
1152
  }
861
1153
 
862
1154
  /** The panel: rules, a filter, and every Workspace in Host order. */
863
- function Panel() {
1155
+ function PanelContent() {
864
1156
  const [, tick] = React.useState(0)
865
1157
  React.useEffect(() => ctx.locale.subscribe(() => tick((n) => n + 1)), [])
866
1158
  const tr = t()
867
- const state = useStore(panel)
868
1159
  const statePrefs = useStore(prefs)
869
1160
  const capability = useStore(capabilities)
1161
+ const options = useStore(settings)
870
1162
  const workspaceSnapshot = useSnapshot(ctx.workspaces.list)
871
1163
  const sessionSnapshot = useSnapshot(ctx.sessions.list)
1164
+ const pendingSnapshot = useSnapshot(ctx.uiSession?.pendingInteractions ?? NO_PENDING)
872
1165
  const [filter, setFilter] = React.useState('')
873
1166
  React.useEffect(() => {
874
- if (!state.open) return undefined
875
1167
  const onKey = (event) => {
876
1168
  if (event.key === 'Escape') panel.set({ open: false })
877
1169
  }
878
1170
  window.addEventListener('keydown', onKey)
879
1171
  return () => window.removeEventListener('keydown', onKey)
880
- }, [state.open])
881
- if (!state.open) return null
1172
+ }, [])
882
1173
  const items = Array.isArray(workspaceSnapshot.items) ? workspaceSnapshot.items : []
883
1174
  const needle = filter.trim().toLowerCase()
884
1175
  const visible = needle.length === 0
@@ -947,6 +1238,7 @@ function newestActivity(activity) {
947
1238
  key: workspace.workspaceId,
948
1239
  workspace,
949
1240
  byId: sessionSnapshot.byId ?? {},
1241
+ pending: pendingSnapshot,
950
1242
  pinned: statePrefs.pins.includes(workspace.workspaceId),
951
1243
  tr,
952
1244
  }),
@@ -958,6 +1250,13 @@ function newestActivity(activity) {
958
1250
  )
959
1251
  }
960
1252
 
1253
+ /** Gate component: subscribes ONLY to `panel` while closed, preventing background store churn. */
1254
+ function Panel() {
1255
+ const state = useStore(panel)
1256
+ if (!state.open) return null
1257
+ return h(PanelContent, null)
1258
+ }
1259
+
961
1260
  /**
962
1261
  * The card on this bundle's page in the Plugins view, and the only entry
963
1262
  * point to the panel — the sidebar deliberately gets no footer icon.
@@ -966,6 +1265,8 @@ function newestActivity(activity) {
966
1265
  * client stores directly.
967
1266
  */
968
1267
  function BundleCard() {
1268
+ const [, tick] = React.useState(0)
1269
+ React.useEffect(() => ctx.locale.subscribe(() => tick((n) => n + 1)), [])
969
1270
  const tr = t()
970
1271
  const statePrefs = useStore(prefs)
971
1272
  const rules = []
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Workspace activity sort",
4
- "description": "Reorders the sidebar workspaces by their most recent human prompt, aggregating a container folder over its whole subtree, and writes the order to the host."
4
+ "description": "Reorders the sidebar workspaces by their most recent human prompt, puts workspaces waiting for your input first, aggregates a container folder over its whole subtree, and writes the order to the host."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "工作区按活动排序",
4
- "description": "按每个工作区最近一次人工提问的时间重排左侧工作区顺序;容器目录按整个子树汇总。顺序写入宿主,与拖拽得到的顺序等价。"
4
+ "description": "按每个工作区最近一次人工提问的时间重排左侧工作区顺序,正在等你输入的排最前;容器目录按整个子树汇总。顺序写入宿主,与拖拽得到的顺序等价。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cooper-zhuang/dsh-workspace-sort",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -29,8 +29,8 @@
29
29
  "test": "node --test test/*.test.mjs"
30
30
  },
31
31
  "engines": {
32
- "node": ">=20",
33
- "dsh": "^0.2.1-0 || ^0.2.2-0"
32
+ "node": ">=24",
33
+ "dsh": "^0.2.1-0 || ^0.2.2-0 || ^0.2.3-0"
34
34
  },
35
35
  "keywords": [
36
36
  "dsh",
@@ -61,5 +61,8 @@
61
61
  "@deepseek-ai/dsh-client-ui-session"
62
62
  ]
63
63
  }
64
+ },
65
+ "peerDependencies": {
66
+ "@deepseek-ai/schemastery": "^3.18.5"
64
67
  }
65
68
  }