dsh-mcviseron-plugin 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  import { useState } from 'react'
2
2
  import type { McviseronKey } from './locales.ts'
3
- import { AUTO_REVIEW_FIELDS, ConfigForm, TASK_GUARD_FIELDS } from './ConfigForm.tsx'
3
+ import { AUTO_REVIEW_FIELDS, ConfigForm, SESSION_END_FIELDS, TASK_GUARD_FIELDS } from './ConfigForm.tsx'
4
4
  import { RestartCard } from './RestartCard.tsx'
5
5
  import { pageStyles } from './styles.ts'
6
6
 
7
- type Tab = 'restart' | 'autoReview' | 'taskGuard' | 'components'
7
+ type Tab = 'restart' | 'autoReview' | 'taskGuard' | 'sessionEnd' | 'components'
8
8
 
9
9
  /** Props composed by the `settings.section` slot. */
10
10
  export interface SettingsSectionProps {
@@ -52,6 +52,15 @@ export function SettingsSection({ t }: SettingsSectionProps) {
52
52
  >
53
53
  {t('page.tab.taskGuard')}
54
54
  </button>
55
+ <button
56
+ type="button"
57
+ role="tab"
58
+ aria-selected={tab === 'sessionEnd'}
59
+ onClick={() => { setTab('sessionEnd') }}
60
+ style={tab === 'sessionEnd' ? { ...pageStyles.tab, ...pageStyles.tabActive } : pageStyles.tab}
61
+ >
62
+ {t('page.tab.sessionEnd')}
63
+ </button>
55
64
  <button
56
65
  type="button"
57
66
  role="tab"
@@ -83,7 +92,16 @@ export function SettingsSection({ t }: SettingsSectionProps) {
83
92
  fields={TASK_GUARD_FIELDS}
84
93
  />
85
94
  )
86
- : (
95
+ : tab === 'sessionEnd'
96
+ ? (
97
+ <ConfigForm
98
+ t={t}
99
+ title="page.sessionEnd.title"
100
+ description="page.sessionEnd.description"
101
+ fields={SESSION_END_FIELDS}
102
+ />
103
+ )
104
+ : (
87
105
  <div style={pageStyles.card}>
88
106
  <div style={pageStyles.cardTitle}>{t('page.components.title')}</div>
89
107
  <div style={pageStyles.componentRow}>
@@ -102,6 +120,10 @@ export function SettingsSection({ t }: SettingsSectionProps) {
102
120
  <span style={pageStyles.componentName}>{t('page.components.restart')}</span>
103
121
  <span style={pageStyles.componentHint}>{t('page.components.restartHint')}</span>
104
122
  </div>
123
+ <div style={pageStyles.componentRow}>
124
+ <span style={pageStyles.componentName}>{t('page.components.sessionEnd')}</span>
125
+ <span style={pageStyles.componentHint}>{t('page.components.sessionEndHint')}</span>
126
+ </div>
105
127
  <div style={pageStyles.cardStatus}>{t('page.components.note')}</div>
106
128
  </div>
107
129
  )}
@@ -5,6 +5,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
5
5
  import type {} from '@deepseek-ai/dsh-client-ui-slots'
6
6
  import { AppearanceScheduleRow } from './AppearanceScheduleRow.tsx'
7
7
  import { FallbackRestartRow } from './FallbackRestartRow.tsx'
8
+ import { SessionEndControl } from './SessionEndControl.tsx'
8
9
  import { SettingsSection } from './SettingsSection.tsx'
9
10
  import { ScheduleDriver, type ThemeFace } from './driver.ts'
10
11
  import { en, zh, type McviseronKey } from './locales.ts'
@@ -16,6 +17,14 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
16
17
  interface LocaleNamespaceMap {
17
18
  mcviseron: McviseronKey
18
19
  }
20
+
21
+ interface SlotMap {
22
+ 'conversation.input.left': {
23
+ kind: 'list'
24
+ scope: 'session'
25
+ owner: { children?: never }
26
+ }
27
+ }
19
28
  }
20
29
 
21
30
  export const inject = ['slots', 'locale']
@@ -105,6 +114,12 @@ export function apply(ctx: ClientContext): void {
105
114
  locale: NS,
106
115
  }, FallbackRestartRow)
107
116
 
117
+ registerSafely(ctx, 'conversation.input.left', {
118
+ id: 'mcviseron-session-end',
119
+ order: 20,
120
+ locale: NS,
121
+ }, SessionEndControl)
122
+
108
123
  registerSafely(ctx, 'settings.section', {
109
124
  id: 'mcviseron',
110
125
  order: 115,
@@ -23,6 +23,19 @@ export const zh = {
23
23
  'restart.restarting': '正在重启…窗口会短暂关闭',
24
24
  'restart.failed': '重启失败,请重试',
25
25
  'restart.confirm': '确定要重启 DeepSeek Harness 吗?正在运行的任务会被中断。',
26
+ 'sessionEnd.label': '会话后重启',
27
+ 'sessionEnd.hint': '本轮最终回复完整显示后执行;AI 需要重启插件时可自动设置。',
28
+ 'sessionEnd.off': '关闭',
29
+ 'sessionEnd.restart': '重启 DSH',
30
+ 'sessionEnd.close': '关闭 DSH',
31
+ 'sessionEnd.shutdown': '关闭电脑',
32
+ 'sessionEnd.aiRestart': 'AI 已请求:本轮结束后重启 DSH',
33
+ 'sessionEnd.aiClose': 'AI 已请求:本轮结束后关闭 DSH',
34
+ 'sessionEnd.aiWaiting': 'AI 已请求重启;等待其它任务结束',
35
+ 'sessionEnd.userShutdown': '本轮结束后将关闭电脑',
36
+ 'sessionEnd.shutdownConfirm': '确定要在本轮结束后关闭电脑吗?',
37
+ 'sessionEnd.failed': '设置失败,请重试',
38
+
26
39
  'page.title': 'MCviseron 插件',
27
40
  'page.description': '总插件的组件设置。外观设置仍在「通用 → 外观」中。',
28
41
  'page.tab.restart': '重启',
@@ -61,7 +74,7 @@ export const zh = {
61
74
  'form.unavailable': '无法读取插件设置:请确认 profile 中的插件条目 id 为 mcviseron',
62
75
  'form.autoSave': '修改后自动保存',
63
76
  'form.autoReview.translate': '翻译审批理由',
64
- 'form.autoReview.translateHint': '英文审查理由会附上中文翻译,并写入审批事件,邮箱提醒也能收到',
77
+ 'form.autoReview.translateHint': '英文审查理由会附上中文翻译,并写入审批事件;转手动后被拒时,自动审查理由会作为 notice 交回 AI',
65
78
  'form.autoReview.keepPreset': '退出时保持权限预设',
66
79
  'form.autoReview.keepPresetHint': '关闭 DSH 时不再把 Auto 会话改成完全访问',
67
80
  'form.autoReview.timeout': '翻译超时(毫秒)',
@@ -85,13 +98,28 @@ export const zh = {
85
98
  'form.taskGuard.sourceV4': 'v4',
86
99
  'form.taskGuard.maxListItems': 'notice 最多列出任务数',
87
100
  'form.taskGuard.detectStepIntent': '识别步骤意图',
88
- 'form.taskGuard.detectStepIntentHint': '从思考/正文识别「Now I will …」等句式并匹配 pending todo',
101
+ 'form.taskGuard.detectStepIntentHint': '识别「Now I will …」等步骤意图,以及「All nets routed」「DRC passes」「原理图完成」等阶段完成语句;命中时提供可直接发送的 todo_write',
89
102
  'form.taskGuard.translateTodo': '中文展示 todo 标题',
90
103
  'form.taskGuard.translateTodoHint': '只影响 notice 展示,不改写模型写入的 todo',
91
104
  'form.taskGuard.todoTimeout': 'todo 翻译超时(毫秒)',
92
105
  'form.taskGuard.include': '只统计这些工具',
93
106
  'form.taskGuard.exclude': '不统计这些工具',
94
107
  'form.taskGuard.listHint': '逗号分隔,支持 *;留空表示全部',
108
+ 'page.tab.sessionEnd': '会话后动作',
109
+ 'page.sessionEnd.title': '会话后动作',
110
+ 'page.sessionEnd.description': '本轮最终回复完整显示后执行一次动作;重启会等待所有会话与后台任务结束,设置页的重启不受此约束。',
111
+ 'page.components.sessionEnd': '会话后动作',
112
+ 'page.components.sessionEndHint': '输入框左侧的「会话后重启」下拉',
113
+ 'form.sessionEnd.enabled': '启用会话后动作',
114
+ 'form.sessionEnd.enabledHint': '在对话输入框显示「会话后重启」下拉,并允许 AI 设置',
115
+ 'form.sessionEnd.grace': '最终回复显示等待(毫秒)',
116
+ 'form.sessionEnd.graceHint': 'turn/end 后再等待这段时间,避免文字还在渲染就重启',
117
+ 'form.sessionEnd.notifyEmail': 'AI 开启时发送邮件提醒',
118
+ 'form.sessionEnd.notifyEmailHint': '需要已安装并配置可发送的 dsh-email-notify;复用其 SMTP 配置,不修改邮件插件',
119
+ 'form.sessionEnd.emailSubject': '邮件主题模板',
120
+ 'form.sessionEnd.emailBody': '邮件正文模板',
121
+ 'form.sessionEnd.emailBodyHint': '可用 {{actionText}} / {{sessionName}} / {{sessionId}} / {{time}} / {{reason}}',
122
+
95
123
  } as const
96
124
 
97
125
  export const en = {
@@ -119,6 +147,19 @@ export const en = {
119
147
  'restart.restarting': 'Restarting… the window will close briefly',
120
148
  'restart.failed': 'Restart failed — try again',
121
149
  'restart.confirm': 'Restart DeepSeek Harness now? Running tasks will be interrupted.',
150
+ 'sessionEnd.label': 'Restart after session',
151
+ 'sessionEnd.hint': 'Runs after the final reply is fully displayed; the AI can arm it when a plugin change needs a restart.',
152
+ 'sessionEnd.off': 'Off',
153
+ 'sessionEnd.restart': 'Restart DSH',
154
+ 'sessionEnd.close': 'Close DSH',
155
+ 'sessionEnd.shutdown': 'Shut down PC',
156
+ 'sessionEnd.aiRestart': 'AI requested: restart DSH after this turn',
157
+ 'sessionEnd.aiClose': 'AI requested: close DSH after this turn',
158
+ 'sessionEnd.aiWaiting': 'AI requested restart; waiting for other tasks',
159
+ 'sessionEnd.userShutdown': 'The computer will shut down after this turn',
160
+ 'sessionEnd.shutdownConfirm': 'Shut down the computer after this turn?',
161
+ 'sessionEnd.failed': 'Could not update the session-end action',
162
+
122
163
  'page.title': 'MCviseron plugin',
123
164
  'page.description': 'Settings for the master plugin components. Appearance still lives under General → Appearance.',
124
165
  'page.tab.restart': 'Restart',
@@ -157,7 +198,7 @@ export const en = {
157
198
  'form.unavailable': 'Cannot read the plugin settings: check that the profile entry id is mcviseron',
158
199
  'form.autoSave': 'Changes save automatically',
159
200
  'form.autoReview.translate': 'Translate the approval reason',
160
- 'form.autoReview.translateHint': 'Appends a Chinese translation to the reviewer note and writes it into the approval event for email reminders',
201
+ 'form.autoReview.translateHint': 'Appends a Chinese translation to the reviewer note and writes it into the approval event; a manual rejection returns the auto-review reason to the AI',
161
202
  'form.autoReview.keepPreset': 'Keep the permission preset on shutdown',
162
203
  'form.autoReview.keepPresetHint': 'Stops DSH from rewriting Auto sessions to Full access while exiting',
163
204
  'form.autoReview.timeout': 'Translation timeout (ms)',
@@ -181,13 +222,28 @@ export const en = {
181
222
  'form.taskGuard.sourceV4': 'v4',
182
223
  'form.taskGuard.maxListItems': 'Maximum tasks listed in a notice',
183
224
  'form.taskGuard.detectStepIntent': 'Detect step intent',
184
- 'form.taskGuard.detectStepIntentHint': 'Recognizes “Now I will …”-style reasoning and matches pending todos',
225
+ 'form.taskGuard.detectStepIntentHint': 'Recognizes step intent (“Now I will …”) and completion statements (“All nets routed”, “DRC passes”); the notice carries a ready todo_write',
185
226
  'form.taskGuard.translateTodo': 'Show todo titles in Chinese',
186
227
  'form.taskGuard.translateTodoHint': 'Display-only; stored todos are never rewritten',
187
228
  'form.taskGuard.todoTimeout': 'Todo translation timeout (ms)',
188
229
  'form.taskGuard.include': 'Count only these tools',
189
230
  'form.taskGuard.exclude': 'Exclude these tools',
190
231
  'form.taskGuard.listHint': 'Comma-separated, * supported; empty means all',
232
+ 'page.tab.sessionEnd': 'After-session action',
233
+ 'page.sessionEnd.title': 'After-session action',
234
+ 'page.sessionEnd.description': 'One action after the final reply is fully displayed. A restart waits for every running conversation and background job; the Settings restart button is not delayed.',
235
+ 'page.components.sessionEnd': 'After-session action',
236
+ 'page.components.sessionEndHint': 'The “Restart after session” dropdown left of the composer',
237
+ 'form.sessionEnd.enabled': 'Enable after-session actions',
238
+ 'form.sessionEnd.enabledHint': 'Show the “Restart after session” dropdown in the composer and let the AI arm it',
239
+ 'form.sessionEnd.grace': 'Final-reply render grace (ms)',
240
+ 'form.sessionEnd.graceHint': 'Wait after turn/end so the final text is fully rendered before acting',
241
+ 'form.sessionEnd.notifyEmail': 'Email me when the AI arms it',
242
+ 'form.sessionEnd.notifyEmailHint': 'Requires an installed, sendable dsh-email-notify; reuses its SMTP settings without modifying it',
243
+ 'form.sessionEnd.emailSubject': 'Email subject template',
244
+ 'form.sessionEnd.emailBody': 'Email body template',
245
+ 'form.sessionEnd.emailBodyHint': 'Placeholders: {{actionText}} / {{sessionName}} / {{sessionId}} / {{time}} / {{reason}}',
246
+
191
247
  } satisfies Record<keyof typeof zh, string>
192
248
 
193
249
  export type McviseronKey = keyof typeof zh
@@ -1,9 +1,10 @@
1
+ import { randomUUID } from 'node:crypto'
1
2
  import type { Context } from '@deepseek-ai/cordis'
2
3
  import {
3
4
  chineseKey,
4
5
  cleanTranslation,
5
6
  clearTranslationCache,
6
- containsCjk,
7
+ isPredominantlyChinese,
7
8
  englishText,
8
9
  hasTranslation,
9
10
  isAutoReviewText,
@@ -208,8 +209,9 @@ export async function decorateApprovalRequest(
208
209
  const excerpt = reviewerExcerpt(english)
209
210
  if (excerpt.length === 0 || excerpt.length > settings.maxChars) return request
210
211
  // The reviewer already wrote this note in Chinese: appending a "translation"
211
- // would duplicate the same text, so leave the prompt untouched.
212
- if (containsCjk(excerpt)) return request
212
+ // would duplicate the same text. A few quoted Chinese instructions or a
213
+ // Windows path inside an English note are not predominantly Chinese.
214
+ if (isPredominantlyChinese(excerpt)) return request
213
215
  if (translationRoute(settings, request) === undefined) return request
214
216
 
215
217
  const llm = serviceOf(scope, 'llm') as { stream?: (options: unknown) => unknown } | undefined
@@ -232,7 +234,138 @@ export async function decorateApprovalRequest(
232
234
  }
233
235
 
234
236
  /** Guard the approval seam so the escalation prompt carries a translation. */
235
- function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings): void {
237
+ /** One notice waiting for the denied tool's post-execute pass. */
238
+ interface RejectionNotice {
239
+ id: string
240
+ role: 'user'
241
+ content: [{ type: 'text'; text: string }]
242
+ source: Record<string, unknown>
243
+ }
244
+
245
+ interface RejectionRelay {
246
+ remember(key: string, notice: RejectionNotice): void
247
+ take(key: string): RejectionNotice | undefined
248
+ }
249
+
250
+ /** Session id of an approval request / tool execution. */
251
+ function sessionIdOf(agent: unknown): string {
252
+ const session = (agent as { session?: { id?: unknown } } | undefined)?.session
253
+ return typeof session?.id === 'string' ? session.id : ''
254
+ }
255
+
256
+ /** DSH session format version, when the agent exposes it. */
257
+ function sessionVersion(agent: unknown): number | undefined {
258
+ const version = (agent as { session?: { header?: { version?: unknown } } } | undefined)?.session?.header?.version
259
+ return typeof version === 'number' ? version : undefined
260
+ }
261
+
262
+ function rejectionKey(agent: unknown, callId: unknown): string {
263
+ if (typeof callId !== 'string' || callId === '') return ''
264
+ const sessionId = sessionIdOf(agent)
265
+ return sessionId === '' ? '' : sessionId + ':' + callId
266
+ }
267
+
268
+ /** The localized reviewer reason, falling back to the audited text. */
269
+ function approvalReasonText(request: unknown): string {
270
+ const record = request as { reason?: unknown; displayReason?: unknown }
271
+ const display = record.displayReason
272
+ if (display !== null && typeof display === 'object' && !Array.isArray(display)) {
273
+ const key = chineseKey(display as LocaleText)
274
+ if (key !== undefined) {
275
+ const value = (display as Record<string, unknown>)[key]
276
+ if (typeof value === 'string' && value !== '') return value
277
+ }
278
+ const english = englishText(display as LocaleText)
279
+ if (english !== undefined && english !== '') return english
280
+ }
281
+ return typeof record.reason === 'string' ? record.reason : ''
282
+ }
283
+
284
+ /** Whether this approval is the Auto-review denial that became manual approval. */
285
+ function isAutoReviewApproval(request: unknown): boolean {
286
+ const record = request as { reason?: unknown; displayReason?: unknown }
287
+ if (typeof record.reason === 'string' && isAutoReviewText(record.reason)) return true
288
+ const display = record.displayReason
289
+ if (display !== null && typeof display === 'object' && !Array.isArray(display)) {
290
+ const english = englishText(display as LocaleText)
291
+ if (english !== undefined && isAutoReviewText(english)) return true
292
+ }
293
+ return false
294
+ }
295
+
296
+ function rejectionSource(agent: unknown, summary: string): Record<string, unknown> {
297
+ return sessionVersion(agent) === 3
298
+ ? { kind: 'plugin', plugin: 'auto-review-fix', form: 'notice', summary }
299
+ : { kind: 'plugin:auto-review-fix', form: 'notice', summary }
300
+ }
301
+
302
+ function buildRejectionNotice(agent: unknown, request: unknown): RejectionNotice | undefined {
303
+ const reason = approvalReasonText(request)
304
+ if (reason === '') return undefined
305
+ const toolName = typeof (request as { toolName?: unknown }).toolName === 'string' && (request as { toolName: string }).toolName !== ''
306
+ ? (request as { toolName: string }).toolName
307
+ : '未知工具'
308
+ const text = [
309
+ '【审批被拒】工具 "' + toolName + '" 的人工审批被拒绝。',
310
+ '自动审查理由:',
311
+ reason,
312
+ '',
313
+ '请根据该理由调整方案,不要重复同一操作。',
314
+ ].join('\n')
315
+ return {
316
+ id: randomUUID(),
317
+ role: 'user',
318
+ content: [{ type: 'text', text }],
319
+ source: rejectionSource(agent, '审批被拒 · ' + toolName),
320
+ }
321
+ }
322
+
323
+ function createRejectionRelay(): RejectionRelay {
324
+ const notes = new Map<string, { notice: RejectionNotice; at: number }>()
325
+ const ttl = 120_000
326
+ return {
327
+ remember(key, notice) {
328
+ const now = Date.now()
329
+ for (const [oldKey, entry] of notes) if (now - entry.at > ttl) notes.delete(oldKey)
330
+ if (notes.size >= 50) {
331
+ const oldest = notes.keys().next().value
332
+ if (oldest !== undefined) notes.delete(oldest)
333
+ }
334
+ notes.set(key, { notice, at: now })
335
+ },
336
+ take(key) {
337
+ const entry = notes.get(key)
338
+ if (entry === undefined) return undefined
339
+ notes.delete(key)
340
+ return entry.notice
341
+ },
342
+ }
343
+ }
344
+
345
+ const relayedContexts = new WeakSet<object>()
346
+
347
+ function installRejectionRelay(ctx: Context, relay: RejectionRelay): void {
348
+ const target = ctx as unknown as { on?: (event: string, handler: (...args: any[]) => any) => unknown }
349
+ if (typeof target.on !== 'function' || relayedContexts.has(ctx as unknown as object)) return
350
+ relayedContexts.add(ctx as unknown as object)
351
+ target.on.call(ctx, 'tools/post-execute', async (exec: any, result: any, next: () => Promise<any>) => {
352
+ const downstream = (await next()) ?? { kind: 'accept' }
353
+ if (result?.isError !== true) return downstream
354
+ const key = rejectionKey(exec?.agent, exec?.callId)
355
+ if (key === '') return downstream
356
+ const notice = relay.take(key)
357
+ if (notice === undefined) return downstream
358
+ return {
359
+ ...downstream,
360
+ additionalContexts: [
361
+ ...(Array.isArray(downstream.additionalContexts) ? downstream.additionalContexts : []),
362
+ notice,
363
+ ],
364
+ }
365
+ })
366
+ }
367
+
368
+ function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings, relay: RejectionRelay): void {
236
369
  whenService(ctx, 'approval', (scope) => {
237
370
  const approval = serviceOf(scope, 'approval') as { request?: unknown } | undefined
238
371
  if (approval === null || typeof approval !== 'object') return
@@ -247,7 +380,14 @@ function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings):
247
380
  } catch {
248
381
  decorated = request
249
382
  }
250
- return call.call(this, decorated)
383
+ const outcome = await call.call(this, decorated)
384
+ if (outcome === 'rejected' && isAutoReviewApproval(decorated)) {
385
+ const request = decorated as { agent?: unknown; callId?: unknown }
386
+ const key = rejectionKey(request.agent, request.callId)
387
+ const notice = buildRejectionNotice(request.agent, decorated)
388
+ if (key !== '' && notice !== undefined) relay.remember(key, notice)
389
+ }
390
+ return outcome
251
391
  }
252
392
  try {
253
393
  approval.request = wrapper
@@ -270,7 +410,11 @@ function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings):
270
410
  export function installAutoReview(ctx: Context, config?: unknown): void {
271
411
  const settings = normalizeConfig(config)
272
412
  if (settings.keepPresetGuard) installPresetGuard(ctx)
273
- if (settings.enabled) installApprovalTranslation(ctx, settings)
413
+ if (settings.enabled) {
414
+ const relay = createRejectionRelay()
415
+ installRejectionRelay(ctx, relay)
416
+ installApprovalTranslation(ctx, settings, relay)
417
+ }
274
418
  }
275
419
 
276
420
  /** Test seam: forget every cached display translation. */
@@ -77,7 +77,7 @@ export function isAutoReviewText(text: string): boolean {
77
77
  * translated ("Auto review denied this call: <reason>" -> "<reason>").
78
78
  */
79
79
  export function reviewerExcerpt(text: string): string {
80
- const match = /^\s*auto[\s\-_]*review\s+denied\s+this\s+call\s*[::.]?\s*/i.exec(text)
80
+ const match = /^\s*auto[\s\-_]*review\s+(?:denied\s+this\s+call|拒绝了此调用)\s*[::.]?\s*/i.exec(text)
81
81
  if (match === null) return text.trim()
82
82
  const rest = text.slice(match[0].length).trim()
83
83
  return rest.length === 0 ? text.trim() : rest
@@ -95,11 +95,24 @@ export function hasTranslation(value: string): boolean {
95
95
  return value.includes(TRANSLATION_LABEL)
96
96
  }
97
97
 
98
- /** Whether text already contains CJK characters, i.e. it needs no translation. */
98
+ /** Whether text already contains CJK characters. */
99
99
  export function containsCjk(text: string): boolean {
100
100
  return /[\u3400-\u9fff\uf900-\ufaff]/.test(text)
101
101
  }
102
102
 
103
+ /**
104
+ * Whether the reviewer wrote the note in Chinese. A few quoted Chinese
105
+ * instructions or a Windows path inside an English note ("... (\"这个提示框
106
+ * 似乎卡住了?\") ...") must not suppress translation; compare the number of
107
+ * Chinese characters with the number of English word tokens instead.
108
+ */
109
+ export function isPredominantlyChinese(text: string): boolean {
110
+ const han = (text.match(/[\u3400-\u9fff\uf900-\ufaff]/g) ?? []).length
111
+ if (han === 0) return false
112
+ const englishWords = (text.match(/[A-Za-z][A-Za-z0-9_.-]*/g) ?? []).length
113
+ return englishWords <= Math.max(2, Math.ceil(han / 2))
114
+ }
115
+
103
116
  /** Drop wrapping quotes, fences, and stray whitespace a model may add. */
104
117
  export function cleanTranslation(raw: string): string {
105
118
  let text = raw.trim()