@sparkelf/dsh-genui 0.11.4-patch.2 → 0.13.0-sparkelf.2

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.
Files changed (111) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/ICON-NAMES.md +30 -0
  3. package/README.md +26 -28
  4. package/README.zh-CN.md +26 -28
  5. package/SKILL.md +128 -19
  6. package/THIRD_PARTY_NOTICES.md +42 -0
  7. package/assets/genui-icon.svg +20 -0
  8. package/assets/genui-logo.svg +18 -0
  9. package/lib/assets/icons.js +1 -0
  10. package/lib/assets/mermaid.js +325 -325
  11. package/lib/assets/standalone-runtime.js +10 -9
  12. package/lib/client.js +32 -31
  13. package/lib/index.js +489 -80
  14. package/lib/types/client/action-context.d.ts +1 -1
  15. package/lib/types/client/artifact/types.d.ts +1 -1
  16. package/lib/types/client/asset-loader.d.ts +2 -2
  17. package/lib/types/client/blocks/blocks.d.ts +12 -0
  18. package/lib/types/client/blocks/icon.d.ts +4 -0
  19. package/lib/types/client/dom-fence.d.ts +2 -1
  20. package/lib/types/client/fence-render.d.ts +5 -21
  21. package/lib/types/client/file-address.d.ts +4 -0
  22. package/lib/types/client/file-link-context.d.ts +49 -0
  23. package/lib/types/client/file-link.d.ts +17 -0
  24. package/lib/types/client/gallery.d.ts +8 -2
  25. package/lib/types/client/genui-runtime/diagnostics.d.ts +1 -1
  26. package/lib/types/client/genui-runtime/limits.d.ts +4 -0
  27. package/lib/types/client/genui-runtime/schema.d.ts +14 -1
  28. package/lib/types/client/guard.d.ts +4 -1
  29. package/lib/types/client/i18n/en.d.ts +5 -1
  30. package/lib/types/client/i18n/index.d.ts +1 -1
  31. package/lib/types/client/icons/asset-icons.d.ts +1 -0
  32. package/lib/types/client/icons/icon-data-full.d.ts +23 -0
  33. package/lib/types/client/icons/icon-data.d.ts +24 -0
  34. package/lib/types/client/icons/icon-lazy.d.ts +18 -0
  35. package/lib/types/client/icons/icon-names-full.d.ts +12 -0
  36. package/lib/types/client/index.d.ts +5 -15
  37. package/lib/types/client/inline.d.ts +1 -1
  38. package/lib/types/client/mermaid-colors.d.ts +2 -0
  39. package/lib/types/client/mermaid-core.d.ts +2 -1
  40. package/lib/types/client/mermaid-lazy.d.ts +5 -1
  41. package/lib/types/client/panel-command.d.ts +21 -1
  42. package/lib/types/client/panel.d.ts +6 -1
  43. package/lib/types/client/primitive-adapter.d.ts +0 -2
  44. package/lib/types/client/session-resolver.d.ts +13 -2
  45. package/lib/types/client/source-fence.d.ts +1 -1
  46. package/lib/types/client/spec.d.ts +107 -3
  47. package/lib/types/client/standalone/asset-loader.d.ts +1 -1
  48. package/lib/types/client/standalone/primitive-adapter.d.ts +0 -4
  49. package/lib/types/plugin/fence-feedback.d.ts +11 -7
  50. package/lib/types/plugin/index.d.ts +6 -2
  51. package/lib/types/shared/fence-language.d.ts +14 -0
  52. package/lib/types/shared/fence-repair.d.ts +2 -1
  53. package/lib/types/shared/fence-resolve.d.ts +1 -1
  54. package/package.json +92 -83
  55. package/src/client/EChartNode.tsx +17 -3
  56. package/src/client/GenuiBlock.module.css +411 -76
  57. package/src/client/action-context.ts +5 -15
  58. package/src/client/artifact/ArtifactExport.module.css +34 -3
  59. package/src/client/artifact/ExportableGenuiBlock.tsx +23 -2
  60. package/src/client/artifact/portability.ts +6 -1
  61. package/src/client/artifact/types.ts +1 -1
  62. package/src/client/asset-loader.ts +3 -3
  63. package/src/client/blocks/advanced.tsx +101 -14
  64. package/src/client/blocks/blocks.tsx +143 -0
  65. package/src/client/blocks/charts.tsx +22 -6
  66. package/src/client/blocks/icon.tsx +93 -0
  67. package/src/client/blocks/image.tsx +1 -0
  68. package/src/client/blocks/render-node.tsx +84 -52
  69. package/src/client/dom-fence.tsx +546 -72
  70. package/src/client/fence-render.tsx +5 -21
  71. package/src/client/file-address.ts +37 -0
  72. package/src/client/file-link-context.tsx +116 -0
  73. package/src/client/file-link.ts +46 -0
  74. package/src/client/gallery.ts +161 -133
  75. package/src/client/genui-runtime/diagnostics.ts +1 -1
  76. package/src/client/genui-runtime/limits.ts +4 -0
  77. package/src/client/genui-runtime/normalize.ts +42 -6
  78. package/src/client/genui-runtime/schema.ts +39 -7
  79. package/src/client/guard.ts +170 -15
  80. package/src/client/i18n/en.ts +5 -1
  81. package/src/client/i18n/index.ts +1 -1
  82. package/src/client/i18n/zh.ts +5 -1
  83. package/src/client/icons/asset-icons.ts +16 -0
  84. package/src/client/icons/icon-data-full.ts +5715 -0
  85. package/src/client/icons/icon-data.ts +507 -0
  86. package/src/client/icons/icon-lazy.ts +80 -0
  87. package/src/client/icons/icon-names-full.ts +12 -0
  88. package/src/client/index.tsx +27 -51
  89. package/src/client/inline.ts +17 -6
  90. package/src/client/mermaid-colors.ts +40 -0
  91. package/src/client/mermaid-core.ts +69 -61
  92. package/src/client/mermaid-lazy.ts +99 -4
  93. package/src/client/panel-command.ts +16 -2
  94. package/src/client/panel.tsx +18 -5
  95. package/src/client/primitive-adapter.ts +0 -11
  96. package/src/client/session-resolver.ts +12 -21
  97. package/src/client/source-fence.ts +4 -2
  98. package/src/client/spec.ts +116 -2
  99. package/src/client/standalone/asset-loader.ts +1 -1
  100. package/src/client/standalone/primitive-adapter.tsx +1 -9
  101. package/src/client/table-details.ts +4 -3
  102. package/src/plugin/fence-feedback.ts +60 -14
  103. package/src/plugin/index.ts +45 -20
  104. package/src/plugin/tool.ts +11 -2
  105. package/src/shared/fence-language.ts +30 -0
  106. package/src/shared/fence-repair.ts +37 -1
  107. package/src/shared/fence-resolve.ts +1 -1
  108. package/tsdown.config.ts +7 -8
  109. package/lib/invariant.js +0 -19
  110. package/lib/types/plugin/invariant.d.ts +0 -15
  111. package/src/plugin/invariant.ts +0 -30
@@ -1,5 +1,5 @@
1
1
  /**
2
- * DOM render channel: pure-plugin fence rendering for pristine hosts.
2
+ * DOM render channel: plugin-owned rendering of DSH conversation fences.
3
3
  *
4
4
  * Stock DSH renders every fenced code block through the shared CodeBlock
5
5
  * surface (stable class `md-code-block`, language label rendered as the
@@ -30,7 +30,7 @@
30
30
  * 1s sweep is the backstop.
31
31
  * - **Settled transition**: when `[data-streaming]` leaves the row, the
32
32
  * mount re-renders with the stable source identity — the moment panels
33
- * publish and durable state keys in (mirrors the registry channel's
33
+ * publish and durable state keys in (mirrors inline fence rendering's
34
34
  * settled-source semantics; streaming renders are identity-less).
35
35
  * - **Visible failure**: a settled block that stays a code block (malformed
36
36
  * JSON, guard rejection, chart contract) mounts {@link FenceDiagnostic}
@@ -46,7 +46,7 @@
46
46
  * - Removal (branch switch, unload): each mount is unmounted with its root,
47
47
  * and the stock block is restored.
48
48
  *
49
- * Security posture matches the registry channel: only code shipped in this
49
+ * Security posture: only code shipped in this
50
50
  * plugin's browser bundle mounts React roots, the model can only author
51
51
  * fence text, and unrepairable bodies remain visible in their host form.
52
52
  */
@@ -58,6 +58,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
58
58
  import type { ChatNode, ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client'
59
59
  import type { SessionId } from '@deepseek-ai/dsh-session/types'
60
60
  import { GenuiActionContext, type GenuiActionHandler } from './action-context.ts'
61
+ import { withFileLinkContext, type FileLinkAvailability, type FileLinkCordisContext } from './file-link-context.tsx'
61
62
  import css from './GenuiBlock.module.css'
62
63
  import { renderSvgFence } from './svg-fence.tsx'
63
64
  import { repairFenceJson, trimToBalancedRoot } from '../shared/fence-repair.ts'
@@ -67,14 +68,44 @@ import { validateCanonicalGenuiSpec } from './guard.ts'
67
68
  import { diagnoseUnknownGenuiFields } from './genui-runtime/diagnostics.ts'
68
69
  import { normalizeGenuiSpec } from './genui-runtime/normalize.ts'
69
70
  import { sourceFencesOfAssistant, sourceLanguageAt } from './source-fence.ts'
71
+ import { normalizeFenceLanguage } from '../shared/fence-language.ts'
70
72
 
71
- /** Fence surfaces the channel can take over, newest host first: the shared
72
- * CodeBlock surface every rc.6+ markdown fence renders through
73
- * (`.md-code-block`) and the deepsuite-style surfaces some host builds
74
- * render instead (`.code-block` / `.code-block-small`). Surfaces with an
75
- * unlisted class are still found by the structural backstop (label + `<pre>`),
76
- * so this list is an optimization, not a hard contract. */
73
+ /** 优先用宿主代码块内容的语义标记定位包装节点;隐藏语言或改变类名不能阻断
74
+ * 原始消息的围栏识别。类名也用于仍以这些表面呈现的代码块。 */
77
75
  const CODE_BLOCK_SELECTORS = '.md-code-block, .code-block, .code-block-small'
76
+
77
+ /** 在同一处收集代码块包装节点,供候选扫描和原始围栏序号共用。 */
78
+ function codeBlockSurfaces(scope: ParentNode): HTMLElement[] {
79
+ const surfaces = new Set(scope.querySelectorAll<HTMLElement>(CODE_BLOCK_SELECTORS))
80
+ for (const content of scope.querySelectorAll<HTMLElement>('[data-code-block-content]')) {
81
+ if (content.parentElement !== null) surfaces.add(content.parentElement)
82
+ }
83
+ return [...surfaces].sort((left, right) => left.compareDocumentPosition(right) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1)
84
+ }
85
+
86
+ /** 返回拥有代码内容语义节点、或已知代码块类名的最近包装节点。 */
87
+ function closestCodeBlockSurface(
88
+ element: Element | null,
89
+ owners?: WeakMap<Element, Element | null>,
90
+ ): Element | null {
91
+ // 缓存仅在同一次同步候选扫描内复用,后续 DOM 更新会创建新的缓存。
92
+ const visited: Element[] = []
93
+ let owner: Element | null = null
94
+ for (let current = element; current !== null; current = current.parentElement) {
95
+ if (owners?.has(current)) {
96
+ owner = owners.get(current) ?? null
97
+ break
98
+ }
99
+ visited.push(current)
100
+ if (current.matches(CODE_BLOCK_SELECTORS)
101
+ || [...current.children].some(child => child.hasAttribute('data-code-block-content'))) {
102
+ owner = current
103
+ break
104
+ }
105
+ }
106
+ for (const current of visited) owners?.set(current, owner)
107
+ return owner
108
+ }
78
109
  /** Marker attribute set on blocks this channel has taken over. */
79
110
  const PROCESSED = 'data-genui-rendered'
80
111
  /** The settled marker on AssistantMarkdown (absent = settled). */
@@ -83,9 +114,49 @@ const STREAMING = '[data-streaming]'
83
114
  const CONTAINER_CLASS = 'genui-dom-fence'
84
115
  /** Container class for the visible diagnostic of an unrenderable fence. */
85
116
  const DIAGNOSTIC_CLASS = 'genui-dom-fence-diagnostic'
117
+ /** Host containers a takeover never reaches: our own mounted trees. Every
118
+ * discovery path shares these gates, so a changed node cannot enqueue what a
119
+ * full scan rejects. */
120
+ const SURFACE_EXCLUDES = `.${CONTAINER_CLASS}, .${DIAGNOSTIC_CLASS}, [data-genui-svg-fence]`
121
+ /** Same for tag-text spans: the host renders these rows outside the
122
+ * transcript (reasoning, tool output, sidebars, plugin panels). */
123
+ const TAG_TEXT_EXCLUDES = `.${CONTAINER_CLASS}, .${DIAGNOSTIC_CLASS}, [data-chat-group-part="reasoning"], [data-tool], [data-sidebar-chat], [data-sidebar-right-session], [data-sidebar-right-panel], [data-panel-conversation], [data-plugin-panel]`
124
+ /**
125
+ * Subtrees whose mutations cannot change a fence.
126
+ *
127
+ * The observer has to watch the whole body (a history load or a session switch
128
+ * replaces the transcript wholesale), but the composer types into a subtree no
129
+ * fence can live in, and this plugin's own containers are React's to mutate.
130
+ * Without this gate every keystroke and every panel interaction ran
131
+ * `repairSurgery` and scheduled a sweep, which on a long transcript is a frame
132
+ * of work per key.
133
+ */
134
+ const IGNORED_MUTATION_SCOPE = `${SURFACE_EXCLUDES}, [data-composer-seat], [data-composer-input]`
86
135
  /** Slow sweep interval: the observer catches everything, this is the 1s
87
136
  * belt-and-braces pass (history loads, missed attribute batches). */
88
137
  const SWEEP_MS = 1000
138
+ /** Cooperative per-sweep budget (ms) for discovery and takeover. Work yields
139
+ * between targets and candidates, not inside a subtree scan or block render;
140
+ * a once-deferred scan also runs to completion to avoid starvation. This is
141
+ * not a hard frame-time cap. Remaining candidates wait for the next sweep. */
142
+ const SWEEP_BUDGET_MS = 8
143
+ /** Rows re-checked by {@link rotationSweep}, and how many slow ticks apart
144
+ * those passes run. The observer sees structure, text, and `data-streaming`,
145
+ * so the belt-and-braces pass only has to cover changes it cannot see — in
146
+ * slices, and rarely: it re-queries every row in the document, which on a
147
+ * large transcript costs more than the work it guards. */
148
+ const ROTATION_ROWS = 24
149
+ const ROTATION_TICKS = 5
150
+ /** Upper bound on nodes awaiting discovery. A larger set means a re-render
151
+ * storm; the rotation pass picks those blocks up on its own schedule. */
152
+ const DIRTY_TARGET_LIMIT = 512
153
+ /** Contexts a fence can appear in: a code body, a surface class, or a
154
+ * surface's content holder. Prose and layout changes fail this gate. */
155
+ const CODE_CONTEXT = `pre, ${CODE_BLOCK_SELECTORS}, [data-code-block-content]`
156
+ const NO_FILE_LINK_AVAILABILITY: FileLinkAvailability = {
157
+ subscribe: () => () => {},
158
+ getSnapshot: () => false,
159
+ }
89
160
 
90
161
  /** Max ancestors walked from a `<pre>` to its fence surface root (banner +
91
162
  * pre holder). Most hosts put the pre directly under the surface; some wrap
@@ -167,12 +238,12 @@ function isTextNode(node: Node): node is Text {
167
238
  /** 读取 DSH Desktop 0.11.0 将 dsh-ui 围栏呈现为纯文本标签时的正文。 */
168
239
  function tagTextBodyOf(block: Element): string | null {
169
240
  if (block.tagName !== 'SPAN' || block.childElementCount !== 0) return null
170
- const flowKind = block.closest('[data-chat-flow-kind]')?.getAttribute('data-chat-flow-kind')
171
- if (flowKind !== undefined && flowKind !== null && flowKind !== 'assistant-step') return null
172
241
  const text = block.textContent?.trim() ?? ''
173
242
  const opening = '<dsh-ui>'
174
243
  const closing = '</dsh-ui>'
175
244
  if (!text.startsWith(opening) || !text.endsWith(closing)) return null
245
+ const flowKind = block.closest('[data-chat-flow-kind]')?.getAttribute('data-chat-flow-kind')
246
+ if (flowKind !== undefined && flowKind !== null && flowKind !== 'assistant-step') return null
176
247
  return text.slice(opening.length, -closing.length).trim()
177
248
  }
178
249
 
@@ -189,14 +260,14 @@ function infostringOf(block: Element): 'dsh-ui' | 'svg' | null {
189
260
  const pre = block.querySelector('pre')
190
261
  for (const el of block.querySelectorAll('*')) {
191
262
  if (el.childElementCount !== 0) continue
192
- const lang = el.textContent?.trim()
263
+ const lang = normalizeFenceLanguage(el.textContent?.trim() ?? '')
193
264
  if (lang !== 'dsh-ui' && lang !== 'svg') continue
194
265
  if (pre !== null && pre.contains(el)) continue
195
266
  // A leaf label that belongs to a NESTED known code surface is that
196
267
  // surface's banner, not `block`'s own banner. Only accept labels whose
197
268
  // nearest known surface is `block` itself (or none — unknown surfaces
198
269
  // stay supported by the structural backstop).
199
- const owner = el.closest(CODE_BLOCK_SELECTORS)
270
+ const owner = closestCodeBlockSurface(el)
200
271
  if (owner !== null && owner !== block) continue
201
272
  return lang
202
273
  }
@@ -229,13 +300,38 @@ const KNOWN_LANGUAGE_LABELS = new Set([
229
300
  /**
230
301
  * Read a language that the host still exposes in its CodeBlock banner.
231
302
  *
232
- * 只有标签命中 {@link KNOWN_LANGUAGE_LABELS} 才返回语言;空标签与本地化通用词
303
+ * 先规范化 GenUI 标签,再识别已知语言与明确的 `dsh-ui-*` 变体;空标签与本地化通用词
233
304
  * («Код» / Código / 代码块 …)是宿主的**呈现文案**、不是语义,一律返回 null——
234
305
  * 此前它们会被当成真语言,连 ChatSnapshot 来源都被短路(issue #258)。
235
306
  */
236
307
  function domLanguageOf(block: Element): string | null {
237
- const label = labelTextOf(block)
238
- return label !== '' && KNOWN_LANGUAGE_LABELS.has(label.toLowerCase()) ? label : null
308
+ const label = normalizeFenceLanguage(labelTextOf(block))
309
+ // An explicit GenUI-like language that normalization did not accept is not
310
+ // a localized generic banner; never recover it from JSON-shaped content.
311
+ return label.toLowerCase().startsWith('dsh-ui') || KNOWN_LANGUAGE_LABELS.has(label.toLowerCase()) ? label : null
312
+ }
313
+
314
+ /**
315
+ * 解析一条宿主代码块的围栏语言,并吸收标签书写噪音。
316
+ *
317
+ * 宿主把 `dsh-ui` 写进快照时可能带上尾部标点(```dsh-ui> 这类手滑),mdast 会
318
+ * 原样保留在 `lang` 上。四处判定都要走同一个规范化,否则同一条围栏在「发现」
319
+ * 与「接管」两步得到相反结论,表现就是静默停在代码块上。
320
+ *
321
+ * `null`(围栏确实没有语言)与 `undefined`(来源不可用)必须保持区分:接管判定
322
+ * 只在后者才走内容识别兜底。
323
+ *
324
+ * @param block - 宿主代码块元素。
325
+ * @param sourceLanguage - 读取 ChatSnapshot 侧语言的回调(DOM 无语言时使用)。
326
+ * @returns 规范化后的语言、`null` 或 `undefined`。
327
+ */
328
+ function resolveFenceLanguage(
329
+ block: Element,
330
+ sourceLanguage: (block: Element) => string | null | undefined,
331
+ ): string | null | undefined {
332
+ const domLanguage = tagTextBodyOf(block) !== null ? 'dsh-ui' : domLanguageOf(block)
333
+ const language = domLanguage ?? sourceLanguage(block)
334
+ return typeof language === 'string' ? normalizeFenceLanguage(language) : language
239
335
  }
240
336
 
241
337
  /** The banner label's raw text (empty while streaming — the host renders the
@@ -339,6 +435,43 @@ function implausibleLabeledAncestorOf(pre: HTMLElement, scope: ParentNode = docu
339
435
  return null
340
436
  }
341
437
 
438
+ /** Why a candidate is not a fence. Reported rather than inlined so the full
439
+ * scan keeps its diagnostics and the mutation path reaches the same verdict. */
440
+ type SurfaceRejection = 'nested' | 'plugin-owned' | 'implausible' | null
441
+
442
+ /** The gate every surface candidate passes, whichever path found it. */
443
+ function surfaceRejection(candidate: Element, owners?: WeakMap<Element, Element | null>): SurfaceRejection {
444
+ // Modifier classes can sit inside a surface (e.g. a `code-block-small`
445
+ // child of `code-block`): only the outermost matching element is a
446
+ // candidate, so a fence is never double-counted or taken over twice.
447
+ if (closestCodeBlockSurface(candidate.parentElement, owners) !== null) return 'nested'
448
+ if (candidate.closest(SURFACE_EXCLUDES) !== null) return 'plugin-owned'
449
+ // Message-level containers that happen to carry a surface class must not be
450
+ // taken over: hiding them hides the whole answer (issue #19).
451
+ if (!isPlausibleFenceSurface(candidate)) return 'implausible'
452
+ return null
453
+ }
454
+
455
+ /** Same policy for tag-text spans: a complete `<dsh-ui>` label in assistant
456
+ * prose is a fence, and nothing else is. */
457
+ function isTakeoverTagText(span: Element, owners?: WeakMap<Element, Element | null>): boolean {
458
+ if (tagTextBodyOf(span) === null) return false
459
+ if (closestCodeBlockSurface(span, owners) !== null) return false
460
+ return span.closest(TAG_TEXT_EXCLUDES) === null
461
+ }
462
+
463
+ /** The outermost surface a node sits in. Mutation-driven discovery has to
464
+ * land on the candidate a full scan would pick, not on a modifier inside it. */
465
+ function outermostSurfaceOf(node: Element | null): HTMLElement | null {
466
+ let candidate = closestCodeBlockSurface(node)
467
+ while (candidate !== null) {
468
+ const parent = closestCodeBlockSurface(candidate.parentElement)
469
+ if (parent === null) return candidate as HTMLElement
470
+ candidate = parent
471
+ }
472
+ return null
473
+ }
474
+
342
475
  /**
343
476
  * Every dsh-ui fence surface or complete tag-text span under `scope`, in DOM order.
344
477
  * Known surface classes first (cheap, ordered), then a structural sweep —
@@ -346,39 +479,52 @@ function implausibleLabeledAncestorOf(pre: HTMLElement, scope: ParentNode = docu
346
479
  * unlisted surface shape still renders. The label + `<pre>` gates make the
347
480
  * structural pass false-positive-free: a random code surface without the
348
481
  * exact `dsh-ui` label is never taken over.
482
+ *
483
+ * With `includeScope` the scope element is a candidate too: a mutation hands
484
+ * over the node that changed, and the fence can be that node (an unknown-class
485
+ * surface appended to a row, a tag-text span in a wrapper that arrived whole).
349
486
  */
350
- function findFenceCandidates(scope: ParentNode = document): HTMLElement[] {
487
+ function findFenceCandidates(scope: ParentNode = document, options: { includeScope?: boolean } = {}): HTMLElement[] {
488
+ const self = options.includeScope === true && scope instanceof Element ? scope : null
489
+ const surfaceOwners = new WeakMap<Element, Element | null>()
351
490
  const seen = new Set<HTMLElement>()
352
491
  const out: HTMLElement[] = []
353
- for (const el of scope.querySelectorAll<HTMLElement>(CODE_BLOCK_SELECTORS)) {
354
- // Modifier classes can sit inside a surface (e.g. a `code-block-small`
355
- // child of `code-block`): only the outermost matching element is a
356
- // candidate, so a fence is never double-counted or taken over twice.
357
- if (el.parentElement !== null && el.parentElement.closest(CODE_BLOCK_SELECTORS) !== null) continue
358
- if (el.closest(`.${CONTAINER_CLASS}, .${DIAGNOSTIC_CLASS}, [data-genui-svg-fence]`) !== null) continue
492
+ const surfaces = codeBlockSurfaces(scope)
493
+ if (self !== null && (self.matches(CODE_BLOCK_SELECTORS)
494
+ || [...self.children].some(child => child.hasAttribute('data-code-block-content')))) {
495
+ surfaces.unshift(self as HTMLElement)
496
+ }
497
+ for (const el of surfaces) {
359
498
  if (seen.has(el)) continue
360
- // Message-level containers that happen to carry a surface class must
361
- // not be taken over: hiding them hides the whole answer (issue #19).
362
- if (!isPlausibleFenceSurface(el)) {
363
- if (infostringOf(el) === 'dsh-ui') warnImplausibleSurface(el)
499
+ const rejection = surfaceRejection(el, surfaceOwners)
500
+ if (rejection !== null) {
501
+ if (rejection === 'implausible' && infostringOf(el) === 'dsh-ui') warnImplausibleSurface(el)
364
502
  continue
365
503
  }
366
504
  out.push(el)
367
505
  seen.add(el)
368
506
  }
369
- for (const pre of scope.querySelectorAll<HTMLElement>('pre')) {
507
+ const pres = [...scope.querySelectorAll<HTMLElement>('pre')]
508
+ if (self !== null && self.tagName === 'PRE') pres.unshift(self as HTMLElement)
509
+ // A scan rooted at a changed node has to reach a surface that IS that node,
510
+ // and `surfaceOf` stops at the scope boundary: move the boundary up one hop
511
+ // for this scan only. The three checks below are the shared gate's three
512
+ // verdicts applied to the `<pre>` instead of to the surface it resolves to.
513
+ const surfaceScope: ParentNode = self === null ? scope : self.parentElement ?? self
514
+ for (const pre of pres) {
370
515
  // `<pre>` bodies inside a known surface were already handled by the
371
516
  // selector pass. Walking up from them again would climb PAST their own
372
517
  // (non-dsh-ui or dsh-ui) surface into a shared container — e.g. a
373
518
  // markdown root holding both a dsh-ui fence and a python block — and
374
519
  // the backstop would mislabel that whole container as a fence, hiding
375
520
  // every other code block with it (issue #13).
376
- if (pre.closest(`${CODE_BLOCK_SELECTORS}, .${CONTAINER_CLASS}, .${DIAGNOSTIC_CLASS}, [data-genui-svg-fence]`) !== null) continue
377
- const surface = surfaceOf(pre, scope)
521
+ if (closestCodeBlockSurface(pre, surfaceOwners) !== null
522
+ || pre.closest(SURFACE_EXCLUDES) !== null) continue
523
+ const surface = surfaceOf(pre, surfaceScope)
378
524
  if (surface === null) {
379
525
  // Diagnose the issue #19 guard: a labeled ancestor that is NOT a code
380
526
  // surface (prose/multiple code bodies) was skipped on purpose.
381
- const rejected = implausibleLabeledAncestorOf(pre, scope)
527
+ const rejected = implausibleLabeledAncestorOf(pre, surfaceScope)
382
528
  if (rejected !== null) warnImplausibleSurface(rejected)
383
529
  continue
384
530
  }
@@ -393,9 +539,11 @@ function findFenceCandidates(scope: ParentNode = document): HTMLElement[] {
393
539
  out.push(surface)
394
540
  seen.add(surface)
395
541
  }
396
- for (const span of scope.querySelectorAll<HTMLElement>('span')) {
397
- if (span.closest(`.${CONTAINER_CLASS}, .${DIAGNOSTIC_CLASS}, ${CODE_BLOCK_SELECTORS}, [data-chat-group-part="reasoning"], [data-tool], [data-sidebar-chat], [data-sidebar-right-session], [data-sidebar-right-panel], [data-panel-conversation], [data-plugin-panel]`) !== null) continue
398
- if (tagTextBodyOf(span) === null) continue
542
+ const spans = [...scope.querySelectorAll<HTMLElement>('span')]
543
+ if (self !== null && self.tagName === 'SPAN') spans.unshift(self as HTMLElement)
544
+ for (const span of spans) {
545
+ // 普通文本不进入祖先和代码块归属查找。
546
+ if (!isTakeoverTagText(span, surfaceOwners)) continue
399
547
  out.push(span)
400
548
  }
401
549
  return out.sort((left, right) => left.compareDocumentPosition(right) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1)
@@ -454,7 +602,7 @@ function fenceIndexOf(ctx: Context, row: Element, block: Element, sourceLanguage
454
602
  let fallbackIndex = 0
455
603
  for (const candidate of findFenceCandidates(scope)) {
456
604
  if (candidate.closest(STREAMING) !== null) continue
457
- const language = tagTextBodyOf(candidate) !== null ? 'dsh-ui' : domLanguageOf(candidate) ?? sourceLanguage(candidate)
605
+ const language = resolveFenceLanguage(candidate, sourceLanguage)
458
606
  if (language !== 'dsh-ui' && !(language === undefined && isGenericGenuiFence(candidate, rawOf(candidate)))) continue
459
607
  fallbackIndex += 1
460
608
  if (candidate === block) return fallbackIndex
@@ -466,7 +614,7 @@ function fenceIndexOf(ctx: Context, row: Element, block: Element, sourceLanguage
466
614
  if (candidate.closest(STREAMING) !== null) continue
467
615
  if (candidate.closest(ASSISTANT_FLOW_ROW) !== row) continue
468
616
  if (candidate.closest('[data-chat-group-part="reasoning"]') !== null) continue
469
- const language = tagTextBodyOf(candidate) !== null ? 'dsh-ui' : domLanguageOf(candidate) ?? sourceLanguage(candidate)
617
+ const language = resolveFenceLanguage(candidate, sourceLanguage)
470
618
  if (language !== 'dsh-ui' && !(language === undefined && isGenericGenuiFence(candidate, rawOf(candidate)))) continue
471
619
  index += 1
472
620
  if (candidate === block) return index
@@ -476,8 +624,8 @@ function fenceIndexOf(ctx: Context, row: Element, block: Element, sourceLanguage
476
624
 
477
625
  /** Return outer host Markdown code surfaces in one assistant row's DOM order. */
478
626
  function hostFenceBlocksOf(row: Element): HTMLElement[] {
479
- return [...row.querySelectorAll<HTMLElement>(CODE_BLOCK_SELECTORS)].filter(candidate => {
480
- if (candidate.parentElement?.closest(CODE_BLOCK_SELECTORS) !== null) return false
627
+ return codeBlockSurfaces(row).filter(candidate => {
628
+ if (closestCodeBlockSurface(candidate.parentElement) !== null) return false
481
629
  if (candidate.closest(`.${CONTAINER_CLASS}, .${DIAGNOSTIC_CLASS}, [data-genui], [data-genui-svg-fence]`) !== null) return false
482
630
  if (candidate.closest('[data-chat-group-part="reasoning"], [data-tool], [data-sidebar-chat], [data-sidebar-right-session], [data-sidebar-right-panel], [data-panel-conversation], [data-plugin-panel]') !== null) return false
483
631
  if (candidate.closest(ASSISTANT_FLOW_ROW) !== row) return false
@@ -504,13 +652,18 @@ export function sourceLanguageOf(ctx: Context, block: Element): string | null |
504
652
  }
505
653
 
506
654
  /** Cache each row's Markdown parse for one sweep and retain confirmed opening-line languages per host block. */
507
- function createSourceLanguageResolver(ctx: Context): { beginSweep: () => void; get: (block: Element) => string | null | undefined } {
655
+ function createSourceLanguageResolver(ctx: Context): {
656
+ beginSweep: () => void
657
+ get: (block: Element) => string | null | undefined
658
+ isSessionUnavailable: () => boolean
659
+ } {
508
660
  const stableLanguages = new WeakMap<Element, { sessionId: SessionId; nodeKey: string; language: string | null }>()
509
661
  let sweepLanguages = new Map<Element, string | null | undefined>()
510
662
  let parsedNodes = new Map<string, ReturnType<typeof sourceFencesOfAssistant>>()
511
663
  let sessionId: SessionId | undefined
512
664
  let chat: ChatSnapshot | undefined
513
665
  let chatRead = false
666
+ let sessionUnavailable = false
514
667
 
515
668
  return {
516
669
  beginSweep() {
@@ -519,13 +672,23 @@ function createSourceLanguageResolver(ctx: Context): { beginSweep: () => void; g
519
672
  sessionId = undefined
520
673
  chat = undefined
521
674
  chatRead = false
675
+ sessionUnavailable = false
676
+ },
677
+ isSessionUnavailable() {
678
+ return sessionUnavailable
522
679
  },
523
680
  get(block) {
524
681
  if (sweepLanguages.has(block)) return sweepLanguages.get(block)
525
682
  const row = block.closest<HTMLElement>(`${ASSISTANT_FLOW_ROW}[data-chat-node-key]`)
526
683
  if (row === null || row.dataset.chatGroupPart === 'reasoning') return undefined
527
684
  const nodeKey = row.dataset.chatNodeKey
528
- const activeSessionId = sessionIdOfForSource(ctx)
685
+ const sourceSession = sourceSessionOf(ctx)
686
+ if (!sourceSession.available) {
687
+ sessionUnavailable = true
688
+ sweepLanguages.set(block, undefined)
689
+ return undefined
690
+ }
691
+ const activeSessionId = sourceSession.sessionId
529
692
  if (!nodeKey || activeSessionId === undefined) return undefined
530
693
 
531
694
  const stable = stableLanguages.get(block)
@@ -570,9 +733,25 @@ export function hostFenceIndexOf(row: Element, block: Element): number {
570
733
  return hostFenceBlocksOf(row).indexOf(block as HTMLElement)
571
734
  }
572
735
 
736
+ /** Read the viewed session and report when Cordis rejects access to its Context. */
737
+ function sourceSessionOf(ctx: Context): { available: true; sessionId: SessionId | undefined } | { available: false } {
738
+ try {
739
+ return {
740
+ available: true,
741
+ sessionId: resolveViewedSessionId(
742
+ ctx.sessions.list.getSnapshot(),
743
+ sessionId => ctx.sessions.retainInfo(sessionId),
744
+ ),
745
+ }
746
+ } catch {
747
+ return { available: false }
748
+ }
749
+ }
750
+
573
751
  /** Read the currently viewed session for source Markdown lookup. */
574
752
  function sessionIdOfForSource(ctx: Context): SessionId | undefined {
575
- return resolveViewedSessionId(ctx.sessions.list.getSnapshot())
753
+ const sourceSession = sourceSessionOf(ctx)
754
+ return sourceSession.available ? sourceSession.sessionId : undefined
576
755
  }
577
756
 
578
757
  /** Read uiConversation as an optional service so Cordis does not require a hard inject. */
@@ -650,6 +829,7 @@ function anchorSeqOf(row: Element): number {
650
829
  export function installDomFenceRenderer(
651
830
  ctx: Context,
652
831
  sendAction: (sessionId: SessionId, action: string, payload: Record<string, unknown>) => void,
832
+ fileLinkAvailability: FileLinkAvailability = NO_FILE_LINK_AVAILABILITY,
653
833
  ): () => void {
654
834
  if (typeof document === 'undefined') return () => {}
655
835
  driftWarned = false
@@ -664,13 +844,51 @@ export function installDomFenceRenderer(
664
844
  let activeChatSession: SessionId | undefined
665
845
  let unsubscribeChat: (() => void) | undefined
666
846
  const sourceLanguages = createSourceLanguageResolver(ctx)
847
+ /** Nodes changed since the last sweep, awaiting discovery; the value says
848
+ * whether the whole new subtree has to be scanned (structure or attribute
849
+ * change) or only the code context around the node (text change). Discovery
850
+ * waits for the sweep: inside the mutation microtask a session switch would
851
+ * scan a whole transcript before the next paint. */
852
+ const dirtyTargets = new Map<Node, boolean>()
853
+ /** Discovered fence candidates awaiting takeover, oldest discovery first. */
854
+ const pendingCandidates = new Set<HTMLElement>()
855
+ /** Queue dedupe. Dropped again when a block is evaluated, so a later change
856
+ * to a block that stayed a code block re-queues it. */
857
+ const queuedCandidates = new WeakSet<Element>()
858
+ /** Blocks the DOM alone cannot name: their language may still come from the
859
+ * session source (a restored transcript rendered before its rows arrive in
860
+ * the ChatSnapshot, a history page whose nodes are not loaded yet). Kept so a
861
+ * source change re-checks them. */
862
+ const awaitingSource = new Set<HTMLElement>()
863
+ /** Set by the ChatSnapshot subscription; consumed by the next sweep. */
864
+ let sourceChanged = false
865
+ /** Targets whose subtree scan the budget deferred once. They scan on the
866
+ * next sweep regardless, so a page that stays slow cannot starve discovery. */
867
+ const deferredScans = new WeakSet<Node>()
868
+ /** Rows already consumed from the transcript tail by the rotation pass. */
869
+ let rotationNext = 0
667
870
 
668
- const sessionIdOf = (): SessionId | undefined => {
669
- try {
670
- return resolveViewedSessionId(ctx.sessions.list.getSnapshot())
671
- } catch {
672
- return undefined
673
- }
871
+ /** Apply both plugin contexts to every actual GenUI root render. */
872
+ function wrapFenceNode(node: ReactNode, context: GenuiFenceContext, handler: GenuiActionHandler, streaming: boolean): ReactNode {
873
+ const actionTree = <GenuiActionContext.Provider value={handler}>{node}</GenuiActionContext.Provider>
874
+ return withFileLinkContext(
875
+ ctx as unknown as FileLinkCordisContext,
876
+ fileLinkAvailability,
877
+ context.sessionId,
878
+ streaming,
879
+ actionTree,
880
+ )
881
+ }
882
+
883
+ const sessionIdOf = (): SessionId | undefined => sessionIdOfForSource(ctx)
884
+ let lastAvailableSessionId = sessionIdOf()
885
+
886
+ /** Keep a mounted fence's React identity stable while Cordis temporarily denies session access. */
887
+ function sessionIdForRender(preserveWhenUnavailable: boolean): SessionId | undefined {
888
+ const sourceSession = sourceSessionOf(ctx)
889
+ if (!sourceSession.available) return preserveWhenUnavailable ? lastAvailableSessionId : undefined
890
+ lastAvailableSessionId = sourceSession.sessionId
891
+ return sourceSession.sessionId
674
892
  }
675
893
 
676
894
  /** Retry ChatSnapshot subscription while the active session binding is unavailable. */
@@ -681,14 +899,20 @@ export function installDomFenceRenderer(
681
899
  activeChatSession = sessionId
682
900
  }
683
901
  if (sessionId !== undefined && unsubscribeChat === undefined) {
684
- unsubscribeChat = chatSourceOf(ctx, sessionId)?.subscribe(schedule)
902
+ unsubscribeChat = chatSourceOf(ctx, sessionId)?.subscribe(() => {
903
+ // The source is a discovery trigger of its own: the transcript can be
904
+ // on screen before its rows exist in the snapshot, and only the source
905
+ // can name an unlabelled surface dsh-ui.
906
+ sourceChanged = true
907
+ schedule()
908
+ })
685
909
  }
686
910
  }
687
911
 
688
912
  /** Render context for a block: session always; the stable source identity
689
913
  * only once settled — streaming renders are identity-less (no panel
690
- * publish, no durable state), mirroring the registry channel. */
691
- function contextOf(row: Element, block: Element, settled: boolean): { key: Key; context: GenuiFenceContext } {
914
+ * publish, no durable state), matching inline fence behavior. */
915
+ function contextOf(row: Element, block: Element, settled: boolean, preserveSessionIdentity = false): { key: Key; context: GenuiFenceContext } {
692
916
  if (settled && row.getAttribute('data-chat-anchor-key') === null) {
693
917
  // Safari / fallback render path: the host omitted the row anchor (the
694
918
  // attribute is a React key that React drops when undefined). Fences
@@ -699,7 +923,7 @@ export function installDomFenceRenderer(
699
923
  const fenceIndex = fenceIndexOf(ctx, row, block, sourceLanguages.get)
700
924
  const anchorKey = row.getAttribute('data-chat-anchor-key') ?? 'unknown'
701
925
  const key = `dom:${anchorKey}:${fenceIndex}` as Key
702
- const sessionId = sessionIdOf()
926
+ const sessionId = sessionIdForRender(preserveSessionIdentity)
703
927
  const context: GenuiFenceContext = {
704
928
  ...(sessionId === undefined ? {} : { sessionId }),
705
929
  ...(settled ? { source: { id: key as string, order: [anchorSeqOf(row), 0, fenceIndex] as const } } : {}),
@@ -817,11 +1041,9 @@ export function installDomFenceRenderer(
817
1041
  if (block.hasAttribute(PROCESSED)) return
818
1042
  const row = rowOf(block)
819
1043
  const settled = isSettled(block)
820
- const domLanguage = tagTextBodyOf(block) !== null ? 'dsh-ui' : domLanguageOf(block)
821
- const sourceLanguage = domLanguage === null ? sourceLanguages.get(block) : undefined
822
- const language = domLanguage ?? sourceLanguage
1044
+ const language = resolveFenceLanguage(block, candidate => sourceLanguages.get(candidate))
823
1045
  const raw = rawOf(block)
824
- // DSH 0.1.7-alpha.2 会在最终 DOM 隐去不支持高亮的语言;公开 ChatSnapshot 的原始 Markdown 是 language 来源。
1046
+ // DSH 可能在最终 DOM 隐去不支持高亮的语言;公开 ChatSnapshot 的原始 Markdown 是 language 来源。
825
1047
  // 内容识别只在 source 暂不可用且 assistant 已结束时兜底,不覆盖已确认的 language 或无 language fence。
826
1048
  const genericGenui = language === undefined && settled && isGenericGenuiFence(block, raw)
827
1049
  if (language !== 'dsh-ui' && language !== 'svg' && !genericGenui) return
@@ -868,7 +1090,7 @@ export function installDomFenceRenderer(
868
1090
  }
869
1091
  try {
870
1092
  const handler: GenuiActionHandler = (action, payload) => sendActionForBlock(block, action, payload)
871
- root.render(<GenuiActionContext.Provider value={handler}>{payload}</GenuiActionContext.Provider>)
1093
+ root.render(wrapFenceNode(payload, context, handler, !settled))
872
1094
  } catch (error) {
873
1095
  try {
874
1096
  root.unmount()
@@ -884,6 +1106,190 @@ export function installDomFenceRenderer(
884
1106
  mounts.set(block, { root, container, block, lastRaw: raw, lastSettled: settled, language: acceptedLanguage, lastNode: payload, skeleton: node === null })
885
1107
  }
886
1108
 
1109
+ /** Queue a block for takeover. A block already taken over is skipped here:
1110
+ * its mounted replacement is maintained by the sweep's mount pass, not by a
1111
+ * second takeover. */
1112
+ function enqueueCandidate(block: Element | null | undefined): void {
1113
+ if (block === null || block === undefined) return
1114
+ if (block.hasAttribute(PROCESSED) || queuedCandidates.has(block)) return
1115
+ queuedCandidates.add(block)
1116
+ pendingCandidates.add(block as HTMLElement)
1117
+ }
1118
+
1119
+ /**
1120
+ * Turn one changed node into fence candidates, scoped to the change: the
1121
+ * surface the node belongs to (a streaming body grows in place), the
1122
+ * tag-text span DSH Desktop presents a fence body as, and — for structural
1123
+ * changes — the new subtree itself. A streamed token of ordinary prose costs
1124
+ * one native `closest()` call; nothing walks the transcript.
1125
+ *
1126
+ *
1127
+ * Every candidate leaves through the gates a full scan applies: a mutation
1128
+ * must not reach a block the scan refuses (a message container with prose
1129
+ * next to the fence, a reasoning or tool row, plugin-owned DOM).
1130
+ *
1131
+ * @param target - the changed node (text, element, or added subtree root).
1132
+ * @param structural - true when the change can add a whole new subtree
1133
+ * (childList, `data-streaming`), false for text-node growth.
1134
+ * @param deadline - sweep deadline in `performance.now()` terms; the
1135
+ * subtree scan is deferred (the target stays dirty) once it has passed.
1136
+ */
1137
+ function enqueueMutationTarget(target: Node, structural: boolean, deadline: number): void {
1138
+ const element = target instanceof Element ? target : target.parentElement
1139
+ if (element === null) return
1140
+ // Plugin-owned DOM (our containers and diagnostics) holds no host fence.
1141
+ if (element.closest(SURFACE_EXCLUDES) !== null) return
1142
+ if (element.tagName === 'SPAN' && isTakeoverTagText(element)) enqueueCandidate(element)
1143
+ // A mid-body text update: the outermost surface the node sits in — the
1144
+ // same candidate the scan would pick — plus the structural backstop for
1145
+ // hosts whose surface class this build does not know.
1146
+ const context = element.closest(CODE_CONTEXT)
1147
+ if (context !== null) {
1148
+ const surface = outermostSurfaceOf(context)
1149
+ if (surface !== null && surfaceRejection(surface) === null) enqueueCandidate(surface)
1150
+ const pre = element.closest<HTMLElement>('pre')
1151
+ if (pre !== null) {
1152
+ const labeled = surfaceOf(pre)
1153
+ if (labeled !== null && surfaceRejection(labeled) === null) enqueueCandidate(labeled)
1154
+ }
1155
+ }
1156
+ if (!structural) return
1157
+ // A changed node can carry a fence the node itself is not inside yet: a row
1158
+ // or a wrapper that arrived whole. `includeScope` makes the scan cover the
1159
+ // node and its descendants, so no shape depends on the rotation pass.
1160
+ if (performance.now() >= deadline) {
1161
+ // Budget spent: scanning waits for the next sweep instead of running
1162
+ // unbounded inside this one, and the target stays dirty.
1163
+ deferredScans.add(target)
1164
+ dirtyTargets.set(target, structural)
1165
+ return
1166
+ }
1167
+ const candidates = findFenceCandidates(element, { includeScope: true })
1168
+ // Newest first: a transcript-sized target (session switch, history load)
1169
+ // queues the whole conversation at once, and the tail in view has to be
1170
+ // mounted before the scrollback.
1171
+ for (let index = candidates.length - 1; index >= 0; index -= 1) enqueueCandidate(candidates[index])
1172
+ }
1173
+
1174
+ /** Discovery for the nodes the observer collected, inside the sweep budget. */
1175
+ function resolveDirtyTargets(deadline: number): void {
1176
+ for (const [target, structural] of dirtyTargets) {
1177
+ if (performance.now() >= deadline) return
1178
+ dirtyTargets.delete(target)
1179
+ // A removed subtree holds nothing left to take over.
1180
+ if (!target.isConnected) continue
1181
+ // A target the budget deferred once scans now whatever the clock says:
1182
+ // deferral bounds one sweep, it never starves the queue.
1183
+ const force = deferredScans.delete(target)
1184
+ enqueueMutationTarget(target, structural, force ? Number.POSITIVE_INFINITY : deadline)
1185
+ }
1186
+ }
1187
+
1188
+ /** Take queued candidates over, inside the sweep budget; the rest stays
1189
+ * queued for the next sweep. */
1190
+ function drainCandidates(deadline: number): void {
1191
+ for (const block of pendingCandidates) {
1192
+ if (performance.now() >= deadline) return
1193
+ pendingCandidates.delete(block)
1194
+ // "Queued" only holds until a block has been evaluated: a block that
1195
+ // stays a stock code block has to be re-discovered by the next change
1196
+ // to it (a streaming body growing a token at a time).
1197
+ queuedCandidates.delete(block)
1198
+ if (!block.isConnected) continue
1199
+ // Discovery is not a lease: source retries and frame yields let the
1200
+ // host move a candidate or turn its surface into a message container.
1201
+ // Reapply the same local gates immediately before first takeover. The
1202
+ // mounted-block maintenance path is unchanged, including streaming.
1203
+ const eligible = tagTextBodyOf(block) !== null
1204
+ ? isTakeoverTagText(block)
1205
+ : surfaceRejection(block) === null
1206
+ if (!eligible) {
1207
+ awaitingSource.delete(block)
1208
+ continue
1209
+ }
1210
+ renderBlock(block)
1211
+ noteSourceDecision(block)
1212
+ }
1213
+ }
1214
+
1215
+ /** Remember (or forget) a candidate the DOM cannot name: the session source
1216
+ * may still call it dsh-ui once its snapshot resolves. */
1217
+ function noteSourceDecision(block: HTMLElement): void {
1218
+ if (block.hasAttribute(PROCESSED)
1219
+ || tagTextBodyOf(block) !== null
1220
+ || domLanguageOf(block) !== null
1221
+ || sourceLanguages.get(block) !== undefined) {
1222
+ awaitingSource.delete(block)
1223
+ return
1224
+ }
1225
+ if (awaitingSource.size >= DIRTY_TARGET_LIMIT) return
1226
+ awaitingSource.add(block)
1227
+ }
1228
+
1229
+ /** Re-check the blocks that were waiting on source data. */
1230
+ function requeueAwaitingSource(): void {
1231
+ for (const block of Array.from(awaitingSource)) {
1232
+ awaitingSource.delete(block)
1233
+ if (!block.isConnected || block.hasAttribute(PROCESSED)) continue
1234
+ enqueueCandidate(block)
1235
+ }
1236
+ }
1237
+
1238
+ /** Discovery or takeover left work behind: keep the frame loop going so a
1239
+ * restored transcript drains over the next frames instead of waiting for the
1240
+ * slow tick. */
1241
+ function keepDraining(): void {
1242
+ if (pendingCandidates.size > 0 || dirtyTargets.size > 0) schedule()
1243
+ }
1244
+
1245
+ /** Record a changed node. Cheap by design: the discovery that turns it into
1246
+ * candidates belongs to the sweep, not to the mutation microtask. */
1247
+ function markDirty(node: Node, structural: boolean): void {
1248
+ if (disposed) return
1249
+ const element = node instanceof Element ? node : node.parentElement
1250
+ if (element === null) return
1251
+ if (element.closest(`.${CONTAINER_CLASS}, .${DIAGNOSTIC_CLASS}`) !== null) return
1252
+ const known = dirtyTargets.get(node)
1253
+ if (known === undefined) {
1254
+ if (dirtyTargets.size >= DIRTY_TARGET_LIMIT) return
1255
+ dirtyTargets.set(node, structural)
1256
+ return
1257
+ }
1258
+ // A node that changed structurally after a text-only change needs the
1259
+ // subtree pass as well.
1260
+ if (structural && !known) dirtyTargets.set(node, true)
1261
+ }
1262
+
1263
+ /**
1264
+ * Belt-and-braces pass for what the observer cannot see: it watches
1265
+ * structure, text, and `data-streaming`, so a host that re-classes an
1266
+ * existing block into a code surface fires nothing at all. Rows are
1267
+ * re-checked in slices on the slow tick, so the transcript is covered over a
1268
+ * rotation instead of by one full-document scan per sweep. A host without
1269
+ * rows (a bare span in a projection) has nothing stable to rotate over and
1270
+ * stays covered by the mutation path alone.
1271
+ */
1272
+ function rotationSweep(deadline: number): void {
1273
+ const rows = document.querySelectorAll<HTMLElement>(FLOW_ROW)
1274
+ const total = rows.length
1275
+ if (total === 0) return
1276
+ const step = Math.min(ROTATION_ROWS, total)
1277
+ let visited = 0
1278
+ for (let offset = 0; offset < step; offset += 1) {
1279
+ // This pass is belt-and-braces work: it yields the frame like every
1280
+ // other discovery pass, and the rest of the slice waits for the next
1281
+ // rotation tick.
1282
+ if (performance.now() >= deadline) break
1283
+ // Walk backwards from the transcript tail: the newest row is the one in
1284
+ // view while a fence is being written.
1285
+ const row = rows[total - 1 - ((rotationNext + offset) % total)]
1286
+ if (row === undefined) continue
1287
+ for (const candidate of findFenceCandidates(row)) enqueueCandidate(candidate)
1288
+ visited = offset + 1
1289
+ }
1290
+ rotationNext = (rotationNext + visited) % total
1291
+ }
1292
+
887
1293
  /** Pre-paint repair: the host's React re-renders during streaming can wipe
888
1294
  * our foreign container or reset the hide. Re-apply the surgery in the
889
1295
  * observer microtask (before paint) so raw JSON never flashes between
@@ -936,12 +1342,15 @@ export function installDomFenceRenderer(
936
1342
  }
937
1343
 
938
1344
  /** Sweep: drop dead mounts, re-render changed bodies (streaming growth and
939
- * the streaming→settled transition), repair surgery, then take over every
940
- * new dsh-ui block — settled or still streaming. */
1345
+ * the streaming→settled transition), repair surgery, re-check what the
1346
+ * session source may have unlocked, then take over the dsh-ui blocks
1347
+ * discovery queued — settled or still streaming. */
941
1348
  function sweep(): void {
942
1349
  if (disposed) return
943
1350
  sourceLanguages.beginSweep()
944
- const sessionId = sessionIdOf()
1351
+ const sourceSession = sourceSessionOf(ctx)
1352
+ const sessionId = sourceSession.available ? sourceSession.sessionId : undefined
1353
+ if (sourceSession.available) lastAvailableSessionId = sourceSession.sessionId
945
1354
  syncChatSubscription(sessionId)
946
1355
  for (const [block, mount] of mounts) {
947
1356
  if (!block.isConnected) {
@@ -951,15 +1360,19 @@ export function installDomFenceRenderer(
951
1360
  const raw = rawOf(block)
952
1361
  const settled = isSettled(block)
953
1362
  const domLanguage = tagTextBodyOf(block) !== null ? 'dsh-ui' : domLanguageOf(block)
954
- const sourceLanguage = domLanguage === null ? sourceLanguages.get(block) : undefined
955
- const language = domLanguage ?? sourceLanguage
1363
+ // 宿主把围栏标签写成 `dsh-ui>` 这类带尾部标点的形态时,严格相等会让这条围栏
1364
+ // 永远停在代码块上(真实会话:一条消息内 182 处)。快照侧已在解析时规范化,
1365
+ // 这里再兜一层,覆盖 DOM 语言与历史缓存值两条路径。
1366
+ const language = resolveFenceLanguage(block, () => sourceLanguages.get(block))
1367
+ const sourceUnavailable = domLanguage === null
1368
+ && (!sourceSession.available || sourceLanguages.isSessionUnavailable())
956
1369
  const validGenui = language === 'dsh-ui'
957
1370
  || (language === undefined && settled && isGenericGenuiFence(block, raw))
958
1371
  if (mount.language === 'svg' && language !== 'svg') {
959
1372
  unmountBlock(block)
960
1373
  continue
961
1374
  }
962
- if (mount.language === 'dsh-ui' && !validGenui) {
1375
+ if (mount.language === 'dsh-ui' && !validGenui && !sourceUnavailable) {
963
1376
  unmountBlock(block)
964
1377
  continue
965
1378
  }
@@ -970,7 +1383,7 @@ export function installDomFenceRenderer(
970
1383
  const contentWiped = !isPanelRoot(mount.lastNode) && mount.container.childElementCount === 0
971
1384
  if (mount.lastRaw !== raw || mount.lastSettled !== settled || contentWiped) {
972
1385
  const anchor = rowOf(block)
973
- const { key, context } = contextOf(anchor, block, settled)
1386
+ const { key, context } = contextOf(anchor, block, settled, true)
974
1387
  const node = mount.language === 'svg' ? renderSvgFence(raw, key) : renderResolvedFenceNode(raw, key, context)
975
1388
  if (node === null) {
976
1389
  if (mount.skeleton && !settled) {
@@ -1002,7 +1415,7 @@ export function installDomFenceRenderer(
1002
1415
  try {
1003
1416
  const freshRoot = domRootFactory(fresh)
1004
1417
  const handler: GenuiActionHandler = (action, payload) => sendActionForBlock(block, action, payload)
1005
- freshRoot.render(<GenuiActionContext.Provider value={handler}>{node}</GenuiActionContext.Provider>)
1418
+ freshRoot.render(wrapFenceNode(node, context, handler, !settled))
1006
1419
  mount.root = freshRoot
1007
1420
  mount.container = fresh
1008
1421
  } catch (error) {
@@ -1017,7 +1430,8 @@ export function installDomFenceRenderer(
1017
1430
  }
1018
1431
  } else {
1019
1432
  try {
1020
- mount.root.render(<GenuiActionContext.Provider value={(action, payload) => sendActionForBlock(block, action, payload)}>{node}</GenuiActionContext.Provider>)
1433
+ const handler: GenuiActionHandler = (action, payload) => sendActionForBlock(block, action, payload)
1434
+ mount.root.render(wrapFenceNode(node, context, handler, !settled))
1021
1435
  } catch (error) {
1022
1436
  // Never leave the stock block hidden behind a broken root: restore
1023
1437
  // the raw code block and drop the mount (issue #19).
@@ -1045,18 +1459,24 @@ export function installDomFenceRenderer(
1045
1459
  // label is no longer dsh-ui is somebody else's fence, so our explanation
1046
1460
  // would be about the wrong block.
1047
1461
  if (isSettled(block)) {
1048
- const domLanguage = tagTextBodyOf(block) !== null ? 'dsh-ui' : domLanguageOf(block)
1049
- const sourceLanguage = domLanguage === null ? sourceLanguages.get(block) : undefined
1050
- if ((domLanguage ?? sourceLanguage) !== 'dsh-ui') {
1462
+ const language = resolveFenceLanguage(block, candidate => sourceLanguages.get(candidate))
1463
+ if (language !== 'dsh-ui') {
1051
1464
  clearDiagnostic(block)
1052
1465
  continue
1053
1466
  }
1054
1467
  }
1055
1468
  rebuildWipedDiagnostic(block, diagnostic.raw)
1056
1469
  }
1057
- for (const block of findFenceCandidates()) {
1058
- renderBlock(block)
1470
+ // Discovery and takeover share one budget: an unbounded pass here is what
1471
+ // made a long session stall (every sweep re-read the whole transcript).
1472
+ if (sourceChanged) {
1473
+ sourceChanged = false
1474
+ requeueAwaitingSource()
1059
1475
  }
1476
+ const deadline = performance.now() + SWEEP_BUDGET_MS
1477
+ resolveDirtyTargets(deadline)
1478
+ drainCandidates(deadline)
1479
+ keepDraining()
1060
1480
  }
1061
1481
 
1062
1482
  const schedule = (): void => {
@@ -1073,6 +1493,9 @@ export function installDomFenceRenderer(
1073
1493
  : undefined
1074
1494
 
1075
1495
  const observer = new MutationObserver(records => {
1496
+ // A container the host emptied is repair work wherever it sits, and the
1497
+ // removal is the only record that carries it: mark those first.
1498
+ let relevant = false
1076
1499
  // Restore detached roots before paint, retaining input and pending actions.
1077
1500
  // The latest removal owns the current tree if several commits were batched.
1078
1501
  for (const record of [...records].reverse()) {
@@ -1080,6 +1503,7 @@ export function installDomFenceRenderer(
1080
1503
  const target = record.target
1081
1504
  const mount = [...mounts.values()].find(candidate => candidate.container === target)
1082
1505
  if (mount !== undefined) {
1506
+ relevant = true
1083
1507
  if (!mount.block.isConnected || isPanelRoot(mount.lastNode)) continue
1084
1508
  mount.container.append(...record.removedNodes)
1085
1509
  continue
@@ -1087,7 +1511,38 @@ export function installDomFenceRenderer(
1087
1511
  // The same surgery for a visible diagnostic the host emptied: re-append
1088
1512
  // its own nodes instead of leaving the author without an explanation.
1089
1513
  const diagnostic = [...diagnostics.values()].find(candidate => candidate.container === target)
1090
- if (diagnostic !== undefined) diagnostic.container.append(...record.removedNodes)
1514
+ if (diagnostic !== undefined) {
1515
+ relevant = true
1516
+ diagnostic.container.append(...record.removedNodes)
1517
+ }
1518
+ }
1519
+ // Everything else can only change a fence where a fence can live: the
1520
+ // composer and plugin-owned trees cannot hold a host fence. Sidebars can
1521
+ // contain assistant replies, so they retain normal incremental discovery.
1522
+ if (!relevant) {
1523
+ for (const record of records) {
1524
+ const node = record.target instanceof Element ? record.target : record.target.parentElement
1525
+ if (node === null || node.closest(IGNORED_MUTATION_SCOPE) === null) {
1526
+ relevant = true
1527
+ break
1528
+ }
1529
+ }
1530
+ }
1531
+ if (!relevant) return
1532
+ for (const record of records) {
1533
+ // Structure, and the streaming→settled flip, can unlock a whole subtree
1534
+ // (a history load, a session switch, a row that stopped streaming): those
1535
+ // get the subtree pass. Text growth is the streaming case and stays on
1536
+ // the cheap surface path.
1537
+ if (record.type === 'characterData') {
1538
+ markDirty(record.target, false)
1539
+ continue
1540
+ }
1541
+ if (record.type === 'childList') {
1542
+ for (const node of record.addedNodes) markDirty(node, true)
1543
+ continue
1544
+ }
1545
+ markDirty(record.target, true)
1091
1546
  }
1092
1547
  // Pre-paint pass: surgery repair only (cheap DOM ops); the React
1093
1548
  // re-render goes through the rAF-scheduled sweep.
@@ -1103,7 +1558,23 @@ export function installDomFenceRenderer(
1103
1558
  // observer would only fire on structural changes and miss body growth.
1104
1559
  characterData: true,
1105
1560
  })
1106
- const interval = window.setInterval(sweep, SWEEP_MS)
1561
+ let slowTicks = 0
1562
+ const interval = window.setInterval(() => {
1563
+ sweep()
1564
+ // The rotation is the net for changes the observer cannot see, so it rides
1565
+ // the slow tick only every ROTATION_TICKS of them: it re-queries the whole
1566
+ // transcript, and on a streaming page the sweep already runs per frame.
1567
+ slowTicks += 1
1568
+ if (slowTicks % ROTATION_TICKS === 0) rotationSweep(performance.now() + SWEEP_BUDGET_MS)
1569
+ keepDraining()
1570
+ }, SWEEP_MS)
1571
+ // Initial scan: the transcript is already on screen and no mutation will
1572
+ // fire for it. Newest first, so what is in view mounts within the first
1573
+ // frames while the scrollback drains from the queue. It is one synchronous
1574
+ // pass by design — the budget below bounds discovery, not a single subtree
1575
+ // query, and a session switch must not leave raw spec on screen.
1576
+ const initial = findFenceCandidates()
1577
+ for (let index = initial.length - 1; index >= 0; index -= 1) enqueueCandidate(initial[index])
1107
1578
  sweep()
1108
1579
 
1109
1580
  return () => {
@@ -1117,6 +1588,9 @@ export function installDomFenceRenderer(
1117
1588
  cancelAnimationFrame(rafId)
1118
1589
  rafId = null
1119
1590
  }
1591
+ dirtyTargets.clear()
1592
+ pendingCandidates.clear()
1593
+ awaitingSource.clear()
1120
1594
  for (const block of Array.from(mounts.keys())) unmountBlock(block)
1121
1595
  for (const block of Array.from(diagnostics.keys())) clearDiagnostic(block)
1122
1596
  }