@sparkelf/dsh-genui 0.0.0-stage → 0.11.4-patch.1

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 (210) hide show
  1. package/CHANGELOG.md +597 -0
  2. package/LICENSE +21 -0
  3. package/README.md +292 -2
  4. package/README.zh-CN.md +307 -0
  5. package/SKILL.md +261 -0
  6. package/cordis.patch.yml +9 -0
  7. package/demo-prompts.md +118 -0
  8. package/lib/assets/echarts-core.js +43 -0
  9. package/lib/assets/echarts-full.js +72 -0
  10. package/lib/assets/mermaid.js +3591 -0
  11. package/lib/assets/standalone-runtime.js +1506 -0
  12. package/lib/assets/three.js +3844 -0
  13. package/lib/client.js +405 -0
  14. package/lib/index.js +5187 -0
  15. package/lib/invariant.js +19 -0
  16. package/lib/types/client/EChartNode.d.ts +13 -0
  17. package/lib/types/client/ErrorBoundary.d.ts +30 -0
  18. package/lib/types/client/GenuiBlock.d.ts +9 -0
  19. package/lib/types/client/PlotBlock.d.ts +44 -0
  20. package/lib/types/client/TemplateDrawer.d.ts +7 -0
  21. package/lib/types/client/achievement-store.d.ts +35 -0
  22. package/lib/types/client/achievement-toast.d.ts +2 -0
  23. package/lib/types/client/achievements.d.ts +63 -0
  24. package/lib/types/client/action-context.d.ts +7 -0
  25. package/lib/types/client/artifact/ExportableGenuiBlock.d.ts +6 -0
  26. package/lib/types/client/artifact/create.d.ts +5 -0
  27. package/lib/types/client/artifact/download.d.ts +9 -0
  28. package/lib/types/client/artifact/html.d.ts +5 -0
  29. package/lib/types/client/artifact/index.d.ts +8 -0
  30. package/lib/types/client/artifact/json.d.ts +3 -0
  31. package/lib/types/client/artifact/parse.d.ts +3 -0
  32. package/lib/types/client/artifact/portability.d.ts +4 -0
  33. package/lib/types/client/artifact/standalone-theme.d.ts +2 -0
  34. package/lib/types/client/artifact/types.d.ts +33 -0
  35. package/lib/types/client/asset-echarts-core.d.ts +1 -0
  36. package/lib/types/client/asset-echarts.d.ts +17 -0
  37. package/lib/types/client/asset-loader.d.ts +33 -0
  38. package/lib/types/client/asset-mermaid.d.ts +1 -0
  39. package/lib/types/client/asset-three.d.ts +1 -0
  40. package/lib/types/client/blocks/advanced.d.ts +101 -0
  41. package/lib/types/client/blocks/basic.d.ts +22 -0
  42. package/lib/types/client/blocks/charts.d.ts +53 -0
  43. package/lib/types/client/blocks/checkbox.d.ts +17 -0
  44. package/lib/types/client/blocks/diagram/geometry.d.ts +73 -0
  45. package/lib/types/client/blocks/diagram/index.d.ts +5 -0
  46. package/lib/types/client/blocks/diagram/layout.d.ts +41 -0
  47. package/lib/types/client/blocks/diagram/theme.d.ts +37 -0
  48. package/lib/types/client/blocks/forms.d.ts +77 -0
  49. package/lib/types/client/blocks/image.d.ts +6 -0
  50. package/lib/types/client/blocks/render-node.d.ts +10 -0
  51. package/lib/types/client/blocks/state.d.ts +63 -0
  52. package/lib/types/client/blocks/svg.d.ts +4 -0
  53. package/lib/types/client/dom-fence.d.ts +30 -0
  54. package/lib/types/client/echarts-engine.d.ts +4 -0
  55. package/lib/types/client/echarts-lazy.d.ts +18 -0
  56. package/lib/types/client/embed.d.ts +10 -0
  57. package/lib/types/client/fence-render.d.ts +106 -0
  58. package/lib/types/client/gallery.d.ts +7 -0
  59. package/lib/types/client/genui-runtime/diagnostics.d.ts +18 -0
  60. package/lib/types/client/genui-runtime/index.d.ts +1 -0
  61. package/lib/types/client/genui-runtime/limits.d.ts +54 -0
  62. package/lib/types/client/genui-runtime/normalize.d.ts +15 -0
  63. package/lib/types/client/genui-runtime/schema.d.ts +87 -0
  64. package/lib/types/client/genui-runtime/value-utils.d.ts +18 -0
  65. package/lib/types/client/guard.d.ts +144 -0
  66. package/lib/types/client/i18n/en.d.ts +307 -0
  67. package/lib/types/client/i18n/index.d.ts +44 -0
  68. package/lib/types/client/i18n/runtime.d.ts +64 -0
  69. package/lib/types/client/i18n/zh.d.ts +8 -0
  70. package/lib/types/client/index.d.ts +36 -0
  71. package/lib/types/client/inline.d.ts +5 -0
  72. package/lib/types/client/interaction-store.d.ts +48 -0
  73. package/lib/types/client/mermaid-core.d.ts +8 -0
  74. package/lib/types/client/mermaid-lazy.d.ts +9 -0
  75. package/lib/types/client/mermaid-safe.d.ts +52 -0
  76. package/lib/types/client/panel-command.d.ts +34 -0
  77. package/lib/types/client/panel-store.d.ts +94 -0
  78. package/lib/types/client/panel.d.ts +18 -0
  79. package/lib/types/client/parse-partial.d.ts +63 -0
  80. package/lib/types/client/primitive-adapter.d.ts +4 -0
  81. package/lib/types/client/primitive-labels.d.ts +18 -0
  82. package/lib/types/client/safe-math.d.ts +43 -0
  83. package/lib/types/client/scene3d-core.d.ts +21 -0
  84. package/lib/types/client/scene3d-lazy.d.ts +8 -0
  85. package/lib/types/client/session-resolver.d.ts +8 -0
  86. package/lib/types/client/source-fence.d.ts +29 -0
  87. package/lib/types/client/spec.d.ts +709 -0
  88. package/lib/types/client/standalone/asset-loader.d.ts +2 -0
  89. package/lib/types/client/standalone/bootstrap-types.d.ts +9 -0
  90. package/lib/types/client/standalone/katex-style.d.ts +1 -0
  91. package/lib/types/client/standalone/primitive-adapter.d.ts +54 -0
  92. package/lib/types/client/standalone/runtime.d.ts +2 -0
  93. package/lib/types/client/submission-registry.d.ts +51 -0
  94. package/lib/types/client/svg-fence.d.ts +2 -0
  95. package/lib/types/client/table-details.d.ts +20 -0
  96. package/lib/types/client/templates.d.ts +41 -0
  97. package/lib/types/client/toolview.d.ts +7 -0
  98. package/lib/types/client/walk-spec.d.ts +3 -0
  99. package/lib/types/index.d.ts +1 -0
  100. package/lib/types/plugin/chart-contract.d.ts +9 -0
  101. package/lib/types/plugin/fence-feedback.d.ts +151 -0
  102. package/lib/types/plugin/genui-diagnostic.d.ts +13 -0
  103. package/lib/types/plugin/index.d.ts +35 -0
  104. package/lib/types/plugin/inline-content-diagnostic.d.ts +8 -0
  105. package/lib/types/plugin/invariant.d.ts +15 -0
  106. package/lib/types/plugin/tool.d.ts +27 -0
  107. package/lib/types/shared/fence-repair.d.ts +78 -0
  108. package/lib/types/shared/fence-resolve.d.ts +39 -0
  109. package/package.json +249 -4
  110. package/src/client/EChartNode.tsx +466 -0
  111. package/src/client/ErrorBoundary.tsx +67 -0
  112. package/src/client/GenuiBlock.module.css +2221 -0
  113. package/src/client/GenuiBlock.tsx +235 -0
  114. package/src/client/PlotBlock.module.css +171 -0
  115. package/src/client/PlotBlock.tsx +492 -0
  116. package/src/client/TemplateDrawer.module.css +152 -0
  117. package/src/client/TemplateDrawer.tsx +147 -0
  118. package/src/client/achievement-store.ts +151 -0
  119. package/src/client/achievement-toast.tsx +71 -0
  120. package/src/client/achievements.ts +160 -0
  121. package/src/client/action-context.ts +32 -0
  122. package/src/client/artifact/ArtifactExport.module.css +64 -0
  123. package/src/client/artifact/ExportableGenuiBlock.tsx +100 -0
  124. package/src/client/artifact/create.ts +69 -0
  125. package/src/client/artifact/download.ts +42 -0
  126. package/src/client/artifact/html.ts +157 -0
  127. package/src/client/artifact/index.ts +15 -0
  128. package/src/client/artifact/json.ts +6 -0
  129. package/src/client/artifact/parse.ts +32 -0
  130. package/src/client/artifact/portability.ts +47 -0
  131. package/src/client/artifact/standalone-theme.ts +94 -0
  132. package/src/client/artifact/types.ts +44 -0
  133. package/src/client/asset-echarts-core.ts +39 -0
  134. package/src/client/asset-echarts.ts +27 -0
  135. package/src/client/asset-loader.ts +96 -0
  136. package/src/client/asset-mermaid.ts +13 -0
  137. package/src/client/asset-three.ts +12 -0
  138. package/src/client/blocks/advanced.tsx +537 -0
  139. package/src/client/blocks/basic.tsx +121 -0
  140. package/src/client/blocks/charts.tsx +999 -0
  141. package/src/client/blocks/checkbox.tsx +61 -0
  142. package/src/client/blocks/diagram/geometry.ts +151 -0
  143. package/src/client/blocks/diagram/index.tsx +293 -0
  144. package/src/client/blocks/diagram/layout.ts +202 -0
  145. package/src/client/blocks/diagram/theme.ts +127 -0
  146. package/src/client/blocks/forms.tsx +531 -0
  147. package/src/client/blocks/image.tsx +28 -0
  148. package/src/client/blocks/render-node.tsx +494 -0
  149. package/src/client/blocks/state.ts +65 -0
  150. package/src/client/blocks/svg.tsx +66 -0
  151. package/src/client/dom-fence.tsx +1123 -0
  152. package/src/client/echarts-engine.ts +9 -0
  153. package/src/client/echarts-lazy.ts +41 -0
  154. package/src/client/embed.ts +19 -0
  155. package/src/client/fence-render.tsx +266 -0
  156. package/src/client/gallery.ts +215 -0
  157. package/src/client/genui-runtime/diagnostics.ts +165 -0
  158. package/src/client/genui-runtime/index.ts +1 -0
  159. package/src/client/genui-runtime/limits.ts +54 -0
  160. package/src/client/genui-runtime/normalize.ts +329 -0
  161. package/src/client/genui-runtime/schema.ts +352 -0
  162. package/src/client/genui-runtime/value-utils.ts +67 -0
  163. package/src/client/guard.ts +1965 -0
  164. package/src/client/i18n/en.ts +335 -0
  165. package/src/client/i18n/index.ts +125 -0
  166. package/src/client/i18n/runtime.ts +130 -0
  167. package/src/client/i18n/zh.ts +330 -0
  168. package/src/client/index.tsx +228 -0
  169. package/src/client/inline.ts +106 -0
  170. package/src/client/interaction-store.ts +127 -0
  171. package/src/client/mermaid-core.ts +158 -0
  172. package/src/client/mermaid-lazy.ts +31 -0
  173. package/src/client/mermaid-safe.ts +122 -0
  174. package/src/client/panel-command.ts +138 -0
  175. package/src/client/panel-store.ts +471 -0
  176. package/src/client/panel.tsx +287 -0
  177. package/src/client/parse-partial.ts +170 -0
  178. package/src/client/primitive-adapter.ts +13 -0
  179. package/src/client/primitive-labels.ts +55 -0
  180. package/src/client/safe-math.ts +298 -0
  181. package/src/client/scene3d-core.ts +195 -0
  182. package/src/client/scene3d-lazy.ts +26 -0
  183. package/src/client/session-resolver.ts +33 -0
  184. package/src/client/source-fence.ts +70 -0
  185. package/src/client/spec.ts +896 -0
  186. package/src/client/standalone/asset-loader.ts +9 -0
  187. package/src/client/standalone/bootstrap-types.ts +11 -0
  188. package/src/client/standalone/katex-style.ts +1 -0
  189. package/src/client/standalone/primitive-adapter.tsx +94 -0
  190. package/src/client/standalone/runtime.tsx +27 -0
  191. package/src/client/submission-registry.ts +150 -0
  192. package/src/client/svg-fence.tsx +39 -0
  193. package/src/client/table-details.ts +151 -0
  194. package/src/client/templates.ts +322 -0
  195. package/src/client/toolview.tsx +67 -0
  196. package/src/client/walk-spec.ts +43 -0
  197. package/src/css-modules.d.ts +5 -0
  198. package/src/index.ts +9 -0
  199. package/src/plugin/chart-contract.ts +13 -0
  200. package/src/plugin/fence-feedback.ts +655 -0
  201. package/src/plugin/genui-diagnostic.ts +112 -0
  202. package/src/plugin/index.ts +224 -0
  203. package/src/plugin/inline-content-diagnostic.ts +178 -0
  204. package/src/plugin/invariant.ts +30 -0
  205. package/src/plugin/node-shims.d.ts +31 -0
  206. package/src/plugin/tool.ts +424 -0
  207. package/src/shared/fence-repair.ts +536 -0
  208. package/src/shared/fence-resolve.ts +80 -0
  209. package/tsconfig.json +35 -0
  210. package/tsdown.config.ts +275 -0
@@ -0,0 +1,1123 @@
1
+ /**
2
+ * DOM render channel: pure-plugin fence rendering for pristine hosts.
3
+ *
4
+ * Stock DSH renders every fenced code block through the shared CodeBlock
5
+ * surface (stable class `md-code-block`, language label rendered as the
6
+ * banner's childless label div). This channel observes the conversation DOM,
7
+ * finds blocks labelled `dsh-ui` or complete `<dsh-ui>…</dsh-ui>` text spans,
8
+ * parses the raw fence body and mounts the plugin's own React tree next to
9
+ * the hidden host element:
10
+ *
11
+ * Fence discovery is **multi-surface** (issue #6): besides `md-code-block`,
12
+ * the channel also matches the deepsuite-style surfaces some host builds
13
+ * render instead (`.code-block` / `.code-block-small`), and — as the
14
+ * structural backstop — ANY element whose banner labels it `dsh-ui` and
15
+ * which contains a `<pre>` body. The only invariants are the language label
16
+ * (a leaf element with the exact text `dsh-ui`, outside the code body) and
17
+ * the `<pre>`. Desktop 0.11.0 instead emits a plain-text tag span for the
18
+ * same fence; the DOM channel recognizes that exact wrapper in assistant
19
+ * messages:
20
+ *
21
+ * - **Streaming takeover**: the channel takes over a dsh-ui block as soon as
22
+ * ONE finished component parses (the partial parser), and re-renders the
23
+ * root as the body grows — the UI assembles top-down while the reply
24
+ * streams, no settled marker required. A body with no finished component
25
+ * yet stays a stock code block (partial JSON must never look broken).
26
+ * - **Pre-paint surgery repair**: the host's React re-renders during
27
+ * streaming can wipe our foreign container or reset the hide. A repair
28
+ * pass in the MutationObserver microtask re-applies the surgery before
29
+ * paint (same pattern the annotation plugin proved on this host), and the
30
+ * 1s sweep is the backstop.
31
+ * - **Settled transition**: when `[data-streaming]` leaves the row, the
32
+ * mount re-renders with the stable source identity — the moment panels
33
+ * publish and durable state keys in (mirrors the registry channel's
34
+ * settled-source semantics; streaming renders are identity-less).
35
+ * - **Visible failure**: a settled block that stays a code block (malformed
36
+ * JSON, guard rejection, chart contract) mounts {@link FenceDiagnostic}
37
+ * above the stock block. Console-only reporting made the defect invisible to
38
+ * the person who wrote the fence (issue #158); the raw body is preserved.
39
+ * - Stable identity: the owning row's `data-chat-anchor-key` (session-stable,
40
+ * seq-derived) + the fence's ordinal among settled dsh-ui blocks in that
41
+ * row. `sourceId = dom:<anchor>:<ordinal>` feeds panel dedup and durable
42
+ * state.
43
+ * - Actions ride the plugin-owned GenuiActionContext provider: every tree
44
+ * this channel mounts is wrapped with a handler that relays
45
+ * `[genui-action]` through the scoped conversation send — no host plumbing.
46
+ * - Removal (branch switch, unload): each mount is unmounted with its root,
47
+ * and the stock block is restored.
48
+ *
49
+ * Security posture matches the registry channel: only code shipped in this
50
+ * plugin's browser bundle mounts React roots, the model can only author
51
+ * fence text, and unrepairable bodies remain visible in their host form.
52
+ */
53
+ import { Fragment, isValidElement, type Key, type ReactNode } from 'react'
54
+ import { createRoot, type Root } from 'react-dom/client'
55
+ import type { Context } from '@deepseek-ai/cordis'
56
+ import type {} from '@deepseek-ai/dsh-api-session-controller/client'
57
+ import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
58
+ import type { ChatNode, ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client'
59
+ import type { SessionId } from '@deepseek-ai/dsh-session/types'
60
+ import { GenuiActionContext, type GenuiActionHandler } from './action-context.ts'
61
+ import css from './GenuiBlock.module.css'
62
+ import { renderSvgFence } from './svg-fence.tsx'
63
+ import { repairFenceJson, trimToBalancedRoot } from '../shared/fence-repair.ts'
64
+ import { describeFenceFailure, FenceDiagnostic, renderResolvedFenceNode, type GenuiFenceContext } from './fence-render.tsx'
65
+ import { resolveViewedSessionId } from './session-resolver.ts'
66
+ import { validateCanonicalGenuiSpec } from './guard.ts'
67
+ import { diagnoseUnknownGenuiFields } from './genui-runtime/diagnostics.ts'
68
+ import { normalizeGenuiSpec } from './genui-runtime/normalize.ts'
69
+ import { sourceFencesOfAssistant, sourceLanguageAt } from './source-fence.ts'
70
+
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. */
77
+ const CODE_BLOCK_SELECTORS = '.md-code-block, .code-block, .code-block-small'
78
+ /** Marker attribute set on blocks this channel has taken over. */
79
+ const PROCESSED = 'data-genui-rendered'
80
+ /** The settled marker on AssistantMarkdown (absent = settled). */
81
+ const STREAMING = '[data-streaming]'
82
+ /** Container class for the plugin-owned root. */
83
+ const CONTAINER_CLASS = 'genui-dom-fence'
84
+ /** Container class for the visible diagnostic of an unrenderable fence. */
85
+ const DIAGNOSTIC_CLASS = 'genui-dom-fence-diagnostic'
86
+ /** Slow sweep interval: the observer catches everything, this is the 1s
87
+ * belt-and-braces pass (history loads, missed attribute batches). */
88
+ const SWEEP_MS = 1000
89
+
90
+ /** Max ancestors walked from a `<pre>` to its fence surface root (banner +
91
+ * pre holder). Most hosts put the pre directly under the surface; some wrap
92
+ * it in a content div. */
93
+ const SURFACE_HOPS = 4
94
+
95
+ /** Block-level content that never belongs to a code-block surface: a real
96
+ * fence surface is "banner chrome + ONE code body". An element that also
97
+ * contains paragraphs/lists/headings/tables (or several `<pre>` bodies) is a
98
+ * message-level container, not a fence — taking it over would hide the whole
99
+ * final answer (issue #19's residual variant of the issue #13 class). */
100
+ const BLOCK_CONTENT_SELECTOR = 'p, ul, ol, dl, table, h1, h2, h3, h4, h5, h6, blockquote, hr, img, figure'
101
+
102
+ /** Does this element look like a single code-block surface rather than a
103
+ * message container? The only allowed non-code content is banner chrome. */
104
+ function isPlausibleFenceSurface(candidate: Element): boolean {
105
+ const pres = candidate.querySelectorAll('pre')
106
+ if (pres.length > 1) return false
107
+ const pre = pres[0] ?? null
108
+ for (const el of candidate.querySelectorAll(BLOCK_CONTENT_SELECTOR)) {
109
+ if (pre !== null && pre.contains(el)) continue
110
+ return false
111
+ }
112
+ return true
113
+ }
114
+
115
+ /** `renderResolvedFenceNode` returns a bare Fragment for `panel:true` fences
116
+ * (the publisher renders nothing); every inline fence mounts a real tree.
117
+ * The DOM channel uses this to tell an empty container that was WIPED by a
118
+ * host re-render apart from an intentionally empty panel root. */
119
+ function isPanelRoot(node: ReactNode): boolean {
120
+ return isValidElement(node) && node.type === Fragment
121
+ }
122
+
123
+ /** Streaming placeholder gate: the body is a GenUI spec still arriving.
124
+ * Requires the shape of a spec (an object carrying items/type/title/panel) so
125
+ * a streaming ```json code block never gets a skeleton. */
126
+ function looksLikeGenuiInProgress(raw: string): boolean {
127
+ const text = raw.trimStart()
128
+ if (text.length < 8 || !text.startsWith('{')) return false
129
+ return /"(items|type|title|panel)"\s*:/.test(text)
130
+ }
131
+
132
+ /** Skeleton mounted while a fence body is still streaming and no component has
133
+ * finished yet. It is a REAL mounted tree, so the channel's rule "never hide
134
+ * the stock block without a mounted replacement" (issue #19) still holds: if
135
+ * the body never parses, the settle sweep unmounts the skeleton and the raw
136
+ * code block returns. */
137
+ function GenuiSkeleton() {
138
+ return (
139
+ <div className={css.skeleton} role="status" aria-label="正在生成界面">
140
+ <span className={css.skeletonTitle} />
141
+ <span className={css.skeletonBars}>
142
+ <span style={{ width: '32%' }} />
143
+ <span style={{ width: '52%' }} />
144
+ <span style={{ width: '24%' }} />
145
+ </span>
146
+ <span className={css.skeletonBlock} />
147
+ </div>
148
+ )
149
+ }
150
+
151
+ interface Mount {
152
+ root: Root
153
+ container: HTMLElement
154
+ block: HTMLElement
155
+ lastRaw: string
156
+ lastSettled: boolean
157
+ language: 'dsh-ui' | 'svg'
158
+ lastNode: ReactNode
159
+ /** True while this mount is the streaming skeleton (no component yet). */
160
+ skeleton: boolean
161
+ }
162
+
163
+ function isTextNode(node: Node): node is Text {
164
+ return node.nodeType === Node.TEXT_NODE
165
+ }
166
+
167
+ /** 读取 DSH Desktop 0.11.0 将 dsh-ui 围栏呈现为纯文本标签时的正文。 */
168
+ function tagTextBodyOf(block: Element): string | null {
169
+ 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
+ const text = block.textContent?.trim() ?? ''
173
+ const opening = '<dsh-ui>'
174
+ const closing = '</dsh-ui>'
175
+ if (!text.startsWith(opening) || !text.endsWith(closing)) return null
176
+ return text.slice(opening.length, -closing.length).trim()
177
+ }
178
+
179
+ /** The banner's language label: a leaf element whose text is exactly the
180
+ * lang. CodeBlock renders the label as a childless div; deepsuite-style
181
+ * surfaces use a span; the ONLY structural invariants across hosts are "a
182
+ * leaf element holds exactly the lang text" and "it lives outside the code
183
+ * body" — a fence whose code literally contains the text `dsh-ui` must not
184
+ * self-identify through its body. A container holding SEVERAL code blocks
185
+ * must not self-identify through a nested block's label either (issue #13:
186
+ * the shared markdown root was mistaken for a dsh-ui fence and hid the whole
187
+ * message, losing every other code block). */
188
+ function infostringOf(block: Element): 'dsh-ui' | 'svg' | null {
189
+ const pre = block.querySelector('pre')
190
+ for (const el of block.querySelectorAll('*')) {
191
+ if (el.childElementCount !== 0) continue
192
+ const lang = el.textContent?.trim()
193
+ if (lang !== 'dsh-ui' && lang !== 'svg') continue
194
+ if (pre !== null && pre.contains(el)) continue
195
+ // A leaf label that belongs to a NESTED known code surface is that
196
+ // surface's banner, not `block`'s own banner. Only accept labels whose
197
+ // nearest known surface is `block` itself (or none — unknown surfaces
198
+ // stay supported by the structural backstop).
199
+ const owner = el.closest(CODE_BLOCK_SELECTORS)
200
+ if (owner !== null && owner !== block) continue
201
+ return lang
202
+ }
203
+ return null
204
+ }
205
+
206
+ /**
207
+ * 已知**真实语言标识符**的闭集:语言 id 有限、由本插件维护,白名单列它是对的。
208
+ * 反例——宿主各语言里通用代码块标题的叫法(`Code` / `代码块` / «Код» / Código /
209
+ * Codice / Kode …)——是**无界集合**,白名单永远列不全:旧实现 `GENERIC_CODE_LABELS`
210
+ * 只列了英/中两种,宿主 locale 为其它语言时本地化标题被当成真语言,围栏永远不被
211
+ * 接管(issue #258)。因此判定反转:标签命中本集合才视为「带语言」,其余(空标签、
212
+ * 本地化通用词)一律视为「无语言」,由 {@link isGenericGenuiFence} 的内容校验把关——
213
+ * 同一份正文的渲染结果不因宿主语言而不同。
214
+ */
215
+ const KNOWN_LANGUAGE_LABELS = new Set([
216
+ // 插件自有语言
217
+ 'dsh-ui', 'svg',
218
+ // 数据 / 标记 / 纯文本
219
+ 'json', 'json5', 'yaml', 'yml', 'toml', 'ini', 'xml', 'html', 'css', 'scss', 'sass', 'less',
220
+ 'markdown', 'md', 'text', 'txt', 'plain', 'plaintext', 'log', 'console', 'diff', 'patch',
221
+ // 助手回复里常见的编程语言
222
+ 'js', 'jsx', 'javascript', 'ts', 'tsx', 'typescript', 'python', 'py', 'bash', 'sh', 'shell', 'zsh',
223
+ 'sql', 'graphql', 'gql', 'rust', 'go', 'golang', 'java', 'kotlin', 'kt', 'swift', 'scala', 'dart',
224
+ 'c', 'h', 'cpp', 'c++', 'cxx', 'cs', 'csharp', 'php', 'ruby', 'rb', 'perl', 'lua', 'r', 'matlab',
225
+ 'haskell', 'hs', 'elixir', 'ex', 'erlang', 'clojure', 'clj', 'groovy', 'objc', 'objective-c',
226
+ 'dockerfile', 'docker', 'makefile', 'make', 'cmake', 'protobuf', 'proto',
227
+ ])
228
+
229
+ /**
230
+ * Read a language that the host still exposes in its CodeBlock banner.
231
+ *
232
+ * 只有标签命中 {@link KNOWN_LANGUAGE_LABELS} 才返回语言;空标签与本地化通用词
233
+ * («Код» / Código / 代码块 …)是宿主的**呈现文案**、不是语义,一律返回 null——
234
+ * 此前它们会被当成真语言,连 ChatSnapshot 来源都被短路(issue #258)。
235
+ */
236
+ function domLanguageOf(block: Element): string | null {
237
+ const label = labelTextOf(block)
238
+ return label !== '' && KNOWN_LANGUAGE_LABELS.has(label.toLowerCase()) ? label : null
239
+ }
240
+
241
+ /** The banner label's raw text (empty while streaming — the host renders the
242
+ * language label only once the reply settles). Returns the first leaf
243
+ * outside the code body (banners always lead with the language), so a
244
+ * span-label host reads identically to the div-label host. */
245
+ function labelTextOf(block: Element): string {
246
+ const pre = block.querySelector('pre')
247
+ for (const el of block.querySelectorAll('*')) {
248
+ if (el.childElementCount !== 0) continue
249
+ if (pre !== null && pre.contains(el)) continue
250
+ return el.textContent?.trim() ?? ''
251
+ }
252
+ return ''
253
+ }
254
+
255
+ /**
256
+ * 仅在通用 CodeBlock 的内容经过**与带标签路径相同的标点级修复**后仍是合规 GenUI
257
+ * 规范时,恢复丢失的围栏语言。
258
+ *
259
+ * 宿主会隐去它不认识的语言(高亮器不支持 `dsh-ui`),于是同一份围栏在 DOM 里表现为
260
+ * 一个通用标题的普通代码块(标题随宿主 locale 本地化:`Code` / `代码块` / «Код» …);
261
+ * ChatSnapshot 的语言来源在部分行上不可用
262
+ * 时,内容识别是唯一出路。此前这里要求 `JSON.parse(raw)` 直接通过,导致**正文只差一个
263
+ * 未转义引号(tier-1 能修)的围栏永远不会被接管**——用户看到一个能渲染却始终是代码块的
264
+ * 围栏(真实会话 seq 40530:正文经 tier-1 修 14 处后可渲染,界面却停在代码块)。
265
+ * 结构级修复(tier-2)刻意不参与:内容识别是兜底,不该接管只是"长得像 JSON"的普通代码。
266
+
267
+ *
268
+ * @param block - 宿主提供的代码块元素。
269
+ * @param raw - 未修改的围栏正文。
270
+ * @returns 正文能按原有 GenUI 规范直接识别时返回 true。
271
+ */
272
+ function isGenericGenuiFence(block: Element, raw: string): boolean {
273
+ const row = block.closest<HTMLElement>(ASSISTANT_FLOW_ROW)
274
+ if (row === null || row.dataset.chatGroupPart === 'reasoning') return false
275
+ // domLanguageOf 已反转(#258):banner 是已知真实语言 ⇒ 不是通用块;空标签或
276
+ // 本地化通用词 ⇒ null,进入内容校验。这里不再要求标题命中任何白名单。
277
+ if (domLanguageOf(block) !== null || !block.querySelector('[data-code-block-banner]')) return false
278
+ const repaired = repairFenceJson(raw)
279
+ const candidate = repaired === null ? raw : repaired.text
280
+ let value: unknown
281
+ try {
282
+ value = JSON.parse(candidate)
283
+ } catch {
284
+ // 「合法 JSON + 尾部杂字符」(真实样本:模型把工具调用模板泄漏在 JSON 之后,
285
+ // 而且围栏没闭合)同样要能认出来:裁到平衡根值再试一次。只裁剪、不补全结构。
286
+ const trimmed = trimToBalancedRoot(candidate)
287
+ if (trimmed === null) return false
288
+ try {
289
+ value = JSON.parse(trimmed)
290
+ } catch {
291
+ return false
292
+ }
293
+ }
294
+ if (!validateCanonicalGenuiSpec(value).ok || diagnoseUnknownGenuiFields(value).length > 0) return false
295
+ return JSON.stringify(normalizeGenuiSpec(value).value) === JSON.stringify(value)
296
+ }
297
+
298
+ /** 读取宿主代码块或纯文本标签中的围栏正文。 */
299
+ function rawOf(block: Element): string {
300
+ const tagTextBody = tagTextBodyOf(block)
301
+ if (tagTextBody !== null) return tagTextBody
302
+ const pre = block.querySelector('pre')
303
+ if (pre === null) return ''
304
+ let text = ''
305
+ for (const node of pre.childNodes) {
306
+ if (isTextNode(node)) text += node.textContent ?? ''
307
+ else text += node.textContent ?? ''
308
+ }
309
+ return text
310
+ }
311
+
312
+ /** Settled gate: no streaming marker on any ancestor. */
313
+ function isSettled(block: Element): boolean {
314
+ return block.closest(STREAMING) === null
315
+ }
316
+
317
+ /** Walk up from a `<pre>` to its fence surface root — the ancestor that
318
+ * carries the banner label AND the pre. Returns null when no ancestor within
319
+ * `SURFACE_HOPS` (or the scope boundary) labels itself `dsh-ui`, or when the
320
+ * labeled ancestor is a message-level container rather than a code surface
321
+ * (see {@link isPlausibleFenceSurface}). */
322
+ function surfaceOf(pre: HTMLElement, scope: ParentNode = document): HTMLElement | null {
323
+ let el: HTMLElement | null = pre.parentElement
324
+ for (let hops = 0; el !== null && el !== scope && hops < SURFACE_HOPS; hops += 1, el = el.parentElement) {
325
+ if (infostringOf(el) === null) continue
326
+ if (!isPlausibleFenceSurface(el)) return null
327
+ return el
328
+ }
329
+ return null
330
+ }
331
+
332
+ /** The labeled-but-implausible ancestor `surfaceOf` just rejected, if any:
333
+ * diagnostics for the issue #19 guard so a skipped fence is never silent. */
334
+ function implausibleLabeledAncestorOf(pre: HTMLElement, scope: ParentNode = document): HTMLElement | null {
335
+ let el: HTMLElement | null = pre.parentElement
336
+ for (let hops = 0; el !== null && el !== scope && hops < SURFACE_HOPS; hops += 1, el = el.parentElement) {
337
+ if (infostringOf(el) === 'dsh-ui' && !isPlausibleFenceSurface(el)) return el
338
+ }
339
+ return null
340
+ }
341
+
342
+ /**
343
+ * Every dsh-ui fence surface or complete tag-text span under `scope`, in DOM order.
344
+ * Known surface classes first (cheap, ordered), then a structural sweep —
345
+ * every `<pre>` whose banner labels it `dsh-ui` — so a host with an
346
+ * unlisted surface shape still renders. The label + `<pre>` gates make the
347
+ * structural pass false-positive-free: a random code surface without the
348
+ * exact `dsh-ui` label is never taken over.
349
+ */
350
+ function findFenceCandidates(scope: ParentNode = document): HTMLElement[] {
351
+ const seen = new Set<HTMLElement>()
352
+ 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
359
+ 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)
364
+ continue
365
+ }
366
+ out.push(el)
367
+ seen.add(el)
368
+ }
369
+ for (const pre of scope.querySelectorAll<HTMLElement>('pre')) {
370
+ // `<pre>` bodies inside a known surface were already handled by the
371
+ // selector pass. Walking up from them again would climb PAST their own
372
+ // (non-dsh-ui or dsh-ui) surface into a shared container — e.g. a
373
+ // markdown root holding both a dsh-ui fence and a python block — and
374
+ // the backstop would mislabel that whole container as a fence, hiding
375
+ // 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)
378
+ if (surface === null) {
379
+ // Diagnose the issue #19 guard: a labeled ancestor that is NOT a code
380
+ // surface (prose/multiple code bodies) was skipped on purpose.
381
+ const rejected = implausibleLabeledAncestorOf(pre, scope)
382
+ if (rejected !== null) warnImplausibleSurface(rejected)
383
+ continue
384
+ }
385
+ if (seen.has(surface)) continue
386
+ // Host DOM drift diagnostic: the fence renders (structural backstop),
387
+ // but the surface class is unknown to this build — warn once per
388
+ // renderer install so future drift is never silent again.
389
+ if (!driftWarned) {
390
+ driftWarned = true
391
+ console.warn('[dsh-genui] 围栏表面类名未被已知选择器命中(宿主 DOM 漂移),已按 label+pre 结构识别 dsh-ui 围栏')
392
+ }
393
+ out.push(surface)
394
+ seen.add(surface)
395
+ }
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
399
+ out.push(span)
400
+ }
401
+ return out.sort((left, right) => left.compareDocumentPosition(right) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1)
402
+ }
403
+
404
+ /** One-time-per-install drift diagnostic flag (reset per install, so tests
405
+ * and hot re-installs each get a fresh warning budget). */
406
+ let driftWarned = false
407
+ /** A rejected surface gets one diagnostic; never log its conversation text. */
408
+ let plausibilityWarned = new WeakSet<Element>()
409
+ function warnImplausibleSurface(surface: Element): void {
410
+ if (plausibilityWarned.has(surface)) return
411
+ plausibilityWarned.add(surface)
412
+ const pres = surface.querySelectorAll('pre')
413
+ const tags = [...surface.querySelectorAll(BLOCK_CONTENT_SELECTOR)]
414
+ .filter(el => !el.closest('pre')).map(el => el.tagName.toLowerCase())
415
+ console.warn(`[dsh-genui] 跳过带 dsh-ui 标签但疑似消息容器的节点:pre=${pres.length}, outside-code=${[...new Set(tags)].join(',') || 'none'};保留原文,防止隐藏整条消息(issue #19)`)
416
+ }
417
+
418
+ /** Root factory seam (tests / tuning): the DOM channel creates one React root
419
+ * per taken-over fence through this indirection so mount-failure cleanup is
420
+ * reachable in jsdom without mocking the react-dom module. */
421
+ let domRootFactory: (container: HTMLElement) => Root = createRoot
422
+
423
+ /** Override the React root factory (tests / tuning). */
424
+ export function setDomRootFactory(factory: (container: HTMLElement) => Root): void {
425
+ domRootFactory = factory
426
+ }
427
+
428
+ /**
429
+ * The owning conversation row (stable per-message identity).
430
+ *
431
+ * The host renders `data-chat-anchor-key` from a React key that is OMITTED
432
+ * when the routed node's key is undefined — observed on Safari (and any
433
+ * fallback render path), where every fence row lacks the attribute while
434
+ * Chrome's identical page has it. Fences must not silently die there, so the
435
+ * lookup walks down a fallback chain and never gives up:
436
+ *
437
+ * 1. `[data-chat-anchor-key]` — the canonical stable row anchor;
438
+ * 2. `[data-chat-flow-key]` / `[data-chat-flow-kind]` — the same row div
439
+ * rendered by the host (both carry the routing key/kind, and the kind is
440
+ * a separate value that survives an undefined React key);
441
+ * 3. the code block itself — last resort; identity degrades to
442
+ * `dom:unknown:<ordinal>` (see `fenceIndexOf`/`contextOf`).
443
+ */
444
+ const FLOW_ROW = '[data-chat-flow-key], [data-chat-flow-kind]'
445
+ const ASSISTANT_FLOW_ROW = '[data-chat-flow-kind="assistant-step"]'
446
+ function rowOf(block: Element): Element {
447
+ return block.closest('[data-chat-anchor-key]') ?? block.closest(FLOW_ROW) ?? block
448
+ }
449
+
450
+ /** Return a stable one-based ordinal among settled GenUI fences in this row. */
451
+ function fenceIndexOf(ctx: Context, row: Element, block: Element, sourceLanguage: (block: Element) => string | null | undefined = candidate => sourceLanguageOf(ctx, candidate)): number {
452
+ if (!row.matches(ASSISTANT_FLOW_ROW) || row.getAttribute('data-chat-anchor-key') === null) {
453
+ const scope = row.getAttribute('data-chat-anchor-key') === null ? document : row
454
+ let fallbackIndex = 0
455
+ for (const candidate of findFenceCandidates(scope)) {
456
+ if (candidate.closest(STREAMING) !== null) continue
457
+ const language = tagTextBodyOf(candidate) !== null ? 'dsh-ui' : domLanguageOf(candidate) ?? sourceLanguage(candidate)
458
+ if (language !== 'dsh-ui' && !(language === undefined && isGenericGenuiFence(candidate, rawOf(candidate)))) continue
459
+ fallbackIndex += 1
460
+ if (candidate === block) return fallbackIndex
461
+ }
462
+ return fallbackIndex + 1
463
+ }
464
+ let index = 0
465
+ for (const candidate of findFenceCandidates(row)) {
466
+ if (candidate.closest(STREAMING) !== null) continue
467
+ if (candidate.closest(ASSISTANT_FLOW_ROW) !== row) continue
468
+ if (candidate.closest('[data-chat-group-part="reasoning"]') !== null) continue
469
+ const language = tagTextBodyOf(candidate) !== null ? 'dsh-ui' : domLanguageOf(candidate) ?? sourceLanguage(candidate)
470
+ if (language !== 'dsh-ui' && !(language === undefined && isGenericGenuiFence(candidate, rawOf(candidate)))) continue
471
+ index += 1
472
+ if (candidate === block) return index
473
+ }
474
+ return index + 1
475
+ }
476
+
477
+ /** Return outer host Markdown code surfaces in one assistant row's DOM order. */
478
+ 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
481
+ if (candidate.closest(`.${CONTAINER_CLASS}, .${DIAGNOSTIC_CLASS}, [data-genui], [data-genui-svg-fence]`) !== null) return false
482
+ 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
+ if (candidate.closest(ASSISTANT_FLOW_ROW) !== row) return false
484
+ return isPlausibleFenceSurface(candidate) && candidate.querySelector('pre') !== null
485
+ })
486
+ }
487
+
488
+ /**
489
+ * Resolve source language for the host code surface at its assistant-row ordinal.
490
+ *
491
+ * @param ctx - active plugin context
492
+ * @param block - host Markdown CodeBlock element
493
+ * @returns source language, null for an unlabelled fence, or undefined when unavailable
494
+ */
495
+ export function sourceLanguageOf(ctx: Context, block: Element): string | null | undefined {
496
+ const row = block.closest<HTMLElement>(`${ASSISTANT_FLOW_ROW}[data-chat-node-key]`)
497
+ if (row === null || row.dataset.chatGroupPart === 'reasoning') return undefined
498
+ const nodeKey = row.dataset.chatNodeKey
499
+ const index = hostFenceIndexOf(row, block)
500
+ const sessionId = sessionIdOfForSource(ctx)
501
+ if (!nodeKey || index < 0 || sessionId === undefined) return undefined
502
+ const chat = chatSourceOf(ctx, sessionId)?.getSnapshot()
503
+ return sourceLanguageAt(chat, nodeKey, index)
504
+ }
505
+
506
+ /** 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 } {
508
+ const stableLanguages = new WeakMap<Element, { sessionId: SessionId; nodeKey: string; language: string | null }>()
509
+ let sweepLanguages = new Map<Element, string | null | undefined>()
510
+ let parsedNodes = new Map<string, ReturnType<typeof sourceFencesOfAssistant>>()
511
+ let sessionId: SessionId | undefined
512
+ let chat: ChatSnapshot | undefined
513
+ let chatRead = false
514
+
515
+ return {
516
+ beginSweep() {
517
+ sweepLanguages = new Map()
518
+ parsedNodes = new Map()
519
+ sessionId = undefined
520
+ chat = undefined
521
+ chatRead = false
522
+ },
523
+ get(block) {
524
+ if (sweepLanguages.has(block)) return sweepLanguages.get(block)
525
+ const row = block.closest<HTMLElement>(`${ASSISTANT_FLOW_ROW}[data-chat-node-key]`)
526
+ if (row === null || row.dataset.chatGroupPart === 'reasoning') return undefined
527
+ const nodeKey = row.dataset.chatNodeKey
528
+ const activeSessionId = sessionIdOfForSource(ctx)
529
+ if (!nodeKey || activeSessionId === undefined) return undefined
530
+
531
+ const stable = stableLanguages.get(block)
532
+ if (stable?.sessionId === activeSessionId && stable.nodeKey === nodeKey) {
533
+ sweepLanguages.set(block, stable.language)
534
+ return stable.language
535
+ }
536
+ if (!chatRead || sessionId !== activeSessionId) {
537
+ sessionId = activeSessionId
538
+ chat = chatSourceOf(ctx, activeSessionId)?.getSnapshot()
539
+ chatRead = true
540
+ }
541
+ const node = chat?.nodes.get(nodeKey)
542
+ if (node?.kind !== 'assistant-step') return undefined
543
+ const assistantNode = node as ChatNode<'assistant-step'>
544
+ let fences = parsedNodes.get(nodeKey)
545
+ if (fences === undefined) {
546
+ fences = sourceFencesOfAssistant(assistantNode.data.blocks)
547
+ parsedNodes.set(nodeKey, fences)
548
+ }
549
+ const index = hostFenceIndexOf(row, block)
550
+ if (index < 0) return undefined
551
+ const fence = fences[index]
552
+ const language = fence?.lang
553
+ if (fence !== undefined && fence.openingLineComplete) {
554
+ stableLanguages.set(block, { sessionId: activeSessionId, nodeKey, language: fence.lang })
555
+ }
556
+ sweepLanguages.set(block, language)
557
+ return language
558
+ },
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Resolve a host CodeBlock's zero-based ordinal among assistant Markdown surfaces.
564
+ *
565
+ * @param row - owning assistant row
566
+ * @param block - host Markdown CodeBlock element
567
+ * @returns source-order ordinal or -1 when the element is not a host code surface
568
+ */
569
+ export function hostFenceIndexOf(row: Element, block: Element): number {
570
+ return hostFenceBlocksOf(row).indexOf(block as HTMLElement)
571
+ }
572
+
573
+ /** Read the currently viewed session for source Markdown lookup. */
574
+ function sessionIdOfForSource(ctx: Context): SessionId | undefined {
575
+ return resolveViewedSessionId(ctx.sessions.list.getSnapshot())
576
+ }
577
+
578
+ /** Read uiConversation as an optional service so Cordis does not require a hard inject. */
579
+ function uiConversationOf(ctx: Context): Context['uiConversation'] | undefined {
580
+ if (typeof ctx.get !== 'function') return undefined
581
+ return ctx.get('uiConversation', false) as Context['uiConversation'] | undefined
582
+ }
583
+
584
+ /** Read the current ChatSnapshot source without interrupting sweeps during session transitions. */
585
+ function chatSourceOf(ctx: Context, sessionId: SessionId): { getSnapshot: () => ChatSnapshot | undefined; subscribe: (listener: () => void) => (() => void) | undefined } | undefined {
586
+ try {
587
+ const source = uiConversationOf(ctx)?.binding(sessionId).target('chat')
588
+ if (source === undefined) return undefined
589
+ return {
590
+ getSnapshot: () => {
591
+ try {
592
+ return source.getSnapshot()
593
+ } catch {
594
+ return undefined
595
+ }
596
+ },
597
+ subscribe: listener => {
598
+ try {
599
+ return source.subscribe(listener)
600
+ } catch {
601
+ return undefined
602
+ }
603
+ },
604
+ }
605
+ } catch {
606
+ return undefined
607
+ }
608
+ }
609
+
610
+ /**
611
+ * messageSeq estimate from the row's anchor key.
612
+ *
613
+ * The host's context key is `<kindLen>:<kind><id>` (e.g.
614
+ * `14:assistant-step3:0`); the id of an assistant step is `<turn>:<step>` —
615
+ * the ONLY per-message monotonic counter the host exposes in the DOM. Turn
616
+ * and step strictly increase with message order, so a turn-based seq keeps
617
+ * growing across page reloads: the panel store's persisted replay barrier
618
+ * (hydration: replays at/below the persisted max seq are dead) depends on
619
+ * this monotonicity. Without it every assistant step yields the SAME
620
+ * constant (the kind-length prefix), so after a refresh the barrier equals
621
+ * that constant and silently rejects every new panel fence (issue #4).
622
+ *
623
+ * Fallback (non-assistant rows, anchor-less Safari rows): the row's
624
+ * document-order index among chat rows — monotonic within the current
625
+ * render window, degraded across reloads.
626
+ */
627
+ function anchorSeqOf(row: Element): number {
628
+ const key = row.getAttribute('data-chat-anchor-key') ?? ''
629
+ const turnStep = /assistant-step(\d+):(\d+)$/.exec(key)
630
+ if (turnStep !== null) {
631
+ const turn = Number(turnStep[1])
632
+ const step = Number(turnStep[2])
633
+ if (Number.isFinite(turn) && Number.isFinite(step)) return turn * 1000 + step
634
+ }
635
+ const rows = document.querySelectorAll(`[data-chat-anchor-key], ${FLOW_ROW}`)
636
+ for (let i = 0; i < rows.length; i += 1) {
637
+ if (rows[i] === row) return i
638
+ }
639
+ return 0
640
+ }
641
+
642
+ /**
643
+ * Install the DOM render channel. Returns a disposer that restores every
644
+ * taken-over block and disconnects the observers.
645
+ *
646
+ * @param ctx - the client context (sessions service for the current session).
647
+ * @param sendAction - plugin-owned relay: (sessionId, action, payload) → the
648
+ * scoped conversation send carrying the `[genui-action]` prompt.
649
+ */
650
+ export function installDomFenceRenderer(
651
+ ctx: Context,
652
+ sendAction: (sessionId: SessionId, action: string, payload: Record<string, unknown>) => void,
653
+ ): () => void {
654
+ if (typeof document === 'undefined') return () => {}
655
+ driftWarned = false
656
+ plausibilityWarned = new WeakSet<Element>()
657
+ const mounts = new Map<HTMLElement, Mount>()
658
+ // Blocks we could not render: the stock code block stays visible AND a
659
+ // visible diagnostic explains why (issue #158). Kept apart from `mounts`
660
+ // because a diagnosed block is never hidden.
661
+ const diagnostics = new Map<HTMLElement, { container: HTMLElement; root: Root; raw: string }>()
662
+ let disposed = false
663
+ let rafId: number | null = null
664
+ let activeChatSession: SessionId | undefined
665
+ let unsubscribeChat: (() => void) | undefined
666
+ const sourceLanguages = createSourceLanguageResolver(ctx)
667
+
668
+ const sessionIdOf = (): SessionId | undefined => {
669
+ try {
670
+ return resolveViewedSessionId(ctx.sessions.list.getSnapshot())
671
+ } catch {
672
+ return undefined
673
+ }
674
+ }
675
+
676
+ /** Retry ChatSnapshot subscription while the active session binding is unavailable. */
677
+ function syncChatSubscription(sessionId: SessionId | undefined): void {
678
+ if (sessionId !== activeChatSession) {
679
+ unsubscribeChat?.()
680
+ unsubscribeChat = undefined
681
+ activeChatSession = sessionId
682
+ }
683
+ if (sessionId !== undefined && unsubscribeChat === undefined) {
684
+ unsubscribeChat = chatSourceOf(ctx, sessionId)?.subscribe(schedule)
685
+ }
686
+ }
687
+
688
+ /** Render context for a block: session always; the stable source identity
689
+ * 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 } {
692
+ if (settled && row.getAttribute('data-chat-anchor-key') === null) {
693
+ // Safari / fallback render path: the host omitted the row anchor (the
694
+ // attribute is a React key that React drops when undefined). Fences
695
+ // still render with the degraded `dom:unknown:N` identity — warn once
696
+ // per block so the degraded path is visible in the console.
697
+ warnOnce(block, 'no [data-chat-anchor-key] ancestor for a dsh-ui fence (host render path without row anchor — e.g. Safari); using fallback identity dom:unknown:N')
698
+ }
699
+ const fenceIndex = fenceIndexOf(ctx, row, block, sourceLanguages.get)
700
+ const anchorKey = row.getAttribute('data-chat-anchor-key') ?? 'unknown'
701
+ const key = `dom:${anchorKey}:${fenceIndex}` as Key
702
+ const sessionId = sessionIdOf()
703
+ const context: GenuiFenceContext = {
704
+ ...(sessionId === undefined ? {} : { sessionId }),
705
+ ...(settled ? { source: { id: key as string, order: [anchorSeqOf(row), 0, fenceIndex] as const } } : {}),
706
+ }
707
+ return { key, context }
708
+ }
709
+
710
+ function unmountBlock(block: HTMLElement): void {
711
+ const mount = mounts.get(block)
712
+ if (mount === undefined) return
713
+ mounts.delete(block)
714
+ mount.root.unmount()
715
+ mount.container.remove()
716
+ block.style.display = ''
717
+ block.removeAttribute(PROCESSED)
718
+ clearDiagnostic(block)
719
+ }
720
+
721
+ /** Drop the diagnostic mounted for one block (renderable again, or gone). */
722
+ function clearDiagnostic(block: HTMLElement): void {
723
+ const diagnostic = diagnostics.get(block)
724
+ if (diagnostic === undefined) return
725
+ diagnostics.delete(block)
726
+ try {
727
+ diagnostic.root.unmount()
728
+ } catch {
729
+ // The host's re-render already invalidated the tree; removing the
730
+ // container below is the recovery.
731
+ }
732
+ diagnostic.container.remove()
733
+ }
734
+
735
+ /**
736
+ * Mount (or refresh) the visible diagnostic that explains why a settled
737
+ * dsh-ui fence stays a code block. Idempotent per block: the 1s sweep and
738
+ * every mutation pass re-enter here, and the strip must neither duplicate
739
+ * nor vanish when the host re-renders its message (issues #158/#172).
740
+ *
741
+ * This only ever creates/updates the strip and re-attaches it; it never
742
+ * re-renders on an empty container, because React commits asynchronously —
743
+ * a synchronous "it looks wiped" rebuild inside the mutation callback would
744
+ * re-trigger the observer forever (the sweep owns that recovery).
745
+ */
746
+ function renderDiagnostic(block: HTMLElement, raw: string): void {
747
+ // Nothing to report (renderable, empty, or still streaming): never leave
748
+ // an empty strip behind, and drop one that is no longer true.
749
+ if (describeFenceFailure(raw, { settled: true }) === null) {
750
+ clearDiagnostic(block)
751
+ return
752
+ }
753
+ const existing = diagnostics.get(block)
754
+ if (existing !== undefined) {
755
+ // A host re-render can detach our container without removing the block:
756
+ // re-attach before paint; a changed body rebuilds the strip.
757
+ if (existing.container.parentElement !== block.parentElement || existing.container.nextElementSibling !== block) {
758
+ block.before(existing.container)
759
+ }
760
+ if (existing.raw === raw) return
761
+ clearDiagnostic(block)
762
+ }
763
+ const container = document.createElement('div')
764
+ container.className = DIAGNOSTIC_CLASS
765
+ block.before(container)
766
+ let root: Root
767
+ try {
768
+ root = domRootFactory(container)
769
+ root.render(<FenceDiagnostic raw={raw} settled />)
770
+ } catch (error) {
771
+ container.remove()
772
+ warnOnce(block, `failed to mount the dsh-ui diagnostic (${error instanceof Error ? error.message : String(error)}); keeping the stock code block visible`)
773
+ return
774
+ }
775
+ diagnostics.set(block, { container, root, raw })
776
+ }
777
+
778
+ /**
779
+ * Sweep-only recovery for a diagnostic whose DOM the host threw away
780
+ * without removing the block (a re-render can empty our container). Runs on
781
+ * the rAF-scheduled sweep, never inside the mutation callback, so a commit
782
+ * that lands a frame later cannot re-trigger it in a loop.
783
+ */
784
+ function rebuildWipedDiagnostic(block: HTMLElement, raw: string): void {
785
+ const existing = diagnostics.get(block)
786
+ if (existing === undefined || existing.container.childElementCount > 0) return
787
+ clearDiagnostic(block)
788
+ renderDiagnostic(block, raw)
789
+ }
790
+
791
+ /** One-time-per-block diagnostics: silent returns must be diagnosable
792
+ * (the 1s sweep would otherwise spam the console every pass). */
793
+ const warned = new WeakSet<Element>()
794
+ function warnOnce(block: Element, message: string): void {
795
+ if (warned.has(block)) return
796
+ warned.add(block)
797
+ console.warn(`[dsh-genui] ${message}`)
798
+ }
799
+
800
+ /**
801
+ * 通过当前宿主会话发送 DOM 通道 action。
802
+ *
803
+ * @param block - 触发 action 的围栏元素
804
+ * @param action - 组件声明的 action 名称
805
+ * @param payload - 组件产生的交互数据
806
+ */
807
+ function sendActionForBlock(block: Element, action: string, payload: Record<string, unknown>): void {
808
+ const sessionId = sessionIdOf()
809
+ if (sessionId === undefined) {
810
+ warnOnce(block, `cannot resolve the viewed session; action "${action}" was not sent`)
811
+ return
812
+ }
813
+ sendAction(sessionId, action, payload)
814
+ }
815
+
816
+ function renderBlock(block: HTMLElement): void {
817
+ if (block.hasAttribute(PROCESSED)) return
818
+ const row = rowOf(block)
819
+ 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
823
+ const raw = rawOf(block)
824
+ // DSH 0.1.7-alpha.2 会在最终 DOM 隐去不支持高亮的语言;公开 ChatSnapshot 的原始 Markdown 是 language 来源。
825
+ // 内容识别只在 source 暂不可用且 assistant 已结束时兜底,不覆盖已确认的 language 或无 language fence。
826
+ const genericGenui = language === undefined && settled && isGenericGenuiFence(block, raw)
827
+ if (language !== 'dsh-ui' && language !== 'svg' && !genericGenui) return
828
+ if (!settled && language !== 'dsh-ui') return
829
+ if (raw.trim() === '') {
830
+ if (settled) warnOnce(block, `settled ${language ?? 'dsh-ui'} fence has an empty body; keeping the code block`)
831
+ return
832
+ }
833
+ const { key, context } = contextOf(row, block, settled)
834
+ const acceptedLanguage = language === 'svg' ? 'svg' : 'dsh-ui'
835
+ const node: ReactNode | null = acceptedLanguage === 'svg' ? renderSvgFence(raw, key) : renderResolvedFenceNode(raw, key, context)
836
+ // Null = no finished component yet (streaming half) or unrepairable: the
837
+ // stock code block stays visible. A settled unrepairable body also gets a
838
+ // VISIBLE diagnostic — console-only reporting left the defect invisible
839
+ // to the author (issues #158/#172).
840
+ let payload = node
841
+ if (payload === null) {
842
+ if (settled || !looksLikeGenuiInProgress(raw)) {
843
+ if (settled) {
844
+ renderDiagnostic(block, raw)
845
+ warnOnce(block, 'settled dsh-ui fence body does not parse; keeping the code block')
846
+ }
847
+ return
848
+ }
849
+ // Streaming, spec-shaped, nothing renderable yet: show the skeleton
850
+ // rather than a wall of half-written JSON.
851
+ payload = <GenuiSkeleton />
852
+ }
853
+ clearDiagnostic(block)
854
+ // Mount FIRST, hide AFTER (issue #19): the stock block is only ever
855
+ // hidden once a successfully mounted replacement stands next to it. A
856
+ // mount failure leaves the original code block untouched — the final
857
+ // answer can never be blanked by a half-completed takeover.
858
+ const container = document.createElement('div')
859
+ container.className = CONTAINER_CLASS
860
+ block.after(container)
861
+ let root: Root
862
+ try {
863
+ root = domRootFactory(container)
864
+ } catch (error) {
865
+ container.remove()
866
+ warnOnce(block, `failed to create a React root for a dsh-ui fence (${error instanceof Error ? error.message : String(error)}); keeping the stock code block visible`)
867
+ return
868
+ }
869
+ try {
870
+ const handler: GenuiActionHandler = (action, payload) => sendActionForBlock(block, action, payload)
871
+ root.render(<GenuiActionContext.Provider value={handler}>{payload}</GenuiActionContext.Provider>)
872
+ } catch (error) {
873
+ try {
874
+ root.unmount()
875
+ } catch {
876
+ // Best-effort cleanup; removing the container below restores the DOM.
877
+ }
878
+ container.remove()
879
+ warnOnce(block, `failed to mount a dsh-ui fence (${error instanceof Error ? error.message : String(error)}); keeping the stock code block visible`)
880
+ return
881
+ }
882
+ block.style.display = 'none'
883
+ block.setAttribute(PROCESSED, '')
884
+ mounts.set(block, { root, container, block, lastRaw: raw, lastSettled: settled, language: acceptedLanguage, lastNode: payload, skeleton: node === null })
885
+ }
886
+
887
+ /** Pre-paint repair: the host's React re-renders during streaming can wipe
888
+ * our foreign container or reset the hide. Re-apply the surgery in the
889
+ * observer microtask (before paint) so raw JSON never flashes between
890
+ * chunks; the rAF sweep re-renders React state at its own pace. */
891
+ function repairSurgery(): void {
892
+ // Diagnostics are plugin-owned DOM too: a host re-render that detaches or
893
+ // empties their container must be repaired before paint.
894
+ for (const [block, diagnostic] of Array.from(diagnostics)) {
895
+ if (!block.isConnected) {
896
+ clearDiagnostic(block)
897
+ continue
898
+ }
899
+ renderDiagnostic(block, diagnostic.raw)
900
+ }
901
+ for (const mount of Array.from(mounts.values())) {
902
+ const block = mount.block
903
+ // The host replaced the row: the stock block is gone but our foreign
904
+ // container may still be attached. Drop the mount NOW (removes the
905
+ // orphan container) instead of waiting for the sweep — the new block
906
+ // will be taken over by the sweep's discovery pass.
907
+ if (!block.isConnected) {
908
+ if (mount.container.isConnected) unmountBlock(block)
909
+ continue
910
+ }
911
+ // Re-attach the container BEFORE re-hiding (issue #19: never hide the
912
+ // original while no mounted replacement stands next to it).
913
+ if (mount.container.parentElement !== block.parentElement
914
+ || mount.container.previousElementSibling !== block) {
915
+ block.after(mount.container)
916
+ }
917
+ if (!mount.container.isConnected) {
918
+ // Insertion failed (pathological host re-parent): surrender the
919
+ // takeover and keep the raw stock block visible rather than leaving
920
+ // it hidden with no replacement.
921
+ block.style.display = ''
922
+ block.removeAttribute(PROCESSED)
923
+ mounts.delete(block)
924
+ try {
925
+ mount.root.unmount()
926
+ } catch {
927
+ // Best-effort; the detached container gets removed below.
928
+ }
929
+ mount.container.remove()
930
+ warnOnce(block, 'dsh-ui replacement container could not be re-attached after a host re-render; restoring the stock code block')
931
+ continue
932
+ }
933
+ if (block.style.display !== 'none') block.style.display = 'none'
934
+ if (!block.hasAttribute(PROCESSED)) block.setAttribute(PROCESSED, '')
935
+ }
936
+ }
937
+
938
+ /** 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. */
941
+ function sweep(): void {
942
+ if (disposed) return
943
+ sourceLanguages.beginSweep()
944
+ const sessionId = sessionIdOf()
945
+ syncChatSubscription(sessionId)
946
+ for (const [block, mount] of mounts) {
947
+ if (!block.isConnected) {
948
+ unmountBlock(block)
949
+ continue
950
+ }
951
+ const raw = rawOf(block)
952
+ const settled = isSettled(block)
953
+ const domLanguage = tagTextBodyOf(block) !== null ? 'dsh-ui' : domLanguageOf(block)
954
+ const sourceLanguage = domLanguage === null ? sourceLanguages.get(block) : undefined
955
+ const language = domLanguage ?? sourceLanguage
956
+ const validGenui = language === 'dsh-ui'
957
+ || (language === undefined && settled && isGenericGenuiFence(block, raw))
958
+ if (mount.language === 'svg' && language !== 'svg') {
959
+ unmountBlock(block)
960
+ continue
961
+ }
962
+ if (mount.language === 'dsh-ui' && !validGenui) {
963
+ unmountBlock(block)
964
+ continue
965
+ }
966
+ // A host re-render can also wipe the CONTENT of our container while
967
+ // leaving the node in place. An inline mount whose container came back
968
+ // empty (and was not empty by design — panel roots are) must be
969
+ // re-rendered, otherwise the block stays hidden behind an empty box.
970
+ const contentWiped = !isPanelRoot(mount.lastNode) && mount.container.childElementCount === 0
971
+ if (mount.lastRaw !== raw || mount.lastSettled !== settled || contentWiped) {
972
+ const anchor = rowOf(block)
973
+ const { key, context } = contextOf(anchor, block, settled)
974
+ const node = mount.language === 'svg' ? renderSvgFence(raw, key) : renderResolvedFenceNode(raw, key, context)
975
+ if (node === null) {
976
+ if (mount.skeleton && !settled) {
977
+ // Still streaming and still incomplete: keep the skeleton mounted
978
+ // (no React re-render needed) and wait for the next chunk.
979
+ mount.lastRaw = raw
980
+ mount.lastSettled = settled
981
+ continue
982
+ }
983
+ // Settled, or no longer spec-shaped: restore the raw code block.
984
+ unmountBlock(block)
985
+ continue
986
+ }
987
+ if (contentWiped) {
988
+ // The old root's fiber bookkeeping points at children the host
989
+ // already removed — re-rendering it can throw removeChild errors
990
+ // on missing nodes. Rebuild the mount in place: fresh container +
991
+ // fresh root, block re-hidden only after the replacement exists.
992
+ try {
993
+ mount.root.unmount()
994
+ } catch {
995
+ // The host's wipe already invalidated the tree; the fresh root
996
+ // below is the recovery, not the old one.
997
+ }
998
+ const fresh = document.createElement('div')
999
+ fresh.className = CONTAINER_CLASS
1000
+ mount.container.remove()
1001
+ block.after(fresh)
1002
+ try {
1003
+ const freshRoot = domRootFactory(fresh)
1004
+ const handler: GenuiActionHandler = (action, payload) => sendActionForBlock(block, action, payload)
1005
+ freshRoot.render(<GenuiActionContext.Provider value={handler}>{node}</GenuiActionContext.Provider>)
1006
+ mount.root = freshRoot
1007
+ mount.container = fresh
1008
+ } catch (error) {
1009
+ // Never leave the stock block hidden behind a broken root:
1010
+ // restore the raw code block and drop the mount (issue #19).
1011
+ fresh.remove()
1012
+ block.style.display = ''
1013
+ block.removeAttribute(PROCESSED)
1014
+ mounts.delete(block)
1015
+ warnOnce(block, `failed to rebuild a wiped dsh-ui mount (${error instanceof Error ? error.message : String(error)}); restoring the stock code block`)
1016
+ continue
1017
+ }
1018
+ } else {
1019
+ try {
1020
+ mount.root.render(<GenuiActionContext.Provider value={(action, payload) => sendActionForBlock(block, action, payload)}>{node}</GenuiActionContext.Provider>)
1021
+ } catch (error) {
1022
+ // Never leave the stock block hidden behind a broken root: restore
1023
+ // the raw code block and drop the mount (issue #19).
1024
+ unmountBlock(block)
1025
+ warnOnce(block, `failed to re-render a dsh-ui fence (${error instanceof Error ? error.message : String(error)}); restoring the stock code block`)
1026
+ continue
1027
+ }
1028
+ }
1029
+ mount.lastRaw = raw
1030
+ mount.lastSettled = settled
1031
+ mount.lastNode = node
1032
+ mount.skeleton = false
1033
+ }
1034
+ }
1035
+ repairSurgery()
1036
+ // Diagnostics for blocks that are gone or were taken over must go with
1037
+ // them; one whose DOM the host wiped is rebuilt here (sweep cadence, never
1038
+ // inside the mutation callback).
1039
+ for (const [block, diagnostic] of Array.from(diagnostics)) {
1040
+ if (!block.isConnected || block.hasAttribute(PROCESSED)) {
1041
+ clearDiagnostic(block)
1042
+ continue
1043
+ }
1044
+ // Same re-verification the takeover path does: a settled block whose
1045
+ // label is no longer dsh-ui is somebody else's fence, so our explanation
1046
+ // would be about the wrong block.
1047
+ 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') {
1051
+ clearDiagnostic(block)
1052
+ continue
1053
+ }
1054
+ }
1055
+ rebuildWipedDiagnostic(block, diagnostic.raw)
1056
+ }
1057
+ for (const block of findFenceCandidates()) {
1058
+ renderBlock(block)
1059
+ }
1060
+ }
1061
+
1062
+ const schedule = (): void => {
1063
+ if (disposed || rafId !== null) return
1064
+ rafId = requestAnimationFrame(() => {
1065
+ rafId = null
1066
+ if (disposed) return
1067
+ sweep()
1068
+ })
1069
+ }
1070
+
1071
+ const unsubscribeSessions = typeof ctx.sessions.list.subscribe === 'function'
1072
+ ? ctx.sessions.list.subscribe(schedule)
1073
+ : undefined
1074
+
1075
+ const observer = new MutationObserver(records => {
1076
+ // Restore detached roots before paint, retaining input and pending actions.
1077
+ // The latest removal owns the current tree if several commits were batched.
1078
+ for (const record of [...records].reverse()) {
1079
+ if (record.removedNodes.length === 0 || record.target.childNodes.length > 0) continue
1080
+ const target = record.target
1081
+ const mount = [...mounts.values()].find(candidate => candidate.container === target)
1082
+ if (mount !== undefined) {
1083
+ if (!mount.block.isConnected || isPanelRoot(mount.lastNode)) continue
1084
+ mount.container.append(...record.removedNodes)
1085
+ continue
1086
+ }
1087
+ // The same surgery for a visible diagnostic the host emptied: re-append
1088
+ // its own nodes instead of leaving the author without an explanation.
1089
+ const diagnostic = [...diagnostics.values()].find(candidate => candidate.container === target)
1090
+ if (diagnostic !== undefined) diagnostic.container.append(...record.removedNodes)
1091
+ }
1092
+ // Pre-paint pass: surgery repair only (cheap DOM ops); the React
1093
+ // re-render goes through the rAF-scheduled sweep.
1094
+ repairSurgery()
1095
+ schedule()
1096
+ })
1097
+ observer.observe(document.body, {
1098
+ childList: true,
1099
+ subtree: true,
1100
+ attributes: true,
1101
+ attributeFilter: ['data-streaming'],
1102
+ // React streams tokens as text-node updates: without characterData the
1103
+ // observer would only fire on structural changes and miss body growth.
1104
+ characterData: true,
1105
+ })
1106
+ const interval = window.setInterval(sweep, SWEEP_MS)
1107
+ sweep()
1108
+
1109
+ return () => {
1110
+ disposed = true
1111
+ observer.disconnect()
1112
+ unsubscribeSessions?.()
1113
+ unsubscribeChat?.()
1114
+ unsubscribeChat = undefined
1115
+ window.clearInterval(interval)
1116
+ if (rafId !== null) {
1117
+ cancelAnimationFrame(rafId)
1118
+ rafId = null
1119
+ }
1120
+ for (const block of Array.from(mounts.keys())) unmountBlock(block)
1121
+ for (const block of Array.from(diagnostics.keys())) clearDiagnostic(block)
1122
+ }
1123
+ }