@cooper-zhuang/dsh-workspace-sort 0.2.2 → 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.
Files changed (3) hide show
  1. package/index.js +25 -11
  2. package/lib/client.js +85 -18
  3. package/package.json +2 -5
package/index.js CHANGED
@@ -33,7 +33,8 @@
33
33
  * @module dsh-workspace-sort
34
34
  */
35
35
  import z from '@deepseek-ai/schemastery'
36
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
36
+ import { randomUUID } from 'node:crypto'
37
+ import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
37
38
  import { homedir } from 'node:os'
38
39
  import { dirname, join } from 'node:path'
39
40
 
@@ -147,7 +148,7 @@ export function apply(ctx, config = {}) {
147
148
  }
148
149
  if (request.method === 'GET' || request.method === 'HEAD') {
149
150
  await ready
150
- sendJson(response, 200, { ok: true, config: resolvedConfig(), prefs, lastReport })
151
+ sendJson(response, 200, { ok: true, config: resolvedConfig(), prefs, lastReport }, {}, request.method === 'HEAD')
151
152
  return
152
153
  }
153
154
  if (request.method !== 'POST') {
@@ -213,6 +214,7 @@ export function apply(ctx, config = {}) {
213
214
  }
214
215
  const next = sanitizePrefs(body)
215
216
  try {
217
+ await ready
216
218
  await writeStoredPrefs(next)
217
219
  } catch (error) {
218
220
  ctx.logger?.warn?.('dsh-workspace-sort: could not persist prefs: %o', error)
@@ -304,18 +306,30 @@ async function readStoredPrefs(logger) {
304
306
  }
305
307
  }
306
308
 
309
+ let writeQueue = Promise.resolve()
310
+
307
311
  /**
308
- * Write the prefs atomically (tmp file then rename).
312
+ * Write the prefs atomically (serialized unique tmp file then rename).
309
313
  *
310
314
  * @param prefs - the value to store.
311
315
  * @returns a promise that settles once the rename is durable.
312
316
  */
313
- async function writeStoredPrefs(prefs) {
314
- const file = prefsFile()
315
- await mkdir(dirname(file), { recursive: true })
316
- const tmp = `${file}.tmp`
317
- await writeFile(tmp, `${JSON.stringify(prefs, null, 1)}\n`, 'utf8')
318
- 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
319
333
  }
320
334
 
321
335
  /**
@@ -360,7 +374,7 @@ async function readJsonBody(request) {
360
374
  * @param {unknown} payload - JSON-serializable body.
361
375
  * @param {Record<string, string | string[]>} [headers] - extra headers.
362
376
  */
363
- function sendJson(response, status, payload, headers = {}) {
377
+ function sendJson(response, status, payload, headers = {}, headOnly = false) {
364
378
  const body = Buffer.from(JSON.stringify(payload), 'utf8')
365
379
  response.writeHead(status, {
366
380
  'content-type': 'application/json; charset=utf-8',
@@ -368,7 +382,7 @@ function sendJson(response, status, payload, headers = {}) {
368
382
  'cache-control': 'no-store',
369
383
  ...headers,
370
384
  })
371
- response.end(body)
385
+ response.end(headOnly ? undefined : body)
372
386
  }
373
387
 
374
388
  /**
package/lib/client.js CHANGED
@@ -81,14 +81,30 @@ window.__ModuleLoader__.load({
81
81
  * @param paths - absolute directories of every registered Workspace.
82
82
  * @returns the ancestor's registered path, or `undefined` for a root.
83
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
+
84
93
  function owningParent(path, paths) {
85
94
  if (typeof path !== 'string' || path.length === 0) return undefined
95
+ const normPath = normalizePathForMatch(path)
86
96
  let best
97
+ let bestLen = -1
87
98
  for (const candidate of paths) {
88
- if (typeof candidate !== 'string' || candidate === path) continue
89
- const prefix = candidate.endsWith('/') ? candidate : `${candidate}/`
90
- if (!path.startsWith(prefix)) continue
91
- 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
+ }
92
108
  }
93
109
  return best
94
110
  }
@@ -386,8 +402,9 @@ function newestActivity(activity) {
386
402
  */
387
403
 
388
404
  /** Stand-in when the shell did not mount `uiSession` (nothing can be waiting). */
405
+ const EMPTY_PENDING = new Map()
389
406
  const NO_PENDING = Object.freeze({
390
- getSnapshot: () => new Map(),
407
+ getSnapshot: () => EMPTY_PENDING,
391
408
  subscribe: () => () => {},
392
409
  })
393
410
 
@@ -666,6 +683,14 @@ function newestActivity(activity) {
666
683
  let busy = false
667
684
  /** The Workspace ids of the previous store emission (to see drags apart from add/remove). */
668
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
669
694
 
670
695
  const prefs = createStore({ ...DEFAULT_PREFS })
671
696
  /**
@@ -751,9 +776,17 @@ function newestActivity(activity) {
751
776
  * @param workspaceIds - the ids the Host currently reports.
752
777
  */
753
778
  const prunePins = (workspaceIds) => {
779
+ if (!hydrated || workspaceIds.length === 0) return
754
780
  const pins = prefs.get().pins
755
781
  const next = pins.filter((id) => workspaceIds.indexOf(id) !== -1)
756
- 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
+ }
757
790
  }
758
791
 
759
792
  /**
@@ -812,7 +845,7 @@ function newestActivity(activity) {
812
845
  */
813
846
  const pass = async (manual) => {
814
847
  const options = settings.get()
815
- if (disposed || options.enabled === false) return false
848
+ if (disposed || (!manual && options.enabled === false)) return false
816
849
  const items = readItems()
817
850
  if (items.length < 2) return false
818
851
  const byId = readSummaries()
@@ -844,6 +877,7 @@ function newestActivity(activity) {
844
877
  if (sameOrder(current, desired)) {
845
878
  sorted = true
846
879
  manualHold = false
880
+ consecutiveFailures = 0
847
881
  return false
848
882
  }
849
883
  if (!manual && sorted && manualHold) return false
@@ -851,16 +885,24 @@ function newestActivity(activity) {
851
885
  const moves = planMoves(current, desired)
852
886
  if (moves.length === 0) {
853
887
  sorted = true
888
+ consecutiveFailures = 0
854
889
  return false
855
890
  }
856
891
  for (const move of moves) {
857
892
  // A config change can stop the engine mid-pass; do not keep writing.
858
- if (disposed || settings.get().enabled === false) return false
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
+ }
859
900
  selfWriteAt = Date.now()
860
901
  await ctx.workspaces.insertBefore(move.id, move.before)
861
902
  }
862
903
  sorted = true
863
904
  manualHold = false
905
+ consecutiveFailures = 0
864
906
  report({ current, desired, moves, newest, waiting, manual: manual === true })
865
907
  return true
866
908
  }
@@ -880,6 +922,7 @@ function newestActivity(activity) {
880
922
  if (!wanted) break
881
923
  }
882
924
  } catch (error) {
925
+ consecutiveFailures += 1
883
926
  warn('reorder failed', error)
884
927
  } finally {
885
928
  busy = false
@@ -902,7 +945,10 @@ function newestActivity(activity) {
902
945
  * @param manual - true for a button press.
903
946
  */
904
947
  const request = (manual) => {
905
- if (manual) forced = true
948
+ if (manual) {
949
+ consecutiveFailures = 0
950
+ forced = true
951
+ }
906
952
  schedule(0)
907
953
  }
908
954
 
@@ -921,19 +967,27 @@ function newestActivity(activity) {
921
967
  const response = await fetch(STATE_ROUTE, { headers: { accept: 'application/json' } })
922
968
  body = response.ok ? await response.json() : undefined
923
969
  } catch (error) {
970
+ hydrated = true
924
971
  warn('host half unreachable; keeping pins in memory', error)
925
972
  return
926
973
  }
927
974
  if (body === undefined || body === null || body.ok !== true) {
975
+ hydrated = true
928
976
  warn('host half did not answer; keeping pins in memory')
929
977
  return
930
978
  }
931
979
  if (body.prefs !== undefined && body.prefs !== null) {
932
- prefs.set(sanitizePrefs(body.prefs))
980
+ hydrating = true
981
+ try {
982
+ prefs.set(sanitizePrefs(body.prefs))
983
+ } finally {
984
+ hydrating = false
985
+ }
933
986
  capabilities.set({ persist: true })
934
987
  }
988
+ hydrated = true
935
989
  report({ hello: true, options: settings.get() })
936
- if (settings.get().enabled && settings.get().initialSort) schedule(0)
990
+ if (settings.get().enabled && settings.get().initialSort && prefs.get().auto) schedule(0)
937
991
  }
938
992
 
939
993
  // ------------------------------------------------------------ styles
@@ -954,7 +1008,7 @@ function newestActivity(activity) {
954
1008
  ctx.effect(
955
1009
  () =>
956
1010
  prefs.subscribe(() => {
957
- if (capabilities.get().persist) savePrefs(prefs.get())
1011
+ if (!hydrating && capabilities.get().persist) savePrefs(prefs.get())
958
1012
  }),
959
1013
  'dsh-workspace-sort: prefs',
960
1014
  )
@@ -972,6 +1026,7 @@ function newestActivity(activity) {
972
1026
  const ids = readItems().map((workspace) => workspace.workspaceId)
973
1027
  const membershipChanged = ids.length !== knownIds.length || ids.some((id) => knownIds.indexOf(id) === -1)
974
1028
  const orderChanged = !membershipChanged && ids.some((id, index) => id !== knownIds[index])
1029
+ if (membershipChanged) consecutiveFailures = 0
975
1030
  if (orderChanged && sorted && Date.now() - selfWriteAt > SELF_WRITE_MS) manualHold = true
976
1031
  knownIds = ids
977
1032
  }),
@@ -983,11 +1038,17 @@ function newestActivity(activity) {
983
1038
  ctx.sessions.list.subscribe(() => {
984
1039
  const advanced = noteActivity()
985
1040
  if (advanced) manualHold = false
1041
+ if (consecutiveFailures >= 3) return
986
1042
  if (advanced || (!sorted && prefs.get().auto)) schedule()
987
1043
  }),
988
1044
  )
989
1045
  // A pin or a rule toggle changes the target order: re-sort at once.
990
- offs.push(prefs.subscribe(() => request(true)))
1046
+ offs.push(
1047
+ prefs.subscribe(() => {
1048
+ if (hydrating || pruningPins) return
1049
+ request(true)
1050
+ }),
1051
+ )
991
1052
  // The authoritative "waiting on you" source. Both entering and
992
1053
  // leaving the state re-sort; the debounce absorbs a request being
993
1054
  // replaced by the next one. A waiting Session outranks the user's
@@ -1091,11 +1152,10 @@ function newestActivity(activity) {
1091
1152
  }
1092
1153
 
1093
1154
  /** The panel: rules, a filter, and every Workspace in Host order. */
1094
- function Panel() {
1155
+ function PanelContent() {
1095
1156
  const [, tick] = React.useState(0)
1096
1157
  React.useEffect(() => ctx.locale.subscribe(() => tick((n) => n + 1)), [])
1097
1158
  const tr = t()
1098
- const state = useStore(panel)
1099
1159
  const statePrefs = useStore(prefs)
1100
1160
  const capability = useStore(capabilities)
1101
1161
  const options = useStore(settings)
@@ -1104,14 +1164,12 @@ function newestActivity(activity) {
1104
1164
  const pendingSnapshot = useSnapshot(ctx.uiSession?.pendingInteractions ?? NO_PENDING)
1105
1165
  const [filter, setFilter] = React.useState('')
1106
1166
  React.useEffect(() => {
1107
- if (!state.open) return undefined
1108
1167
  const onKey = (event) => {
1109
1168
  if (event.key === 'Escape') panel.set({ open: false })
1110
1169
  }
1111
1170
  window.addEventListener('keydown', onKey)
1112
1171
  return () => window.removeEventListener('keydown', onKey)
1113
- }, [state.open])
1114
- if (!state.open) return null
1172
+ }, [])
1115
1173
  const items = Array.isArray(workspaceSnapshot.items) ? workspaceSnapshot.items : []
1116
1174
  const needle = filter.trim().toLowerCase()
1117
1175
  const visible = needle.length === 0
@@ -1192,6 +1250,13 @@ function newestActivity(activity) {
1192
1250
  )
1193
1251
  }
1194
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
+
1195
1260
  /**
1196
1261
  * The card on this bundle's page in the Plugins view, and the only entry
1197
1262
  * point to the panel — the sidebar deliberately gets no footer icon.
@@ -1200,6 +1265,8 @@ function newestActivity(activity) {
1200
1265
  * client stores directly.
1201
1266
  */
1202
1267
  function BundleCard() {
1268
+ const [, tick] = React.useState(0)
1269
+ React.useEffect(() => ctx.locale.subscribe(() => tick((n) => n + 1)), [])
1203
1270
  const tr = t()
1204
1271
  const statePrefs = useStore(prefs)
1205
1272
  const rules = []
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cooper-zhuang/dsh-workspace-sort",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -29,7 +29,7 @@
29
29
  "test": "node --test test/*.test.mjs"
30
30
  },
31
31
  "engines": {
32
- "node": ">=20",
32
+ "node": ">=24",
33
33
  "dsh": "^0.2.1-0 || ^0.2.2-0 || ^0.2.3-0"
34
34
  },
35
35
  "keywords": [
@@ -62,9 +62,6 @@
62
62
  ]
63
63
  }
64
64
  },
65
- "dependencies": {
66
- "@deepseek-ai/schemastery": "^3.18.5"
67
- },
68
65
  "peerDependencies": {
69
66
  "@deepseek-ai/schemastery": "^3.18.5"
70
67
  }