dsh-connect-workbuddy 5.21.2 → 5.21.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,128 @@
1
1
  # Changelog
2
2
 
3
+ ## 5.21.4 (2026-11-11)
4
+
5
+ > 版本号是 **patch**:修一个开关的取值时机、一条预热链的启动时机,不动配置键与路由语义。
6
+ > 来自 PR #239(AMagicPear)。
7
+
8
+ ### 修复:SDK 总开关勾上之后,下面那行仍写「已在设置里关闭」
9
+
10
+ 现象是自相矛盾的:勾上「启用真实设备 SDK」,状态行还是 `已在设置里关闭`,还多出两行红字
11
+ `the real-device SDK is turned off in this plugin's settings`;同一次
12
+ `GET /device-sdk` 里 `sdkEnabled: true` 与 `sdk.state: "disabled"` 并存。
13
+
14
+ 根因是同一个配置项被读成了**两份真值**:
15
+
16
+ - `apply()` 里写 `const flag = unwrapVolatile(config.deviceSdkEnabled) === true`,把这个
17
+ 布尔**求值一次**传给 `createTuringSdk({ enabled })`,句柄活到卸载;
18
+ - 卡片勾选框走 `readEnabled()`,每次请求**现读**活引用。
19
+
20
+ `deviceSdkEnabled` 是 `asVolatile` 字段,拨动开关只发 `loader/volatile-update`、**不重挂
21
+ 插件**。于是配置已经是 `true`,句柄里那枚快照还是挂载时的 `false`,`probe()` 永远答
22
+ `disabled`——勾选框和状态行从此各说各话。
23
+
24
+ - `deviceSdkEnabled` 改成函数,SDK 句柄收 `get enabled()`,与 `readEnabled()` 共用同一份
25
+ 活值。这是**唯一**一处需要修的地方:其余 volatile 字段本来就每次现读。
26
+ - 顺带统一了同一字段的两种默认值解释。挂载处是 `=== true`(`undefined` → 关),读开关处
27
+ 曾写 `!== false`(`undefined` → 开),于是老配置缺这一项时界面显示"开"而 SDK 实际是关的。
28
+ 现在两处都是 `=== true`,与 schema 的 `default(false)` 同一个答案。
29
+
30
+ ### 修复:关着启动的进程,打开开关后永远没有预热定时器
31
+
32
+ `startAutoRefresh()` 也只在挂载时判一次。新增 `syncDeviceSdk()` 挂在
33
+ `loader/volatile-update` 上:开则补建(内部幂等),关则立即拆除。
34
+
35
+ 这条修复原 PR 没有测试,合入时补了一条:先用空目录让 `probe()` 答 `missing`(不起子进程),
36
+ 断言挂载后 `lastAttemptMs` 不存在,再拨开开关并等它出现。`lastAttemptMs` 只由
37
+ `fetchOnce()` 写,`probe()` 不碰,所以它出现证明的是**定时链存在**,而不是"又读了一次快照"。
38
+ 变异验证:删掉 `loader/volatile-update` 里那行 `syncDeviceSdk()`,该用例转红。
39
+
40
+ ### 收敛:状态路由的守卫样板
41
+
42
+ `src/web-status.ts` 的 16 条路由原来各抄一遍「方法判断 → `requireLoopback` → 区域解析 →
43
+ `try/catch → 500`」,抄漏一道没有编译错误,却是真实的 DNS-rebinding / 跨区泄漏面。引入
44
+ `raw` / `endpoint` / `endpointRegion` 三个薄封装,handler 只写业务。
45
+
46
+ `ready` 排在区域解析**之前**是刻意的:`models` / `media` 这类路由要先答「宿主没有这项能力」
47
+ 的 503,反过来会让一个缺区域参数的请求先拿到 400。`pool`(嵌套 try)、`__save`(错误体带
48
+ `errorName`)、`transfer`(413 分支)、device 两条(一条路由两种方法)有各自理由,保持原样。
49
+
50
+ | 指标 | 前 | 后 |
51
+ |---|---|---|
52
+ | `requireLoopback` | 16 | 6 |
53
+ | `405` 分支 | 16 | 6 |
54
+ | `500` 应答合计 | 22 | 12 |
55
+ | 其中「兜底 500」 | 12 | 2 |
56
+ | `web-status.ts` 行数 | 2701 | 2594 |
57
+
58
+ **路由卸载不再手写。** 注册时自动收进一个 disposer 数组——`benefit/claim` 曾漏了那一行
59
+ (issue #86),热重载时宿主因重复注册同路径而抛错,后面的路由全部注册不上,卡片半数按钮答
60
+ 405。"新加路由忘了加卸载"这一类错误因此不再可能发生。
61
+
62
+ 其余顺手收敛:生图/视频两份 ~85% 相同的注册状态机合成一个 `mountOptionalTool`(逐区 opt-in
63
+ 判据仍各自独立);卡片里 7 处相同 `catch` 收成 `fail()`,内联复制的"清空目录"块改为复用
64
+ `saveDir('')`;删掉 `WorkerAnswer` 里从未被读的 5 个字段、零引用的
65
+ `WorkBuddyDeviceSdkAction`,以及两处过时的「thirteen routes」注释(其中一处在
66
+ `src/loopback.ts`,原 PR 只改了 `web-status.ts` 那一份)。
67
+
68
+ 变异验证:从 `raw` 里删掉方法闸与 loopback 两道守卫,`tests/web-status.spec.ts` 与
69
+ `tests/pool-route.spec.ts` 共 13 条转红。
70
+
71
+ ### 收敛:opt-in 政策合成一张表,卡片响应类型不再另写一份
72
+
73
+ PR 的第三个提交,不改任何用户可见行为:
74
+
75
+ - 「只认字面 `true`」这条政策原先在五个测试文件里各写一遍。它是一条产品决策(会花钱或多挂
76
+ 一块界面的开关,缺省与类型错误都不能被读成同意),现在集中在 `tests/optin-policy.spec.tsx`
77
+ 一张表里,新增开关只加一行。各文件保留自己独有的断言(逐区隔离、写回只动一个字段等)。
78
+ 变异验证:把 `regionImageToolEnabledOf` 从 `=== true` 改成 `!== false`,新旧两处共 4 条转红。
79
+ - 卡片侧的 `DeviceSdkInfo` / `DeviceSdkToken` / `DeviceSdkReport` 与 Host 的三份逐字段相同,
80
+ 改为 `import type` 取 Host 的类型(构建时擦除)。`normalize()` **保留**:宿主版本对不上
81
+ 或响应只到一半时,它把缺字段折成 `undefined` 让面板显示"不可用",而不是让
82
+ `report.sdk.state` 抛错、把整块卡片交给错误边界。浏览器包已核对不含 `node:` 内建模块。
83
+
84
+ **合入时补回一条断言。** 该提交以「行为断言已覆盖」为由删掉了 `sidebarPanel` 的 schema
85
+ 默认值断言。实测不成立:把 `.default(false)` 改成 `.default(true)`,整个套件依然是绿的——
86
+ 唯一会红的 `privacy-gate` 是另一个原因。`Config({})` 也答不了这个问题(volatile 包装让该字段
87
+ 读成 `{}`,与默认值无关)。
88
+
89
+ 补的不是原来那条源码正则(schema 排版一变就红,却不指向任何回归),而是读 schemastery 自己
90
+ 记在 `meta` 里的默认值:**是数据,不是文本**。同时钉住 `volatile: true`——卡片经 `__save`
91
+ 写入后那一行要立刻出现,重挂才生效就违背了这个开关的用途。
92
+
93
+ ### 验证
94
+
95
+ - `pnpm run check` 全绿(typecheck → build → check:pii → test):3416 passed / 2 skipped。
96
+ - CI(ubuntu-latest / windows-latest / pi-ai 1.1.0)三个 job 全绿。fork 的首次 run 是
97
+ `action_required`,需维护者 approve 后才真正开跑——"没有 checks reported"不等于 CI 通过。
98
+ - 变异验证四条:冻结布尔 → `sdk.state` 断言红;删 `syncDeviceSdk()` → 预热链用例红;
99
+ 删 `raw` 的方法闸与 loopback → 13 条红;`sidebarPanel` 默认值翻成 `true` → 新补的断言红。
100
+
101
+ ## 5.21.3 (2026-11-09)
102
+
103
+ > 版本号是 **patch**:只改一句回复里的账号称谓,不动配置键、路由与重试策略。
104
+
105
+ ### 修复:自动换号的通知写账号名,不再写一串数字(issue #234)
106
+
107
+ 报告里那条通知是:
108
+
109
+ ```
110
+ > [dsh-connect-workbuddy] 「330135985725」被限流,已改用池中另一个账号回答
111
+ ```
112
+
113
+ 方括号里那串数字是 `uin`(手机号),报告者问的是「能不能直接写账号名」。这句话是
114
+ **唯一**一处用标识符而不是名字称呼账号的地方——卡片、账号池表格、输入框面板全都用
115
+ `preferredAccountName`(显示名 → 企业侧用户名 → 登录别名)。
116
+
117
+ - `describeAccount` 改为先走 `preferredAccountName`,`uin` 退为**兜底**。
118
+ - 兜底保留(而不是换成「未知账号」)是刻意的:桌面 App 没写出名字的账号仍要指得出来,
119
+ 一个能和表格里某一行对上的号码,胜过一句谁也没点名的说明。这一处也由测试钉住。
120
+ - 名字的顺序与卡片完全一致(同一个函数),不再有第二套「谁排第一」的知识。
121
+
122
+ 变异验证:把 `describeAccount` 退回「`uin` 优先、昵称其次」,新增的
123
+ `names the account left behind by its NAME` 立刻变红(失败信息里正是
124
+ `「selected」被限流`),恢复后转绿。
125
+
3
126
  ## 5.21.2 (2026-11-09)
4
127
 
5
128
  > 版本号是 **patch**:新增一个配置键(`pollIntervalMs`)与一个「能力」栏控件,
package/lib/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as DEFAULT_WIRE_PROFILE, Cn as hostPeersInfo, F as WorkBuddyCredentialStore, J as workbuddyOwnAuthPath, N as WORKBUDDY_AUTH_FILE_ENV, P as WORKBUDDY_VAULT_DIRNAME, R as defaultDesktopAuthCandidates, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, W as legacyWorkbuddyOwnAuthPath, X as APP_VERSION, Y as workbuddyVaultDir, a as readHostHeartbeat, an as deriveDeviceId, b as readDeviceSettings, c as WORKBUDDY_CONNECT_VERSION, cn as protectCredentialDirectory, d as rosterSeenPath, f as WORKBUDDY_CN_BASE_ENV, g as createTuringSdk, hn as findWorkbuddyAppExecutableWithSource, in as readDeviceSalt, ln as WORKBUDDY_APP_EXECUTABLE_ENV, m as piAiRuntimeInfo, nn as readDeviceTokenFile, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, ot as describeRequestHeaderNames, p as resolveCnGateway, r as isHeartbeatProcessAlive, rn as ensureDeviceSalt, sn as inspectCredentialDirectory, tn as WORKBUDDY_DEVICE_TOKEN_FILE_ENV, u as describeRosterSeenPayload, w as FALLBACK_WORKBUDDY_MODELS, wn as resolveDshHome, z as defaultDesktopAuthDirs } from "./host-heartbeat-CxvijdHh.js";
2
+ import { $ as DEFAULT_WIRE_PROFILE, Cn as hostPeersInfo, F as WorkBuddyCredentialStore, J as workbuddyOwnAuthPath, N as WORKBUDDY_AUTH_FILE_ENV, P as WORKBUDDY_VAULT_DIRNAME, R as defaultDesktopAuthCandidates, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, W as legacyWorkbuddyOwnAuthPath, X as APP_VERSION, Y as workbuddyVaultDir, a as readHostHeartbeat, an as deriveDeviceId, b as readDeviceSettings, c as WORKBUDDY_CONNECT_VERSION, cn as protectCredentialDirectory, d as rosterSeenPath, f as WORKBUDDY_CN_BASE_ENV, g as createTuringSdk, hn as findWorkbuddyAppExecutableWithSource, in as readDeviceSalt, ln as WORKBUDDY_APP_EXECUTABLE_ENV, m as piAiRuntimeInfo, nn as readDeviceTokenFile, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, ot as describeRequestHeaderNames, p as resolveCnGateway, r as isHeartbeatProcessAlive, rn as ensureDeviceSalt, sn as inspectCredentialDirectory, tn as WORKBUDDY_DEVICE_TOKEN_FILE_ENV, u as describeRosterSeenPayload, w as FALLBACK_WORKBUDDY_MODELS, wn as resolveDshHome, z as defaultDesktopAuthDirs } from "./host-heartbeat-Dq3ITRhF.js";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { dirname, join } from "node:path";
5
5
  import { realpathSync } from "node:fs";
package/lib/client.js CHANGED
@@ -126,9 +126,11 @@ window.__ModuleLoader__.load({
126
126
  /**
127
127
  * 真实设备参数(本机安装的桌面端 Turing Shield SDK)的状态与取值。
128
128
  *
129
- * - `GET` → `{ tier, sdk, token }`,`token` 只有掩码与长度。
129
+ * - `GET` → `{ tier, sdk, token }`,`token` 只有掩码与长度;另带 `sdkEnabled`
130
+ * (总开关的当前值),供卡片画出那个勾选框。
130
131
  * - `POST ?action=refresh` → 强制重取一次,再返回同一形状。
131
132
  * - `POST ?action=reveal` → `{ token }`,完整值,**只在用户显式点击时**。
133
+ * - `POST ?action=enable|disable` → 写总开关。
132
134
  *
133
135
  * 为什么把"完整值"单独做成一个动作:这是一枚能代表这台机器的凭据,卡片是
134
136
  * 一个会被截图、被贴进 issue 的界面。默认只给掩码,复制/查看各要一次显式动作。
@@ -4760,6 +4762,7 @@ window.__ModuleLoader__.load({
4760
4762
  }
4761
4763
  //#endregion
4762
4764
  //#region src/client/device-sdk.ts
4765
+ /** 校验并折成 Host 的类型;形状不认识时返回 `undefined`,面板据此显示"不可用"。 */
4763
4766
  function normalize(body) {
4764
4767
  if (typeof body !== "object" || body === null) return void 0;
4765
4768
  const record = body;
@@ -4770,25 +4773,27 @@ window.__ModuleLoader__.load({
4770
4773
  const tokenRecord = token;
4771
4774
  const sdkState = sdkRecord["state"];
4772
4775
  const tokenState = tokenRecord["state"];
4776
+ const info = {
4777
+ state: sdkState === "ready" || sdkState === "unsupported" || sdkState === "missing" || sdkState === "error" || sdkState === "disabled" ? sdkState : "error",
4778
+ bundle: typeof sdkRecord["bundle"] === "string" ? sdkRecord["bundle"] : "",
4779
+ path: typeof sdkRecord["path"] === "string" ? sdkRecord["path"] : "",
4780
+ platform: typeof sdkRecord["platform"] === "string" ? sdkRecord["platform"] : "",
4781
+ arch: typeof sdkRecord["arch"] === "string" ? sdkRecord["arch"] : "",
4782
+ runtime: typeof sdkRecord["runtime"] === "string" ? sdkRecord["runtime"] : "",
4783
+ ...typeof sdkRecord["reason"] === "string" ? { reason: sdkRecord["reason"] } : {}
4784
+ };
4785
+ const readout = {
4786
+ state: tokenState === "ok" || tokenState === "stale" || tokenState === "unavailable" || tokenState === "idle" ? tokenState : "unavailable",
4787
+ masked: typeof tokenRecord["masked"] === "string" ? tokenRecord["masked"] : "",
4788
+ length: typeof tokenRecord["length"] === "number" ? tokenRecord["length"] : 0,
4789
+ ...typeof tokenRecord["fetchedAtMs"] === "number" ? { fetchedAtMs: tokenRecord["fetchedAtMs"] } : {},
4790
+ ...typeof tokenRecord["lastAttemptMs"] === "number" ? { lastAttemptMs: tokenRecord["lastAttemptMs"] } : {},
4791
+ ...typeof tokenRecord["reason"] === "string" ? { reason: tokenRecord["reason"] } : {}
4792
+ };
4773
4793
  return {
4774
4794
  tier: record["tier"] === "real" ? "real" : "virtual",
4775
- sdk: {
4776
- state: sdkState === "ready" || sdkState === "unsupported" || sdkState === "missing" || sdkState === "error" || sdkState === "disabled" ? sdkState : "error",
4777
- bundle: typeof sdkRecord["bundle"] === "string" ? sdkRecord["bundle"] : "",
4778
- path: typeof sdkRecord["path"] === "string" ? sdkRecord["path"] : "",
4779
- platform: typeof sdkRecord["platform"] === "string" ? sdkRecord["platform"] : "",
4780
- arch: typeof sdkRecord["arch"] === "string" ? sdkRecord["arch"] : "",
4781
- runtime: typeof sdkRecord["runtime"] === "string" ? sdkRecord["runtime"] : "",
4782
- ...typeof sdkRecord["reason"] === "string" ? { reason: sdkRecord["reason"] } : {}
4783
- },
4784
- token: {
4785
- state: tokenState === "ok" || tokenState === "stale" || tokenState === "unavailable" || tokenState === "idle" ? tokenState : "unavailable",
4786
- masked: typeof tokenRecord["masked"] === "string" ? tokenRecord["masked"] : "",
4787
- length: typeof tokenRecord["length"] === "number" ? tokenRecord["length"] : 0,
4788
- ...typeof tokenRecord["fetchedAtMs"] === "number" ? { fetchedAtMs: tokenRecord["fetchedAtMs"] } : {},
4789
- ...typeof tokenRecord["lastAttemptMs"] === "number" ? { lastAttemptMs: tokenRecord["lastAttemptMs"] } : {},
4790
- ...typeof tokenRecord["reason"] === "string" ? { reason: tokenRecord["reason"] } : {}
4791
- },
4795
+ sdk: info,
4796
+ token: readout,
4792
4797
  ...typeof record["sdkEnabled"] === "boolean" ? { sdkEnabled: record["sdkEnabled"] } : {}
4793
4798
  };
4794
4799
  }
@@ -4913,6 +4918,8 @@ window.__ModuleLoader__.load({
4913
4918
  */
4914
4919
  const [sdkMasterEnabled, setSdkMasterEnabled] = (0, react.useState)(void 0);
4915
4920
  const [savingMaster, setSavingMaster] = (0, react.useState)(false);
4921
+ /** 七处 `catch` 原本各写一遍同样的展平;收成一个。 */
4922
+ const fail = (cause) => setError(cause instanceof Error ? cause.message : String(cause));
4916
4923
  const load = (0, react.useCallback)(async (refresh) => {
4917
4924
  if (path === "") return;
4918
4925
  setBusy(true);
@@ -4926,7 +4933,7 @@ window.__ModuleLoader__.load({
4926
4933
  setCopied(false);
4927
4934
  }
4928
4935
  } catch (cause) {
4929
- setError(cause instanceof Error ? cause.message : String(cause));
4936
+ fail(cause);
4930
4937
  } finally {
4931
4938
  setBusy(false);
4932
4939
  setLoading(false);
@@ -4994,7 +5001,7 @@ window.__ModuleLoader__.load({
4994
5001
  if (full === void 0) setError(t("sdk.noValue"));
4995
5002
  else setValue(full);
4996
5003
  } catch (cause) {
4997
- setError(cause instanceof Error ? cause.message : String(cause));
5004
+ fail(cause);
4998
5005
  }
4999
5006
  };
5000
5007
  const copy = async () => {
@@ -5011,62 +5018,57 @@ window.__ModuleLoader__.load({
5011
5018
  setCopied(false);
5012
5019
  }, 2e3);
5013
5020
  } catch (cause) {
5014
- setError(cause instanceof Error ? cause.message : String(cause));
5021
+ fail(cause);
5015
5022
  }
5016
5023
  };
5017
5024
  /**
5018
- * 保存目录:写盘之后**立刻重探一次**。
5019
- *
5020
- * 只写不重探会让用户看见"已保存"而状态行还是旧的——那正是这条意见要消掉的
5021
- * 迷雾(`dirSource` 让新目录下一次 `probe` 就生效,所以这里必须主动触发那一次)。
5025
+ * 保存目录:写盘之后**立刻重探一次**。清空按钮复用同一条路径(原来内联重写了
5026
+ * 整个 try/catch/finally,是这份面板里最明显的一处复制粘贴)。
5022
5027
  */
5023
- const saveDir = async () => {
5028
+ const saveDir = async (dir = draftDir.trim()) => {
5024
5029
  if (settingsPath === "") return;
5025
5030
  setSavingDir(true);
5026
5031
  setError(void 0);
5027
5032
  setSavedNote(false);
5028
5033
  try {
5029
- const next = await putDeviceSdk(settingsPath, { sdkDir: draftDir.trim() });
5034
+ const next = await putDeviceSdk(settingsPath, { sdkDir: dir });
5030
5035
  setSdkDir(next.sdkDir);
5031
5036
  setDraftDir(next.sdkDir);
5032
5037
  setSavedNote(true);
5033
5038
  await load(true);
5034
5039
  } catch (cause) {
5035
- setError(cause instanceof Error ? cause.message : String(cause));
5040
+ fail(cause);
5036
5041
  } finally {
5037
5042
  setSavingDir(false);
5038
5043
  }
5039
5044
  };
5040
- const saveFallback = async (value) => {
5045
+ const saveFallback = async (nextValue) => {
5041
5046
  if (settingsPath === "") return;
5042
5047
  setSavingFallback(true);
5043
5048
  setError(void 0);
5044
5049
  try {
5045
- const next = await putDeviceSdk(settingsPath, { sdkFallbackToVirtual: value });
5050
+ const next = await putDeviceSdk(settingsPath, { sdkFallbackToVirtual: nextValue });
5046
5051
  setFallback(next.sdkFallbackToVirtual);
5047
5052
  } catch (cause) {
5048
- setError(cause instanceof Error ? cause.message : String(cause));
5053
+ fail(cause);
5049
5054
  } finally {
5050
5055
  setSavingFallback(false);
5051
5056
  }
5052
5057
  };
5053
5058
  /**
5054
- * 切换 SDK 总开关。
5055
- *
5056
- * 写完之后**重读一次快照**:关掉之后状态行必须立刻变成 `disabled`,而那一条是
5057
- * 从 `GET /device-sdk` 算出来的——只改本地 state 会让"已关"与下面那行"正常"
5058
- * 并存,正是这一页最不该出现的自相矛盾。
5059
+ * 切换 SDK 总开关。写完重读一次快照:状态行是从 `GET /device-sdk` 算的,
5060
+ * 只改本地 state 会让"已关"与下面那行"正常"并存。
5059
5061
  */
5060
- const saveMaster = async (value) => {
5062
+ const saveMaster = async (nextValue) => {
5061
5063
  if (path === "") return;
5062
5064
  setSavingMaster(true);
5063
5065
  setError(void 0);
5064
5066
  try {
5065
- await setDeviceSdkEnabled(path, value);
5066
- setSdkMasterEnabled(value);
5067
+ await setDeviceSdkEnabled(path, nextValue);
5068
+ setSdkMasterEnabled(nextValue);
5067
5069
  await load(false);
5068
5070
  } catch (cause) {
5069
- setError(cause instanceof Error ? cause.message : String(cause));
5071
+ fail(cause);
5070
5072
  } finally {
5071
5073
  setSavingMaster(false);
5072
5074
  }
@@ -5214,22 +5216,7 @@ window.__ModuleLoader__.load({
5214
5216
  className: "dsm-btn dsm-btn-outline",
5215
5217
  disabled: savingDir,
5216
5218
  onClick: () => {
5217
- setDraftDir("");
5218
- (async () => {
5219
- setSavingDir(true);
5220
- setError(void 0);
5221
- try {
5222
- const next = await putDeviceSdk(settingsPath, { sdkDir: "" });
5223
- setSdkDir(next.sdkDir);
5224
- setDraftDir("");
5225
- setSavedNote(true);
5226
- await load(true);
5227
- } catch (cause) {
5228
- setError(cause instanceof Error ? cause.message : String(cause));
5229
- } finally {
5230
- setSavingDir(false);
5231
- }
5232
- })();
5219
+ saveDir("");
5233
5220
  },
5234
5221
  children: t("sdk.dirClear")
5235
5222
  })
@@ -15175,7 +15162,7 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
15175
15162
  "sdk.statusError": "The SDK could not be loaded",
15176
15163
  "sdk.statusDisabled": "Turned off in settings",
15177
15164
  "sdk.masterLabel": "Use the real-device SDK",
15178
- "sdk.masterHint": "On: discover the installed desktop SDK, fetch its device token in a background child process and keep it fresh every 10 minutes. Off: none of that happens — no discovery, no child process, no prewarming — so the Real tier has no token to send. The Virtual tier is unaffected (its ids come from the local salt), so turning this off is safe if you only want virtual devices.",
15165
+ "sdk.masterHint": "On: discover the installed desktop SDK, fetch its device token in a background child process and keep it fresh every 10 minutes. Off: none of that happens — no discovery, no child process, no prewarming — so the Real tier has no token to send. The Virtual tier is unaffected (its ids come from the local salt), so turning this off is safe if you only want virtual devices. The switch takes effect immediately: turning it on starts fetching at once and turning it off stops the timer, with no plugin reload.",
15179
15166
  "sdk.bundle": "SDK",
15180
15167
  "sdk.runtime": "Runtime",
15181
15168
  "sdk.fetched": "Last fetched",
@@ -15729,7 +15716,7 @@ ${u} ${p}-pool .sw input:checked+.sw-track::after{transform:translateX(16px)}
15729
15716
  "sdk.statusError": "SDK 加载失败",
15730
15717
  "sdk.statusDisabled": "已在设置里关闭",
15731
15718
  "sdk.masterLabel": "启用真实设备 SDK",
15732
- "sdk.masterHint": "开启时:查找本机安装的桌面端 SDK、在后台子进程里取设备 token,并每 10 分钟换新一次。关闭时这些事一件都不做——不查找、不起子进程、不预热——「真实值」档因此没有 token 可发。「虚拟值」档不受影响(它的 id 由本机盐派生),只想用虚拟设备的话关掉是安全的。",
15719
+ "sdk.masterHint": "开启时:查找本机安装的桌面端 SDK、在后台子进程里取设备 token,并每 10 分钟换新一次。关闭时这些事一件都不做——不查找、不起子进程、不预热——「真实值」档因此没有 token 可发。「虚拟值」档不受影响(它的 id 由本机盐派生),只想用虚拟设备的话关掉是安全的。开关即时生效:打开后立刻开始取,关掉即停掉定时器,都不用重载插件。",
15733
15720
  "sdk.bundle": "SDK",
15734
15721
  "sdk.runtime": "运行时",
15735
15722
  "sdk.fetched": "最近取到",
@@ -10527,7 +10527,7 @@ function describeRosterSeenPayload(raw) {
10527
10527
  //#endregion
10528
10528
  //#region src/version.ts
10529
10529
  /** The npm package version this build was produced from. */
10530
- const WORKBUDDY_CONNECT_VERSION = "5.21.2";
10530
+ const WORKBUDDY_CONNECT_VERSION = "5.21.4";
10531
10531
  //#endregion
10532
10532
  //#region src/host-heartbeat.ts
10533
10533
  /**
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $t as imageDefaultFor, A as withoutRouters, At as offRefused, B as defaultDesktopAuthPath, Bt as IMAGE_TAG_TEXT_TO_IMAGE, C as setDeviceMode, Ct as attachBusyLevels, D as applyContextBudgets, Dt as defaultOffModelIds, E as WorkBuddyCatalog, En as writeFileAtomic, Et as REFUSES_OFF_MODEL_IDS, F as WorkBuddyCredentialStore, Ft as WorkBuddyVideoError, G as parseWorkBuddyAuth, Gt as isBareBase64Image, H as isEncryptedCredentialError, Ht as WorkBuddyImageError, I as WorkBuddyEncryptedCredentialError, It as parseSupportedSecondsRange, J as workbuddyOwnAuthPath, Jt as sniffImageMime, K as preferredAccountName, Kt as parseImageDataUrl, L as authFileName, Lt as pickVideoModel, M as WORKBUDDY_AUTH_FILENAME, Mt as withEffectiveOff, N as WORKBUDDY_AUTH_FILE_ENV, Nt as VIDEO_TAG_IMAGE_TO_VIDEO, O as deriveCatalog, Ot as lastRefusalFor, Pt as VIDEO_TAG_TEXT_TO_VIDEO, Q as CREDENTIAL_REJECTED_CODE, Qt as NATIVE_MODALITY_BY_MODEL_ID, R as defaultDesktopAuthCandidates, Rt as resolveVideoParams, S as saveDeviceSdkSettings, Sn as workbuddyAppExecutableCandidates, St as rewriteSessionTitleModel, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tn as withFileLock, Tt as selectPromoBadge, U as isVaultAccountId, Ut as imageDataUrl, V as hasEncryptedCredentialFields, Vt as MAX_INPUT_IMAGE_BYTES, W as legacyWorkbuddyOwnAuthPath, Wt as imageMimeForPath, X as APP_VERSION, Xt as queueNoticeText, Yt as parseQueueAnswer, Z as CONTEXT_OVERFLOW_MARKER, Zt as pruneTempDir, _ as createDeviceProfileLookup, _n as isWorkbuddyBundle, _t as parseUpstreamModel, a as readHostHeartbeat, at as declaredTools, b as readDeviceSettings, bn as openEncryptedField, bt as regionOf, c as WORKBUDDY_CONNECT_VERSION, ct as isContextTooLongBody, dn as deriveAtRestKey, dt as isFirstMessageGateBody, en as nativeModalityOf, et as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, fn as deriveAtRestKeyId, ft as knownRegionOf, g as createTuringSdk, gn as isEncryptedFieldWrapper, gt as parseReasoning, h as createDeviceSdkPort, ht as parseCreditMultiplier, i as processStartTimeMs, it as classifyUpstreamError, j as ENCRYPTED_CREDENTIAL_CODE, jt as recordRefusal, k as fallbackModelsFor, kt as offDefaultFor, l as createFileRosterSeenStore, ln as WORKBUDDY_APP_EXECUTABLE_ENV, lt as isConversationIdGateBody, m as piAiRuntimeInfo, mn as findWorkbuddyAppExecutable, mt as openingEvidenceOfBody, n as clearHostHeartbeat, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, on as isDeviceId, p as resolveCnGateway, pn as fetchAtRestKeyPayload, pt as modelIdOfBody, q as workbuddyAccountId, qt as pickMediaModel, r as isHeartbeatProcessAlive, rt as channelGateMemberOf, s as writeHostHeartbeat, st as forceNeutralHead, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as WorkBuddyCredentialRejectedError, un as clearAtRestKeyCache, ut as isCredentialRejectedError, v as describeDerivedDevices, vn as macosBundleExecutable, vt as perturbChannelFingerprints, w as FALLBACK_WORKBUDDY_MODELS, wn as resolveDshHome, wt as promoBadgeTone, x as saveDeviceProfile, xn as readAtRestKey, xt as requestEvidenceOf, y as isDeviceMode, yn as macosNestedAppBundles, yt as prepareChatBody, z as defaultDesktopAuthDirs, zt as IMAGE_TAG_IMAGE_TO_IMAGE } from "./host-heartbeat-CxvijdHh.js";
1
+ import { $t as imageDefaultFor, A as withoutRouters, At as offRefused, B as defaultDesktopAuthPath, Bt as IMAGE_TAG_TEXT_TO_IMAGE, C as setDeviceMode, Ct as attachBusyLevels, D as applyContextBudgets, Dt as defaultOffModelIds, E as WorkBuddyCatalog, En as writeFileAtomic, Et as REFUSES_OFF_MODEL_IDS, F as WorkBuddyCredentialStore, Ft as WorkBuddyVideoError, G as parseWorkBuddyAuth, Gt as isBareBase64Image, H as isEncryptedCredentialError, Ht as WorkBuddyImageError, I as WorkBuddyEncryptedCredentialError, It as parseSupportedSecondsRange, J as workbuddyOwnAuthPath, Jt as sniffImageMime, K as preferredAccountName, Kt as parseImageDataUrl, L as authFileName, Lt as pickVideoModel, M as WORKBUDDY_AUTH_FILENAME, Mt as withEffectiveOff, N as WORKBUDDY_AUTH_FILE_ENV, Nt as VIDEO_TAG_IMAGE_TO_VIDEO, O as deriveCatalog, Ot as lastRefusalFor, Pt as VIDEO_TAG_TEXT_TO_VIDEO, Q as CREDENTIAL_REJECTED_CODE, Qt as NATIVE_MODALITY_BY_MODEL_ID, R as defaultDesktopAuthCandidates, Rt as resolveVideoParams, S as saveDeviceSdkSettings, Sn as workbuddyAppExecutableCandidates, St as rewriteSessionTitleModel, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tn as withFileLock, Tt as selectPromoBadge, U as isVaultAccountId, Ut as imageDataUrl, V as hasEncryptedCredentialFields, Vt as MAX_INPUT_IMAGE_BYTES, W as legacyWorkbuddyOwnAuthPath, Wt as imageMimeForPath, X as APP_VERSION, Xt as queueNoticeText, Yt as parseQueueAnswer, Z as CONTEXT_OVERFLOW_MARKER, Zt as pruneTempDir, _ as createDeviceProfileLookup, _n as isWorkbuddyBundle, _t as parseUpstreamModel, a as readHostHeartbeat, at as declaredTools, b as readDeviceSettings, bn as openEncryptedField, bt as regionOf, c as WORKBUDDY_CONNECT_VERSION, ct as isContextTooLongBody, dn as deriveAtRestKey, dt as isFirstMessageGateBody, en as nativeModalityOf, et as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, fn as deriveAtRestKeyId, ft as knownRegionOf, g as createTuringSdk, gn as isEncryptedFieldWrapper, gt as parseReasoning, h as createDeviceSdkPort, ht as parseCreditMultiplier, i as processStartTimeMs, it as classifyUpstreamError, j as ENCRYPTED_CREDENTIAL_CODE, jt as recordRefusal, k as fallbackModelsFor, kt as offDefaultFor, l as createFileRosterSeenStore, ln as WORKBUDDY_APP_EXECUTABLE_ENV, lt as isConversationIdGateBody, m as piAiRuntimeInfo, mn as findWorkbuddyAppExecutable, mt as openingEvidenceOfBody, n as clearHostHeartbeat, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, on as isDeviceId, p as resolveCnGateway, pn as fetchAtRestKeyPayload, pt as modelIdOfBody, q as workbuddyAccountId, qt as pickMediaModel, r as isHeartbeatProcessAlive, rt as channelGateMemberOf, s as writeHostHeartbeat, st as forceNeutralHead, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as WorkBuddyCredentialRejectedError, un as clearAtRestKeyCache, ut as isCredentialRejectedError, v as describeDerivedDevices, vn as macosBundleExecutable, vt as perturbChannelFingerprints, w as FALLBACK_WORKBUDDY_MODELS, wn as resolveDshHome, wt as promoBadgeTone, x as saveDeviceProfile, xn as readAtRestKey, xt as requestEvidenceOf, y as isDeviceMode, yn as macosNestedAppBundles, yt as prepareChatBody, z as defaultDesktopAuthDirs, zt as IMAGE_TAG_IMAGE_TO_IMAGE } from "./host-heartbeat-Dq3ITRhF.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { appendFile, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -389,15 +389,17 @@ const WORKBUDDY_DEVICE_PROFILE_PATH = "/plugins/dsh-connect-workbuddy/device-pro
389
389
  /**
390
390
  * 真实设备参数(本机安装的桌面端 Turing Shield SDK)的状态与取值。
391
391
  *
392
- * - `GET` → `{ tier, sdk, token }`,`token` 只有掩码与长度。
392
+ * - `GET` → `{ tier, sdk, token }`,`token` 只有掩码与长度;另带 `sdkEnabled`
393
+ * (总开关的当前值),供卡片画出那个勾选框。
393
394
  * - `POST ?action=refresh` → 强制重取一次,再返回同一形状。
394
395
  * - `POST ?action=reveal` → `{ token }`,完整值,**只在用户显式点击时**。
396
+ * - `POST ?action=enable|disable` → 写总开关。
395
397
  *
396
398
  * 为什么把"完整值"单独做成一个动作:这是一枚能代表这台机器的凭据,卡片是
397
399
  * 一个会被截图、被贴进 issue 的界面。默认只给掩码,复制/查看各要一次显式动作。
398
400
  */
399
401
  const WORKBUDDY_DEVICE_SDK_PATH = "/plugins/dsh-connect-workbuddy/device-sdk";
400
- /** Query parameter selecting it. */
402
+ /** Query parameter selecting the POST action. */
401
403
  const WORKBUDDY_DEVICE_SDK_ACTION_PARAM = "action";
402
404
  /**
403
405
  * The refresh intervals the card offers, in milliseconds.
@@ -3384,8 +3386,8 @@ function attachUsage(directory, report, onError) {
3384
3386
  * live here rather than being re-derived per route. A previous version kept the
3385
3387
  * Host check inside `shim.ts` and only the Origin check inside `web-status.ts`,
3386
3388
  * which meant the shim's chat route had both guards while the settings card's
3387
- * thirteen routes (ten POST + three GET) had one — the asymmetry was invisible
3388
- * because each file looked internally consistent.
3389
+ * routes had one — the asymmetry was invisible because each file looked
3390
+ * internally consistent.
3389
3391
  *
3390
3392
  * - **Host** answers "is this request addressed to the interface it landed on?".
3391
3393
  * A DNS-rebinding page sends requests whose `Host` is the *attacker's* domain
@@ -5349,17 +5351,26 @@ function callsFrame(chunk, choice, calls) {
5349
5351
  return `data: ${JSON.stringify(next)}\n\n`;
5350
5352
  }
5351
5353
  /**
5352
- * How to name a pool account in a sentence the USER reads.
5354
+ * How to name a pool account in a sentence the USER reads (issue #234).
5353
5355
  *
5354
- * Prefers the phone number (`uin`) because that is what the pool table shows and
5355
- * what a person recognises; the nickname and the opaque account id are fallbacks
5356
- * so this can never render an empty name. Deliberately NOT the hashed account id
5357
- * on its own: a 24-character hex digest identifies an account to the plugin, but
5358
- * to the person reading the answer it identifies nothing.
5356
+ * The NAME comes first, in the very order the card and the pool table use —
5357
+ * `preferredAccountName` (display name, then the enterprise-side name, then the
5358
+ * login alias). The notice used to lead with `uin`, which is the phone number:
5359
+ * a reporter read 「330135985725」 and could not tell whether that was an
5360
+ * account at all, let alone which one. Every other surface names an account by
5361
+ * its name, so this one must too.
5362
+ *
5363
+ * The identifier survives only as a LAST resort, for the account the desktop
5364
+ * app published no name for — an unnamed account still has to be pointed at,
5365
+ * and a number the user can match against a row beats a sentence that names
5366
+ * nobody. Deliberately NOT the hashed account id while a `uin` exists: a
5367
+ * 24-character hex digest identifies an account to the plugin, but to the
5368
+ * person reading the answer it identifies nothing.
5359
5369
  */
5360
5370
  function describeAccount(credential) {
5371
+ const name = preferredAccountName(credential);
5372
+ if (name !== "") return name;
5361
5373
  if (credential.uin !== void 0 && credential.uin !== "") return credential.uin;
5362
- if (credential.nickname !== void 0 && credential.nickname !== "") return credential.nickname;
5363
5374
  return workbuddyAccountId(credential);
5364
5375
  }
5365
5376
  /**
@@ -11568,7 +11579,7 @@ function readJsonBody(req, limitBytes = PROBE_BODY_LIMIT) {
11568
11579
  * Origin alone is not enough. It answers "did a foreign page cause this?", but a
11569
11580
  * DNS-rebinding attack arrives with the attacker's domain in `Host` and no
11570
11581
  * useful Origin, so the Host check is what drops it — and until this function
11571
- * existed, all thirteen routes below (ten POST, three GET) had only the Origin
11582
+ * existed, all of the routes below had only the Origin
11572
11583
  * half while the shim's chat route had both. The asymmetry was invisible per-file.
11573
11584
  *
11574
11585
  * Both halves are cheap and NEITHER IS AUTHENTICATION. A local process — or any
@@ -12071,211 +12082,174 @@ function requestRegion(req, res) {
12071
12082
  */
12072
12083
  function registerWorkBuddyStatusRoute(ctx, deps) {
12073
12084
  ctx.effect(() => {
12074
- const disposeUsage = ctx.webServer.register({
12075
- kind: "exact",
12076
- path: WORKBUDDY_USAGE_PATH,
12077
- handler: async (req, res) => {
12078
- if (req.method !== "GET") {
12079
- json(res, 405, { error: "method not allowed" });
12080
- return;
12085
+ /**
12086
+ * 注册时自动收好 disposer。曾经每个路由 `const disposeX = register(...)`,再
12087
+ * 在末尾手写 16 行 `disposeX()`——`benefit/claim` 漏了一行(issue #86),热重载
12088
+ * 时宿主因重复注册同路径而抛错,后面的路由全部注册不上,卡片半数按钮答 405。
12089
+ * 收成一个数组后,「新加路由忘了加卸载」这一类错误不可能再发生。
12090
+ */
12091
+ const disposers = [];
12092
+ const route = (entry) => {
12093
+ disposers.push(ctx.webServer.register(entry));
12094
+ };
12095
+ /**
12096
+ * 路由骨架:方法闸 → loopback → 可选前置条件 → 区域 → try/catch → 500。
12097
+ *
12098
+ * 这几道闸原先在每个 handler 里各抄一遍(16 处 `requireLoopback`、16 处
12099
+ * `405`、22 处 `500`)。抄漏一道不会有任何编译错误,却是一个真实的
12100
+ * DNS-rebinding 或跨区泄漏面——见 `requireLoopback` 自己的注释。收进这里
12101
+ * 之后,handler 只写业务,也不可能漏闸。
12102
+ *
12103
+ * `ready` 在区域解析**之前**跑:`models` / `media` 这类路由要先答「宿主没有
12104
+ * 这项能力」的 503,再谈区域;反过来会让一个缺区域参数的请求先拿到 400。
12105
+ */
12106
+ function raw(spec, run) {
12107
+ route({
12108
+ kind: "exact",
12109
+ path: spec.path,
12110
+ handler: async (req, res) => {
12111
+ if (req.method !== spec.method) return json(res, 405, { error: "method not allowed" });
12112
+ if (!requireLoopback(req, res)) return;
12113
+ if (spec.ready !== void 0 && !spec.ready(res)) return;
12114
+ try {
12115
+ await run(req, res);
12116
+ } catch (error) {
12117
+ json(res, 500, { error: safeMessage(error) });
12118
+ }
12081
12119
  }
12082
- if (!requireLoopback(req, res)) return;
12120
+ });
12121
+ }
12122
+ /**
12123
+ * 带区域参数的路由:区域解析在 try 之外,与原来的顺序一致。
12124
+ * 不带区域参数的路由直接调 `raw`——区域参数会让 `requestRegion` 把一个
12125
+ * 合法读答成 400(`cli-live` 就是这种)。
12126
+ */
12127
+ function endpointRegion(spec, handle) {
12128
+ raw(spec, (req, res) => {
12083
12129
  const region = requestRegion(req, res);
12084
12130
  if (region === void 0) return;
12085
- const detail = fastDetailOf(req.url ?? "") ? "fast" : "full";
12086
- try {
12087
- json(res, 200, await workBuddyWebStatus(deps, region, { detail }));
12088
- } catch (error) {
12089
- json(res, 500, { error: safeMessage(error) });
12090
- }
12091
- }
12131
+ return handle(req, res, region);
12132
+ });
12133
+ }
12134
+ endpointRegion({
12135
+ path: WORKBUDDY_USAGE_PATH,
12136
+ method: "GET"
12137
+ }, async (req, res, region) => {
12138
+ json(res, 200, await workBuddyWebStatus(deps, region, { detail: fastDetailOf(req.url ?? "") ? "fast" : "full" }));
12092
12139
  });
12093
- const disposeAccountCredits = ctx.webServer.register({
12094
- kind: "exact",
12140
+ endpointRegion({
12095
12141
  path: WORKBUDDY_ACCOUNT_CREDITS_PATH,
12096
- handler: async (req, res) => {
12097
- if (req.method !== "GET") return json(res, 405, { error: "method not allowed" });
12098
- if (!requireLoopback(req, res)) return;
12099
- const region = requestRegion(req, res);
12100
- if (region === void 0) return;
12101
- try {
12102
- json(res, 200, { accounts: await workBuddyAccountCredits(deps, region) });
12103
- } catch (error) {
12104
- json(res, 500, { error: safeMessage(error) });
12105
- }
12106
- }
12142
+ method: "GET"
12143
+ }, async (_req, res, region) => {
12144
+ json(res, 200, { accounts: await workBuddyAccountCredits(deps, region) });
12107
12145
  });
12108
- const disposeAccounts = ctx.webServer.register({
12109
- kind: "exact",
12146
+ endpointRegion({
12110
12147
  path: WORKBUDDY_ACCOUNTS_REFRESH_PATH,
12111
- handler: async (req, res) => {
12112
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12113
- if (!requireLoopback(req, res)) return;
12114
- const region = requestRegion(req, res);
12115
- if (region === void 0) return;
12116
- try {
12117
- const store = deps.store(region);
12118
- const dismissalsCleared = await store.clearDismissals();
12119
- const accounts = await store.accounts();
12120
- deps.regionUsable?.(region, accounts.length > 0);
12121
- json(res, 200, {
12122
- accounts: accounts.map(toWebAccount),
12123
- dismissalsCleared
12124
- });
12125
- } catch (error) {
12126
- json(res, 500, { error: safeMessage(error) });
12127
- }
12128
- }
12148
+ method: "POST"
12149
+ }, async (_req, res, region) => {
12150
+ const store = deps.store(region);
12151
+ const dismissalsCleared = await store.clearDismissals();
12152
+ const accounts = await store.accounts();
12153
+ deps.regionUsable?.(region, accounts.length > 0);
12154
+ json(res, 200, {
12155
+ accounts: accounts.map(toWebAccount),
12156
+ dismissalsCleared
12157
+ });
12129
12158
  });
12130
- const disposeCheckin = ctx.webServer.register({
12131
- kind: "exact",
12159
+ endpointRegion({
12132
12160
  path: WORKBUDDY_CHECKIN_PATH,
12133
- handler: async (req, res) => {
12134
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12135
- if (!requireLoopback(req, res)) return;
12136
- const region = requestRegion(req, res);
12137
- if (region === void 0) return;
12138
- try {
12139
- const credential = await deps.store(region).resolve();
12140
- const current = await deps.client.fetchCheckinStatus(credential);
12141
- if (!current.active) return json(res, 409, { error: "check-in activity is not active" });
12142
- if (current.todayCheckedIn) return json(res, 200, {
12143
- alreadyCheckedIn: true,
12144
- checkin: current
12145
- });
12146
- json(res, 200, {
12147
- alreadyCheckedIn: false,
12148
- claim: await deps.client.claimDailyCheckin(credential),
12149
- checkin: await deps.client.fetchCheckinStatus(credential)
12150
- });
12151
- } catch (error) {
12152
- json(res, 500, { error: safeMessage(error) });
12153
- }
12154
- }
12161
+ method: "POST"
12162
+ }, async (_req, res, region) => {
12163
+ const credential = await deps.store(region).resolve();
12164
+ const current = await deps.client.fetchCheckinStatus(credential);
12165
+ if (!current.active) return json(res, 409, { error: "check-in activity is not active" });
12166
+ if (current.todayCheckedIn) return json(res, 200, {
12167
+ alreadyCheckedIn: true,
12168
+ checkin: current
12169
+ });
12170
+ json(res, 200, {
12171
+ alreadyCheckedIn: false,
12172
+ claim: await deps.client.claimDailyCheckin(credential),
12173
+ checkin: await deps.client.fetchCheckinStatus(credential)
12174
+ });
12155
12175
  });
12156
- const disposeBenefitClaim = ctx.webServer.register({
12157
- kind: "exact",
12176
+ endpointRegion({
12158
12177
  path: WORKBUDDY_BENEFIT_CLAIM_PATH,
12159
- handler: async (req, res) => {
12160
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12161
- if (!requireLoopback(req, res)) return;
12162
- const region = requestRegion(req, res);
12163
- if (region === void 0) return;
12164
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
12165
- const accountId = url.searchParams.get(WORKBUDDY_POOL_ACCOUNT_PARAM);
12166
- const kind = url.searchParams.get("kind");
12167
- if (accountId === null || accountId === "") return json(res, 400, { error: "accountId is required" });
12168
- if (kind !== "compensation" && kind !== "gift") return json(res, 400, { error: "kind must be compensation or gift" });
12169
- try {
12170
- const credential = await deps.store(region).credentialFor(accountId);
12171
- if (credential === void 0) return json(res, 404, { error: "no credential for this account" });
12172
- if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") return json(res, 409, { error: "enterprise-account-unsupported" });
12173
- const target = (await deps.client.fetchBenefits(credential)).find((benefit) => benefit.kind === kind);
12174
- if (target === void 0) return json(res, 404, { error: "benefit not available on this account" });
12175
- if (target.claimed) return json(res, 409, {
12176
- error: "benefit already claimed",
12177
- benefit: target
12178
- });
12179
- if (!target.active) return json(res, 409, {
12180
- error: "benefit activity is not active",
12181
- benefit: target
12182
- });
12183
- await deps.client.claimBenefit(credential, kind);
12184
- deps.pool?.invalidateBenefit?.(region, accountId);
12185
- json(res, 200, {
12186
- claimed: true,
12187
- benefit: (await deps.client.fetchBenefits(credential)).find((benefit) => benefit.kind === kind) ?? target
12188
- });
12189
- } catch (error) {
12190
- json(res, 500, { error: safeMessage(error) });
12191
- }
12192
- }
12178
+ method: "POST"
12179
+ }, async (req, res, region) => {
12180
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
12181
+ const accountId = url.searchParams.get(WORKBUDDY_POOL_ACCOUNT_PARAM);
12182
+ const kind = url.searchParams.get("kind");
12183
+ if (accountId === null || accountId === "") return json(res, 400, { error: "accountId is required" });
12184
+ if (kind !== "compensation" && kind !== "gift") return json(res, 400, { error: "kind must be compensation or gift" });
12185
+ const credential = await deps.store(region).credentialFor(accountId);
12186
+ if (credential === void 0) return json(res, 404, { error: "no credential for this account" });
12187
+ if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") return json(res, 409, { error: "enterprise-account-unsupported" });
12188
+ const target = (await deps.client.fetchBenefits(credential)).find((benefit) => benefit.kind === kind);
12189
+ if (target === void 0) return json(res, 404, { error: "benefit not available on this account" });
12190
+ if (target.claimed) return json(res, 409, {
12191
+ error: "benefit already claimed",
12192
+ benefit: target
12193
+ });
12194
+ if (!target.active) return json(res, 409, {
12195
+ error: "benefit activity is not active",
12196
+ benefit: target
12197
+ });
12198
+ await deps.client.claimBenefit(credential, kind);
12199
+ deps.pool?.invalidateBenefit?.(region, accountId);
12200
+ json(res, 200, {
12201
+ claimed: true,
12202
+ benefit: (await deps.client.fetchBenefits(credential)).find((benefit) => benefit.kind === kind) ?? target
12203
+ });
12193
12204
  });
12194
- const disposeRefresh = ctx.webServer.register({
12195
- kind: "exact",
12205
+ endpointRegion({
12196
12206
  path: WORKBUDDY_MODELS_REFRESH_PATH,
12197
- handler: async (req, res) => {
12198
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12199
- if (!requireLoopback(req, res)) return;
12200
- if (deps.discoverModels === void 0) return json(res, 503, { error: "model refresh unavailable" });
12201
- if (deps.persistModels === void 0) return json(res, 503, { error: "model refresh cannot be persisted" });
12202
- const region = requestRegion(req, res);
12203
- if (region === void 0) return;
12204
- try {
12205
- const models = await deps.discoverModels(region);
12206
- await deps.persistModels(region, models);
12207
- json(res, 200, { models: models.map((model) => toWebModel(model, deps.contextBudgets(region))) });
12208
- } catch (error) {
12209
- json(res, 500, { error: safeMessage(error) });
12210
- }
12211
- }
12207
+ method: "POST",
12208
+ ready: (res) => deps.discoverModels === void 0 ? (json(res, 503, { error: "model refresh unavailable" }), false) : deps.persistModels === void 0 ? (json(res, 503, { error: "model refresh cannot be persisted" }), false) : true
12209
+ }, async (_req, res, region) => {
12210
+ const models = await deps.discoverModels(region);
12211
+ await deps.persistModels(region, models);
12212
+ json(res, 200, { models: models.map((model) => toWebModel(model, deps.contextBudgets(region))) });
12212
12213
  });
12213
- const disposeMediaModels = ctx.webServer.register({
12214
- kind: "exact",
12214
+ endpointRegion({
12215
12215
  path: WORKBUDDY_MEDIA_MODELS_PATH,
12216
- handler: async (req, res) => {
12217
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12218
- if (!requireLoopback(req, res)) return;
12219
- if (deps.mediaModels === void 0) return json(res, 503, { error: "media model list unavailable" });
12220
- const region = requestRegion(req, res);
12221
- if (region === void 0) return;
12222
- try {
12223
- const refresh = new URL(req.url ?? "/", "http://localhost").searchParams.get("refresh") === "1";
12224
- json(res, 200, { models: (await deps.mediaModels(region, { refresh })).map((model) => ({
12225
- id: model.id,
12226
- name: model.name,
12227
- tags: [...model.tags]
12228
- })) });
12229
- } catch (error) {
12230
- json(res, 500, { error: safeMessage(error) });
12231
- }
12232
- }
12216
+ method: "POST",
12217
+ ready: (res) => deps.mediaModels !== void 0 ? true : (json(res, 503, { error: "media model list unavailable" }), false)
12218
+ }, async (req, res, region) => {
12219
+ const refresh = new URL(req.url ?? "/", "http://localhost").searchParams.get("refresh") === "1";
12220
+ json(res, 200, { models: (await deps.mediaModels(region, { refresh })).map((model) => ({
12221
+ id: model.id,
12222
+ name: model.name,
12223
+ tags: [...model.tags]
12224
+ })) });
12233
12225
  });
12234
- const disposeProbe = ctx.webServer.register({
12235
- kind: "exact",
12226
+ endpointRegion({
12236
12227
  path: WORKBUDDY_PROBE_PATH,
12237
- handler: async (req, res) => {
12238
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12239
- if (!requireLoopback(req, res)) return;
12240
- if (deps.probeModels === void 0) return json(res, 503, { error: "model probe unavailable" });
12241
- const region = requestRegion(req, res);
12242
- if (region === void 0) return;
12243
- try {
12244
- const body = await readJsonBody(req);
12245
- const modelIds = Array.isArray(body.modelIds) ? body.modelIds.filter((id) => typeof id === "string" && id !== "") : [];
12246
- if (modelIds.length === 0) return json(res, 400, { error: "modelIds must be a non-empty array of strings" });
12247
- if (modelIds.length > 1) return json(res, 400, { error: "a probe accepts exactly one model" });
12248
- const results = [];
12249
- for (const modelId of modelIds) results.push(...await deps.probeModels(region, [modelId]));
12250
- json(res, 200, { results });
12251
- } catch (error) {
12252
- json(res, 500, { error: safeMessage(error) });
12253
- }
12254
- }
12228
+ method: "POST",
12229
+ ready: (res) => deps.probeModels !== void 0 ? true : (json(res, 503, { error: "model probe unavailable" }), false)
12230
+ }, async (req, res, region) => {
12231
+ const body = await readJsonBody(req);
12232
+ const modelIds = Array.isArray(body.modelIds) ? body.modelIds.filter((id) => typeof id === "string" && id !== "") : [];
12233
+ if (modelIds.length === 0) return json(res, 400, { error: "modelIds must be a non-empty array of strings" });
12234
+ if (modelIds.length > 1) return json(res, 400, { error: "a probe accepts exactly one model" });
12235
+ const results = [];
12236
+ for (const modelId of modelIds) results.push(...await deps.probeModels(region, [modelId]));
12237
+ json(res, 200, { results });
12255
12238
  });
12256
- const disposeTps = ctx.webServer.register({
12257
- kind: "exact",
12239
+ endpointRegion({
12258
12240
  path: WORKBUDDY_TPS_PATH,
12259
- handler: async (req, res) => {
12260
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12261
- if (!requireLoopback(req, res)) return;
12262
- if (deps.measureTps === void 0) return json(res, 503, { error: "tps measurement unavailable" });
12263
- const region = requestRegion(req, res);
12264
- if (region === void 0) return;
12265
- try {
12266
- const body = await readJsonBody(req);
12267
- const modelIds = Array.isArray(body.modelIds) ? body.modelIds.filter((id) => typeof id === "string" && id !== "") : [];
12268
- if (modelIds.length === 0) return json(res, 400, { error: "modelIds must be a non-empty array of strings" });
12269
- if (modelIds.length > 1) return json(res, 400, { error: "a tps measurement accepts exactly one model" });
12270
- const results = [];
12271
- for (const modelId of modelIds) results.push(...await deps.measureTps(region, [modelId]));
12272
- json(res, 200, { results });
12273
- } catch (error) {
12274
- json(res, 500, { error: safeMessage(error) });
12275
- }
12276
- }
12241
+ method: "POST",
12242
+ ready: (res) => deps.measureTps !== void 0 ? true : (json(res, 503, { error: "tps measurement unavailable" }), false)
12243
+ }, async (req, res, region) => {
12244
+ const body = await readJsonBody(req);
12245
+ const modelIds = Array.isArray(body.modelIds) ? body.modelIds.filter((id) => typeof id === "string" && id !== "") : [];
12246
+ if (modelIds.length === 0) return json(res, 400, { error: "modelIds must be a non-empty array of strings" });
12247
+ if (modelIds.length > 1) return json(res, 400, { error: "a tps measurement accepts exactly one model" });
12248
+ const results = [];
12249
+ for (const modelId of modelIds) results.push(...await deps.measureTps(region, [modelId]));
12250
+ json(res, 200, { results });
12277
12251
  });
12278
- const disposePool = ctx.webServer.register({
12252
+ route({
12279
12253
  kind: "exact",
12280
12254
  path: WORKBUDDY_POOL_PATH,
12281
12255
  handler: async (req, res) => {
@@ -12418,7 +12392,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12418
12392
  }
12419
12393
  }
12420
12394
  });
12421
- const disposeDiagWrite = ctx.webServer.register({
12395
+ route({
12422
12396
  kind: "exact",
12423
12397
  path: "/plugins/dsh-connect-workbuddy/__save",
12424
12398
  handler: async (req, res) => {
@@ -12505,35 +12479,26 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12505
12479
  }
12506
12480
  }
12507
12481
  });
12508
- const disposeOAuth = ctx.webServer.register({
12509
- kind: "exact",
12482
+ endpointRegion({
12510
12483
  path: WORKBUDDY_OAUTH_PATH,
12511
- handler: async (req, res) => {
12512
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12513
- if (!requireLoopback(req, res)) return;
12514
- const region = requestRegion(req, res);
12515
- if (region === void 0) return;
12516
- const action = oauthActionOf(req.url ?? "/");
12517
- if (action === void 0) return json(res, 400, { error: "action must be start or poll" });
12518
- const oauth = deps.oauth;
12519
- if (oauth === void 0) return json(res, 503, {
12520
- reason: "oauth-unavailable",
12521
- error: "OAuth sign-in is not available in this build"
12522
- });
12523
- try {
12524
- if (action === "start") {
12525
- json(res, 200, await oauth.start(region));
12526
- return;
12527
- }
12528
- const body = await readJsonBody(req);
12529
- if (typeof body.loginId !== "string" || body.loginId === "") return json(res, 400, { error: "loginId must be a non-empty string" });
12530
- json(res, 200, await oauth.poll(region, body.loginId));
12531
- } catch (error) {
12532
- json(res, 500, { error: safeMessage(error) });
12533
- }
12484
+ method: "POST"
12485
+ }, async (req, res, region) => {
12486
+ const action = oauthActionOf(req.url ?? "/");
12487
+ if (action === void 0) return json(res, 400, { error: "action must be start or poll" });
12488
+ const oauth = deps.oauth;
12489
+ if (oauth === void 0) return json(res, 503, {
12490
+ reason: "oauth-unavailable",
12491
+ error: "OAuth sign-in is not available in this build"
12492
+ });
12493
+ if (action === "start") {
12494
+ json(res, 200, await oauth.start(region));
12495
+ return;
12534
12496
  }
12497
+ const body = await readJsonBody(req);
12498
+ if (typeof body.loginId !== "string" || body.loginId === "") return json(res, 400, { error: "loginId must be a non-empty string" });
12499
+ json(res, 200, await oauth.poll(region, body.loginId));
12535
12500
  });
12536
- const disposeTransfer = ctx.webServer.register({
12501
+ route({
12537
12502
  kind: "exact",
12538
12503
  path: WORKBUDDY_TRANSFER_PATH,
12539
12504
  handler: async (req, res) => {
@@ -12588,21 +12553,14 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12588
12553
  * leave a ghost pill describing a turn that already ended. Answering an
12589
12554
  * empty document keeps "off" inside the same code path as "no turns".
12590
12555
  */
12591
- const disposeCliLive = ctx.webServer.register({
12592
- kind: "exact",
12556
+ raw({
12593
12557
  path: WORKBUDDY_CLI_LIVE_PATH,
12594
- handler: (req, res) => {
12595
- if (req.method !== "GET") return json(res, 405, { error: "method not allowed" });
12596
- if (!requireLoopback(req, res)) return;
12597
- try {
12598
- json(res, 200, deps.cliLive?.() ?? {
12599
- turns: [],
12600
- serverTime: Date.now()
12601
- });
12602
- } catch (error) {
12603
- json(res, 500, { error: safeMessage(error) });
12604
- }
12605
- }
12558
+ method: "GET"
12559
+ }, (_req, res) => {
12560
+ json(res, 200, deps.cliLive?.() ?? {
12561
+ turns: [],
12562
+ serverTime: Date.now()
12563
+ });
12606
12564
  });
12607
12565
  /**
12608
12566
  * 设备头设置:档位切换 + 每账号的虚拟参数。
@@ -12611,7 +12569,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12611
12569
  * 都是**即时生效**——这里没有草稿,因为齿轮改的是"这台机器对外声称自己是谁",
12612
12570
  * 一个需要点保存才生效的设备身份,会让"我改完到底发出去的是什么"变成猜测。
12613
12571
  */
12614
- const disposeDeviceProfile = ctx.webServer.register({
12572
+ route({
12615
12573
  kind: "exact",
12616
12574
  path: WORKBUDDY_DEVICE_PROFILE_PATH,
12617
12575
  handler: async (req, res) => {
@@ -12710,7 +12668,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12710
12668
  * 放在 POST 后面不是形式主义——它会进浏览器历史、会被 proxy 记日志、会被截图,
12711
12669
  * 而 `GET` 是三者里最容易被动触发的(预取、刷新、插件间的探测)。
12712
12670
  */
12713
- const disposeDeviceSdk = ctx.webServer.register({
12671
+ route({
12714
12672
  kind: "exact",
12715
12673
  path: WORKBUDDY_DEVICE_SDK_PATH,
12716
12674
  handler: async (req, res) => {
@@ -12771,22 +12729,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12771
12729
  }
12772
12730
  });
12773
12731
  return () => {
12774
- disposeBenefitClaim();
12775
- disposeRefresh();
12776
- disposeMediaModels();
12777
- disposeCheckin();
12778
- disposeAccounts();
12779
- disposeUsage();
12780
- disposeAccountCredits();
12781
- disposeProbe();
12782
- disposeTps();
12783
- disposePool();
12784
- disposeOAuth();
12785
- disposeTransfer();
12786
- disposeDiagWrite();
12787
- disposeCliLive();
12788
- disposeDeviceProfile();
12789
- disposeDeviceSdk();
12732
+ for (const dispose of disposers) dispose();
12790
12733
  };
12791
12734
  }, "dsh-connect-workbuddy: Web status route");
12792
12735
  }
@@ -13341,28 +13284,28 @@ function apply(ctx, config) {
13341
13284
  * 卸载,而设置随时会变,所以目录每次 `probe` 现问一次。`deviceProfiles` 读盘有
13342
13285
  * 5 秒缓存,保存会立即失效它。
13343
13286
  *
13344
- * ⚠️ **总开关优先于预热**(`deviceSdkEnabled`):关掉就不建定时器、不预取。
13345
- * 留着 `createTuringSdk()` 本身是因为端口(`createDeviceSdkPort`)仍要能回答
13346
- * "这个功能被关掉了"——它读到的是 `disabled` 状态,而不是一块空白面板。
13347
- */
13348
- /**
13349
- * 总开关:**默认关**(`default(false)`)。
13350
- *
13351
- * 与档位默认值一致:档位默认「虚拟值」本来就不发这个 token,那么默认去发现
13352
- * SDK、起子进程、每 10 分钟取一次,取到的东西一次也用不上。更一般地说,一个
13353
- * 会碰用户机器上第三方原生模块的能力,默认该由用户主动打开。
13287
+ * 总开关只留**一份活真值**。曾经这里写 `const flag = unwrapVolatile(...) === true`
13288
+ * 把布尔在 apply 期求值一次传给句柄,而 `readEnabled()` 却每次现读活引用——
13289
+ * volatile 字段就地修改、插件不重挂,于是「勾选框是开的、probe 永远答 disabled」。
13290
+ * 现在两处共用 `deviceSdkEnabled()`。句柄即使关掉也保留,因为端口仍要能回答
13291
+ * "这个功能被关掉了"(`disabled`),而不是给一块空白面板。
13354
13292
  *
13355
- * `=== true` 而不是 `!== false`:`undefined`(老配置文件里没有这个字段)必须
13356
- * 落到"关",与 `default(false)` 同一个答案。写成 `!== false` 会让"未设置"和
13357
- * "显式开启"分叉,升级后老用户静默拿到与 schema 默认相反的行为。
13293
+ * `=== true`:`undefined`(老配置没有这一项)落到"关",与 `default(false)` 一致。
13358
13294
  */
13359
- const deviceSdkEnabled = unwrapVolatile(config.deviceSdkEnabled) === true;
13295
+ const deviceSdkEnabled = () => unwrapVolatile(config.deviceSdkEnabled) === true;
13360
13296
  const turing = createTuringSdk({
13361
13297
  productVersion: APP_VERSION,
13362
13298
  dirSource: () => deviceProfiles.sdkDir(),
13363
- enabled: deviceSdkEnabled
13299
+ get enabled() {
13300
+ return deviceSdkEnabled();
13301
+ }
13364
13302
  });
13365
- if (deviceSdkEnabled) turing.startAutoRefresh();
13303
+ /** 让预热链跟随开关:开则补建(内部幂等),关则立即拆除。 */
13304
+ const syncDeviceSdk = () => {
13305
+ if (deviceSdkEnabled()) turing.startAutoRefresh();
13306
+ else turing.stopAutoRefresh();
13307
+ };
13308
+ syncDeviceSdk();
13366
13309
  ctx.effect(() => () => {
13367
13310
  turing.stopAutoRefresh();
13368
13311
  });
@@ -13954,87 +13897,70 @@ function apply(ctx, config) {
13954
13897
  declared: false
13955
13898
  })));
13956
13899
  };
13957
- let imageTools;
13958
- let disposeImageTool;
13959
- const syncImageTool = (value) => {
13960
- const wanted = imageToolRegionOf(value) !== void 0;
13961
- if (wanted && disposeImageTool === void 0 && imageTools !== void 0) {
13962
- disposeImageTool = registerWorkBuddyImageTool(imageTools, {
13963
- resolveCredential: async () => {
13964
- const live = current();
13965
- for (const region of REGION_KEYS) {
13966
- if (!regionEnabled(live, region)) continue;
13967
- if (regionStateOf(live, region).imageToolEnabled !== true) continue;
13968
- try {
13969
- return await stacks[region].store.resolve();
13970
- } catch {
13971
- continue;
13972
- }
13973
- }
13974
- },
13975
- listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
13976
- generateImage: (credential, request, signal) => client.generateImage(credential, request, signal),
13977
- editImage: (credential, request, signal) => client.editImage(credential, request, signal),
13978
- logger: ctx.logger
13900
+ function mountOptionalTool(options) {
13901
+ let tools;
13902
+ let dispose;
13903
+ const sync = (value) => {
13904
+ const wanted = options.wanted(value);
13905
+ if (wanted && dispose === void 0 && tools !== void 0) {
13906
+ dispose = options.register(tools);
13907
+ return;
13908
+ }
13909
+ if (!wanted && dispose !== void 0) {
13910
+ dispose();
13911
+ dispose = void 0;
13912
+ }
13913
+ };
13914
+ ctx.inject(["tools"], (toolsCtx) => {
13915
+ tools = toolsCtx.tools;
13916
+ if (tools === void 0) return;
13917
+ sync(current());
13918
+ toolsCtx.effect(() => () => {
13919
+ dispose?.();
13920
+ dispose = void 0;
13921
+ tools = void 0;
13979
13922
  });
13980
- return;
13981
- }
13982
- if (!wanted && disposeImageTool !== void 0) {
13983
- disposeImageTool();
13984
- disposeImageTool = void 0;
13985
- }
13986
- };
13987
- ctx.inject(["tools"], (toolsCtx) => {
13988
- imageTools = toolsCtx.tools;
13989
- if (imageTools === void 0) return;
13990
- syncImageTool(current());
13991
- toolsCtx.effect(() => () => {
13992
- disposeImageTool?.();
13993
- disposeImageTool = void 0;
13994
- imageTools = void 0;
13995
13923
  });
13996
- });
13997
- let videoTools;
13998
- let disposeVideoTool;
13999
- const syncVideoTool = (value) => {
14000
- const wanted = videoToolRegionOf(value) !== void 0;
14001
- if (wanted && disposeVideoTool === void 0 && videoTools !== void 0) {
14002
- disposeVideoTool = registerWorkBuddyVideoTool(videoTools, {
14003
- resolveCredential: async () => {
14004
- const live = current();
14005
- for (const region of REGION_KEYS) {
14006
- if (!regionEnabled(live, region)) continue;
14007
- if (regionStateOf(live, region).videoToolEnabled !== true) continue;
14008
- try {
14009
- return await stacks[region].store.resolve();
14010
- } catch {
14011
- continue;
14012
- }
14013
- }
14014
- },
14015
- listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
14016
- submitVideo: (credential, request, signal) => client.submitVideo(credential, request, signal),
14017
- pollVideoTask: (credential, taskId, signal) => client.pollVideoTask(credential, taskId, signal),
14018
- preferredVideoModel: (credential, tag) => regionStateOf(current(), regionOf(credential.domain)).preferredVideoModels?.[tag],
14019
- downloadVideo: (credential, url, signal) => client.downloadVideo(credential, url, signal),
14020
- logger: ctx.logger
14021
- });
14022
- return;
14023
- }
14024
- if (!wanted && disposeVideoTool !== void 0) {
14025
- disposeVideoTool();
14026
- disposeVideoTool = void 0;
13924
+ return sync;
13925
+ }
13926
+ /**
13927
+ * 每次调用现挑区、现解析凭据:用户在两次调用之间换账号或关掉某区都要生效。
13928
+ * `optIn` 必须是该工具自己的逐区开关 —— 生图不能借用视频已授权的区,否则绕过
13929
+ * 用户按区做出的授权。
13930
+ */
13931
+ const toolCredential = (optIn) => async () => {
13932
+ const live = current();
13933
+ for (const region of REGION_KEYS) {
13934
+ if (!regionEnabled(live, region)) continue;
13935
+ if (regionStateOf(live, region)[optIn] !== true) continue;
13936
+ try {
13937
+ return await stacks[region].store.resolve();
13938
+ } catch {
13939
+ continue;
13940
+ }
14027
13941
  }
14028
13942
  };
14029
- ctx.inject(["tools"], (toolsCtx) => {
14030
- videoTools = toolsCtx.tools;
14031
- if (videoTools === void 0) return;
14032
- syncVideoTool(current());
14033
- toolsCtx.effect(() => () => {
14034
- disposeVideoTool?.();
14035
- disposeVideoTool = void 0;
14036
- videoTools = void 0;
14037
- });
13943
+ const syncImageTool = mountOptionalTool({
13944
+ wanted: (value) => imageToolRegionOf(value) !== void 0,
13945
+ register: (tools) => registerWorkBuddyImageTool(tools, {
13946
+ resolveCredential: toolCredential("imageToolEnabled"),
13947
+ listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
13948
+ generateImage: (credential, request, signal) => client.generateImage(credential, request, signal),
13949
+ editImage: (credential, request, signal) => client.editImage(credential, request, signal),
13950
+ logger: ctx.logger
13951
+ })
13952
+ });
13953
+ const syncVideoTool = mountOptionalTool({
13954
+ wanted: (value) => videoToolRegionOf(value) !== void 0,
13955
+ register: (tools) => registerWorkBuddyVideoTool(tools, {
13956
+ resolveCredential: toolCredential("videoToolEnabled"),
13957
+ listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
13958
+ submitVideo: (credential, request, signal) => client.submitVideo(credential, request, signal),
13959
+ pollVideoTask: (credential, taskId, signal) => client.pollVideoTask(credential, taskId, signal),
13960
+ preferredVideoModel: (credential, tag) => regionStateOf(current(), regionOf(credential.domain)).preferredVideoModels?.[tag],
13961
+ downloadVideo: (credential, url, signal) => client.downloadVideo(credential, url, signal),
13962
+ logger: ctx.logger
13963
+ })
14038
13964
  });
14039
13965
  let cliTools;
14040
13966
  let cliCommands;
@@ -14224,14 +14150,11 @@ function apply(ctx, config) {
14224
14150
  sdk: turing,
14225
14151
  mode: async () => (await readDeviceSettings()).mode,
14226
14152
  /**
14227
- * 总开关走插件配置(`Config.deviceSdkEnabled`),不走设备设置文件。
14228
- *
14229
- * `read` 取的是 `current()`——也就是宿主交给 `apply()` 的那份活的引用,
14230
- * 所以 `ctx.settings.update` 写完它就能读到新值(`asVolatile` 会就地改)。
14231
- * 回 `undefined` 让卡片把开关标成不可用,而不是把它画成"关"。
14153
+ * 总开关走插件配置(`Config.deviceSdkEnabled`),与 SDK 句柄的 `enabled`
14154
+ * getter 共用同一个 `deviceSdkEnabled()`,因此勾选框与 probe 不会分叉。
14232
14155
  */
14233
14156
  enabled: {
14234
- read: async () => unwrapVolatile(config.deviceSdkEnabled) !== false,
14157
+ read: async () => deviceSdkEnabled(),
14235
14158
  write: writeDeviceSdkEnabled
14236
14159
  }
14237
14160
  }),
@@ -15403,6 +15326,7 @@ function apply(ctx, config) {
15403
15326
  ctx.on("loader/volatile-update", () => {
15404
15327
  applySelection(current());
15405
15328
  syncAutoCheckin();
15329
+ syncDeviceSdk();
15406
15330
  });
15407
15331
  applySelection(config);
15408
15332
  (async () => {
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-connect-workbuddy",
3
3
  "displayName": "DSH Connect WorkBuddy",
4
4
  "description": "把本机登录的 WorkBuddy 模型(国内版与国际版)接入 DeepSeek Harness:每次刷新按上游目录自动读取每个模型的积分倍率,支持逐模型图片输入开关、多账号切换与账号池自动换号,并提供每日签到、卡片与输入框里的胶囊积分读数等只读积分概览。",
5
- "version": "5.21.2",
5
+ "version": "5.21.4",
6
6
  "author": "dingminhua",
7
7
  "copyright": "Copyright (c) 2026 LaoDing",
8
8
  "license": "MIT",