@mealsea/dsh-prompt-enhance 1.0.0 → 1.1.0

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/client.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Prompt improve — Client 半(单文件、纯 JS、无构建、无第三方依赖)。
2
+ * Improve prompt — Client 半(单文件、纯 JS、无构建、无第三方依赖)。
3
3
  *
4
4
  * 职责:
5
5
  * 1. 在输入框卡片底部工具行里(权限控件右侧)挂一枚 28px 芯片;
@@ -29,7 +29,7 @@ window.__ModuleLoader__.load({
29
29
  /** 记住用户选的模型,换会话也生效;值形状 `{ provider, model, name }`。 */
30
30
  const MODEL_KEY = 'prompt-enhance:model'
31
31
  // 构建标记:悬停芯片可见,用来判断页面跑的是不是最新客户端代码。
32
- const BUILD = '2026-12-05.16'
32
+ const BUILD = '2026-12-06.1'
33
33
  const OUTPUT_MAX = 12000
34
34
  const UNDO_TTL = 5000
35
35
  // 诊断行开关:地址带 #pe-debug(或 ?pe-debug)时显示,平时保持面板干净。
@@ -115,7 +115,15 @@ window.__ModuleLoader__.load({
115
115
  const TIMEOUT_SECONDS = new Set([10, 20, 30])
116
116
  // 语言:auto = 跟随 DSH 语言设置;zh/en = 用户手动锁定。
117
117
  const LANGUAGE_MODES = new Set(['auto', 'zh', 'en'])
118
- const DEFAULT_SETTINGS = { fontSize: 'follow', language: 'auto', mode: 'auto', timeoutSec: 20, debug: false }
118
+ // 工作区感知:默认关闭;三组分段控件只接受契约固定的档位。
119
+ const AWARENESS_MODES = new Set(['off', 'on'])
120
+ const CONTEXT_TOKENS = new Set([400, 800, 1200])
121
+ const CONTEXT_LINES = new Set([40, 80, 160])
122
+ const CONTEXT_FILES = new Set([3, 5, 8])
123
+ const DEFAULT_SETTINGS = {
124
+ fontSize: 'follow', language: 'auto', mode: 'auto', timeoutSec: 20, debug: false,
125
+ awareness: 'off', contextTokens: 800, contextLines: 80, contextFiles: 5,
126
+ }
119
127
 
120
128
  function normalizeSettings(raw) {
121
129
  const next = { ...DEFAULT_SETTINGS }
@@ -125,6 +133,10 @@ window.__ModuleLoader__.load({
125
133
  if (ENHANCE_MODES.has(raw.mode)) next.mode = raw.mode
126
134
  if (TIMEOUT_SECONDS.has(Number(raw.timeoutSec))) next.timeoutSec = Number(raw.timeoutSec)
127
135
  if (typeof raw.debug === 'boolean') next.debug = raw.debug
136
+ if (AWARENESS_MODES.has(raw.awareness)) next.awareness = raw.awareness
137
+ if (CONTEXT_TOKENS.has(Number(raw.contextTokens))) next.contextTokens = Number(raw.contextTokens)
138
+ if (CONTEXT_LINES.has(Number(raw.contextLines))) next.contextLines = Number(raw.contextLines)
139
+ if (CONTEXT_FILES.has(Number(raw.contextFiles))) next.contextFiles = Number(raw.contextFiles)
128
140
  return next
129
141
  }
130
142
 
@@ -318,18 +330,26 @@ window.__ModuleLoader__.load({
318
330
  return excess
319
331
  }
320
332
 
333
+ /** 命令名归一化:无前导斜杠、小写、[a-z0-9][a-z0-9_-]{0,63};失败返回空串。 */
334
+ function normalizeCommandName(raw) {
335
+ if (typeof raw !== 'string') return ''
336
+ const name = raw.trim().replace(/^\/+/, '').toLowerCase()
337
+ return /^[a-z0-9][a-z0-9_-]{0,63}$/.test(name) ? name : ''
338
+ }
339
+
321
340
  function analyzeDraft(input) {
322
341
  const draft = String(input.draft == null ? '' : input.draft)
323
342
  const phase = input.phase
324
343
  const claimToken = typeof input.claimToken === 'string' ? input.claimToken : ''
344
+ const claimName = typeof input.claimName === 'string' ? input.claimName : ''
325
345
  const occurrences = input.occurrences || []
326
- if (draft.trim() === '') return { kind: 'blocked', reason: 'empty' }
346
+ if (draft.trim() === '') return { kind: 'blocked', reason: 'empty', commandName: null }
327
347
  const prefixEnd = prefixChipEnd(draft, occurrences, claimToken)
328
348
  if (prefixEnd > 0) {
329
349
  let start = prefixEnd
330
350
  while (start < draft.length && /\s/.test(draft.charAt(start))) start += 1
331
351
  const body = draft.slice(start)
332
- if (body.trim() === '') return { kind: 'blocked', reason: 'empty' }
352
+ if (body.trim() === '') return { kind: 'blocked', reason: 'empty', commandName: null }
333
353
  const detectStart = start - chipExcess(draft, occurrences, claimToken, prefixEnd)
334
354
  return {
335
355
  kind: 'command',
@@ -339,12 +359,13 @@ window.__ModuleLoader__.load({
339
359
  end: draft.length,
340
360
  detectStart,
341
361
  detectEnd: detectStart + body.length,
362
+ commandName: normalizeCommandName(claimName) || null,
342
363
  }
343
364
  }
344
- if (phase === 'claimed') return { kind: 'blocked', reason: 'busy' }
345
- if (phase !== 'plain') return { kind: 'blocked', reason: 'busy' }
346
- if (occurrences.length > 0) return { kind: 'blocked', reason: 'chips' }
347
- return { kind: 'plain', prefix: '', body: draft, start: 0, end: draft.length }
365
+ if (phase === 'claimed') return { kind: 'blocked', reason: 'busy', commandName: null }
366
+ if (phase !== 'plain') return { kind: 'blocked', reason: 'busy', commandName: null }
367
+ if (occurrences.length > 0) return { kind: 'blocked', reason: 'chips', commandName: null }
368
+ return { kind: 'plain', prefix: '', body: draft, start: 0, end: draft.length, commandName: null }
348
369
  }
349
370
 
350
371
  /** 草稿里"真正要优化的正文":前缀(命令/引用芯片)之后的文本;不可用时为 null。 */
@@ -506,11 +527,33 @@ window.__ModuleLoader__.load({
506
527
  return 'rules'
507
528
  }
508
529
 
509
- async function enhanceWithModel(text, locale, signal, selection) {
510
- // 选了模型就显式带上组合;没选则由 Host 用默认模型。
511
- const request = selection && selection.provider && selection.model
512
- ? { text, locale, provider: selection.provider, model: selection.model }
513
- : { text, locale }
530
+ /**
531
+ * 组装 `/enhance` 请求体:旧字段逐字节兼容,新字段只在有值时出现。
532
+ * `awareness` 缺省也照发(Host 会按 enabled=false 忽略);`sessionId`/`commandName` 为空则省略。
533
+ */
534
+ function buildEnhanceBody(text, locale, selection, extras) {
535
+ const body = { text, locale }
536
+ if (selection && selection.provider && selection.model) {
537
+ body.provider = selection.provider
538
+ body.model = selection.model
539
+ }
540
+ if (extras && typeof extras.sessionId === 'string' && extras.sessionId) body.sessionId = extras.sessionId
541
+ if (extras && extras.awareness) {
542
+ body.awareness = {
543
+ enabled: extras.awareness.enabled === true,
544
+ maxFiles: extras.awareness.maxFiles,
545
+ maxLinesPerFile: extras.awareness.maxLinesPerFile,
546
+ maxTokens: extras.awareness.maxTokens,
547
+ }
548
+ }
549
+ if (extras && typeof extras.commandName === 'string' && extras.commandName) {
550
+ body.commandName = extras.commandName
551
+ }
552
+ return body
553
+ }
554
+
555
+ async function enhanceWithModel(text, locale, signal, selection, extras) {
556
+ const request = buildEnhanceBody(text, locale, selection, extras)
514
557
  let ns = null
515
558
  try {
516
559
  ns = runtime && runtime.remote ? runtime.remote[PKG] : null
@@ -528,7 +571,7 @@ window.__ModuleLoader__.load({
528
571
  throw new EnhanceError('model')
529
572
  }
530
573
  }
531
- if (httpChannelAvailable()) return enhanceViaHttp(text, locale, signal, selection)
574
+ if (httpChannelAvailable()) return enhanceViaHttp(text, locale, signal, selection, extras)
532
575
  throw new EnhanceError('unsupported')
533
576
  }
534
577
 
@@ -536,11 +579,11 @@ window.__ModuleLoader__.load({
536
579
  * 走本插件 Host 半的 HTTP 路由(同源、仅回环)。
537
580
  * 主路由挂在 `/api/` 下,可能被 api-gateway 的前缀路由先接管;此时换备用路由重试一次。
538
581
  */
539
- async function enhanceViaHttp(text, locale, signal, selection) {
582
+ async function enhanceViaHttp(text, locale, signal, selection, extras) {
540
583
  let lastError = null
541
584
  for (const endpoint of HTTP_ENDPOINTS) {
542
585
  try {
543
- return await postEnhance(endpoint, text, locale, signal, selection)
586
+ return await postEnhance(endpoint, text, locale, signal, selection, extras)
544
587
  } catch (err) {
545
588
  lastError = err
546
589
  const code = err && err.code
@@ -550,10 +593,8 @@ window.__ModuleLoader__.load({
550
593
  throw lastError || new EnhanceError('unsupported')
551
594
  }
552
595
 
553
- async function postEnhance(endpoint, text, locale, signal, selection) {
554
- const payload = selection && selection.provider && selection.model
555
- ? { text, locale, provider: selection.provider, model: selection.model }
556
- : { text, locale }
596
+ async function postEnhance(endpoint, text, locale, signal, selection, extras) {
597
+ const payload = buildEnhanceBody(text, locale, selection, extras)
557
598
  let res
558
599
  try {
559
600
  res = await fetch(endpoint, {
@@ -587,6 +628,10 @@ window.__ModuleLoader__.load({
587
628
  return normalizeModelResult(data)
588
629
  }
589
630
 
631
+ /**
632
+ * 归一化 Host 响应:旧字段(text/notes)保持原样;context/symbols/command 是可选的
633
+ * 感知附件,任何形状问题都静默丢弃,绝不因此让整次增强失败。
634
+ */
590
635
  function normalizeModelResult(res) {
591
636
  const text = cleanModelText(res && res.text)
592
637
  if (!text) throw new EnhanceError('model')
@@ -597,7 +642,65 @@ window.__ModuleLoader__.load({
597
642
  label: 'panel.note.' + n,
598
643
  }))
599
644
  : []
600
- return { text, notes }
645
+
646
+ const out = { text, notes }
647
+
648
+ const c = res && res.context
649
+ if (c && typeof c.enabled === 'boolean' && Array.isArray(c.files) && c.budget && typeof c.budget === 'object') {
650
+ const context = {
651
+ enabled: c.enabled,
652
+ files: c.files
653
+ .filter((f) => f && typeof f.path === 'string'
654
+ && Number.isFinite(f.startLine) && Number.isFinite(f.endLine)
655
+ && Number.isFinite(f.lines) && Number.isFinite(f.tokens)
656
+ && Number.isFinite(f.score))
657
+ .map((f) => ({
658
+ path: f.path,
659
+ absolutePath: typeof f.absolutePath === 'string' ? f.absolutePath : '',
660
+ startLine: f.startLine,
661
+ endLine: f.endLine,
662
+ lines: f.lines,
663
+ tokens: f.tokens,
664
+ score: f.score,
665
+ })),
666
+ totalFiles: Number.isFinite(c.totalFiles) ? c.totalFiles : 0,
667
+ totalLines: Number.isFinite(c.totalLines) ? c.totalLines : 0,
668
+ totalTokens: Number.isFinite(c.totalTokens) ? c.totalTokens : 0,
669
+ budget: {
670
+ maxFiles: Number.isFinite(c.budget.maxFiles) ? c.budget.maxFiles : 0,
671
+ maxLinesPerFile: Number.isFinite(c.budget.maxLinesPerFile) ? c.budget.maxLinesPerFile : 0,
672
+ maxTokens: Number.isFinite(c.budget.maxTokens) ? c.budget.maxTokens : 0,
673
+ },
674
+ skippedFiles: Number.isFinite(c.skippedFiles) ? c.skippedFiles : 0,
675
+ truncated: c.truncated === true,
676
+ sessionId: typeof c.sessionId === 'string' ? c.sessionId : null,
677
+ workspaceRoot: typeof c.workspaceRoot === 'string' ? c.workspaceRoot : null,
678
+ source: c.source === 'live' || c.source === 'persisted' ? c.source : 'none',
679
+ }
680
+ if (typeof c.skipped === 'string' && c.skipped) context.skipped = c.skipped
681
+ if (c.error && typeof c.error.code === 'string') {
682
+ context.error = { code: c.error.code, message: typeof c.error.message === 'string' ? c.error.message : '' }
683
+ }
684
+ out.context = context
685
+ }
686
+
687
+ if (Array.isArray(res && res.symbols)) {
688
+ const symbols = res.symbols
689
+ .filter((s) => s && typeof s.name === 'string' && s.name
690
+ && (s.kind === 'function' || s.kind === 'variable' || s.kind === 'class')
691
+ && typeof s.file === 'string'
692
+ && Number.isFinite(s.line) && s.line >= 1)
693
+ .map((s) => ({ name: s.name, kind: s.kind, file: s.file, line: s.line }))
694
+ if (symbols.length > 0) out.symbols = symbols
695
+ }
696
+
697
+ const cmd = res && res.command
698
+ if (cmd && typeof cmd.name === 'string' && typeof cmd.description === 'string'
699
+ && (cmd.source === 'registry' || cmd.source === 'fallback')) {
700
+ out.command = { name: cmd.name, description: cmd.description, source: cmd.source }
701
+ }
702
+
703
+ return out
601
704
  }
602
705
 
603
706
  function withTimeout(promise, ms, signal) {
@@ -630,10 +733,10 @@ window.__ModuleLoader__.load({
630
733
  })
631
734
  }
632
735
 
633
- async function runModel(text, locale, signal, selection, timeoutMs) {
736
+ async function runModel(text, locale, signal, selection, timeoutMs, extras) {
634
737
  try {
635
738
  return await withTimeout(
636
- enhanceWithModel(text, locale, signal, selection),
739
+ enhanceWithModel(text, locale, signal, selection, extras),
637
740
  timeoutMs || MODEL_TIMEOUT,
638
741
  signal,
639
742
  )
@@ -646,10 +749,10 @@ window.__ModuleLoader__.load({
646
749
 
647
750
  /**
648
751
  * 增强入口(引擎层)。
649
- * @param {{ text: string, locale?: string, mode?: 'auto'|'model'|'rules', signal?: AbortSignal, selection?: { provider: string, model: string } | null, timeoutMs?: number, onPartial?: Function }} options
752
+ * @param {{ text: string, locale?: string, mode?: 'auto'|'model'|'rules', signal?: AbortSignal, selection?: { provider: string, model: string } | null, timeoutMs?: number, onPartial?: Function, sessionId?: string, awareness?: { enabled: boolean, maxFiles: number, maxLinesPerFile: number, maxTokens: number }, commandName?: string | null }} options
650
753
  * @returns {Promise<{ text: string, notes: Array, channel: 'model'|'rules', elapsedMs: number, degraded?: boolean }>}
651
754
  */
652
- async function enhance({ text, locale, mode, signal, selection, timeoutMs, onPartial }) {
755
+ async function enhance({ text, locale, mode, signal, selection, timeoutMs, onPartial, sessionId, awareness, commandName }) {
653
756
  const t0 = Date.now()
654
757
  trace('enter:' + (mode || 'auto'))
655
758
  if (!text || !text.trim()) throw new EnhanceError('empty')
@@ -664,8 +767,11 @@ window.__ModuleLoader__.load({
664
767
 
665
768
  if (mode === 'rules') return rulesResult()
666
769
 
770
+ // 感知附件只在真正调用模型时出现;规则通道完全不联网,不构造也不发送。
771
+ const extras = { sessionId, awareness, commandName }
772
+
667
773
  if (mode === 'model') {
668
- const out = await runModel(text, locale, signal, selection, timeoutMs)
774
+ const out = await runModel(text, locale, signal, selection, timeoutMs, extras)
669
775
  return { ...out, channel: 'model', elapsedMs: Date.now() - t0 }
670
776
  }
671
777
 
@@ -674,7 +780,7 @@ window.__ModuleLoader__.load({
674
780
  if (onPartial) onPartial(quick)
675
781
  trace('model:start')
676
782
  try {
677
- const out = await runModel(text, locale, signal, selection, timeoutMs)
783
+ const out = await runModel(text, locale, signal, selection, timeoutMs, extras)
678
784
  trace('model:ok')
679
785
  return { ...out, channel: 'model', elapsedMs: Date.now() - t0, debug: debugInfo() }
680
786
  } catch (err) {
@@ -743,9 +849,38 @@ window.__ModuleLoader__.load({
743
849
  status: { loading: '生成中…' },
744
850
  retryModel: '重试模型',
745
851
  model: { hint: '选择用于改写的模型', default: '默认模型', follow: '跟随默认', loading: '加载模型列表…', failed: '模型列表不可用', empty: '没有可用模型', retry: '重试', switched: '已切换模型,点“开始优化”用新模型改写。' },
746
- diff: { original: '原文', enhanced: '增强后' },
852
+ diff: {
853
+ original: '原文',
854
+ enhanced: '增强后',
855
+ legend: '差异图例',
856
+ 'legend.add': '新增',
857
+ 'legend.del': '删除',
858
+ 'legend.equal': '未变',
859
+ },
860
+ context: {
861
+ title: '读取的工作区上下文',
862
+ file: '{path} · {lines} 行 · {tokens} tokens',
863
+ total: '共 {files} 个文件 · {lines} 行 · {tokens} tokens',
864
+ workspace: '工作区:{root}',
865
+ source: { live: '当前会话', persisted: '历史会话' },
866
+ truncated: '已达上限,清单为部分结果',
867
+ skippedFiles: '跳过 {count} 个文件(越界、非文本或过大)',
868
+ empty: '草稿中没有可匹配的文件',
869
+ skip: {
870
+ noSession: '未找到会话,未读取上下文',
871
+ noWorkspace: '会话没有工作区,未读取上下文',
872
+ searchFailed: '文件搜索失败,未读取上下文',
873
+ readFailed: '文件读取失败,未读取上下文',
874
+ budgetExhausted: '上下文预算不足,未纳入文件',
875
+ },
876
+ error: {
877
+ awarenessDenied: '上下文访问被拒绝,已按无上下文继续',
878
+ awarenessFailed: '上下文读取异常,已按无上下文继续',
879
+ },
880
+ },
881
+ hover: { position: '≈ {file}:{line}(附近 ±3 行)' },
747
882
  confirm: { meta: '尚未调用模型', hint: '点“开始优化”才会调用模型改写;取消不会产生消耗。' },
748
- command: { note: '草稿开头有命令或引用:只优化它们后面的正文,前缀原样保留。' },
883
+ command: { label: '命令', note: '草稿开头有命令或引用:只优化它们后面的正文,前缀原样保留。' },
749
884
  action: { apply: '应用修改', regenerate: '重新生成', cancel: '取消', start: '开始优化', stop: '停止', close: '关闭' },
750
885
  applied: '已应用',
751
886
  undo: '撤销',
@@ -783,24 +918,70 @@ window.__ModuleLoader__.load({
783
918
  modeModel: '仅模型',
784
919
  modeRules: '仅规则',
785
920
  timeoutLabel: '请求超时',
921
+ context: {
922
+ title: '工作区上下文',
923
+ enabledLabel: '读取工作区上下文',
924
+ enabledHint: '只读当前会话工作区的文件(不写入、不改动);读取清单会随结果展示,便于审计。',
925
+ filesLabel: '最多文件数',
926
+ files3: '3 个文件',
927
+ files5: '5 个文件',
928
+ files8: '8 个文件',
929
+ linesLabel: '每文件行数',
930
+ lines40: '40 行',
931
+ lines80: '80 行',
932
+ lines160: '160 行',
933
+ tokensLabel: '总 token 上限',
934
+ tokens400: '400 tokens',
935
+ tokens800: '800 tokens',
936
+ tokens1200: '1200 tokens',
937
+ },
786
938
  debugLabel: '显示调试信息',
787
939
  debugHint: '在结果下方显示通道、耗时与调用链,排查问题时用。',
788
940
  reset: '恢复默认',
789
- resetHint: '字号、语言、增强方式、超时与调试开关一起复位。',
941
+ resetHint: '字号、语言、增强方式、超时、调试开关与工作区上下文参数一起复位。',
790
942
  },
791
943
  }
792
944
 
793
945
  const EN_NESTED = {
794
946
  trigger: { label: 'Improve prompt', tip: { empty: 'Type something first', busy: 'Sending — try again in a moment', chips: 'Draft has reference chips that a rewrite would drop' } },
795
947
  panel: {
796
- title: 'Prompt improve',
948
+ title: 'Improve prompt',
797
949
  channel: { rules: 'Local rules', model: 'Model' },
798
950
  status: { loading: 'Improving…' },
799
951
  retryModel: 'Retry with model',
800
952
  model: { hint: 'Model used for rewriting', default: 'Default model', follow: 'Follow default', loading: 'Loading models…', failed: 'Model list unavailable', empty: 'No models available', retry: 'Retry', switched: 'Model switched; click Start to rewrite with it.' },
801
- diff: { original: 'Original', enhanced: 'Improved' },
953
+ diff: {
954
+ original: 'Original',
955
+ enhanced: 'Improved',
956
+ legend: 'Diff legend',
957
+ 'legend.add': 'Added',
958
+ 'legend.del': 'Removed',
959
+ 'legend.equal': 'Unchanged',
960
+ },
961
+ context: {
962
+ title: 'Workspace context',
963
+ file: '{path} · {lines} lines · {tokens} tokens',
964
+ total: '{files} files · {lines} lines · {tokens} tokens',
965
+ workspace: 'Workspace: {root}',
966
+ source: { live: 'Live session', persisted: 'Stored session' },
967
+ truncated: 'Limit reached; the list is partial',
968
+ skippedFiles: '{count} file(s) skipped (outside workspace, binary, or too large)',
969
+ empty: 'No files matched the draft',
970
+ skip: {
971
+ noSession: 'No session found; context was not read',
972
+ noWorkspace: 'The session has no workspace; context was not read',
973
+ searchFailed: 'File search failed; context was not read',
974
+ readFailed: 'File read failed; context was not read',
975
+ budgetExhausted: 'Context budget too small; no files included',
976
+ },
977
+ error: {
978
+ awarenessDenied: 'Context access was denied; continuing without context',
979
+ awarenessFailed: 'Context reading failed; continuing without context',
980
+ },
981
+ },
982
+ hover: { position: '≈ {file}:{line} (±3 lines)' },
802
983
  confirm: { meta: 'Model not called yet', hint: 'The model only runs after you click Start; cancelling costs nothing.' },
803
- command: { note: 'The draft starts with a command or reference: only the text after it is rewritten, the prefix stays as is.' },
984
+ command: { label: 'Command', note: 'The draft starts with a command or reference: only the text after it is rewritten, the prefix stays as is.' },
804
985
  action: { apply: 'Apply', regenerate: 'Regenerate', cancel: 'Cancel', start: 'Start', stop: 'Stop', close: 'Close' },
805
986
  applied: 'Applied',
806
987
  undo: 'Undo',
@@ -838,10 +1019,27 @@ window.__ModuleLoader__.load({
838
1019
  modeModel: 'Model only',
839
1020
  modeRules: 'Rules only',
840
1021
  timeoutLabel: 'Request timeout',
1022
+ context: {
1023
+ title: 'Workspace context',
1024
+ enabledLabel: 'Read workspace context',
1025
+ enabledHint: "Read-only: reads files from the current session's workspace (nothing is written or modified); the read list is shown with the result for auditing.",
1026
+ filesLabel: 'Max files',
1027
+ files3: '3 files',
1028
+ files5: '5 files',
1029
+ files8: '8 files',
1030
+ linesLabel: 'Lines per file',
1031
+ lines40: '40 lines',
1032
+ lines80: '80 lines',
1033
+ lines160: '160 lines',
1034
+ tokensLabel: 'Total token budget',
1035
+ tokens400: '400 tokens',
1036
+ tokens800: '800 tokens',
1037
+ tokens1200: '1200 tokens',
1038
+ },
841
1039
  debugLabel: 'Show diagnostics',
842
1040
  debugHint: 'Print the channel, timing, and call trace under the result.',
843
1041
  reset: 'Reset to defaults',
844
- resetHint: 'Resets font size, language, enhancement mode, timeout, and diagnostics.',
1042
+ resetHint: 'Resets font size, language, enhancement mode, timeout, diagnostics, and workspace-context settings.',
845
1043
  },
846
1044
  }
847
1045
 
@@ -1004,6 +1202,40 @@ window.__ModuleLoader__.load({
1004
1202
  .pe-error { color: var(--dsw-alias-state-error-primary); }
1005
1203
  .pe-muted { color: var(--dsw-alias-label-tertiary); font-size: calc(12px * var(--pe-scale)); }
1006
1204
  .pe-applied { color: var(--dsw-alias-state-success-primary); }
1205
+ .pe-context { display: flex; flex-direction: column; gap: 2px; padding: 6px 8px;
1206
+ border: 0.5px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-md);
1207
+ background: var(--dsw-alias-bg-layer-1); }
1208
+ .pe-context-head { display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
1209
+ color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); line-height: 16px; font-weight: 500; }
1210
+ .pe-context-workspace { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%;
1211
+ color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); }
1212
+ .pe-context-list { display: flex; flex-direction: column; gap: 1px; }
1213
+ .pe-context-row { color: var(--dsw-alias-label-secondary); font-size: calc(12px * var(--pe-scale));
1214
+ line-height: 18px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
1215
+ .pe-context-total { color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); line-height: 16px; }
1216
+ .pe-context-note { color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); line-height: 16px; }
1217
+ .pe-context-note.pe-context-warn { color: var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary)); }
1218
+
1219
+ .pe-command { display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
1220
+ color: var(--dsw-alias-label-secondary); font-size: calc(12px * var(--pe-scale)); line-height: 18px; }
1221
+ .pe-command-name { color: var(--dsw-alias-label-primary); font-weight: 500; }
1222
+
1223
+ .pe-diff { white-space: pre-wrap; overflow-wrap: anywhere; }
1224
+ .pe-diff-hunk { display: inline; }
1225
+ .pe-diff-add { background: var(--dsw-alias-interactive-bg-hover);
1226
+ background: color-mix(in srgb, var(--dsw-alias-state-success-primary) 18%, transparent);
1227
+ border-radius: 2px; }
1228
+ .pe-diff-del { text-decoration: line-through; opacity: .65; }
1229
+ .pe-diff-cjk { letter-spacing: 0; }
1230
+ .pe-diff-legend { display: flex; align-items: center; gap: 8px; margin-top: 4px;
1231
+ color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); line-height: 16px; }
1232
+ .pe-diff-legend-item { display: inline-flex; align-items: center; gap: 3px; }
1233
+ .pe-diff-legend-swatch { display: inline-block; width: 8px; height: 8px; border-radius: 2px; }
1234
+ .pe-diff-legend-swatch[data-kind='add'] { background: var(--dsw-alias-state-success-primary); opacity: .45; }
1235
+ .pe-diff-legend-swatch[data-kind='del'] { background: var(--dsw-alias-label-tertiary); opacity: .45; }
1236
+
1237
+ .pe-sym { cursor: help; }
1238
+ .pe-sym-repeat { text-decoration: underline; text-decoration-style: dotted; text-underline-offset: 2px; }
1007
1239
  `
1008
1240
 
1009
1241
  // ---------------------------------------------------------------- 组件
@@ -1024,7 +1256,7 @@ window.__ModuleLoader__.load({
1024
1256
  }
1025
1257
 
1026
1258
  function EnhanceTrigger(props) {
1027
- const { t, useInput, inputActions } = props
1259
+ const { t, useInput, inputActions, sessionId } = props
1028
1260
  // 语言设置变化 / DSH 切换语言时,芯片文案要跟着重渲染。
1029
1261
  useSettings()
1030
1262
  useLocaleClock()
@@ -1033,13 +1265,14 @@ window.__ModuleLoader__.load({
1033
1265
  const rev = useInput((s) => s.draftRev)
1034
1266
  const occurrences = useInput((s) => s.occurrences)
1035
1267
  const claimToken = useInput((s) => (s.claim && s.claim.token) || '')
1268
+ const claimName = useInput((s) => (s.claim && s.claim.name) || '')
1036
1269
  const [open, setOpen] = React.useState(false)
1037
1270
  const [wasOpen, setWasOpen] = React.useState(false)
1038
1271
  const btnRef = React.useRef(null)
1039
1272
 
1040
1273
  // 命令模式:草稿以 `/goal`、`/plan` 等命令芯片开头时,DSH 会把 phase 置为 claimed;
1041
- // 这里只优化命令后面的正文,写回时保留命令芯片。
1042
- const view = analyzeDraft({ draft, phase, claimToken, occurrences })
1274
+ // 这里只优化命令后面的正文,写回时保留命令芯片。命令名只从 claim.name 解析。
1275
+ const view = analyzeDraft({ draft, phase, claimToken, claimName, occurrences })
1043
1276
  const disabledReason = view.kind === 'command' || view.kind === 'plain'
1044
1277
  ? ''
1045
1278
  : view.reason === 'empty'
@@ -1070,7 +1303,7 @@ window.__ModuleLoader__.load({
1070
1303
  h('span', { className: 'pe-label' }, t('trigger.label')),
1071
1304
  ),
1072
1305
  open ? h(EnhancePopover, {
1073
- t, useInput, inputActions, draft, rev, phase, occurrences, claimToken, anchorRef: btnRef, onClose: () => setOpen(false),
1306
+ t, useInput, inputActions, draft, rev, phase, occurrences, claimToken, claimName, sessionId, anchorRef: btnRef, onClose: () => setOpen(false),
1074
1307
  }) : null,
1075
1308
  )
1076
1309
  }
@@ -1122,7 +1355,7 @@ window.__ModuleLoader__.load({
1122
1355
  }
1123
1356
 
1124
1357
  function EnhancePopover(props) {
1125
- const { t, useInput, inputActions, draft, rev, phase, occurrences, claimToken, anchorRef, onClose } = props
1358
+ const { t, useInput, inputActions, draft, rev, phase, occurrences, claimToken, claimName, sessionId, anchorRef, onClose } = props
1126
1359
  const ref = React.useRef(null)
1127
1360
  const style = useAnchoredStyle(anchorRef, ref, true)
1128
1361
  // 外观:主题切换时浮层重渲染,把 color-scheme 同步给原生滚动条/控件。
@@ -1163,14 +1396,14 @@ window.__ModuleLoader__.load({
1163
1396
  }
1164
1397
  },
1165
1398
  },
1166
- h(EnhancePanel, { t, useInput, inputActions, draft, rev, phase, occurrences, claimToken, onClose }),
1399
+ h(EnhancePanel, { t, useInput, inputActions, draft, rev, phase, occurrences, claimToken, claimName, sessionId, onClose }),
1167
1400
  ),
1168
1401
  document.body,
1169
1402
  )
1170
1403
  }
1171
1404
 
1172
1405
  function EnhancePanel(props) {
1173
- const { t, inputActions, draft, rev, phase, occurrences, claimToken, onClose } = props
1406
+ const { t, inputActions, draft, rev, phase, occurrences, claimToken, claimName, sessionId, onClose } = props
1174
1407
  const conf = useSettings()
1175
1408
  const [view, setView] = React.useState('enhance')
1176
1409
  const [state, setState] = React.useState({ kind: 'confirm' })
@@ -1186,9 +1419,16 @@ window.__ModuleLoader__.load({
1186
1419
  const [switched, setSwitched] = React.useState(false)
1187
1420
  const abortRef = React.useRef(null)
1188
1421
  // 草稿形态:普通文本 / 命令前缀 + 正文。打开面板与"重新生成"各取一次快照。
1189
- const draftView = analyzeDraft({ draft, phase, claimToken, occurrences })
1190
- const snapRef = React.useRef({ text: draft, rev, view: draftView })
1422
+ const draftView = analyzeDraft({ draft, phase, claimToken, claimName, occurrences })
1423
+ const snapRef = React.useRef({ text: draft, rev, view: draftView, sessionId })
1191
1424
  const appliedRef = React.useRef(null)
1425
+ // 工作区感知参数:一次构造,随每次模型请求发送;关闭时不带 sessionId。
1426
+ const awareness = {
1427
+ enabled: conf.awareness === 'on',
1428
+ maxFiles: conf.contextFiles,
1429
+ maxLinesPerFile: conf.contextLines,
1430
+ maxTokens: conf.contextTokens,
1431
+ }
1192
1432
 
1193
1433
  /** 写回:命令模式只替换正文区间(保留命令芯片),普通模式整段替换。 */
1194
1434
  const writeBack = (target, snap, draftRev) => {
@@ -1225,6 +1465,10 @@ window.__ModuleLoader__.load({
1225
1465
  selection: choice,
1226
1466
  timeoutMs: conf.timeoutSec * 1000,
1227
1467
  signal: ctrl.signal,
1468
+ // 关闭工作区感知时不发送 sessionId(也不发空串)。
1469
+ sessionId: awareness.enabled ? snapRef.current.sessionId : undefined,
1470
+ awareness,
1471
+ commandName: snapRef.current.view.commandName,
1228
1472
  onPartial: accept,
1229
1473
  }).then(accept).catch((err) => {
1230
1474
  trace('panel:catch:' + ((err && err.code) || 'generic'))
@@ -1366,7 +1610,7 @@ window.__ModuleLoader__.load({
1366
1610
 
1367
1611
  const regenerate = () => {
1368
1612
  appliedRef.current = null
1369
- snapRef.current = { text: draft, rev, view: draftView }
1613
+ snapRef.current = { text: draft, rev, view: draftView, sessionId }
1370
1614
  setState({ kind: 'loading' })
1371
1615
  setGen((n) => n + 1)
1372
1616
  }
@@ -1447,7 +1691,16 @@ window.__ModuleLoader__.load({
1447
1691
  ? h('div', { className: 'pe-muted', style: { fontSize: 12 } }, t('panel.command.note'))
1448
1692
  : null,
1449
1693
  state.kind === 'preview' || state.kind === 'conflict'
1450
- ? h(Diff, { t, before: snapRef.current.text, after: compose(snapRef.current, state.res.text) })
1694
+ ? h(Diff, {
1695
+ t,
1696
+ before: snapRef.current.view.body,
1697
+ after: state.res.text,
1698
+ symbols: state.res.symbols || [],
1699
+ })
1700
+ : null,
1701
+ // 审计清单放在 diff 之后:先看改了什么,再看读了哪些文件。
1702
+ (state.kind === 'preview' || state.kind === 'conflict') && (state.res.context || state.res.command)
1703
+ ? h(ContextList, { t, context: state.res.context, command: state.res.command })
1451
1704
  : null,
1452
1705
  state.kind === 'loading' ? h('div', { className: 'pe-muted' }, t('panel.status.loading')) : null,
1453
1706
  state.kind === 'error' && state.detail
@@ -1545,6 +1798,22 @@ window.__ModuleLoader__.load({
1545
1798
  { value: 'zh', label: 'CN' },
1546
1799
  { value: 'en', label: 'EN' },
1547
1800
  ]
1801
+ // 工作区上下文三档预算;键名与契约 §5 固定,值由 normalizeSettings 白名单校验。
1802
+ const CONTEXT_FILE_OPTIONS = [
1803
+ { value: 3, labelKey: 'settings.context.files3' },
1804
+ { value: 5, labelKey: 'settings.context.files5' },
1805
+ { value: 8, labelKey: 'settings.context.files8' },
1806
+ ]
1807
+ const CONTEXT_LINE_OPTIONS = [
1808
+ { value: 40, labelKey: 'settings.context.lines40' },
1809
+ { value: 80, labelKey: 'settings.context.lines80' },
1810
+ { value: 160, labelKey: 'settings.context.lines160' },
1811
+ ]
1812
+ const CONTEXT_TOKEN_OPTIONS = [
1813
+ { value: 400, labelKey: 'settings.context.tokens400' },
1814
+ { value: 800, labelKey: 'settings.context.tokens800' },
1815
+ { value: 1200, labelKey: 'settings.context.tokens1200' },
1816
+ ]
1548
1817
 
1549
1818
  function SettingsView({ t, backable, onBack }) {
1550
1819
  const conf = useSettings()
@@ -1611,6 +1880,45 @@ window.__ModuleLoader__.load({
1611
1880
  onChange: (e) => updateSettings({ debug: Boolean(e.target.checked) }),
1612
1881
  }),
1613
1882
  }),
1883
+ h('div', { className: 'pe-section' }, t('settings.context.title')),
1884
+ h(SettingRow, {
1885
+ label: t('settings.context.enabledLabel'),
1886
+ hint: t('settings.context.enabledHint'),
1887
+ control: h('input', {
1888
+ type: 'checkbox',
1889
+ className: 'pe-check',
1890
+ checked: conf.awareness === 'on',
1891
+ onChange: (e) => updateSettings({ awareness: e.target.checked ? 'on' : 'off' }),
1892
+ }),
1893
+ }),
1894
+ conf.awareness === 'on'
1895
+ ? h(React.Fragment, null,
1896
+ h(SettingRow, {
1897
+ label: t('settings.context.filesLabel'),
1898
+ control: h(SettingsSeg, {
1899
+ value: conf.contextFiles,
1900
+ onChange: (value) => updateSettings({ contextFiles: value }),
1901
+ options: localize(CONTEXT_FILE_OPTIONS),
1902
+ }),
1903
+ }),
1904
+ h(SettingRow, {
1905
+ label: t('settings.context.linesLabel'),
1906
+ control: h(SettingsSeg, {
1907
+ value: conf.contextLines,
1908
+ onChange: (value) => updateSettings({ contextLines: value }),
1909
+ options: localize(CONTEXT_LINE_OPTIONS),
1910
+ }),
1911
+ }),
1912
+ h(SettingRow, {
1913
+ label: t('settings.context.tokensLabel'),
1914
+ control: h(SettingsSeg, {
1915
+ value: conf.contextTokens,
1916
+ onChange: (value) => updateSettings({ contextTokens: value }),
1917
+ options: localize(CONTEXT_TOKEN_OPTIONS),
1918
+ }),
1919
+ }),
1920
+ )
1921
+ : null,
1614
1922
  h('div', { className: 'pe-row' },
1615
1923
  h('button', { type: 'button', className: 'pe-btn', onClick: () => resetSettings() }, t('settings.reset')),
1616
1924
  h('span', { className: 'pe-row-hint' }, t('settings.resetHint')),
@@ -1715,12 +2023,340 @@ window.__ModuleLoader__.load({
1715
2023
  )
1716
2024
  }
1717
2025
 
1718
- function Diff({ t, before, after }) {
2026
+ // ---------------------------------------------------------------- 感知附件
2027
+
2028
+ /** 模板占位替换:`{name}` 用 vars[name] 替换;未知占位保留原样。 */
2029
+ function interpolate(template, vars) {
2030
+ const source = String(template == null ? '' : template)
2031
+ return source.replace(/\{(\w+)\}/g, (match, key) => (
2032
+ vars && Object.prototype.hasOwnProperty.call(vars, key) ? String(vars[key]) : match
2033
+ ))
2034
+ }
2035
+
2036
+ /** 悬浮提示的位置文案:`≈ file:line(附近 ±3 行)`。 */
2037
+ function positionLabel(t, symbol) {
2038
+ return interpolate(t('panel.hover.position'), { file: symbol.file, line: symbol.line })
2039
+ }
2040
+
2041
+ function isSymbolChar(ch) {
2042
+ return /^[A-Za-z0-9_$]$/.test(ch)
2043
+ }
2044
+
2045
+ /**
2046
+ * 把文本切成普通文本 / 符号片段(整词匹配,长名优先)。
2047
+ * `seen` 由调用方整块创建,保证同一 symbol 只第一个出现带 title。
2048
+ */
2049
+ function matchSymbols(text, symbols, seen) {
2050
+ const source = String(text == null ? '' : text)
2051
+ const out = []
2052
+ const byName = new Map()
2053
+ for (const symbol of Array.isArray(symbols) ? symbols : []) {
2054
+ if (!symbol || typeof symbol.name !== 'string' || !symbol.name) continue
2055
+ if (symbol.kind !== 'function' && symbol.kind !== 'variable' && symbol.kind !== 'class') continue
2056
+ if (typeof symbol.file !== 'string' || !symbol.file) continue
2057
+ if (!Number.isInteger(symbol.line) || symbol.line < 1) continue
2058
+ if (byName.has(symbol.name)) continue
2059
+ byName.set(symbol.name, { name: symbol.name, kind: symbol.kind, file: symbol.file, line: symbol.line })
2060
+ }
2061
+ // 长名优先,避免 `foo` 抢在 `foobar` 前面;同长度按字典序保证确定性。
2062
+ const candidates = Array.from(byName.values()).sort((a, b) => (
2063
+ b.name.length - a.name.length || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
2064
+ ))
2065
+ let plain = ''
2066
+ const flush = () => {
2067
+ if (plain) {
2068
+ out.push({ text: plain, symbol: null, first: false })
2069
+ plain = ''
2070
+ }
2071
+ }
2072
+ let i = 0
2073
+ while (i < source.length) {
2074
+ if (i > 0 && isSymbolChar(source.charAt(i - 1))) {
2075
+ plain += source.charAt(i)
2076
+ i += 1
2077
+ continue
2078
+ }
2079
+ let hit = null
2080
+ for (const candidate of candidates) {
2081
+ if (!source.startsWith(candidate.name, i)) continue
2082
+ const next = source.charAt(i + candidate.name.length)
2083
+ if (next !== '' && isSymbolChar(next)) continue
2084
+ hit = candidate
2085
+ break
2086
+ }
2087
+ if (hit) {
2088
+ flush()
2089
+ const first = !seen.has(hit.name)
2090
+ seen.add(hit.name)
2091
+ out.push({ text: hit.name, symbol: hit, first })
2092
+ i += hit.name.length
2093
+ } else {
2094
+ plain += source.charAt(i)
2095
+ i += 1
2096
+ }
2097
+ }
2098
+ flush()
2099
+ return out
2100
+ }
2101
+
2102
+ function SymbolText({ text, symbols, seen, labelOf }) {
2103
+ const segments = matchSymbols(text, symbols, seen)
2104
+ return h(React.Fragment, null, segments.map((segment, i) => {
2105
+ if (!segment.symbol) return segment.text
2106
+ const label = segment.first ? labelOf(segment.symbol) : undefined
2107
+ return h('span', {
2108
+ key: 'seg-' + i,
2109
+ className: 'pe-sym' + (segment.first ? '' : ' pe-sym-repeat'),
2110
+ title: label,
2111
+ 'aria-label': label,
2112
+ 'data-pe-symbol': segment.first ? segment.symbol.name : undefined,
2113
+ }, segment.text)
2114
+ }))
2115
+ }
2116
+
2117
+ const CJK_RE = /[\u2E80-\u9FFF\uF900-\uFAFF\uFF00-\uFFEF]/
2118
+ const DIFF_TOKEN_LIMIT = 400
2119
+
2120
+ /** 按 code point 切 token:连续空白 / CJK 单字 / 标识符 / 其它单字符。 */
2121
+ function diffTokenize(text) {
2122
+ const chars = Array.from(String(text == null ? '' : text))
2123
+ const tokens = []
2124
+ let i = 0
2125
+ while (i < chars.length) {
2126
+ const ch = chars[i]
2127
+ if (/\s/.test(ch)) {
2128
+ let j = i + 1
2129
+ while (j < chars.length && /\s/.test(chars[j])) j += 1
2130
+ tokens.push({ kind: 'space', text: chars.slice(i, j).join('') })
2131
+ i = j
2132
+ continue
2133
+ }
2134
+ if (CJK_RE.test(ch)) {
2135
+ tokens.push({ kind: 'cjk', text: ch })
2136
+ i += 1
2137
+ continue
2138
+ }
2139
+ if (/[A-Za-z0-9_$]/.test(ch)) {
2140
+ let j = i + 1
2141
+ while (j < chars.length && /[A-Za-z0-9_$]/.test(chars[j])) j += 1
2142
+ tokens.push({ kind: 'ident', text: chars.slice(i, j).join('') })
2143
+ i = j
2144
+ continue
2145
+ }
2146
+ tokens.push({ kind: 'punct', text: ch })
2147
+ i += 1
2148
+ }
2149
+ return tokens
2150
+ }
2151
+
2152
+ function diffLines(text) {
2153
+ return String(text == null ? '' : text).split('\n').map((line) => ({ kind: 'line', text: line }))
2154
+ }
2155
+
2156
+ function withChinese(hunk) {
2157
+ return CJK_RE.test(hunk.text) ? { ...hunk, chinese: true } : hunk
2158
+ }
2159
+
2160
+ /** LCS + 回溯(平局优先 del);相邻同类型 hunk 合并。 */
2161
+ function diffHunks(a, b, lineMode) {
2162
+ const n = a.length
2163
+ const m = b.length
2164
+ let start = 0
2165
+ let endA = n
2166
+ let endB = m
2167
+ // 行级降级 + 超长文本时先裁公共前后缀,避免 DP 的内存失控。
2168
+ if ((n + 1) * (m + 1) > 20000000) {
2169
+ while (start < endA && start < endB && a[start].text === b[start].text) start += 1
2170
+ while (endA > start && endB > start && a[endA - 1].text === b[endB - 1].text) {
2171
+ endA -= 1
2172
+ endB -= 1
2173
+ }
2174
+ }
2175
+ const rows = endA - start
2176
+ const cols = endB - start
2177
+ const hunks = []
2178
+ const push = (type, text) => {
2179
+ const last = hunks[hunks.length - 1]
2180
+ if (last && last.type === type) {
2181
+ last.text = lineMode
2182
+ ? (last.text === '' ? text : last.text + '\n' + text)
2183
+ : last.text + text
2184
+ } else {
2185
+ hunks.push({ type, text })
2186
+ }
2187
+ }
2188
+ const join = (tokens) => tokens.map((token) => token.text).join(lineMode ? '\n' : '')
2189
+ // 仍然过大(整篇重写):退化为「整段删除 + 整段新增」,避免 LCS 表撑爆内存。
2190
+ if ((rows + 1) * (cols + 1) > 20000000) {
2191
+ if (start > 0) push('equal', join(a.slice(0, start)))
2192
+ if (rows > 0) push('del', join(a.slice(start, endA)))
2193
+ if (cols > 0) push('add', join(b.slice(start, endB)))
2194
+ if (endA < n) push('equal', join(a.slice(endA)))
2195
+ return hunks
2196
+ }
2197
+ const dp = new Array(rows + 1)
2198
+ for (let i = rows; i >= 0; i -= 1) {
2199
+ const row = new Int32Array(cols + 1)
2200
+ dp[i] = row
2201
+ for (let j = cols; j >= 0; j -= 1) {
2202
+ if (i === rows || j === cols) continue
2203
+ row[j] = a[start + i].text === b[start + j].text
2204
+ ? dp[i + 1][j + 1] + 1
2205
+ : Math.max(dp[i + 1][j], row[j + 1])
2206
+ }
2207
+ }
2208
+ if (start > 0) push('equal', join(a.slice(0, start)))
2209
+ let i = 0
2210
+ let j = 0
2211
+ while (i < rows || j < cols) {
2212
+ if (i < rows && j < cols && a[start + i].text === b[start + j].text) {
2213
+ push('equal', a[start + i].text)
2214
+ i += 1
2215
+ j += 1
2216
+ } else if (i < rows && (j >= cols || dp[i + 1][j] >= dp[i][j + 1])) {
2217
+ push('del', a[start + i].text)
2218
+ i += 1
2219
+ } else {
2220
+ push('add', b[start + j].text)
2221
+ j += 1
2222
+ }
2223
+ }
2224
+ if (endA < n) push('equal', join(a.slice(endA)))
2225
+ return hunks
2226
+ }
2227
+
2228
+ /**
2229
+ * 语义 diff:token 级 LCS(>400 token 降级为行级)。
2230
+ * token 模式折叠空白;折叠后为空的 hunk 丢弃。
2231
+ */
2232
+ function computeSemanticDiff(before, after) {
2233
+ const beforeTokens = diffTokenize(before)
2234
+ const afterTokens = diffTokenize(after)
2235
+ const lineMode = beforeTokens.length > DIFF_TOKEN_LIMIT || afterTokens.length > DIFF_TOKEN_LIMIT
2236
+ const raw = diffHunks(
2237
+ lineMode ? diffLines(before) : beforeTokens,
2238
+ lineMode ? diffLines(after) : afterTokens,
2239
+ lineMode,
2240
+ )
2241
+ const hunks = []
2242
+ for (const hunk of raw) {
2243
+ if (lineMode) {
2244
+ hunks.push(withChinese({ type: hunk.type, text: hunk.text }))
2245
+ continue
2246
+ }
2247
+ const text = hunk.text.replace(/[ \t]+/g, ' ').replace(/\n{2,}/g, '\n')
2248
+ if (text === '') continue
2249
+ hunks.push(withChinese({ type: hunk.type, text }))
2250
+ }
2251
+ return { mode: lineMode ? 'line' : 'token', hunks }
2252
+ }
2253
+
2254
+ const CONTEXT_SKIP_KEYS = {
2255
+ 'no-session': 'panel.context.skip.noSession',
2256
+ 'no-workspace': 'panel.context.skip.noWorkspace',
2257
+ 'search-failed': 'panel.context.skip.searchFailed',
2258
+ 'read-failed': 'panel.context.skip.readFailed',
2259
+ 'budget-exhausted': 'panel.context.skip.budgetExhausted',
2260
+ }
2261
+ const CONTEXT_ERROR_KEYS = {
2262
+ awareness_denied: 'panel.context.error.awarenessDenied',
2263
+ awareness_failed: 'panel.context.error.awarenessFailed',
2264
+ }
2265
+
2266
+ /**
2267
+ * 审计清单:命令描述 + 读取的工作区文件,全部通过模板替换渲染。
2268
+ * 只读展示,不提供任何写操作。
2269
+ */
2270
+ function ContextList({ t, context, command }) {
2271
+ if (!context && !command) return null
2272
+ const rows = []
2273
+ if (command) {
2274
+ rows.push(h('div', { key: 'command', className: 'pe-command' },
2275
+ h('span', null, t('panel.command.label')),
2276
+ h('span', { className: 'pe-command-name' }, command.name),
2277
+ h('span', { className: 'pe-context-note' }, command.description),
2278
+ ))
2279
+ }
2280
+ if (context) {
2281
+ const sourceKey = context.source === 'live'
2282
+ ? 'panel.context.source.live'
2283
+ : context.source === 'persisted'
2284
+ ? 'panel.context.source.persisted'
2285
+ : ''
2286
+ rows.push(h('div', { key: 'head', className: 'pe-context-head' },
2287
+ t('panel.context.title'),
2288
+ sourceKey ? h('span', null, t(sourceKey)) : null,
2289
+ ))
2290
+ if (context.workspaceRoot) {
2291
+ rows.push(h('div', { key: 'workspace', className: 'pe-context-workspace' },
2292
+ interpolate(t('panel.context.workspace'), { root: context.workspaceRoot })))
2293
+ }
2294
+ if (context.enabled && context.files.length > 0) {
2295
+ rows.push(h('div', { key: 'files', className: 'pe-context-list' },
2296
+ context.files.map((file) => h('div', { key: file.path, className: 'pe-context-row' },
2297
+ interpolate(t('panel.context.file'), { path: file.path, lines: file.lines, tokens: file.tokens }))),
2298
+ ))
2299
+ rows.push(h('div', { key: 'total', className: 'pe-context-total' },
2300
+ interpolate(t('panel.context.total'), {
2301
+ files: context.totalFiles,
2302
+ lines: context.totalLines,
2303
+ tokens: context.totalTokens,
2304
+ })))
2305
+ }
2306
+ if (context.truncated === true) {
2307
+ rows.push(h('div', { key: 'truncated', className: 'pe-context-note' }, t('panel.context.truncated')))
2308
+ }
2309
+ if (context.skippedFiles > 0) {
2310
+ rows.push(h('div', { key: 'skipped-files', className: 'pe-context-note' },
2311
+ interpolate(t('panel.context.skippedFiles'), { count: context.skippedFiles })))
2312
+ }
2313
+ if (!context.enabled && !context.skipped && !context.error && context.files.length === 0) {
2314
+ rows.push(h('div', { key: 'empty', className: 'pe-context-note' }, t('panel.context.empty')))
2315
+ }
2316
+ const skipKey = context.skipped && CONTEXT_SKIP_KEYS[context.skipped]
2317
+ if (skipKey) {
2318
+ rows.push(h('div', { key: 'skipped', className: 'pe-context-note' }, t(skipKey)))
2319
+ }
2320
+ const errorKey = context.error && CONTEXT_ERROR_KEYS[context.error.code]
2321
+ if (errorKey) {
2322
+ rows.push(h('div', { key: 'error', className: 'pe-context-note pe-context-warn' }, t(errorKey)))
2323
+ }
2324
+ }
2325
+ return h('div', { className: 'pe-context' }, rows)
2326
+ }
2327
+
2328
+ function DiffLegend({ t }) {
2329
+ const item = (kind, key) => h('span', { className: 'pe-diff-legend-item' },
2330
+ h('span', { className: 'pe-diff-legend-swatch', 'data-kind': kind }),
2331
+ t(key),
2332
+ )
2333
+ return h('div', { className: 'pe-diff-legend', 'aria-label': t('panel.diff.legend') },
2334
+ item('add', 'panel.diff.legend.add'),
2335
+ item('del', 'panel.diff.legend.del'),
2336
+ item('equal', 'panel.diff.legend.equal'),
2337
+ )
2338
+ }
2339
+
2340
+ function SemanticDiff({ before, after, symbols, labelOf }) {
2341
+ const { hunks } = computeSemanticDiff(before, after)
2342
+ // 整块只建一次 seen:同一 symbol 跨 hunk 只保留第一个 title。
2343
+ const seen = new Set()
2344
+ return h('span', { className: 'pe-diff' },
2345
+ hunks.map((hunk, i) => h('span', {
2346
+ key: 'hunk-' + i,
2347
+ className: 'pe-diff-hunk pe-diff-' + hunk.type + (hunk.chinese ? ' pe-diff-cjk' : ''),
2348
+ }, hunk.type === 'del' ? hunk.text : h(SymbolText, { text: hunk.text, symbols, seen, labelOf }))),
2349
+ )
2350
+ }
2351
+
2352
+ function Diff({ t, before, after, symbols }) {
2353
+ const labelOf = (symbol) => positionLabel(t, symbol)
1719
2354
  return h('div', null,
1720
2355
  h('div', { className: 'pe-diff-label' }, t('panel.diff.original')),
1721
2356
  h('div', { className: 'pe-block pe-block-original' }, before),
1722
2357
  h('div', { className: 'pe-diff-label', style: { marginTop: 8 } }, t('panel.diff.enhanced')),
1723
- h('div', { className: 'pe-block pe-block-enhanced' }, after),
2358
+ h('div', { className: 'pe-block pe-block-enhanced' }, h(SemanticDiff, { before, after, symbols, labelOf })),
2359
+ h(DiffLegend, { t }),
1724
2360
  )
1725
2361
  }
1726
2362
 
@@ -1850,7 +2486,7 @@ window.__ModuleLoader__.load({
1850
2486
  )
1851
2487
  },
1852
2488
  // 仅用于本地单测(加载器只读取 inject/apply,未知字段被忽略)
1853
- __test__: { RULES, enhanceWithRules, analyzeDraft, planWrite, bodyOf, cleanModelText, probe, enhance, fetchModels, readStoredModel, storeModel, readSettings, updateSettings, resetSettings, normalizeSettings, makeT, currentLocale, detectedLanguage, activeLanguage, promptLocale, publishLocaleChange, ZH, EN },
2489
+ __test__: { RULES, enhanceWithRules, analyzeDraft, planWrite, bodyOf, cleanModelText, probe, enhance, fetchModels, readStoredModel, storeModel, readSettings, updateSettings, resetSettings, normalizeSettings, makeT, currentLocale, detectedLanguage, activeLanguage, promptLocale, publishLocaleChange, ZH, EN, buildEnhanceBody, normalizeModelResult, normalizeCommandName, computeSemanticDiff, matchSymbols, positionLabel, interpolate, SemanticDiff, ContextList, SymbolText, Diff },
1854
2490
  }
1855
2491
  },
1856
2492
  })