@jxgame2020/dsh-token-quota 0.1.50 → 0.1.52

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.
@@ -0,0 +1,9 @@
1
+ # Composition bundle for @jxgame2020/dsh-token-quota.
2
+ #
3
+ # The Harness plugin manager installs a package only when it declares
4
+ # `dsh.bundle` and ships this patch: the patch is what actually mounts the
5
+ # plugin into the profile's loader tree. Installing the package alone puts the
6
+ # code in node_modules; this row is what makes the Harness load it.
7
+ - insert:
8
+ - id: token-quota
9
+ name: '@jxgame2020/dsh-token-quota'
package/lib/client.js CHANGED
@@ -132,7 +132,7 @@ window.__ModuleLoader__.load({
132
132
  d.transcribe = settings;
133
133
  },
134
134
  setUpgrade: (d, upgrade) => {
135
- const normalized = upgrade !== null && upgrade.latestVersion !== "" && upgrade.latestVersion !== "0.1.50" ? upgrade : null;
135
+ const normalized = upgrade !== null && upgrade.latestVersion !== "" && upgrade.latestVersion !== "0.1.52" ? upgrade : null;
136
136
  if (d.upgrade === null || d.upgrade.latestVersion !== normalized?.latestVersion) d.upgradeDismissed = false;
137
137
  d.upgrade = normalized;
138
138
  },
@@ -262,147 +262,147 @@ window.__ModuleLoader__.load({
262
262
  document.head.appendChild(tag);
263
263
  }
264
264
  var TokenQuotaPanel_module_css_default = {
265
- "controls": "NPLLIq_controls",
266
- "noteWinResize": "NPLLIq_noteWinResize",
267
- "balanceRefreshAll": "NPLLIq_balanceRefreshAll",
268
- "logClearDate": "NPLLIq_logClearDate",
265
+ "balanceBarDim": "NPLLIq_balanceBarDim",
266
+ "logPageSizeSelect": "NPLLIq_logPageSizeSelect",
267
+ "upgradeBannerFlash": "NPLLIq_upgradeBannerFlash",
268
+ "rowDragging": "NPLLIq_rowDragging",
269
+ "noteWin": "NPLLIq_noteWin",
270
+ "row": "NPLLIq_row",
271
+ "balanceBarBadge": "NPLLIq_balanceBarBadge",
272
+ "fullNotice": "NPLLIq_fullNotice",
273
+ "tabIcon": "NPLLIq_tabIcon",
274
+ "upgradeBanner": "NPLLIq_upgradeBanner",
275
+ "logSearch": "NPLLIq_logSearch",
276
+ "resetRow": "NPLLIq_resetRow",
277
+ "noteWinTitle": "NPLLIq_noteWinTitle",
278
+ "balanceToggleOpen": "NPLLIq_balanceToggleOpen",
269
279
  "balanceBarError": "NPLLIq_balanceBarError",
270
- "logClearBtn": "NPLLIq_logClearBtn",
271
- "version": "NPLLIq_version",
272
- "balanceWinBody": "NPLLIq_balanceWinBody",
273
280
  "balanceValueError": "NPLLIq_balanceValueError",
274
- "gearBtn": "NPLLIq_gearBtn",
275
- "settingsBtn": "NPLLIq_settingsBtn",
281
+ "monitorList": "NPLLIq_monitorList",
282
+ "noteChip": "NPLLIq_noteChip",
283
+ "rowName": "NPLLIq_rowName",
284
+ "balanceLastLine": "NPLLIq_balanceLastLine",
285
+ "dialogSection": "NPLLIq_dialogSection",
286
+ "balanceWinTitle": "NPLLIq_balanceWinTitle",
287
+ "logClearDate": "NPLLIq_logClearDate",
288
+ "rowDropTarget": "NPLLIq_rowDropTarget",
289
+ "dialogTabs": "NPLLIq_dialogTabs",
276
290
  "rowDrag": "NPLLIq_rowDrag",
277
- "upgradeBanner": "NPLLIq_upgradeBanner",
278
- "balanceSortBtn": "NPLLIq_balanceSortBtn",
279
- "logPagerInfo": "NPLLIq_logPagerInfo",
280
- "noteNewPlus": "NPLLIq_noteNewPlus",
291
+ "logDayCol": "NPLLIq_logDayCol",
292
+ "monitorRow": "NPLLIq_monitorRow",
293
+ "keyRow": "NPLLIq_keyRow",
294
+ "title": "NPLLIq_title",
281
295
  "fillIdle": "NPLLIq_fillIdle",
282
- "balanceBarLow": "NPLLIq_balanceBarLow",
283
- "upgradeHint": "NPLLIq_upgradeHint",
284
- "notesBar": "NPLLIq_notesBar",
285
- "noteWinBtn": "NPLLIq_noteWinBtn",
286
- "balanceWinHeader": "NPLLIq_balanceWinHeader",
287
296
  "header": "NPLLIq_header",
288
- "balanceRowName": "NPLLIq_balanceRowName",
289
- "balanceWin": "NPLLIq_balanceWin",
290
- "balanceBarBadge": "NPLLIq_balanceBarBadge",
291
- "dialogBtnPrimary": "NPLLIq_dialogBtnPrimary",
292
- "body": "NPLLIq_body",
293
297
  "noteWinBar": "NPLLIq_noteWinBar",
294
- "balanceRowValue": "NPLLIq_balanceRowValue",
295
- "fillWarn": "NPLLIq_fillWarn",
296
- "fullNotice": "NPLLIq_fullNotice",
297
- "logDialog": "NPLLIq_logDialog",
298
- "balanceBarDim": "NPLLIq_balanceBarDim",
299
- "panelDimStrong": "NPLLIq_panelDimStrong",
300
- "logPageSizeSelect": "NPLLIq_logPageSizeSelect",
301
- "dialogHeader": "NPLLIq_dialogHeader",
302
- "balanceLastLine": "NPLLIq_balanceLastLine",
303
- "notice": "NPLLIq_notice",
304
- "checkUpdatesLabel": "NPLLIq_checkUpdatesLabel",
305
- "balanceBarRefresh": "NPLLIq_balanceBarRefresh",
306
- "upgradeBannerText": "NPLLIq_upgradeBannerText",
307
- "selectBtn": "NPLLIq_selectBtn",
308
298
  "balanceRow": "NPLLIq_balanceRow",
309
- "monitorName": "NPLLIq_monitorName",
310
- "dialog": "NPLLIq_dialog",
311
- "logToolbar": "NPLLIq_logToolbar",
312
299
  "checkErrorHint": "NPLLIq_checkErrorHint",
313
- "logPagerBtn": "NPLLIq_logPagerBtn",
314
- "dialogHint": "NPLLIq_dialogHint",
315
- "fillOver": "NPLLIq_fillOver",
316
- "headerText": "NPLLIq_headerText",
317
- "balanceToggleOpen": "NPLLIq_balanceToggleOpen",
318
- "balanceStateError": "NPLLIq_balanceStateError",
319
- "upgradeCommandRow": "NPLLIq_upgradeCommandRow",
320
- "dialogOverlay": "NPLLIq_dialogOverlay",
321
- "panel": "NPLLIq_panel",
322
- "keyBadgeOk": "NPLLIq_keyBadgeOk",
323
- "noticeError": "NPLLIq_noticeError",
300
+ "dialogLabel": "NPLLIq_dialogLabel",
301
+ "monitorHint": "NPLLIq_monitorHint",
324
302
  "collapse": "NPLLIq_collapse",
325
- "noteChip": "NPLLIq_noteChip",
326
- "balanceWinTitle": "NPLLIq_balanceWinTitle",
327
- "dialogTab": "NPLLIq_dialogTab",
328
- "dialogTabActive": "NPLLIq_dialogTabActive",
303
+ "dialogClose": "NPLLIq_dialogClose",
329
304
  "keyBadgeOff": "NPLLIq_keyBadgeOff",
330
- "tabLabel": "NPLLIq_tabLabel",
331
- "rowDragging": "NPLLIq_rowDragging",
332
- "settingsDialog": "NPLLIq_settingsDialog",
333
- "balanceValueOk": "NPLLIq_balanceValueOk",
334
- "dialogTabs": "NPLLIq_dialogTabs",
335
- "balanceStateHint": "NPLLIq_balanceStateHint",
336
- "keyRow": "NPLLIq_keyRow",
337
- "keyError": "NPLLIq_keyError",
305
+ "balanceValueLow": "NPLLIq_balanceValueLow",
338
306
  "checkUpdatesRow": "NPLLIq_checkUpdatesRow",
339
- "radioRow": "NPLLIq_radioRow",
340
- "logModelCol": "NPLLIq_logModelCol",
341
- "logUsedCol": "NPLLIq_logUsedCol",
342
- "tab": "NPLLIq_tab",
343
- "currentBadge": "NPLLIq_currentBadge",
307
+ "balanceToggle": "NPLLIq_balanceToggle",
344
308
  "checkBtn": "NPLLIq_checkBtn",
309
+ "fillOver": "NPLLIq_fillOver",
310
+ "balanceBar": "NPLLIq_balanceBar",
311
+ "balanceValueOk": "NPLLIq_balanceValueOk",
312
+ "upgradeCommandRow": "NPLLIq_upgradeCommandRow",
313
+ "upgradeClose": "NPLLIq_upgradeClose",
314
+ "dialogBtn": "NPLLIq_dialogBtn",
315
+ "logPagerControls": "NPLLIq_logPagerControls",
316
+ "tabLabel": "NPLLIq_tabLabel",
317
+ "noteWinGripBar": "NPLLIq_noteWinGripBar",
345
318
  "noteWinCollapsed": "NPLLIq_noteWinCollapsed",
346
- "logSearch": "NPLLIq_logSearch",
319
+ "upgradeHint": "NPLLIq_upgradeHint",
320
+ "controls": "NPLLIq_controls",
321
+ "dialog": "NPLLIq_dialog",
322
+ "upgradeBannerText": "NPLLIq_upgradeBannerText",
323
+ "logModelCol": "NPLLIq_logModelCol",
324
+ "balanceRefreshAll": "NPLLIq_balanceRefreshAll",
325
+ "logPagerPages": "NPLLIq_logPagerPages",
326
+ "logClearDialog": "NPLLIq_logClearDialog",
347
327
  "panelDim": "NPLLIq_panelDim",
348
- "noteWinTitle": "NPLLIq_noteWinTitle",
328
+ "body": "NPLLIq_body",
329
+ "settingsDialog": "NPLLIq_settingsDialog",
330
+ "logPagerBtn": "NPLLIq_logPagerBtn",
331
+ "noteWinResize": "NPLLIq_noteWinResize",
332
+ "versionNew": "NPLLIq_versionNew",
333
+ "logDialog": "NPLLIq_logDialog",
334
+ "panel": "NPLLIq_panel",
335
+ "noteNewPlus": "NPLLIq_noteNewPlus",
336
+ "balanceBarRefresh": "NPLLIq_balanceBarRefresh",
337
+ "balanceWin": "NPLLIq_balanceWin",
338
+ "gearBtn": "NPLLIq_gearBtn",
339
+ "logHeader": "NPLLIq_logHeader",
340
+ "keyBadgeOk": "NPLLIq_keyBadgeOk",
341
+ "logPagerInfo": "NPLLIq_logPagerInfo",
342
+ "input": "NPLLIq_input",
343
+ "keyError": "NPLLIq_keyError",
344
+ "keySaveBtn": "NPLLIq_keySaveBtn",
345
+ "noticeError": "NPLLIq_noticeError",
349
346
  "subtitle": "NPLLIq_subtitle",
350
347
  "noteMenu": "NPLLIq_noteMenu",
351
- "tabIcon": "NPLLIq_tabIcon",
348
+ "fillWarn": "NPLLIq_fillWarn",
349
+ "noteWinBtn": "NPLLIq_noteWinBtn",
350
+ "logToolbar": "NPLLIq_logToolbar",
351
+ "copyBtn": "NPLLIq_copyBtn",
352
+ "version": "NPLLIq_version",
353
+ "dialogTab": "NPLLIq_dialogTab",
354
+ "logTable": "NPLLIq_logTable",
355
+ "tab": "NPLLIq_tab",
356
+ "save": "NPLLIq_save",
357
+ "settingsBtn": "NPLLIq_settingsBtn",
358
+ "balanceRowName": "NPLLIq_balanceRowName",
359
+ "noteMenuItem": "NPLLIq_noteMenuItem",
360
+ "dialogHint": "NPLLIq_dialogHint",
361
+ "noteNew": "NPLLIq_noteNew",
362
+ "currentBadge": "NPLLIq_currentBadge",
352
363
  "upgradeCommand": "NPLLIq_upgradeCommand",
353
- "resetSelect": "NPLLIq_resetSelect",
364
+ "upgradeCommands": "NPLLIq_upgradeCommands",
365
+ "checkUpdatesLabel": "NPLLIq_checkUpdatesLabel",
354
366
  "noteChipOpen": "NPLLIq_noteChipOpen",
355
- "bar": "NPLLIq_bar",
356
- "switch": "NPLLIq_switch",
367
+ "dialogBody": "NPLLIq_dialogBody",
368
+ "balanceRowRefresh": "NPLLIq_balanceRowRefresh",
357
369
  "balanceRowHeader": "NPLLIq_balanceRowHeader",
358
- "logPagerPages": "NPLLIq_logPagerPages",
359
- "logScroll": "NPLLIq_logScroll",
360
- "title": "NPLLIq_title",
361
- "rowName": "NPLLIq_rowName",
362
370
  "headerActions": "NPLLIq_headerActions",
363
- "rowMeta": "NPLLIq_rowMeta",
364
- "dialogBody": "NPLLIq_dialogBody",
365
- "upgradeBannerFlash": "NPLLIq_upgradeBannerFlash",
371
+ "headerText": "NPLLIq_headerText",
372
+ "dialogOverlay": "NPLLIq_dialogOverlay",
373
+ "resetSelect": "NPLLIq_resetSelect",
374
+ "notice": "NPLLIq_notice",
375
+ "selectBtn": "NPLLIq_selectBtn",
376
+ "noteMenuBackdrop": "NPLLIq_noteMenuBackdrop",
366
377
  "balanceBarText": "NPLLIq_balanceBarText",
367
- "dialogClose": "NPLLIq_dialogClose",
368
- "noteWin": "NPLLIq_noteWin",
369
- "upgradeClose": "NPLLIq_upgradeClose",
370
- "copyBtn": "NPLLIq_copyBtn",
371
- "dialogActions": "NPLLIq_dialogActions",
372
- "dialogLabel": "NPLLIq_dialogLabel",
373
- "noteWinTitleText": "NPLLIq_noteWinTitleText",
374
- "upgradeCommands": "NPLLIq_upgradeCommands",
378
+ "panelDimStrong": "NPLLIq_panelDimStrong",
379
+ "logPager": "NPLLIq_logPager",
380
+ "monitorName": "NPLLIq_monitorName",
381
+ "balanceSortBtn": "NPLLIq_balanceSortBtn",
382
+ "balanceBarLow": "NPLLIq_balanceBarLow",
383
+ "dialogHeader": "NPLLIq_dialogHeader",
384
+ "logScroll": "NPLLIq_logScroll",
385
+ "notesBar": "NPLLIq_notesBar",
386
+ "balanceWinBody": "NPLLIq_balanceWinBody",
387
+ "dialogTitle": "NPLLIq_dialogTitle",
388
+ "logUsedCol": "NPLLIq_logUsedCol",
389
+ "logClearBtn": "NPLLIq_logClearBtn",
390
+ "rowMeta": "NPLLIq_rowMeta",
391
+ "radioRow": "NPLLIq_radioRow",
392
+ "balanceStateError": "NPLLIq_balanceStateError",
393
+ "dialogBtnPrimary": "NPLLIq_dialogBtnPrimary",
375
394
  "copyBtnDone": "NPLLIq_copyBtnDone",
376
- "resetRow": "NPLLIq_resetRow",
377
- "noteWinGripBar": "NPLLIq_noteWinGripBar",
378
- "dialogBtn": "NPLLIq_dialogBtn",
379
- "logPagerControls": "NPLLIq_logPagerControls",
380
- "input": "NPLLIq_input",
381
- "logDayCol": "NPLLIq_logDayCol",
382
- "logClearDialog": "NPLLIq_logClearDialog",
383
- "rowDropTarget": "NPLLIq_rowDropTarget",
395
+ "settingsBtnActive": "NPLLIq_settingsBtnActive",
396
+ "switch": "NPLLIq_switch",
384
397
  "rowHeader": "NPLLIq_rowHeader",
385
- "dialogTitle": "NPLLIq_dialogTitle",
386
- "dialogSection": "NPLLIq_dialogSection",
398
+ "balanceRowValue": "NPLLIq_balanceRowValue",
399
+ "balanceStateHint": "NPLLIq_balanceStateHint",
400
+ "dialogTabActive": "NPLLIq_dialogTabActive",
387
401
  "noteWinText": "NPLLIq_noteWinText",
388
- "noteMenuBackdrop": "NPLLIq_noteMenuBackdrop",
389
- "balanceToggle": "NPLLIq_balanceToggle",
390
- "save": "NPLLIq_save",
391
- "row": "NPLLIq_row",
392
- "logTable": "NPLLIq_logTable",
393
- "monitorList": "NPLLIq_monitorList",
394
- "noteMenuItem": "NPLLIq_noteMenuItem",
395
- "monitorHint": "NPLLIq_monitorHint",
396
- "balanceBar": "NPLLIq_balanceBar",
397
- "logHeader": "NPLLIq_logHeader",
398
- "logPager": "NPLLIq_logPager",
399
- "balanceRowRefresh": "NPLLIq_balanceRowRefresh",
400
- "keySaveBtn": "NPLLIq_keySaveBtn",
401
- "balanceValueLow": "NPLLIq_balanceValueLow",
402
- "versionNew": "NPLLIq_versionNew",
403
- "noteNew": "NPLLIq_noteNew",
404
- "settingsBtnActive": "NPLLIq_settingsBtnActive",
405
- "monitorRow": "NPLLIq_monitorRow"
402
+ "dialogActions": "NPLLIq_dialogActions",
403
+ "balanceWinHeader": "NPLLIq_balanceWinHeader",
404
+ "noteWinTitleText": "NPLLIq_noteWinTitleText",
405
+ "bar": "NPLLIq_bar"
406
406
  };
407
407
  //#endregion
408
408
  //#region lib/types/client/TokenQuotaPanel.js
@@ -701,7 +701,9 @@ window.__ModuleLoader__.load({
701
701
  window.localStorage.setItem(PANEL_POS_KEY, JSON.stringify(pos));
702
702
  } catch {}
703
703
  };
704
- const sessionId = useSessions((s) => s.current);
704
+ const sessionId = useSessions((state) => {
705
+ for (const session of Object.values(state.byId)) if ((session.retainedBy.mainView ?? 0) > 0) return session.id;
706
+ });
705
707
  const snapshot = useStore((s) => s.snapshot);
706
708
  const groups = useStore((s) => s.groups);
707
709
  const current = useStore((s) => s.current);
@@ -1137,13 +1139,13 @@ window.__ModuleLoader__.load({
1137
1139
  title: t("upgradeAvailableHint"),
1138
1140
  children: [
1139
1141
  "v",
1140
- "0.1.50",
1142
+ "0.1.52",
1141
1143
  " → v",
1142
1144
  upgrade.latestVersion
1143
1145
  ]
1144
1146
  }) : (0, react_jsx_runtime.jsxs)("span", {
1145
1147
  className: TokenQuotaPanel_module_css_default.version,
1146
- children: ["v", "0.1.50"]
1148
+ children: ["v", "0.1.52"]
1147
1149
  })]
1148
1150
  })
1149
1151
  }),
@@ -3003,12 +3005,12 @@ window.__ModuleLoader__.load({
3003
3005
  document.head.appendChild(tag);
3004
3006
  }
3005
3007
  var mic_module_css_default = {
3008
+ "micErr": "KCoVpa_micErr",
3009
+ "micBtn": "KCoVpa_micBtn",
3010
+ "micErrTip": "KCoVpa_micErrTip",
3006
3011
  "micWrap": "KCoVpa_micWrap",
3007
3012
  "micRec": "KCoVpa_micRec",
3008
- "micErrTip": "KCoVpa_micErrTip",
3009
- "micErr": "KCoVpa_micErr",
3010
3013
  "micPulse": "KCoVpa_micPulse",
3011
- "micBtn": "KCoVpa_micBtn",
3012
3014
  "micBusy": "KCoVpa_micBusy"
3013
3015
  };
3014
3016
  //#endregion
@@ -3203,12 +3205,12 @@ window.__ModuleLoader__.load({
3203
3205
  document.head.appendChild(tag);
3204
3206
  }
3205
3207
  var TokenQuotaStash_module_css_default = {
3206
- "stashChip": "x_tEcG_stashChip",
3208
+ "selPopup": "x_tEcG_selPopup",
3207
3209
  "stashRow": "x_tEcG_stashRow",
3208
3210
  "selDivider": "x_tEcG_selDivider",
3209
- "selPopup": "x_tEcG_selPopup",
3210
3211
  "selBtn": "x_tEcG_selBtn",
3211
- "stashTip": "x_tEcG_stashTip"
3212
+ "stashTip": "x_tEcG_stashTip",
3213
+ "stashChip": "x_tEcG_stashChip"
3212
3214
  };
3213
3215
  //#endregion
3214
3216
  //#region lib/types/client/TokenQuotaStash.js
@@ -3822,8 +3824,8 @@ window.__ModuleLoader__.load({
3822
3824
  "slots",
3823
3825
  "sessions",
3824
3826
  "locale",
3825
- "settingsScope",
3826
3827
  "remote",
3828
+ "remote.settings",
3827
3829
  "remote.session",
3828
3830
  "remote.credentials"
3829
3831
  ];
@@ -3839,7 +3841,59 @@ window.__ModuleLoader__.load({
3839
3841
  en
3840
3842
  }), "token-quota-ui: panel dictionaries");
3841
3843
  const t = ctx.locale.bind(NS);
3842
- const scope = ctx.settingsScope.bind({ namespace: TOKEN_QUOTA_NAMESPACE });
3844
+ let settingsValue;
3845
+ let settingsRevision;
3846
+ /** Re-read the token-quota namespace from the Host. */
3847
+ const readSettings = async () => {
3848
+ try {
3849
+ const response = await ctx.remote.settings.describe();
3850
+ if (!response.ok) return settingsValue;
3851
+ const view = response.value.namespaces.find((entry) => entry.ns === TOKEN_QUOTA_NAMESPACE);
3852
+ if (view !== void 0) {
3853
+ settingsRevision = view.revision;
3854
+ settingsValue = view.value;
3855
+ }
3856
+ return settingsValue;
3857
+ } catch {
3858
+ return settingsValue;
3859
+ }
3860
+ };
3861
+ /**
3862
+ * Write one path of the namespace. Path ops avoid the read-modify-write race
3863
+ * a whole-object update would introduce (two editors, one section each), and
3864
+ * a stale revision is retried once against a fresh read instead of dropping
3865
+ * the change.
3866
+ */
3867
+ const writeSetting = (path, value) => {
3868
+ (async () => {
3869
+ const op = value === void 0 ? {
3870
+ op: "unset",
3871
+ path
3872
+ } : {
3873
+ op: "set",
3874
+ path,
3875
+ value
3876
+ };
3877
+ try {
3878
+ let response = await ctx.remote.settings.mutate(TOKEN_QUOTA_NAMESPACE, [op], settingsRevision);
3879
+ if (!response.ok) {
3880
+ await readSettings();
3881
+ response = await ctx.remote.settings.mutate(TOKEN_QUOTA_NAMESPACE, [op], settingsRevision);
3882
+ }
3883
+ if (response.ok) {
3884
+ settingsRevision = response.value.revision;
3885
+ settingsValue = response.value.value;
3886
+ }
3887
+ } catch {}
3888
+ })();
3889
+ };
3890
+ const scope = {
3891
+ getSnapshot: () => ({ value: settingsValue }),
3892
+ set: (key, value) => {
3893
+ writeSetting([key], value);
3894
+ return Promise.resolve();
3895
+ }
3896
+ };
3843
3897
  const sessions = ctx.get("sessions");
3844
3898
  const store = createTokenQuotaPanelStore();
3845
3899
  let bound;
@@ -4041,7 +4095,11 @@ window.__ModuleLoader__.load({
4041
4095
  }, () => {});
4042
4096
  };
4043
4097
  const pull = () => {
4098
+ pullOnce();
4099
+ };
4100
+ const pullOnce = async () => {
4044
4101
  pullCount += 1;
4102
+ await readSettings();
4045
4103
  const doc = scope.getSnapshot().value;
4046
4104
  lastMonitored = doc?.monitored !== void 0 && doc.monitored.length > 0 ? doc.monitored : null;
4047
4105
  const rawOnFull = doc?.onFull ?? "stop";
@@ -4115,11 +4173,7 @@ window.__ModuleLoader__.load({
4115
4173
  });
4116
4174
  };
4117
4175
  const setLimit = (key, limit) => {
4118
- const current = scope.getSnapshot().value?.limits ?? {};
4119
- scope.set("limits", {
4120
- ...current,
4121
- [key]: limit
4122
- });
4176
+ writeSetting(["limits", key], limit);
4123
4177
  };
4124
4178
  const setMonitored = (monitored) => {
4125
4179
  lastMonitored = monitored;
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { assertTokenQuotaLimit, splitTokenQuotaKey } from "./invariant.js";
1
+ import { splitTokenQuotaKey } from "./invariant.js";
2
2
  import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
@@ -7,20 +7,6 @@ import z from "@deepseek-ai/schemastery";
7
7
  import "@deepseek-ai/dsh-agent";
8
8
  import { LlmError } from "@deepseek-ai/dsh-llm";
9
9
  //#region lib/types/types.js
10
- /**
11
- * Shared wire/type vocabulary for the daily token-quota plugin.
12
- *
13
- * The Host half owns the durable per-model daily counter and the enforcement
14
- * gate; the browser half renders a floating panel from the snapshot it pulls
15
- * over a plugin-owned HTTP route, and writes per-model limits and panel
16
- * preferences through the settings document. This module is the one meeting
17
- * point of the two planes: it carries strings and shapes only, never a
18
- * runtime import from the other half.
19
- *
20
- * @module @jxgame2020/dsh-token-quota/types
21
- */
22
- /** Settings namespace owning the per-model daily limits document. */
23
- const TOKEN_QUOTA_NAMESPACE = "token-quota";
24
10
  /** Stable machine code thrown from `agent/request` when a model is over its daily cap. */
25
11
  const TOKEN_QUOTA_EXCEEDED_CODE = "TOKEN_QUOTA_EXCEEDED";
26
12
  const TOKEN_QUOTA_DEFAULT_BALANCE = {
@@ -213,7 +199,7 @@ function isNewer(latest, current) {
213
199
  return false;
214
200
  }
215
201
  /** Settings schema resolving the per-model daily caps document. */
216
- const TOKEN_QUOTA_SETTINGS_SCHEMA = z.object({
202
+ const TOKEN_QUOTA_SETTINGS_FIELDS = {
217
203
  limits: z.dict(z.number().step(1).min(0)).default({}),
218
204
  monitored: z.array(z.string()).default([]),
219
205
  onFull: z.union([
@@ -257,7 +243,7 @@ const TOKEN_QUOTA_SETTINGS_SCHEMA = z.object({
257
243
  apiKeyEnv: z.string().default(TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv),
258
244
  model: z.string().default(TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model)
259
245
  }).default({ ...TOKEN_QUOTA_DEFAULT_TRANSCRIBE })
260
- });
246
+ };
261
247
  /** Two-digit zero-pad helper. */
262
248
  function pad2(value) {
263
249
  return String(value).padStart(2, "0");
@@ -360,7 +346,10 @@ function parseTeamorouterBalance(data) {
360
346
  };
361
347
  }
362
348
  var TokenQuotaService = class TokenQuotaService extends Service {
363
- static Config = z.object({ storagePath: z.string().default("") });
349
+ static Config = z.object({
350
+ storagePath: z.string().default(""),
351
+ ...TOKEN_QUOTA_SETTINGS_FIELDS
352
+ });
364
353
  storagePath;
365
354
  reset = {
366
355
  offsetHours: localOffsetHours(),
@@ -372,7 +361,8 @@ var TokenQuotaService = class TokenQuotaService extends Service {
372
361
  history = {};
373
362
  limits = {};
374
363
  monitored = void 0;
375
- settingsSource = () => ({
364
+ /** Settings resolved from this plugin entry's own config (see applySettings). */
365
+ resolvedSettings = {
376
366
  limits: {},
377
367
  monitored: [],
378
368
  onFull: "stop",
@@ -383,7 +373,66 @@ var TokenQuotaService = class TokenQuotaService extends Service {
383
373
  notes: [],
384
374
  balance: { ...TOKEN_QUOTA_DEFAULT_BALANCE },
385
375
  transcribe: { ...TOKEN_QUOTA_DEFAULT_TRANSCRIBE }
386
- });
376
+ };
377
+ /** The settings document this instance runs with. */
378
+ settingsSource = () => this.resolvedSettings;
379
+ /**
380
+ * Normalize this entry's config into the plugin's settings shape and apply
381
+ * it. Called once per instantiation: a settings write from the panel reloads
382
+ * the entry, so this is the live-apply path that used to be an onChange
383
+ * callback.
384
+ * @param config - the plugin entry config (Config schema, defaults applied).
385
+ */
386
+ applySettings(config) {
387
+ const doc = config;
388
+ const settings = {
389
+ limits: doc.limits ?? {},
390
+ monitored: doc.monitored ?? [],
391
+ onFull: doc.onFull === "switchPriority" ? "switchAll" : doc.onFull ?? "stop",
392
+ checkUpdates: doc.checkUpdates ?? true,
393
+ dimWhenIdle: doc.dimWhenIdle ?? false,
394
+ order: Array.isArray(doc.order) ? doc.order : [],
395
+ balance: {
396
+ enabled: doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled,
397
+ pollMinutes: typeof doc.balance?.pollMinutes === "number" ? Math.max(1, Math.min(120, Math.round(doc.balance.pollMinutes))) : TOKEN_QUOTA_DEFAULT_BALANCE.pollMinutes
398
+ },
399
+ transcribe: {
400
+ enabled: doc.transcribe?.enabled ?? TOKEN_QUOTA_DEFAULT_TRANSCRIBE.enabled,
401
+ baseURL: typeof doc.transcribe?.baseURL === "string" && doc.transcribe.baseURL !== "" ? doc.transcribe.baseURL.replace(/\/+$/, "") : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.baseURL,
402
+ apiKeyEnv: typeof doc.transcribe?.apiKeyEnv === "string" && doc.transcribe.apiKeyEnv !== "" ? doc.transcribe.apiKeyEnv : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv,
403
+ model: typeof doc.transcribe?.model === "string" && doc.transcribe.model !== "" ? doc.transcribe.model : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model
404
+ },
405
+ music: {
406
+ enabled: doc.music?.enabled ?? TOKEN_QUOTA_DEFAULT_MUSIC.enabled,
407
+ volume: doc.music?.volume ?? TOKEN_QUOTA_DEFAULT_MUSIC.volume,
408
+ style: doc.music?.style ?? TOKEN_QUOTA_DEFAULT_MUSIC.style,
409
+ onlyCurrentSession: doc.music?.onlyCurrentSession ?? TOKEN_QUOTA_DEFAULT_MUSIC.onlyCurrentSession
410
+ },
411
+ notes: Array.isArray(doc.notes) ? doc.notes.slice(0, 5) : [],
412
+ ...doc.reset !== void 0 && doc.reset !== null ? { reset: doc.reset } : {}
413
+ };
414
+ this.resolvedSettings = settings;
415
+ this.limits = { ...settings.limits };
416
+ this.monitored = settings.monitored.length > 0 ? new Set(settings.monitored) : void 0;
417
+ this.checkUpdates = settings.checkUpdates;
418
+ const balanceEnabled = settings.balance.enabled;
419
+ const turnedOn = balanceEnabled && !this.balanceEnabled;
420
+ this.balanceEnabled = balanceEnabled;
421
+ if (!balanceEnabled) this.balances.clear();
422
+ const configured = settings.reset;
423
+ if (configured !== void 0 && typeof configured === "object" && configured !== null && typeof configured.offsetHours === "number" && typeof configured.hour === "number" && typeof configured.minute === "number") this.reset = {
424
+ offsetHours: Math.max(-12, Math.min(14, Math.round(configured.offsetHours))),
425
+ hour: Math.max(0, Math.min(23, Math.round(configured.hour))),
426
+ minute: Math.max(0, Math.min(59, Math.round(configured.minute)))
427
+ };
428
+ else this.reset = {
429
+ offsetHours: localOffsetHours(),
430
+ hour: 0,
431
+ minute: 0
432
+ };
433
+ this.rollCycleIfNeeded();
434
+ if (turnedOn) this.refreshAllBalances();
435
+ }
387
436
  /** Whether update checks are enabled (mirrors the settings document). */
388
437
  checkUpdates = true;
389
438
  /** Cached upgrade availability; recomputed by {@link refreshUpgrade}. */
@@ -436,89 +485,7 @@ var TokenQuotaService = class TokenQuotaService extends Service {
436
485
  super(ctx, "tokenQuota");
437
486
  this.storagePath = config.storagePath !== void 0 && config.storagePath.length > 0 ? config.storagePath : defaultStoragePath();
438
487
  this.load();
439
- ctx.inject(["settings"], (settingsCtx) => {
440
- settingsCtx.settings.installSection(ctx, TOKEN_QUOTA_NAMESPACE, TOKEN_QUOTA_SETTINGS_SCHEMA, { limits: {} }, {
441
- setSource: (current) => {
442
- this.settingsSource = () => {
443
- const doc = current();
444
- return {
445
- limits: doc.limits ?? {},
446
- monitored: doc.monitored ?? [],
447
- onFull: doc.onFull === "switchPriority" ? "switchAll" : doc.onFull ?? "stop",
448
- checkUpdates: doc.checkUpdates ?? true,
449
- dimWhenIdle: doc.dimWhenIdle ?? false,
450
- order: Array.isArray(doc.order) ? doc.order : [],
451
- balance: {
452
- enabled: doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled,
453
- pollMinutes: typeof doc.balance?.pollMinutes === "number" ? Math.max(1, Math.min(120, Math.round(doc.balance.pollMinutes))) : TOKEN_QUOTA_DEFAULT_BALANCE.pollMinutes
454
- },
455
- transcribe: {
456
- enabled: doc.transcribe?.enabled ?? TOKEN_QUOTA_DEFAULT_TRANSCRIBE.enabled,
457
- baseURL: typeof doc.transcribe?.baseURL === "string" && doc.transcribe.baseURL !== "" ? doc.transcribe.baseURL.replace(/\/+$/, "") : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.baseURL,
458
- apiKeyEnv: typeof doc.transcribe?.apiKeyEnv === "string" && doc.transcribe.apiKeyEnv !== "" ? doc.transcribe.apiKeyEnv : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv,
459
- model: typeof doc.transcribe?.model === "string" && doc.transcribe.model !== "" ? doc.transcribe.model : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model
460
- },
461
- notes: Array.isArray(doc.notes) ? doc.notes.slice(0, 5).flatMap((note) => {
462
- if (typeof note.id !== "string") return [];
463
- return [{
464
- id: note.id,
465
- title: note.title ?? "",
466
- text: note.text ?? "",
467
- x: note.x ?? 80,
468
- y: note.y ?? 80,
469
- width: note.width ?? 220,
470
- height: note.height ?? 220,
471
- collapsed: note.collapsed ?? false,
472
- visible: note.visible ?? true
473
- }];
474
- }) : [],
475
- reset: doc.reset ?? void 0,
476
- music: {
477
- enabled: doc.music?.enabled ?? TOKEN_QUOTA_DEFAULT_MUSIC.enabled,
478
- volume: doc.music?.volume ?? TOKEN_QUOTA_DEFAULT_MUSIC.volume,
479
- style: doc.music?.style ?? TOKEN_QUOTA_DEFAULT_MUSIC.style,
480
- onlyCurrentSession: doc.music?.onlyCurrentSession ?? TOKEN_QUOTA_DEFAULT_MUSIC.onlyCurrentSession
481
- }
482
- };
483
- };
484
- },
485
- validate: (value) => {
486
- for (const [key, limit] of Object.entries(value.limits ?? {})) {
487
- assertTokenQuotaLimit(limit, key);
488
- splitTokenQuotaKey(key);
489
- }
490
- },
491
- onChange: () => {
492
- const doc = this.settingsSource();
493
- this.limits = { ...doc.limits };
494
- this.monitored = doc.monitored !== void 0 && doc.monitored.length > 0 ? new Set(doc.monitored) : void 0;
495
- this.checkUpdates = doc.checkUpdates;
496
- this.syncUpdateChecking();
497
- const balanceEnabled = doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled;
498
- const turnedOn = balanceEnabled && !this.balanceEnabled;
499
- this.balanceEnabled = balanceEnabled;
500
- if (!balanceEnabled) this.balances.clear();
501
- this.syncBalancePolling();
502
- if (turnedOn) this.refreshAllBalances();
503
- if (doc.reset !== void 0 && typeof doc.reset === "object" && doc.reset !== null && typeof doc.reset.offsetHours === "number" && typeof doc.reset.hour === "number" && typeof doc.reset.minute === "number") {
504
- const configured = doc.reset;
505
- this.reset = {
506
- offsetHours: Math.max(-12, Math.min(14, Math.round(configured.offsetHours))),
507
- hour: Math.max(0, Math.min(23, Math.round(configured.hour))),
508
- minute: Math.max(0, Math.min(59, Math.round(configured.minute)))
509
- };
510
- this.rollCycleIfNeeded();
511
- } else {
512
- this.reset = {
513
- offsetHours: localOffsetHours(),
514
- hour: 0,
515
- minute: 0
516
- };
517
- this.rollCycleIfNeeded();
518
- }
519
- }
520
- });
521
- });
488
+ this.applySettings(config);
522
489
  this.tryMountRoute();
523
490
  if (this.disposeRoute === void 0) this.disposeRouteWatcher = ctx.on("internal/service", (name) => {
524
491
  if (name === "webServer") this.tryMountRoute();
@@ -720,7 +687,7 @@ var TokenQuotaService = class TokenQuotaService extends Service {
720
687
  return this.upgradeCheck;
721
688
  }
722
689
  async doRefreshUpgrade() {
723
- const current = "0.1.50";
690
+ const current = "0.1.52";
724
691
  let latest;
725
692
  try {
726
693
  const response = await fetch(REGISTRY_LATEST_URL, {
@@ -807,7 +774,14 @@ var TokenQuotaService = class TokenQuotaService extends Service {
807
774
  discoverBalanceSources() {
808
775
  const found = /* @__PURE__ */ new Map();
809
776
  const llm = this.ctx.get("llm");
810
- const settings = this.ctx.get("settings");
777
+ const configEditor = this.ctx.get("configEditor");
778
+ const liveConfigs = /* @__PURE__ */ new Map();
779
+ try {
780
+ for (const row of configEditor?.configuration() ?? []) {
781
+ const id = row.entry.options.id;
782
+ if (id !== void 0) liveConfigs.set(id, row.entry.options.config);
783
+ }
784
+ } catch {}
811
785
  const fallback = () => ({
812
786
  provider: "deepseek",
813
787
  keyEnv: "DEEPSEEK_API_KEY",
@@ -819,7 +793,7 @@ var TokenQuotaService = class TokenQuotaService extends Service {
819
793
  return found;
820
794
  }
821
795
  for (const entry of llm.listConfigurableProviders()) try {
822
- let profile = settings?.get(entry.settingsNs);
796
+ let profile = liveConfigs.get(entry.settingsNs);
823
797
  for (const segment of entry.settingsPath ?? []) profile = profile !== null && typeof profile === "object" ? profile[segment] : void 0;
824
798
  if (profile === null || typeof profile !== "object") continue;
825
799
  const record = profile;
@@ -348,7 +348,15 @@ export function TokenQuotaPanel({ t, load, setLimit, selectModel, setMonitored,
348
348
  // Storage unavailable: the position still applies for this session.
349
349
  }
350
350
  };
351
- const sessionId = useSessions(s => s.current);
351
+ // This Harness version dropped the list's `current` field: the visible
352
+ // conversation is the session the main view retains.
353
+ const sessionId = useSessions((state) => {
354
+ for (const session of Object.values(state.byId)) {
355
+ if ((session.retainedBy.mainView ?? 0) > 0)
356
+ return session.id;
357
+ }
358
+ return undefined;
359
+ });
352
360
  const snapshot = useStore(s => s.snapshot);
353
361
  const groups = useStore(s => s.groups);
354
362
  const current = useStore(s => s.current);
@@ -14,7 +14,7 @@ const TOKEN_QUOTA_NAMESPACE = 'token-quota';
14
14
  /** Snapshot pull cadence in milliseconds. */
15
15
  const POLL_INTERVAL_MS = 3000;
16
16
  /** Required services: slot registry, sessions, locale, settings scope, and the Host remote faces. */
17
- export const inject = ['slots', 'sessions', 'locale', 'settingsScope', 'remote', 'remote.session', 'remote.credentials'];
17
+ export const inject = ['slots', 'sessions', 'locale', 'remote', 'remote.settings', 'remote.session', 'remote.credentials'];
18
18
  /**
19
19
  * Client plugin body: poll the Host snapshot route, run the full-quota
20
20
  * strategy, wire the injected face (directory load, limit write, model
@@ -24,7 +24,67 @@ export const inject = ['slots', 'sessions', 'locale', 'settingsScope', 'remote',
24
24
  export function apply(ctx) {
25
25
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'token-quota-ui: panel dictionaries');
26
26
  const t = ctx.locale.bind(NS);
27
- const scope = ctx.settingsScope.bind({ namespace: TOKEN_QUOTA_NAMESPACE });
27
+ // --- Settings namespace adapter -------------------------------------------
28
+ // The client used to hold a synchronous settings scope (`settingsScope.bind`).
29
+ // This Harness version moved configuration onto the remotes contract, so the
30
+ // document is read with `remote.settings.describe()` and written with
31
+ // `mutate()` path ops (guarded by the revision the last read observed). The
32
+ // adapter keeps the old synchronous `getSnapshot()/set()` shape so the rest
33
+ // of this module stays readable.
34
+ let settingsValue;
35
+ let settingsRevision;
36
+ /** Re-read the token-quota namespace from the Host. */
37
+ const readSettings = async () => {
38
+ try {
39
+ const response = await ctx.remote.settings.describe();
40
+ if (!response.ok)
41
+ return settingsValue;
42
+ const view = response.value.namespaces.find(entry => entry.ns === TOKEN_QUOTA_NAMESPACE);
43
+ if (view !== undefined) {
44
+ settingsRevision = view.revision;
45
+ settingsValue = view.value;
46
+ }
47
+ return settingsValue;
48
+ }
49
+ catch {
50
+ // Remotes unavailable (offline, older Host): keep the last document.
51
+ return settingsValue;
52
+ }
53
+ };
54
+ /**
55
+ * Write one path of the namespace. Path ops avoid the read-modify-write race
56
+ * a whole-object update would introduce (two editors, one section each), and
57
+ * a stale revision is retried once against a fresh read instead of dropping
58
+ * the change.
59
+ */
60
+ const writeSetting = (path, value) => {
61
+ void (async () => {
62
+ const op = value === undefined
63
+ ? { op: 'unset', path }
64
+ : { op: 'set', path, value: value };
65
+ try {
66
+ let response = await ctx.remote.settings.mutate(TOKEN_QUOTA_NAMESPACE, [op], settingsRevision);
67
+ if (!response.ok) {
68
+ await readSettings();
69
+ response = await ctx.remote.settings.mutate(TOKEN_QUOTA_NAMESPACE, [op], settingsRevision);
70
+ }
71
+ if (response.ok) {
72
+ settingsRevision = response.value.revision;
73
+ settingsValue = response.value.value;
74
+ }
75
+ }
76
+ catch {
77
+ // Leave the last good document in place; the next poll re-reads it.
78
+ }
79
+ })();
80
+ };
81
+ const scope = {
82
+ getSnapshot: () => ({ value: settingsValue }),
83
+ set: (key, value) => {
84
+ writeSetting([key], value);
85
+ return Promise.resolve();
86
+ },
87
+ };
28
88
  // The Host `dsh-session` package's `ctx.sessions: SessionStore` merge can
29
89
  // shadow the client ISessions face in a combined type-check; the runtime
30
90
  // 'sessions' service is the ISessions implementation regardless.
@@ -291,7 +351,13 @@ export function apply(ctx) {
291
351
  }, () => { });
292
352
  };
293
353
  const pull = () => {
354
+ void pullOnce();
355
+ };
356
+ const pullOnce = async () => {
294
357
  pullCount += 1;
358
+ // Settings now arrive over the remotes contract: refresh the document
359
+ // before reading any of it below.
360
+ await readSettings();
295
361
  const doc = scope.getSnapshot().value;
296
362
  lastMonitored = doc?.monitored !== undefined && doc.monitored.length > 0 ? doc.monitored : null;
297
363
  // Legacy `switchPriority` (removed in 0.1.7) maps to `switchAll`.
@@ -379,8 +445,9 @@ export function apply(ctx) {
379
445
  });
380
446
  };
381
447
  const setLimit = (key, limit) => {
382
- const current = scope.getSnapshot().value?.limits ?? {};
383
- void scope.set('limits', { ...current, [key]: limit });
448
+ // One path op, not a whole-map rewrite: two editors setting different
449
+ // models must not clobber each other.
450
+ writeSetting(['limits', key], limit);
384
451
  };
385
452
  const setMonitored = (monitored) => {
386
453
  lastMonitored = monitored;
@@ -48,7 +48,18 @@ export declare class TokenQuotaService extends Service {
48
48
  private history;
49
49
  private limits;
50
50
  private monitored;
51
+ /** Settings resolved from this plugin entry's own config (see applySettings). */
52
+ private resolvedSettings;
53
+ /** The settings document this instance runs with. */
51
54
  private settingsSource;
55
+ /**
56
+ * Normalize this entry's config into the plugin's settings shape and apply
57
+ * it. Called once per instantiation: a settings write from the panel reloads
58
+ * the entry, so this is the live-apply path that used to be an onChange
59
+ * callback.
60
+ * @param config - the plugin entry config (Config schema, defaults applied).
61
+ */
62
+ private applySettings;
52
63
  /** Whether update checks are enabled (mirrors the settings document). */
53
64
  private checkUpdates;
54
65
  /** Cached upgrade availability; recomputed by {@link refreshUpgrade}. */
@@ -38,8 +38,8 @@ import z from '@deepseek-ai/schemastery';
38
38
  // the service listens to without importing any runtime value.
39
39
  import '@deepseek-ai/dsh-agent';
40
40
  import { LlmError } from '@deepseek-ai/dsh-llm';
41
- import { TOKEN_QUOTA_EXCEEDED_CODE, TOKEN_QUOTA_NAMESPACE, tokenQuotaKey, TOKEN_QUOTA_DEFAULT_MUSIC, TOKEN_QUOTA_MAX_NOTES, TOKEN_QUOTA_DEFAULT_BALANCE, TOKEN_QUOTA_DEFAULT_TRANSCRIBE, } from "./types.js";
42
- import { assertTokenQuotaLimit, splitTokenQuotaKey } from "./invariant.js";
41
+ import { TOKEN_QUOTA_EXCEEDED_CODE, tokenQuotaKey, TOKEN_QUOTA_DEFAULT_MUSIC, TOKEN_QUOTA_MAX_NOTES, TOKEN_QUOTA_DEFAULT_BALANCE, TOKEN_QUOTA_DEFAULT_TRANSCRIBE, } from "./types.js";
42
+ import { splitTokenQuotaKey } from "./invariant.js";
43
43
  /** The plugin's package name, used to locate the profile dependency and the registry endpoint. */
44
44
  const PACKAGE_NAME = '@jxgame2020/dsh-token-quota';
45
45
  /** npm registry endpoint for the plugin's latest version. */
@@ -191,7 +191,7 @@ function isNewer(latest, current) {
191
191
  return false;
192
192
  }
193
193
  /** Settings schema resolving the per-model daily caps document. */
194
- const TOKEN_QUOTA_SETTINGS_SCHEMA = z.object({
194
+ const TOKEN_QUOTA_SETTINGS_FIELDS = {
195
195
  limits: z.dict(z.number().step(1).min(0)).default({}),
196
196
  monitored: z.array(z.string()).default([]),
197
197
  // `switchPriority` is a legacy value accepted for documents saved by older
@@ -240,7 +240,7 @@ const TOKEN_QUOTA_SETTINGS_SCHEMA = z.object({
240
240
  apiKeyEnv: z.string().default(TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv),
241
241
  model: z.string().default(TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model),
242
242
  }).default({ ...TOKEN_QUOTA_DEFAULT_TRANSCRIBE }),
243
- });
243
+ };
244
244
  /** Two-digit zero-pad helper. */
245
245
  function pad2(value) {
246
246
  return String(value).padStart(2, '0');
@@ -366,6 +366,7 @@ function parseTeamorouterBalance(data) {
366
366
  export class TokenQuotaService extends Service {
367
367
  static Config = z.object({
368
368
  storagePath: z.string().default(''),
369
+ ...TOKEN_QUOTA_SETTINGS_FIELDS,
369
370
  });
370
371
  storagePath;
371
372
  reset = {
@@ -378,7 +379,84 @@ export class TokenQuotaService extends Service {
378
379
  history = {};
379
380
  limits = {};
380
381
  monitored = undefined;
381
- settingsSource = () => ({ limits: {}, monitored: [], onFull: 'stop', checkUpdates: true, dimWhenIdle: false, music: { ...TOKEN_QUOTA_DEFAULT_MUSIC }, order: [], notes: [], balance: { ...TOKEN_QUOTA_DEFAULT_BALANCE }, transcribe: { ...TOKEN_QUOTA_DEFAULT_TRANSCRIBE } });
382
+ /** Settings resolved from this plugin entry's own config (see applySettings). */
383
+ resolvedSettings = { limits: {}, monitored: [], onFull: 'stop', checkUpdates: true, dimWhenIdle: false, music: { ...TOKEN_QUOTA_DEFAULT_MUSIC }, order: [], notes: [], balance: { ...TOKEN_QUOTA_DEFAULT_BALANCE }, transcribe: { ...TOKEN_QUOTA_DEFAULT_TRANSCRIBE } };
384
+ /** The settings document this instance runs with. */
385
+ settingsSource = () => this.resolvedSettings;
386
+ /**
387
+ * Normalize this entry's config into the plugin's settings shape and apply
388
+ * it. Called once per instantiation: a settings write from the panel reloads
389
+ * the entry, so this is the live-apply path that used to be an onChange
390
+ * callback.
391
+ * @param config - the plugin entry config (Config schema, defaults applied).
392
+ */
393
+ applySettings(config) {
394
+ const doc = config;
395
+ const settings = {
396
+ limits: doc.limits ?? {},
397
+ monitored: doc.monitored ?? [],
398
+ onFull: doc.onFull === 'switchPriority' ? 'switchAll' : (doc.onFull ?? 'stop'),
399
+ checkUpdates: doc.checkUpdates ?? true,
400
+ dimWhenIdle: doc.dimWhenIdle ?? false,
401
+ order: Array.isArray(doc.order) ? doc.order : [],
402
+ balance: {
403
+ enabled: doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled,
404
+ pollMinutes: typeof doc.balance?.pollMinutes === 'number'
405
+ ? Math.max(1, Math.min(120, Math.round(doc.balance.pollMinutes)))
406
+ : TOKEN_QUOTA_DEFAULT_BALANCE.pollMinutes,
407
+ },
408
+ transcribe: {
409
+ enabled: doc.transcribe?.enabled ?? TOKEN_QUOTA_DEFAULT_TRANSCRIBE.enabled,
410
+ baseURL: typeof doc.transcribe?.baseURL === 'string' && doc.transcribe.baseURL !== ''
411
+ ? doc.transcribe.baseURL.replace(/\/+$/, '')
412
+ : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.baseURL,
413
+ apiKeyEnv: typeof doc.transcribe?.apiKeyEnv === 'string' && doc.transcribe.apiKeyEnv !== ''
414
+ ? doc.transcribe.apiKeyEnv
415
+ : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv,
416
+ model: typeof doc.transcribe?.model === 'string' && doc.transcribe.model !== ''
417
+ ? doc.transcribe.model
418
+ : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model,
419
+ },
420
+ music: {
421
+ enabled: doc.music?.enabled ?? TOKEN_QUOTA_DEFAULT_MUSIC.enabled,
422
+ volume: doc.music?.volume ?? TOKEN_QUOTA_DEFAULT_MUSIC.volume,
423
+ style: doc.music?.style ?? TOKEN_QUOTA_DEFAULT_MUSIC.style,
424
+ onlyCurrentSession: doc.music?.onlyCurrentSession ?? TOKEN_QUOTA_DEFAULT_MUSIC.onlyCurrentSession,
425
+ },
426
+ notes: Array.isArray(doc.notes) ? doc.notes.slice(0, TOKEN_QUOTA_MAX_NOTES) : [],
427
+ ...doc.reset !== undefined && doc.reset !== null ? { reset: doc.reset } : {},
428
+ };
429
+ this.resolvedSettings = settings;
430
+ // Live-apply the parts the service acts on.
431
+ this.limits = { ...settings.limits };
432
+ this.monitored = settings.monitored.length > 0 ? new Set(settings.monitored) : undefined;
433
+ this.checkUpdates = settings.checkUpdates;
434
+ const balanceEnabled = settings.balance.enabled;
435
+ const turnedOn = balanceEnabled && !this.balanceEnabled;
436
+ this.balanceEnabled = balanceEnabled;
437
+ if (!balanceEnabled)
438
+ this.balances.clear();
439
+ const configured = settings.reset;
440
+ if (configured !== undefined
441
+ && typeof configured === 'object'
442
+ && configured !== null
443
+ && typeof configured.offsetHours === 'number'
444
+ && typeof configured.hour === 'number'
445
+ && typeof configured.minute === 'number') {
446
+ this.reset = {
447
+ offsetHours: Math.max(-12, Math.min(14, Math.round(configured.offsetHours))),
448
+ hour: Math.max(0, Math.min(23, Math.round(configured.hour))),
449
+ minute: Math.max(0, Math.min(59, Math.round(configured.minute))),
450
+ };
451
+ }
452
+ else {
453
+ this.reset = { offsetHours: localOffsetHours(), hour: 0, minute: 0 };
454
+ }
455
+ this.rollCycleIfNeeded();
456
+ // Turning balance polling on fetches immediately so the panel has numbers.
457
+ if (turnedOn)
458
+ void this.refreshAllBalances();
459
+ }
382
460
  /** Whether update checks are enabled (mirrors the settings document). */
383
461
  checkUpdates = true;
384
462
  /** Cached upgrade availability; recomputed by {@link refreshUpgrade}. */
@@ -433,118 +511,11 @@ export class TokenQuotaService extends Service {
433
511
  ? config.storagePath
434
512
  : defaultStoragePath();
435
513
  this.load();
436
- // Limits live in the user settings document; the Web panel writes them and
437
- // the section watcher pushes every change back here. DSH 0.1.5 replaced
438
- // the standalone `installSettingsSection` helper with
439
- // `SettingsProvider.installSection`, reached through `ctx.inject` so the
440
- // settings service is guaranteed to be up before registration.
441
- ctx.inject(['settings'], (settingsCtx) => {
442
- settingsCtx.settings.installSection(ctx, TOKEN_QUOTA_NAMESPACE, TOKEN_QUOTA_SETTINGS_SCHEMA, { limits: {} }, {
443
- setSource: (current) => {
444
- // Normalize the resolved (schema-shaped) document into the plugin's
445
- // required shape: empty monitored = monitor everything, absent onFull
446
- // falls back to 'stop'.
447
- this.settingsSource = () => {
448
- const doc = current();
449
- return {
450
- limits: doc.limits ?? {},
451
- monitored: doc.monitored ?? [],
452
- // Legacy `switchPriority` (removed in 0.1.7) maps to `switchAll`:
453
- // capped models first, then uncapped — both monitored-only.
454
- onFull: doc.onFull === 'switchPriority' ? 'switchAll' : (doc.onFull ?? 'stop'),
455
- checkUpdates: doc.checkUpdates ?? true,
456
- dimWhenIdle: doc.dimWhenIdle ?? false,
457
- order: Array.isArray(doc.order) ? doc.order : [],
458
- balance: {
459
- enabled: doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled,
460
- pollMinutes: typeof doc.balance?.pollMinutes === 'number'
461
- ? Math.max(1, Math.min(120, Math.round(doc.balance.pollMinutes)))
462
- : TOKEN_QUOTA_DEFAULT_BALANCE.pollMinutes,
463
- },
464
- transcribe: {
465
- enabled: doc.transcribe?.enabled ?? TOKEN_QUOTA_DEFAULT_TRANSCRIBE.enabled,
466
- baseURL: typeof doc.transcribe?.baseURL === 'string' && doc.transcribe.baseURL !== ''
467
- ? doc.transcribe.baseURL.replace(/\/+$/, '')
468
- : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.baseURL,
469
- apiKeyEnv: typeof doc.transcribe?.apiKeyEnv === 'string' && doc.transcribe.apiKeyEnv !== ''
470
- ? doc.transcribe.apiKeyEnv
471
- : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv,
472
- model: typeof doc.transcribe?.model === 'string' && doc.transcribe.model !== ''
473
- ? doc.transcribe.model
474
- : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model,
475
- },
476
- notes: Array.isArray(doc.notes)
477
- ? doc.notes.slice(0, TOKEN_QUOTA_MAX_NOTES).flatMap((note) => {
478
- if (typeof note.id !== 'string')
479
- return [];
480
- return [{
481
- id: note.id,
482
- title: note.title ?? '',
483
- text: note.text ?? '',
484
- x: note.x ?? 80,
485
- y: note.y ?? 80,
486
- width: note.width ?? 220,
487
- height: note.height ?? 220,
488
- collapsed: note.collapsed ?? false,
489
- visible: note.visible ?? true,
490
- }];
491
- })
492
- : [],
493
- reset: doc.reset ?? undefined,
494
- music: {
495
- enabled: doc.music?.enabled ?? TOKEN_QUOTA_DEFAULT_MUSIC.enabled,
496
- volume: doc.music?.volume ?? TOKEN_QUOTA_DEFAULT_MUSIC.volume,
497
- style: doc.music?.style ?? TOKEN_QUOTA_DEFAULT_MUSIC.style,
498
- onlyCurrentSession: doc.music?.onlyCurrentSession ?? TOKEN_QUOTA_DEFAULT_MUSIC.onlyCurrentSession,
499
- },
500
- };
501
- };
502
- },
503
- validate: (value) => {
504
- for (const [key, limit] of Object.entries(value.limits ?? {})) {
505
- assertTokenQuotaLimit(limit, key);
506
- splitTokenQuotaKey(key);
507
- }
508
- },
509
- onChange: () => {
510
- const doc = this.settingsSource();
511
- this.limits = { ...doc.limits };
512
- this.monitored = doc.monitored !== undefined && doc.monitored.length > 0
513
- ? new Set(doc.monitored)
514
- : undefined;
515
- this.checkUpdates = doc.checkUpdates;
516
- this.syncUpdateChecking();
517
- const balanceEnabled = doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled;
518
- const turnedOn = balanceEnabled && !this.balanceEnabled;
519
- this.balanceEnabled = balanceEnabled;
520
- if (!balanceEnabled)
521
- this.balances.clear();
522
- this.syncBalancePolling();
523
- // Flipping the toggle on: fetch right away so the panel shows numbers.
524
- if (turnedOn)
525
- void this.refreshAllBalances();
526
- if (doc.reset !== undefined
527
- && typeof doc.reset === 'object'
528
- && doc.reset !== null
529
- && typeof doc.reset.offsetHours === 'number'
530
- && typeof doc.reset.hour === 'number'
531
- && typeof doc.reset.minute === 'number') {
532
- const configured = doc.reset;
533
- this.reset = {
534
- offsetHours: Math.max(-12, Math.min(14, Math.round(configured.offsetHours))),
535
- hour: Math.max(0, Math.min(23, Math.round(configured.hour))),
536
- minute: Math.max(0, Math.min(59, Math.round(configured.minute))),
537
- };
538
- this.rollCycleIfNeeded();
539
- }
540
- else {
541
- // null / malformed (unset) = machine-local midnight — the default.
542
- this.reset = { offsetHours: localOffsetHours(), hour: 0, minute: 0 };
543
- this.rollCycleIfNeeded();
544
- }
545
- },
546
- });
547
- });
514
+ // This Harness version exposes a plugin's Config AS its settings namespace:
515
+ // the panel writes through `remote.settings`, the loader re-applies this
516
+ // entry, and the live-apply work that used to hang off `installSection`'s
517
+ // onChange callback happens once per instantiation instead.
518
+ this.applySettings(config);
548
519
  // Snapshot route: optional — only mounted when a webServer service exists
549
520
  // (the Web profile); headless deployments keep the enforcement without it.
550
521
  this.tryMountRoute();
@@ -875,7 +846,21 @@ export class TokenQuotaService extends Service {
875
846
  discoverBalanceSources() {
876
847
  const found = new Map();
877
848
  const llm = this.ctx.get('llm');
878
- const settings = this.ctx.get('settings');
849
+ // Provider profiles live in OTHER plugins' entry configs. This Harness
850
+ // version dropped `settings.get(ns)`, so read the composed configuration
851
+ // once from the config editor and index it by profile entry id.
852
+ const configEditor = this.ctx.get('configEditor');
853
+ const liveConfigs = new Map();
854
+ try {
855
+ for (const row of configEditor?.configuration() ?? []) {
856
+ const id = row.entry.options.id;
857
+ if (id !== undefined)
858
+ liveConfigs.set(id, row.entry.options.config);
859
+ }
860
+ }
861
+ catch {
862
+ // No config editor in this deployment: balance discovery falls back.
863
+ }
879
864
  const fallback = () => ({
880
865
  provider: 'deepseek',
881
866
  keyEnv: 'DEEPSEEK_API_KEY',
@@ -888,7 +873,7 @@ export class TokenQuotaService extends Service {
888
873
  }
889
874
  for (const entry of llm.listConfigurableProviders()) {
890
875
  try {
891
- let profile = settings?.get(entry.settingsNs);
876
+ let profile = liveConfigs.get(entry.settingsNs);
892
877
  for (const segment of entry.settingsPath ?? []) {
893
878
  profile = profile !== null && typeof profile === 'object'
894
879
  ? profile[segment]
@@ -246,8 +246,10 @@ export interface TokenQuotaSettings {
246
246
  */
247
247
  order: string[];
248
248
  }
249
- /** Token-quota plugin configuration. */
250
- export interface TokenQuotaConfig {
249
+ /** Token-quota plugin configuration (the entry config doubles as the namespace). */
250
+ export interface TokenQuotaConfig extends Partial<Omit<TokenQuotaSettings, 'onFull'>> {
251
+ /** Legacy `switchPriority` stays accepted in the schema; the runtime maps it. */
252
+ onFull?: TokenQuotaFullAction | 'switchPriority';
251
253
  /**
252
254
  * Counter JSON file path. Defaults to `token-quota.json` under the Harness
253
255
  * home (`DSH_HOME` or `~/.dsh`).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jxgame2020/dsh-token-quota",
3
3
  "description": "Daily per-model token quota accounting, enforcement, and a floating quota panel for the DeepSeek Harness — a fully self-contained plugin (no core-Harness wiring, no generated RPC contract)",
4
- "version": "0.1.50",
4
+ "version": "0.1.52",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -39,6 +39,9 @@
39
39
  "@deepseek-ai/dsh-api-remotes"
40
40
  ],
41
41
  "platform": "web"
42
+ },
43
+ "bundle": {
44
+ "patch": "./cordis.patch.yml"
42
45
  }
43
46
  },
44
47
  "scripts": {
@@ -50,6 +53,7 @@
50
53
  "lib/index.js",
51
54
  "lib/invariant.js",
52
55
  "lib/client.js",
56
+ "cordis.patch.yml",
53
57
  "lib/types/**/*.js",
54
58
  "lib/types/**/*.d.ts"
55
59
  ],