dsh-team-bots 0.2.460 → 0.2.465

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/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { format } from 'node:util'
1
2
  import { resolveConfig } from './src/config.js'
2
3
  import { openDatabase } from './src/db.js'
3
4
  import { installHttp } from './src/http.js'
@@ -10,13 +11,20 @@ import { installTeamTools } from './src/tools.js'
10
11
  export const name = 'dsh-team-bots'
11
12
  export const inject = ['llm', 'tools', 'systemPrompt', 'sessionController', 'sessionTitle', 'connection', 'webServer']
12
13
 
14
+ // 前缀并入首参格式串后再交给 console.*:Node 只格式化首参,'[dsh-team]' 独占首参时
15
+ // 后续参数里的 %s/%d 永不插值(owner 看到的字面 %s 即此缺陷)。
16
+ export function createLogger() {
17
+ const prefixed = write => (...args) => write(`[dsh-team] ${format(...args)}`)
18
+ return {
19
+ info: prefixed(console.log),
20
+ warn: prefixed(console.warn),
21
+ error: prefixed(console.error),
22
+ }
23
+ }
24
+
13
25
  export function apply(ctx, config = {}) {
14
26
  const resolved = resolveConfig(config)
15
- const logger = {
16
- info: (...args) => console.log('[dsh-team]', ...args),
17
- warn: (...args) => console.warn('[dsh-team]', ...args),
18
- error: (...args) => console.error('[dsh-team]', ...args),
19
- }
27
+ const logger = createLogger()
20
28
  const store = openDatabase(resolved.dbPath)
21
29
  const service = new TeamService({ store, config: resolved, logger })
22
30
  const runtime = new DshRuntime({ ctx, config: resolved, store, logger })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-team-bots",
3
- "version": "0.2.460",
3
+ "version": "0.2.465",
4
4
  "description": "Project spaces, group chats, task boards, memory and usage for teams of DSH bots",
5
5
  "repository": {
6
6
  "type": "git",
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { effectiveFeishuCredentials } from '../config.js'
6
6
  import { badRequest } from '../errors.js'
7
- import { nowIso } from '../util.js'
7
+ import { nowIso, parseMentions } from '../util.js'
8
8
  import { recordWechatTriggerRow } from './wechat-trigger-schema.js'
9
9
 
10
10
  /** 项目外导演通道的正文来源标记(对齐微信 WECHAT_SOLO_SOURCE_MARK):让 director 一眼看出该消息来自飞书管理员。 */
@@ -152,9 +152,12 @@ export const feishuMethods = {
152
152
  },
153
153
 
154
154
  /**
155
- * 飞书直达对话(与微信 wechatChat 同口径):自由文本与 /tr <key> 显式转发都落
156
- * director 专属工作区(origin='feishu',正文带 [飞书管理员] 来源标记);key 未命中
157
- * 返回 null;解析不到 director 返回 { error: 'no_director' }。
155
+ * 飞书直达对话(与微信 wechatChat 同口径):自由文本落 director 专属工作区
156
+ * (origin='feishu',正文带 [飞书管理员] 来源标记);/tr <key> 显式转发直达指定
157
+ * 项目群聊——消息以飞书管理员身份插入项目群聊并触发 chat 运行(origin='feishu',
158
+ * 运行收尾把 bot 回复推回飞书管理员)。正文可 @成员 定向;无 @ 且 owner 不可用
159
+ * 返回 { error: 'no_owner', project };key 未命中返回 null;自由文本解析不到
160
+ * director 返回 { error: 'no_director' }。
158
161
  */
159
162
  async feishuChat(key, body) {
160
163
  let project = null
@@ -164,18 +167,25 @@ export const feishuMethods = {
164
167
  String(key ?? '').trim(),
165
168
  )
166
169
  if (!project) return null
170
+ const members = this.membersOf(project.id).filter(bot => bot.status === 'active')
171
+ const textBody = String(body ?? '')
172
+ if (parseMentions(textBody, members).length === 0
173
+ && !members.some(bot => bot.id === project.owner_bot_id)) {
174
+ return { error: 'no_owner', project }
175
+ }
176
+ const adminOuId = this.feishu?.status?.()?.adminOuId ?? null
177
+ const result = await this.sendMessage(
178
+ project.id,
179
+ textBody,
180
+ { type: 'user', id: adminOuId ?? 'user:feishu' },
181
+ null,
182
+ [],
183
+ { origin: 'feishu' },
184
+ )
185
+ return { project, ...result }
167
186
  }
168
187
  const director = this.feishuDirectorBot()
169
- if (!director) return { error: 'no_director', ...(project ? { project } : {}) }
170
- if (!project) return this.feishuDirectorChat(director, String(body ?? ''))
171
- const adminOuId = this.feishu?.status?.()?.adminOuId ?? null
172
- const result = await this.sendSoloMessage(
173
- director.id,
174
- `${FEISHU_SOLO_SOURCE_MARK}[项目 ${project.key}] ${String(body ?? '')}`,
175
- { type: 'user', id: adminOuId ?? 'user:feishu' },
176
- [],
177
- { origin: 'feishu' },
178
- )
179
- return { project, director, messageId: result?.messageId ?? null }
188
+ if (!director) return { error: 'no_director' }
189
+ return this.feishuDirectorChat(director, String(body ?? ''))
180
190
  },
181
191
  }
@@ -277,8 +277,12 @@ export const memoryMethods = {
277
277
  scopeType, scopeId, 'active',
278
278
  )?.count ?? 0)
279
279
  },
280
- memoryCapacityMessage(scopeType, scopeId, count) {
280
+ memoryCapacityMessage(scopeType, scopeId, count, latched = false) {
281
281
  const label = scopeType === 'bot' ? `Bot(${scopeId})` : `项目(${scopeId})`
282
+ // 锁定带(滞回标志在、34–63 条):如实说明此前触顶、现处整理锁定期,不得谎称「已达 N/64」。
283
+ if (latched) {
284
+ return `${label}记忆此前触顶 ${MEMORY_CAP} 条上限,现处整理锁定期(当前 ${count} 条),新增被拒绝;需整理到 ≤${MEMORY_COMPACT_TO} 条恢复新增:去废弃(team_memory_cleanup 清理已闭环任务或过时主题)、去冗与融合(同主题 team_memory_write 覆盖写、合并相近条目);同主题覆盖写不受影响。`
285
+ }
282
286
  return `${label}记忆已达 ${count}/${MEMORY_CAP} 条上限,新增被拒绝;请先去废弃(team_memory_cleanup 清理已闭环任务或过时主题)、去冗(同主题用 team_memory_write 覆盖写)、融合(合并相近条目),整理到 ≤${MEMORY_COMPACT_TO} 条后再新增。`
283
287
  },
284
288
  assertMemoryCapacity(scopeType, scopeId) {
@@ -290,7 +294,7 @@ export const memoryMethods = {
290
294
  throw conflict(this.memoryCapacityMessage(scopeType, scopeId, count))
291
295
  }
292
296
  if (this.store.setting(flagKey) === null) return
293
- if (count > MEMORY_COMPACT_TO) throw conflict(this.memoryCapacityMessage(scopeType, scopeId, count))
297
+ if (count > MEMORY_COMPACT_TO) throw conflict(this.memoryCapacityMessage(scopeType, scopeId, count, true))
294
298
  this.store.run('DELETE FROM settings WHERE key = ?', flagKey)
295
299
  },
296
300
 
@@ -37,6 +37,7 @@ const FAILURE_CATEGORY_NOTICES = {
37
37
  sandbox_denied: { label: '沙箱拒绝', summary: '文件或命令操作被沙箱策略拒绝。' },
38
38
  timeout: { label: '超时', summary: '上游响应超时。' },
39
39
  network: { label: '网络', summary: '网络瞬态失败,已按退避策略自动重试。' },
40
+ blocked: { label: '会话受阻', summary: '宿主拒绝执行该会话(可能已被归档),未产生任何模型输出。' },
40
41
  internal: { label: '内部错误', summary: '服务内部错误。' },
41
42
  unknown: { label: '未知', summary: '运行失败,完整原因见运行日志。' },
42
43
  }
@@ -47,6 +48,7 @@ export function classifyFailure(error) {
47
48
  if (SANDBOX_DENIED_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.sandbox_denied
48
49
  if (TIMEOUT_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.timeout
49
50
  if (isTransientNetworkError(error)) return FAILURE_CATEGORY_NOTICES.network
51
+ if (error?.code === 'SESSION_BLOCKED') return FAILURE_CATEGORY_NOTICES.blocked
50
52
  if (INTERNAL_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.internal
51
53
  return FAILURE_CATEGORY_NOTICES.unknown
52
54
  }
@@ -261,18 +261,23 @@ export const lifecycleMethods = {
261
261
  this.pending.delete(sessionId)
262
262
  this.pendingByRun.delete(root.runId)
263
263
  const reason = reasonOf(event)
264
- const failed = reason.kind === 'error' || reason.kind === 'aborted'
265
264
  const output = selectDeliverableText(root.texts)
266
- const error = failed
267
- ? {
268
- code: reason.kind === 'aborted' ? 'ABORTED' : (reason.error?.code ?? 'MODEL_ERROR'),
269
- message: reason.error?.message ?? (reason.kind === 'aborted' ? '运行被中止' : '模型调用失败'),
270
- // 限流退避只有 provider 真发 Retry-After 才有值(宿主 failureSnapshot 已校验正有限数),拿不到就是 null,不伪造。
271
- retryAfterMs: reason.kind === 'error' && Number.isFinite(reason.error?.providerRetryAfterMs) && reason.error.providerRetryAfterMs > 0
272
- ? reason.error.providerRetryAfterMs
273
- : null,
274
- }
275
- : null
265
+ // 宿主侧拒绝(归档闸等 pre-step reject)不产生任何模型调用与文本:按成功收尾会把空回复
266
+ // 落库成「模型未返回文本」。无输出时按失败上报,走既有失败链路(可见错误/重试)。
267
+ const blocked = reason.kind === 'blocked' && !output
268
+ const failed = blocked || reason.kind === 'error' || reason.kind === 'aborted'
269
+ const error = blocked
270
+ ? { code: 'SESSION_BLOCKED', message: '宿主拒绝执行该会话(可能已被归档),未产生任何模型输出。', retryAfterMs: null }
271
+ : failed
272
+ ? {
273
+ code: reason.kind === 'aborted' ? 'ABORTED' : (reason.error?.code ?? 'MODEL_ERROR'),
274
+ message: reason.error?.message ?? (reason.kind === 'aborted' ? '运行被中止' : '模型调用失败'),
275
+ // 限流退避只有 provider 真发 Retry-After 才有值(宿主 failureSnapshot 已校验正有限数),拿不到就是 null,不伪造。
276
+ retryAfterMs: reason.kind === 'error' && Number.isFinite(reason.error?.providerRetryAfterMs) && reason.error.providerRetryAfterMs > 0
277
+ ? reason.error.providerRetryAfterMs
278
+ : null,
279
+ }
280
+ : null
276
281
  this.releaseAttribution(root.runId)
277
282
  await this.completionHandler?.({
278
283
  runId: root.runId,
@@ -63,6 +63,21 @@ export function effectiveReviewTimeoutMinutes(getSetting
63
63
  // 按次开全新会话会无限累积宿主会话列表,有界绑定把宿主会话数压到 1/N。
64
64
  export const MEMORY_REVIEW_BINDING_MAX_RUNS = 8
65
65
 
66
+ // 宿主归档闸(ArchivedSessionGate):归档会话在宿主侧不执行任何模型步骤,turn/end 记
67
+ // blocked 且无 assistant 文本。照常复用会把空回复当成功落库(群聊表现为「模型未返回文本」)。
68
+ // 与宿主同口径查 workspaceRegistry.archivedSessionIds;服务缺失(旧宿主)时视为未归档。
69
+ export function isSessionArchived(ctx, sessionId) {
70
+ const archived = ctx?.get?.('workspaceRegistry')?.archivedSessionIds
71
+ return Array.isArray(archived) && archived.includes(sessionId)
72
+ }
73
+
74
+ // 复用前的存活解析:归档与宿主查不到同等处理——返回 null,调用方 retireBinding 后走新建。
75
+ export async function liveAgentFor(ctx, sessionId) {
76
+ if (!sessionId || isSessionArchived(ctx, sessionId)) return null
77
+ const resolved = await ctx.sessionController.resolveAgent(sessionId)
78
+ return resolved?.error ? null : resolved
79
+ }
80
+
66
81
  export const sessionMethods = {
67
82
  bindingOfSession(sessionId) {
68
83
  if (!sessionId) return undefined
@@ -430,8 +445,8 @@ export const sessionMethods = {
430
445
  // 且不能参与阈值判定——否则这两类运行自己又会触发结转/压缩;solo 摘要运行也没有
431
446
  // 项目上下文,不查项目。
432
447
  if ((run?.kind === 'rollover_summary' || run?.kind === 'session_compact') && run.session_id) {
433
- const resolved = await this.ctx.sessionController.resolveAgent(run.session_id)
434
- if (!resolved?.error) {
448
+ const resolved = await liveAgentFor(this.ctx, run.session_id)
449
+ if (resolved) {
435
450
  this.applyFilePolicy(resolved, bot, run, task)
436
451
  applyBotToolPolicy(resolved, { isOwner, logger: this.logger })
437
452
  await this.selectModel(run.session_id, bot, modelOverride)
@@ -455,8 +470,8 @@ export const sessionMethods = {
455
470
  ? undefined
456
471
  : this.taskAffinityBinding(task)
457
472
  if (affinity) {
458
- const resolved = await this.ctx.sessionController.resolveAgent(affinity.session_id)
459
- if (!resolved?.error) {
473
+ const resolved = await liveAgentFor(this.ctx, affinity.session_id)
474
+ if (resolved) {
460
475
  this.applyFilePolicy(resolved, bot, run, task)
461
476
  applyBotToolPolicy(resolved, { isOwner, logger: this.logger })
462
477
  await this.selectModel(affinity.session_id, bot, modelOverride)
@@ -552,14 +567,12 @@ export const sessionMethods = {
552
567
  )
553
568
  if (existing) {
554
569
  const served = this.store.get('SELECT COUNT(*) AS n FROM runs WHERE session_id = ?', existing.session_id)?.n ?? 0
555
- if (served < MEMORY_REVIEW_BINDING_MAX_RUNS) {
556
- const resolved = await this.ctx.sessionController.resolveAgent(existing.session_id)
557
- if (!resolved?.error) {
558
- this.applyFilePolicy(resolved, bot, run, null)
559
- applyBotToolPolicy(resolved, { isOwner, logger: this.logger })
560
- await this.selectModel(existing.session_id, bot, modelOverride)
561
- return existing.session_id
562
- }
570
+ const resolved = served < MEMORY_REVIEW_BINDING_MAX_RUNS ? await liveAgentFor(this.ctx, existing.session_id) : null
571
+ if (resolved) {
572
+ this.applyFilePolicy(resolved, bot, run, null)
573
+ applyBotToolPolicy(resolved, { isOwner, logger: this.logger })
574
+ await this.selectModel(existing.session_id, bot, modelOverride)
575
+ return existing.session_id
563
576
  }
564
577
  this.retireBinding(existing.session_id)
565
578
  }
@@ -619,8 +632,8 @@ export const sessionMethods = {
619
632
  )
620
633
  let rolledOver = false
621
634
  if (existing) {
622
- const resolved = await this.ctx.sessionController.resolveAgent(existing.session_id)
623
- if (!resolved?.error) {
635
+ const resolved = await liveAgentFor(this.ctx, existing.session_id)
636
+ if (resolved) {
624
637
  // 结转(DSHBOTS-145):控制面会话长期承接全量流量,照旧阈值判定——摘要就绪即
625
638
  // alias 化落到下方重建路径,摘要由新会话首轮提示词注入;未就绪补排摘要运行,
626
639
  // 本轮继续复用。alias 行不可能走到这里(查询条件 alias=0),幂等由查询保证。
@@ -17,29 +17,39 @@ export const taskReviewMethods = {
17
17
  const task = this.resolveBotTask(project, input.task)
18
18
  // 验收机械闸(DSHBOTS-318)只拦真验收动作(in_review 卡):非待验收状态保持既有
19
19
  // 校验顺序,仍由 applyReview 抛 in_review conflict,闸不抢跑。
20
- if (task.status === 'in_review') this.assertReviewSubagentVerified(sessionId, input.comment)
20
+ if (task.status === 'in_review') this.assertReviewSubagentVerified(sessionId, project, task, input.comment)
21
21
  return this.applyReview(task, project, input.decision, input.comment, actor)
22
22
  },
23
23
 
24
- // 验收机械闸(DSHBOTS-318):把「验收必须经由子代理」从提示约束升级为机械约束——
25
- // owner bot 的 team_review_task 前置校验调用方当前活跃运行的子代理账目
26
- // (run_events 的 subagent_spawned),无账目即拒绝;comment 显式注明「兜底验收」
27
- // 放行(对应 router 硬流程第 4 条:子代理失败重试一次仍失败时 director 兜底)。
24
+ // 验收机械闸(DSHBOTS-318/353):把「验收必须经由子代理」从提示约束升级为机械约束——
25
+ // owner bot 的 team_review_task 前置校验本评审周期内的子代理账目(run_events 的
26
+ // subagent_spawned)。周期起点 T=最近一次交付(run_succeeded)或看板流转
27
+ // (status→in_review)事件的 created_at 取 MAX;账目归属两条认领线:
28
+ // 本任务的 owner 运行(task_id+bot_id)或调用方会话的任意运行——两跳正规流程
29
+ // (review_delegate 派子代理 → 新运行只裁决)的账目挂在上一跳已结束运行上,
30
+ // 按「当运行有账」查必漏,故按周期查。comment 显式注明「兜底验收」放行
31
+ // (对应 router 硬流程第 4 条:子代理失败重试一次仍失败时 director 兜底)。
28
32
  // 仅机器人路径:微信管理员/看板 owner 走 applyReview,不经过本闸。
29
- assertReviewSubagentVerified(sessionId, comment) {
33
+ assertReviewSubagentVerified(sessionId, project, task, comment) {
30
34
  if (comment?.includes('兜底验收')) return
31
- const run = this.store.get(
32
- "SELECT id FROM runs WHERE session_id = ? AND status IN ('running', 'queued') ORDER BY queued_at DESC LIMIT 1",
33
- sessionId,
34
- )
35
- const ledger = run && this.store.get(
36
- "SELECT id FROM run_events WHERE run_id = ? AND type = 'subagent_spawned' LIMIT 1",
37
- run.id,
35
+ // run_events 无 run_id 索引:先筛 runs 再 EXISTS,量级与旧「当运行」查询相同。
36
+ const windowStart = this.store.get(
37
+ `SELECT MAX(created_at) AS t FROM task_events WHERE task_id = ?
38
+ AND (type = 'run_succeeded' OR (type = 'status' AND json_extract(data_json, '$.to') = 'in_review'))`,
39
+ task.id,
40
+ )?.t ?? ''
41
+ const ledger = this.store.get(
42
+ `SELECT 1 AS hit FROM runs r
43
+ WHERE ((r.task_id = ? AND r.bot_id = ?) OR r.session_id = ?)
44
+ AND EXISTS (SELECT 1 FROM run_events e
45
+ WHERE e.run_id = r.id AND e.type = 'subagent_spawned' AND e.created_at >= ?)
46
+ LIMIT 1`,
47
+ task.id, project.owner_bot_id, sessionId, windowStart,
38
48
  )
39
49
  if (ledger) return
40
50
  // DSHBOTS-269 失败语义引导:拒绝文案 = 原因 + 正确下一步。
41
51
  throw badRequest(
42
- '当前运行没有子代理账目(subagent_spawned),验收必须先经子代理核验:'
52
+ '本次评审没有子代理账目(subagent_spawned),验收必须先经子代理核验:'
43
53
  + '先派验收子代理(subagent/subagent_fork)做范围比对/目标测试/红线预测,把结论作为 comment;'
44
54
  + '如需 director 兜底,在 comment 里注明「兜底验收」。',
45
55
  )
@@ -7,7 +7,7 @@ import { createRequire } from 'node:module'
7
7
  import { effectiveWechatEnabled } from '../config.js'
8
8
  import { AppError, conflict } from '../errors.js'
9
9
  import { WechatIlinkError } from '../wechat/commands.js'
10
- import { jsonParse, nowIso } from '../util.js'
10
+ import { jsonParse, nowIso, parseMentions } from '../util.js'
11
11
  import { answerFailed, answerReceipt, approvalCard, questionCard, wechatToken } from '../wechat/format.js'
12
12
  import { recordWechatTriggerRow } from './wechat-trigger-schema.js'
13
13
 
@@ -176,15 +176,14 @@ export const wechatMethods = {
176
176
  },
177
177
 
178
178
  /**
179
- * 微信直达对话(DSHBOTS-208 起,258 四次拍板,299 会话域三分后收敛为单一去向):
180
- * 微信通道一律落 director 专属工作区 solo 会话(A 口径:微信=用户↔director 直接通信)——
181
- * 自由文本(key 为空)与 /tr <key> 显式转发(key 非空)都投 director 的 solo_messages
182
- * 并触发 solo_chat 运行(trigger_type='wechat',运行收尾按此把回复推回微信管理员,
183
- * run-finish 回程链路对 chat/solo 两类同门禁,语义不回退);
184
- * /tr 的 key 命中项目后在正文携带 [项目 KEY] 上下文,director 自行把工作派进对应项目,
185
- * 不再以工作台用户身份插项目群聊触发 chat 运行(原路径 trigger_type='wechat' 的
186
- * chat 运行落项目控制面会话,违反三分域);key 未命中 → null;解析不到 director
187
- * (通道异常)→ { error: 'no_director' }。
179
+ * 微信直达对话(DSHBOTS-208 起,258/299 演进后现为二值路由):
180
+ * 自由文本(key 为空)一律落 director 专属工作区 solo 会话(用户↔director 直接
181
+ * 通信,solo_chat 运行 trigger_type='wechat',回复经 run-finish 推回微信管理员);
182
+ * /tr <key> 显式转发(key 非空)直达指定项目群聊——消息以微信管理员身份(admin
183
+ * peer id,不冒充工作台用户)插入项目群聊并触发 chat 运行(origin='wechat' →
184
+ * trigger_type='wechat',运行收尾把 bot 回复推回微信管理员)。正文可 @成员 定向;
185
+ * 无 @ 时 sendMessage 兜底定向 owner_bot_id,owner 不可用则拒投(no_owner);
186
+ * key 未命中 → null;自由文本解析不到 director(通道异常)→ { error: 'no_director' }。
188
187
  */
189
188
  async wechatChat(key, body) {
190
189
  let project = null
@@ -200,19 +199,24 @@ export const wechatMethods = {
200
199
  if (director) return this.wechatDirectorChat(director, String(body ?? ''))
201
200
  return { error: 'no_director' }
202
201
  }
203
- // DSHBOTS-299 A 口径:/tr 显式转发同落 director 专属工作区——正文带 [项目 KEY]
204
- // 上下文(与自由文本的 [微信管理员] 前缀同链路),由 director 以团队工具派单进项目。
205
- const director = this.wechatDirectorBot()
206
- if (!director) return { error: 'no_director', project }
202
+ // /tr 显式直达项目群聊:正文原样进群(保留 @mention 语义),无 @ 且总监不可用时
203
+ // 拒投,不让消息落库却无人接。
204
+ const members = this.membersOf(project.id).filter(bot => bot.status === 'active')
205
+ const textBody = String(body ?? '')
206
+ if (parseMentions(textBody, members).length === 0
207
+ && !members.some(bot => bot.id === project.owner_bot_id)) {
208
+ return { error: 'no_owner', project }
209
+ }
207
210
  const adminPeerId = this.wechat?.status?.()?.adminPeerId ?? null
208
- const result = await this.sendSoloMessage(
209
- director.id,
210
- `${WECHAT_SOLO_SOURCE_MARK}[项目 ${project.key}] ${String(body ?? '')}`,
211
+ const result = await this.sendMessage(
212
+ project.id,
213
+ textBody,
211
214
  { type: 'user', id: adminPeerId ?? 'user:wechat' },
215
+ null,
212
216
  [],
213
217
  { origin: 'wechat' },
214
218
  )
215
- return { project, director, messageId: result?.messageId ?? null }
219
+ return { project, ...result }
216
220
  },
217
221
 
218
222
  /**
@@ -32,6 +32,10 @@ export function installSubagentLedger(ctx, store, logger) {
32
32
  // 暂存 subagent/end 载荷:childId → info,tools/result 到达时按 id 出现在结果 JSON 里配对
33
33
  const endsByChild = new Map()
34
34
 
35
+ // DSHBOTS-353 落账放宽:owner bot 的派单账优先记 kind='task' running(D-294 施工账语义),
36
+ // 无施工运行时回退该 bot 任意 kind 的 running 运行(review/chat)——总监验收链的核验
37
+ // 子代理(review_delegate 运行)此前永远查不中而不落账。域串行(D-308 one_active_run_per_bot)
38
+ // 保证该 bot 当前 running 即派单所在运行。
35
39
  const ownerRunOf = (agentSessionId) => {
36
40
  const binding = agentSessionId
37
41
  ? store.get('SELECT * FROM session_bindings WHERE session_id = ?', agentSessionId)
@@ -40,6 +44,9 @@ export function installSubagentLedger(ctx, store, logger) {
40
44
  const run = store.get(
41
45
  "SELECT id FROM runs WHERE bot_id = ? AND kind = 'task' AND status = 'running' ORDER BY started_at DESC LIMIT 1",
42
46
  binding.bot_id,
47
+ ) ?? store.get(
48
+ "SELECT id FROM runs WHERE bot_id = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1",
49
+ binding.bot_id,
43
50
  )
44
51
  return run ? { botId: binding.bot_id, runId: run.id } : null
45
52
  }
@@ -100,7 +100,6 @@ export async function handleCommand(service, rawText, ctx = null) {
100
100
  if (!chat || chat.error === 'no_target') {
101
101
  return needPickProject(service.stateView().projects ?? [])
102
102
  }
103
- if (chat.error === 'no_owner') return noOwner(chat.project)
104
103
  return ''
105
104
  }
106
105
 
@@ -166,9 +165,8 @@ async function handleFixedCommand(service, body, ctx) {
166
165
  const message = match[2].trim()
167
166
  const chat = await service.wechatChat(key, message)
168
167
  if (!chat) return projectNotFound(key, service.stateView().projects ?? [])
169
- // DSHBOTS-299:/tr 转发一律落 director 专属工作区(携带 [项目 KEY] 上下文),
170
- // 总监不可用属通道异常,独立出口;no_owner 出口随项目群直达一并退役。
171
- if (chat.error === 'no_director') return noDirector()
168
+ // 直达项目群聊无可定向 Bot(无 @ 且总监不可用):独立出口,不入对话。
169
+ if (chat.error === 'no_owner') return noOwner(chat.project)
172
170
  ctx?.bind?.(chat.project.key)
173
171
  return connectedReceipt(chat.project, 'dispatch')
174
172
  }
@@ -21,7 +21,7 @@ export function helpText() {
21
21
  ' /states 未验收任务清单',
22
22
  ' /detail <任务号> 任务详情',
23
23
  ' /reject <任务号> <理由> 退回重做(管理员)',
24
- ' /tr <key> <消息> 跨项目直达(管理员)',
24
+ ' /tr <key> <消息> 直达指定项目(管理员)',
25
25
  '',
26
26
  '其余消息直接发给项目外 director 的专属工作区,回复会推送到微信。',
27
27
  ].join('\n')
@@ -106,17 +106,17 @@ export function projectList(projects) {
106
106
  return lines.join('\n')
107
107
  }
108
108
 
109
- /** 直达连接回执:dispatch=显式 <key>: 指定;bind=自由文本首次绑定/换项目。 */
109
+ /** 直达连接回执:dispatch=/tr 显式直达项目群聊;bind=自由文本首次绑定/换项目。 */
110
110
  export function connectedReceipt(project, via) {
111
111
  const name = project.name || project.key
112
112
  return via === 'dispatch'
113
- ? `已直达【${name}】总监,之后的回复会推送到微信;直接发消息即可继续对话。`
113
+ ? `已直达【${name}】项目群,Bot 回复会推送到微信;继续给该项目发消息仍用「/tr <key> <消息>」。`
114
114
  : `已连接【${name}】总监,直接发消息即可,回复会推送到这里;换项目用「<key>: <消息>」。`
115
115
  }
116
116
 
117
117
  /** 项目无可定向总监。 */
118
118
  export function noOwner(project) {
119
- return `项目【${project.name || project.key}】没有可用的总监 Bot,无法直达。`
119
+ return `项目【${project.name || project.key}】没有可用的总监 Bot,无法直达;可在消息里 @成员名 指定接收人。`
120
120
  }
121
121
 
122
122
  /** 项目外导演通道不可达(DSHBOTS-258):通道异常,语义与「需要用户选项目」不同。 */
package/ui/app.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { state, STATUS, STATUS_ORDER, PRIORITY, PROPOSAL_STATUS, COLORS, COLOR_NAMES, BOT_STATUS, RUN_STATUS, RUN_KIND, CHAT_PAGE_SIZE, CHAT_ACTIVE_TASK_LIMIT, SKILL_STATUS, MEMORY_STATUS, PROPOSAL_KIND, TERMINAL_STATUS, CREATOR_TYPE, EFFORT, FILE_POLICY, DEFAULT_FILE_POLICY, VIEW_ACTION, NAV, SOLO_NAV } from './modules/state.js'
2
2
  import { icon } from './modules/icons.js'
3
3
  import { applyUiScale, applyUiTheme, initColorScheme, esc, attr, pathCode, costValue, clamp, botById, shortRefId, actorLabel, taskById, activeProject, inSoloContext, pageProject, activeBots, formatNumber, CURRENCY_SYMBOL, formatCost, timeAgo, formatTime, duration, avatar, statusPill, runDot, memberRunDot, runDotHtml, memorySource, toast, filePolicyOptions } from './modules/util.js'
4
- import { richText, mdPlainSummary, mdChatScope } from './modules/markdown.js'
4
+ import { richText, mdPlainSummary, mdChatScope, mdImageChipTitle } from './modules/markdown.js'
5
5
  import { api, loadState, markVisibleChatRead } from './modules/api.js'
6
6
  import { t, setLanguage } from './modules/i18n.js'
7
7
  import { typingLingerRowsHtml, applyOptimisticTyping, pruneTypingLinger } from './modules/typing-linger.js'
@@ -25,20 +25,24 @@ const GLOBAL_VIEWS = new Set(['global', 'bots-overview', 'channel', 'secrets'])
25
25
  const app = document.getElementById('app')
26
26
  const UI_SCALE_KEY = 'dshb:ui-scale'
27
27
  const UI_THEME_KEY = 'dshb:ui-theme'
28
+ const UI_COLOR_SCHEME_KEY = 'dshb:ui-color-scheme'
28
29
 
29
30
  // 任务分组默认全展开(DSHBOTS-58):把各分组的展开态 key 预置进 state.openPanels,
30
31
  // 与 <details data-panel> 同一套通道(key 形如 task-group:<status>),折叠即从集合里删掉。
31
32
  for (const status of STATUS_ORDER) state.openPanels.add(taskGroupKey(status))
32
33
 
33
34
  if (window.matchMedia?.('(max-width: 980px)').matches) state.tree = { chats: false, bots: false }
34
- const savedScale = (() => {
35
- try { return Number(localStorage.getItem(UI_SCALE_KEY)) || null } catch { return null }
36
- })()
35
+ // 偏好读取的唯一出口:本地存储不可用(隐私模式/无权限)一律回落默认值。
36
+ const readPref = (key ) => {
37
+ try { return localStorage.getItem(key) } catch { return null }
38
+ }
39
+ const savedScale = Number(readPref(UI_SCALE_KEY)) || null
37
40
  if (savedScale) applyUiScale(savedScale)
41
+ // 明暗偏好先于 initColorScheme 落地:手动档(日间/夜间)压过宿主/系统自动判定,
42
+ // auto 档仍由 initColorScheme 的观察器在宿主切深浅时实时跟随。
43
+ state.colorSchemePref = readPref(UI_COLOR_SCHEME_KEY)
38
44
  initColorScheme()
39
- state.theme = applyUiTheme((() => {
40
- try { return localStorage.getItem(UI_THEME_KEY) } catch { return null }
41
- })())
45
+ state.theme = applyUiTheme(readPref(UI_THEME_KEY))
42
46
 
43
47
  // UI 语言跟随 DSH 宿主 Language 设定(DSHBOTS-120):服务端把解析结果(zh/en/auto)
44
48
  // 注入 <html data-dsh-language>,模块加载即设定语言并替换静态 boot 文案(CSP 禁内联
@@ -701,16 +705,17 @@ window.addEventListener('error', (event) => {
701
705
  const img = event.target
702
706
  if (!(img instanceof HTMLImageElement)) return
703
707
  if (!img.closest('.message-bubble, .comment-body')) return
708
+ const src = img.getAttribute('src') ?? ''
704
709
  let name = ''
705
710
  try {
706
- const url = new URL(img.getAttribute('src') ?? '', location.href)
711
+ const url = new URL(src, location.href)
707
712
  name = url.searchParams.get('path')?.split('/').pop() ?? url.pathname.split('/').pop() ?? ''
708
713
  } catch { name = '' }
709
714
  if (!name) name = img.alt?.trim() || t('chat.imageFallback')
710
715
  const chip = document.createElement('span')
711
716
  chip.className = 'md-img-missing'
712
717
  chip.textContent = `${name}${t('chat.imageMissingSuffix')}`
713
- chip.title = t('chat.imageMissingHint')
718
+ chip.title = mdImageChipTitle(chip, img)
714
719
  img.replaceWith(chip)
715
720
  }, true)
716
721
 
@@ -788,6 +793,6 @@ void init()
788
793
 
789
794
  // DSHBOTS-15 批次3:IIFE 包裹已拆除(模块作用域等价于原 IIFE 私有作用域,模块天然 strict)。
790
795
  // 以下导出仅供后续批次外迁的 ui/modules/*.js 反向依赖(调用期解析);随各域搬出逐步收缩。
791
- export { app, UI_SCALE_KEY, UI_THEME_KEY, savedScale, refresh, startWechatPoll, stopWechatPoll, startTerminalPoll, stopTerminalPoll, syncTerminalPoll, updateTerminalDom, bootError, isTyping, pendingProposals, tabDot, renderShell, syncChromeHeight, renderKeepingChatScroll, panelKey, isPanelOpen, panelOpenAttr }
796
+ export { app, UI_SCALE_KEY, UI_THEME_KEY, UI_COLOR_SCHEME_KEY, savedScale, refresh, startWechatPoll, stopWechatPoll, startTerminalPoll, stopTerminalPoll, syncTerminalPoll, updateTerminalDom, bootError, isTyping, pendingProposals, tabDot, renderShell, syncChromeHeight, renderKeepingChatScroll, panelKey, isPanelOpen, panelOpenAttr }
792
797
  export { applyPanelToggle, panelAttrs, lastRenderedView, captureViewScroll, restoreViewScroll, CHAT_BOTTOM_THRESHOLD, nextChatAtBottom, render, renderView, noProject, runStatusLabel, sideRowStatusHtml, runKindLabel, chatContextPending, beginChatPending, endChatPending }
793
798
  export { observer, updateRunClocks, init, syncLanguage, formPayload }
@@ -15,6 +15,9 @@ export default {
15
15
  "chat.imageFallback": "Image",
16
16
  "chat.imageMissingSuffix": " (image failed to load)",
17
17
  "chat.imageMissingHint": "The image was not found in the workspace, or its type/size is not on the allowlist",
18
+ "chat.imageMissingUnrewritten": "Image path was not rewritten to the workspace file endpoint: it may contain spaces, a file:// scheme, or backslashes; use a workspace-relative path",
19
+ "chat.imageMissingForbidden": "Image path escapes the workspace and was rejected (403)",
20
+ "chat.imageMissingNotFound": "Image not found in the workspace (404)",
18
21
  // Message history pagination
19
22
  "chat.loadingOlder": "Loading…",
20
23
  "chat.loadOlder": "Load ${count} earlier",
@@ -47,6 +47,11 @@ export default {
47
47
  "global.uiScaleSmall": "Small",
48
48
  "global.uiScaleLarge": "Large",
49
49
  "global.theme": "Theme",
50
+ "global.colorScheme": "Light / dark",
51
+ "global.colorSchemeAuto": "Follow",
52
+ "global.colorSchemeLight": "Day",
53
+ "global.colorSchemeDark": "Night",
54
+ "global.colorSchemeHint": "Follow tracks the host or system automatically; Day and Night pin the mode manually.",
50
55
  "global.scaleRange": "Scale range",
51
56
  "global.prefStorage": "Preference storage",
52
57
  "global.prefStorageValue": "Local browser (except language)",
@@ -15,6 +15,9 @@ export default {
15
15
  "chat.imageFallback": "图片",
16
16
  "chat.imageMissingSuffix": "(图片未能加载)",
17
17
  "chat.imageMissingHint": "工作区里找不到该图片,或类型/大小不在白名单内",
18
+ "chat.imageMissingUnrewritten": "图片路径未被改写为工作区文件端点:可能含空格、file:// 协议或反斜杠,请改用工作区相对路径",
19
+ "chat.imageMissingForbidden": "图片路径越界,服务端拒绝(403)",
20
+ "chat.imageMissingNotFound": "工作区里找不到该图片(404)",
18
21
  // 历史消息分页
19
22
  "chat.loadingOlder": "加载中…",
20
23
  "chat.loadOlder": "加载前 ${count} 条",
@@ -47,6 +47,11 @@ export default {
47
47
  "global.uiScaleSmall": "小",
48
48
  "global.uiScaleLarge": "大",
49
49
  "global.theme": "配色",
50
+ "global.colorScheme": "明暗",
51
+ "global.colorSchemeAuto": "跟随",
52
+ "global.colorSchemeLight": "日间",
53
+ "global.colorSchemeDark": "夜间",
54
+ "global.colorSchemeHint": "跟随 = 随宿主或系统自动切换;日间/夜间为手动固定。",
50
55
  "global.scaleRange": "缩放范围",
51
56
  "global.prefStorage": "偏好存储",
52
57
  "global.prefStorageValue": "本地浏览器(语言除外)",
@@ -1,6 +1,6 @@
1
1
  import { state } from './state.js'
2
2
  import { t } from './i18n.js'
3
- import { activeProject, applyUiScale, applyUiTheme, toast } from './util.js'
3
+ import { activeProject, applyUiScale, applyUiTheme, setColorSchemePreference, toast } from './util.js'
4
4
  import { api, loadState, mergeSettingsDraft } from './api.js'
5
5
  import { sendMessage } from './composer.js'
6
6
  import { closeModal, openBot, openModal, openTask, openTrajectory } from './modal-forms.js'
@@ -8,7 +8,7 @@ import { loadOlderMessages, loadSoloDetail } from './chat.js'
8
8
  import { taskChildrenKey, taskGroupKey } from './tasks.js'
9
9
  import { toggleDesktopNotify } from './cards.js'
10
10
  import { usageMode } from './usage.js'
11
- import { UI_SCALE_KEY, UI_THEME_KEY, syncLanguage, refresh, startWechatPoll, stopWechatPoll, bootError, render, chatContextPending, beginChatPending, endChatPending, init } from '../app.js'
11
+ import { UI_SCALE_KEY, UI_THEME_KEY, UI_COLOR_SCHEME_KEY, syncLanguage, refresh, startWechatPoll, stopWechatPoll, bootError, render, chatContextPending, beginChatPending, endChatPending, init } from '../app.js'
12
12
 
13
13
  // 设置保存 + 409 冲突三方合并(B2/DSHBOTS-325):key→inputId 映射驱动 patch 采集。
14
14
  // 冲突时静默接管 api 错误:重取最新设置后,对方未动字段的用户草稿贴回表单(编辑不丢),
@@ -19,7 +19,7 @@ async function saveSettingsWithMerge(inputIds, successToast) {
19
19
  for (const [key, id] of Object.entries(inputIds)) patch[key] = value(id)
20
20
  const baseSettings = state.data?.settings ?? {}
21
21
  try {
22
- await api('update_settings', { ...patch, revision: state.data?.settingsRevision }, { quiet: true })
22
+ await api('update_settings', { patch: { ...patch }, revision: state.data?.settingsRevision }, { quiet: true })
23
23
  await loadState(state.projectId)
24
24
  toast(successToast, 'success')
25
25
  } catch (error ) {
@@ -113,6 +113,13 @@ export async function handleBoardAction(action, target) {
113
113
  render()
114
114
  break
115
115
  }
116
+ case 'set-color-scheme': {
117
+ // 明暗三档:跟随宿主/系统、日间、夜间;手动档压过自动判定,落盘后即时生效。
118
+ const pref = setColorSchemePreference(target.dataset.colorScheme)
119
+ try { localStorage.setItem(UI_COLOR_SCHEME_KEY, pref) } catch {}
120
+ render()
121
+ break
122
+ }
116
123
  case 'toggle-notify': {
117
124
  await toggleDesktopNotify()
118
125
  break
@@ -136,10 +143,10 @@ export async function handleBoardAction(action, target) {
136
143
  // 由既有 syncLanguage 热切换(换字典 + toast.languageSwitched + render),无需重启。
137
144
  case 'save-ui-language': {
138
145
  const value = (document.getElementById('settings-ui-language') )?.value ?? 'auto'
139
- // revision 仅在有值时携带(无 state 数据的旧环境回退无令牌形态)。
140
- const languagePatch = { ui_language: value }
141
- if (Number.isFinite(Number(state.data?.settingsRevision))) languagePatch.revision = state.data?.settingsRevision
142
- await api('update_settings', languagePatch)
146
+ // B2/DSHBOTS-325 契约:patch 与 revision 分离;revision 仅在有值时携带。
147
+ const languagePayload = { patch: { ui_language: value } }
148
+ if (Number.isFinite(Number(state.data?.settingsRevision))) languagePayload.revision = state.data?.settingsRevision
149
+ await api('update_settings', languagePayload)
143
150
  await loadState(state.projectId)
144
151
  // poll() 只取数不切语言(ui/app.js:620-642),热切换必须由保存动作自己触发(DSHBOTS-162 R1)。
145
152
  syncLanguage()
@@ -1,5 +1,6 @@
1
1
  import { state } from './state.js'
2
2
  import { esc, inSoloContext, botById, pageProject } from './util.js'
3
+ import { t } from './i18n.js'
3
4
 
4
5
  // markdown-render:start —— 聊天 markdown 渲染纯逻辑(tests/markdown.test.js 抽取此块断言)。
5
6
  // 管线固定:md → mdRewriteImageSources → marked.parse → DOMPurify.sanitize → innerHTML。
@@ -7,9 +8,28 @@ import { esc, inSoloContext, botById, pageProject } from './util.js'
7
8
  // mdCreateRenderer 返回 null,调用方回退 esc 纯文本,绝不裸插 HTML。
8
9
  // 工作区图片路径改写成 GET /api/dsh-team/file(服务端再做 MIME 白名单与防穿越)。
9
10
  const MD_SCHEME = /^(?:[a-z][a-z0-9+.-]*:|#|\/\/)/i
11
+ // 图片语法内部:href 允许含空格(到标题或右括号前止),标题可为 "..." / '...' / (...)。
12
+ const MD_IMAGE = /(!\[[^\]]*\]\()([^)\n]*?)(?:\s+("[^"]*"|'[^']*'|\([^)]*\)))?\s*\)/g
13
+ // 只剥尾部标题:含空格的路径若被标题正则误切会丢文件名,故仅匹配整段结尾的引号/括号标题。
14
+ const MD_IMAGE_TITLE = /\s+("[^"]*"|'[^']*'|\([^)]*\))$/
15
+ function mdImageTarget(inner) {
16
+ const text = String(inner ?? '').trim()
17
+ if (!text) return ''
18
+ if (text.startsWith('<')) {
19
+ const end = text.indexOf('>')
20
+ if (end >= 0) return text.slice(1, end).trim()
21
+ }
22
+ const title = MD_IMAGE_TITLE.exec(text)
23
+ return title ? text.slice(0, title.index) : text
24
+ }
10
25
  function mdImageFileUrl(href, scope) {
11
26
  if (!scope || !href) return null
12
- const raw = String(href)
27
+ let raw = String(href).trim()
28
+ if (!raw) return null
29
+ // 先还原转义再判定:%20 空格、%2F 斜杠都要按真实路径处理。
30
+ try { raw = decodeURIComponent(raw) } catch { /* 非法转义保持原样 */ }
31
+ // file:// URI 与 Windows 反斜杠都归一到工作区相对/绝对路径形态。
32
+ raw = raw.replace(/^file:\/\//i, '').replace(/\\/g, '/')
13
33
  // 只改写本地路径形态;http(s)/data:/锚点等协议引用原样交给消毒层。
14
34
  if (MD_SCHEME.test(raw)) return null
15
35
  let rel = raw
@@ -27,8 +47,8 @@ function mdImageFileUrl(href, scope) {
27
47
  return `/api/dsh-team/file?${params.toString()}`
28
48
  }
29
49
  function mdRewriteImageSources(source, scope) {
30
- return String(source ?? '').replace(/(!\[[^\]]*\]\()\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\)/g, (whole, lead, href) => {
31
- const url = mdImageFileUrl(href, scope)
50
+ return String(source ?? '').replace(MD_IMAGE, (whole, lead, inner) => {
51
+ const url = mdImageFileUrl(mdImageTarget(inner), scope)
32
52
  return url ? `${lead}${url})` : whole
33
53
  })
34
54
  }
@@ -114,3 +134,22 @@ export function mdChatScope() {
114
134
  const project = pageProject()
115
135
  return project ? { projectId: project.id, root: project.workspace_path } : null
116
136
  }
137
+
138
+ // 图片失败 chip 的原因诊断:src 未被改写成文件端点(路径形态没接住,浏览器按页面 URL 解析)
139
+ // 与已改写但端点拒绝分开;已改写的再探一次状态码,403/404 直接写进 chip title。
140
+ export function mdImageChipTitle(chip, img) {
141
+ const src = img.getAttribute('src') ?? ''
142
+ let rewritten = false
143
+ try { rewritten = new URL(src, location.href).pathname === '/api/dsh-team/file' } catch { /* 解析失败按未改写 */ }
144
+ // 外链图片失败与本地路径漏改写是两回事:前者只给通用提示,后者才指路改用工作区相对路径。
145
+ if (!rewritten) return /^(?:https?:|data:)/i.test(src) ? t('chat.imageMissingHint') : t('chat.imageMissingUnrewritten')
146
+ void fetch(src)
147
+ .then((res) => {
148
+ if (res.ok) return
149
+ chip.title = res.status === 403 ? t('chat.imageMissingForbidden')
150
+ : res.status === 404 ? t('chat.imageMissingNotFound')
151
+ : t('chat.imageMissingHint')
152
+ })
153
+ .catch(() => {})
154
+ return t('chat.imageMissingHint')
155
+ }
@@ -423,6 +423,8 @@ function renderGlobal() {
423
423
  // 用 || 而非 ??:settingsView() 对未保存键返回 ''(见 core.js),空串必须回落 auto,否则三选项都不选中。
424
424
  const uiLanguage = data.settings?.ui_language || 'auto'
425
425
  const notify = notifyToggleView()
426
+ // 明暗偏好读内存态(非服务端设置):三档跟随/日间/夜间,与调色板正交。
427
+ const colorSchemePref = state.colorSchemePref || 'auto'
426
428
  return pageShell(
427
429
  pageHead('GLOBAL CONFIGURATION', t('global.title'), t('global.desc'), refreshAction()),
428
430
  pageNav([
@@ -448,6 +450,15 @@ function renderGlobal() {
448
450
  <span class="faint" style="margin-left:auto">${t('global.uiScaleLarge')}</span>
449
451
  </div>
450
452
  </div>
453
+ <div class="field">
454
+ <span class="field-label" id="ui-color-scheme-label">${t('global.colorScheme')}</span>
455
+ <div class="seg" role="group" aria-labelledby="ui-color-scheme-label">
456
+ <button data-action="set-color-scheme" data-color-scheme="auto" aria-pressed="${colorSchemePref === 'auto'}">${t('global.colorSchemeAuto')}</button>
457
+ <button data-action="set-color-scheme" data-color-scheme="light" aria-pressed="${colorSchemePref === 'light'}">${t('global.colorSchemeLight')}</button>
458
+ <button data-action="set-color-scheme" data-color-scheme="dark" aria-pressed="${colorSchemePref === 'dark'}">${t('global.colorSchemeDark')}</button>
459
+ </div>
460
+ <div class="hint">${esc(t('global.colorSchemeHint'))}</div>
461
+ </div>
451
462
  <div class="field">
452
463
  <span class="field-label" id="ui-theme-label">${t('global.theme')}</span>
453
464
  <div class="seg" role="group" aria-labelledby="ui-theme-label">
@@ -57,6 +57,8 @@ export const state = {
57
57
  memoryQuery: '',
58
58
  memoryResults: null,
59
59
  theme: 'dsh',
60
+ // 明暗偏好三态:auto=跟随宿主/系统,light=日间,dark=夜间(与调色板 theme 正交)。
61
+ colorSchemePref: 'auto',
60
62
  tree: { chats: true, bots: true, archived: false },
61
63
  // 群聊已读水位:`<projectId>:<最新消息时间>`,用于避免重复上报已读。
62
64
  markedRead: null,
@@ -29,8 +29,25 @@ export function resolveColorScheme() {
29
29
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
30
30
  }
31
31
 
32
+ // 明暗偏好三态:auto=跟随宿主/系统,light=日间,dark=夜间。手动档压过自动判定,
33
+ // auto 档仍走 resolveColorScheme 的宿主/系统回落链。
34
+ export function normalizeColorSchemePref(value) {
35
+ return value === 'light' || value === 'dark' ? value : 'auto'
36
+ }
37
+
38
+ // 应用明暗偏好:写状态 + 立即生效。返回偏好档本身(不是生效明暗)——落盘要的是档位,
39
+ // 否则「跟随」会被存成当时的生效值,刷新后变成手动固定。
40
+ export function setColorSchemePreference(value) {
41
+ const pref = normalizeColorSchemePref(value)
42
+ state.colorSchemePref = pref
43
+ applyColorScheme()
44
+ return pref
45
+ }
46
+
47
+ // 当前生效明暗:手动档直接定;auto 档实时跟随宿主/系统。
32
48
  export function applyColorScheme() {
33
- const scheme = resolveColorScheme()
49
+ const pref = normalizeColorSchemePref(state.colorSchemePref)
50
+ const scheme = pref === 'auto' ? resolveColorScheme() : pref
34
51
  document.documentElement.setAttribute('data-color-scheme', scheme)
35
52
  document.documentElement.style.colorScheme = scheme
36
53
  return scheme