@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.11

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 (211) hide show
  1. package/CHANGELOG.md +611 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.md +13 -0
  4. package/README.en.md +171 -0
  5. package/README.md +170 -2
  6. package/chart_service.py +687 -0
  7. package/config/basic-symbols.json +570 -0
  8. package/config/dsh-kline.patch.yml +4 -0
  9. package/config/dsh-tool-catalog.json +3875 -0
  10. package/cordis.patch.yml +33 -0
  11. package/core/__init__.py +0 -0
  12. package/core/adjustment.py +16 -0
  13. package/core/calc.py +691 -0
  14. package/core/rows.py +228 -0
  15. package/core/ta_engine.py +99 -0
  16. package/docs/anonymous-market-support.md +33 -0
  17. package/docs/automatic-drawing.md +24 -0
  18. package/docs/chart-functions.md +136 -0
  19. package/docs/drawing-examples.en.md +13 -0
  20. package/docs/drawing-examples.md +13 -0
  21. package/docs/embedding.md +77 -0
  22. package/docs/fixtures/price-pattern-real-v1.json +1 -0
  23. package/docs/free-foreign-daily.md +44 -0
  24. package/docs/guide.en.md +232 -0
  25. package/docs/guide.md +248 -0
  26. package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
  27. package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
  28. package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
  29. package/docs/images/dsh-kline-tab-workspace.png +0 -0
  30. package/docs/images/dsh-market.png +0 -0
  31. package/docs/images/kline-news.png +0 -0
  32. package/docs/images/kline-range-stats.png +0 -0
  33. package/docs/images/kline-support.png +0 -0
  34. package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
  35. package/docs/images/market-overview-v0.6.9.png +0 -0
  36. package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
  37. package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
  38. package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
  39. package/docs/npm-release.md +33 -0
  40. package/docs/price-pattern-rules-v1.md +40 -0
  41. package/docs/price-pattern-samples-v1.md +42 -0
  42. package/docs/provider-adaptation.md +73 -0
  43. package/docs/release-acceptance-v0.4.0.md +46 -0
  44. package/docs/release-acceptance-v0.4.1.md +43 -0
  45. package/docs/release-acceptance-v0.5.0.md +40 -0
  46. package/docs/release-acceptance-v0.6.0.md +33 -0
  47. package/docs/release-acceptance-v0.6.1.md +19 -0
  48. package/docs/release-acceptance-v0.6.10.md +21 -0
  49. package/docs/release-acceptance-v0.6.11.md +21 -0
  50. package/docs/release-acceptance-v0.6.2.md +31 -0
  51. package/docs/release-acceptance-v0.6.3.md +25 -0
  52. package/docs/release-acceptance-v0.6.4.md +24 -0
  53. package/docs/release-acceptance-v0.6.5.md +21 -0
  54. package/docs/release-acceptance-v0.6.6.md +21 -0
  55. package/docs/release-acceptance-v0.6.7.md +18 -0
  56. package/docs/release-acceptance-v0.6.8.md +18 -0
  57. package/docs/release-acceptance-v0.6.9.md +98 -0
  58. package/docs/release-notes-v0.5.0.md +23 -0
  59. package/docs/release-notes-v0.6.0.md +11 -0
  60. package/docs/release-notes-v0.6.1.md +20 -0
  61. package/docs/release-notes-v0.6.10.md +11 -0
  62. package/docs/release-notes-v0.6.11.md +16 -0
  63. package/docs/release-notes-v0.6.2.md +14 -0
  64. package/docs/release-notes-v0.6.3.md +26 -0
  65. package/docs/release-notes-v0.6.4.md +12 -0
  66. package/docs/release-notes-v0.6.5.md +13 -0
  67. package/docs/release-notes-v0.6.6.md +13 -0
  68. package/docs/release-notes-v0.6.7.md +17 -0
  69. package/docs/release-notes-v0.6.8.md +10 -0
  70. package/docs/release-notes-v0.6.9.md +16 -0
  71. package/lib/candle-sequence.js +15 -0
  72. package/lib/chart-adjustment.js +7 -0
  73. package/lib/chart-annotations.js +33 -0
  74. package/lib/chart-applications.js +171 -0
  75. package/lib/chart-context.js +164 -0
  76. package/lib/chart-observation.js +251 -0
  77. package/lib/chart-service-status.js +82 -0
  78. package/lib/chart-source-status.js +39 -0
  79. package/lib/chart-sources.js +354 -0
  80. package/lib/client/BetterSidebarTab.js +70 -0
  81. package/lib/client/ClassicShell.js +254 -0
  82. package/lib/client/KlineContent.js +155 -0
  83. package/lib/client/PanelHost.js +46 -0
  84. package/lib/client/chart-apply.js +73 -0
  85. package/lib/client/chart-context.js +233 -0
  86. package/lib/client/chart-handoff.js +34 -0
  87. package/lib/client/chart-session-resolver.js +74 -0
  88. package/lib/client/client-context.js +1 -0
  89. package/lib/client/conversation.js +88 -0
  90. package/lib/client/default-tab.js +83 -0
  91. package/lib/client/embed.js +50 -0
  92. package/lib/client/generated-view.js +12983 -0
  93. package/lib/client/horizontal-lines.js +19 -0
  94. package/lib/client/host-options.js +41 -0
  95. package/lib/client/host-panels.js +111 -0
  96. package/lib/client/index.js +77 -0
  97. package/lib/client/mode-preferences.js +48 -0
  98. package/lib/client/native-sidebar-contract.js +45 -0
  99. package/lib/client/native-sidebar-register.js +133 -0
  100. package/lib/client/native-sidebar-services.js +1 -0
  101. package/lib/client/native-sidebar.js +98 -0
  102. package/lib/client/sidebar-integration.js +93 -0
  103. package/lib/client/ui-onboarding.js +48 -0
  104. package/lib/client/version.js +14 -0
  105. package/lib/client.js +17581 -0
  106. package/lib/client.js.map +1 -0
  107. package/lib/drawing-feedback.js +284 -0
  108. package/lib/fibonacci.js +18 -0
  109. package/lib/ftshare-settings-bridge.js +159 -0
  110. package/lib/index.js +279 -0
  111. package/lib/labeled-polyline.js +17 -0
  112. package/lib/pattern-groups.js +91 -0
  113. package/lib/price-bands.js +55 -0
  114. package/lib/price-series.js +47 -0
  115. package/lib/price-sticks.js +32 -0
  116. package/lib/types/candle-sequence.d.ts +2 -0
  117. package/lib/types/chart-adjustment.d.ts +2 -0
  118. package/lib/types/chart-annotations.d.ts +4 -0
  119. package/lib/types/chart-applications.d.ts +26 -0
  120. package/lib/types/chart-context.d.ts +14 -0
  121. package/lib/types/chart-observation.d.ts +8 -0
  122. package/lib/types/chart-service-status.d.ts +22 -0
  123. package/lib/types/chart-source-status.d.ts +47 -0
  124. package/lib/types/chart-sources.d.ts +25 -0
  125. package/lib/types/client/BetterSidebarTab.d.ts +12 -0
  126. package/lib/types/client/ClassicShell.d.ts +4 -0
  127. package/lib/types/client/KlineContent.d.ts +37 -0
  128. package/lib/types/client/PanelHost.d.ts +25 -0
  129. package/lib/types/client/chart-apply.d.ts +13 -0
  130. package/lib/types/client/chart-context.d.ts +23 -0
  131. package/lib/types/client/chart-handoff.d.ts +5 -0
  132. package/lib/types/client/chart-session-resolver.d.ts +2 -0
  133. package/lib/types/client/client-context.d.ts +16 -0
  134. package/lib/types/client/conversation.d.ts +43 -0
  135. package/lib/types/client/default-tab.d.ts +3 -0
  136. package/lib/types/client/embed.d.ts +37 -0
  137. package/lib/types/client/generated-view.d.ts +2 -0
  138. package/lib/types/client/horizontal-lines.d.ts +1 -0
  139. package/lib/types/client/host-options.d.ts +38 -0
  140. package/lib/types/client/host-panels.d.ts +55 -0
  141. package/lib/types/client/index.d.ts +4 -0
  142. package/lib/types/client/mode-preferences.d.ts +25 -0
  143. package/lib/types/client/native-sidebar-contract.d.ts +52 -0
  144. package/lib/types/client/native-sidebar-register.d.ts +46 -0
  145. package/lib/types/client/native-sidebar-services.d.ts +45 -0
  146. package/lib/types/client/native-sidebar.d.ts +47 -0
  147. package/lib/types/client/sidebar-integration.d.ts +12 -0
  148. package/lib/types/client/ui-onboarding.d.ts +7 -0
  149. package/lib/types/client/version.d.ts +1 -0
  150. package/lib/types/drawing-feedback.d.ts +5 -0
  151. package/lib/types/fibonacci.d.ts +5 -0
  152. package/lib/types/ftshare-settings-bridge.d.ts +50 -0
  153. package/lib/types/index.d.ts +26 -0
  154. package/lib/types/labeled-polyline.d.ts +11 -0
  155. package/lib/types/pattern-groups.d.ts +2 -0
  156. package/lib/types/price-bands.d.ts +3 -0
  157. package/lib/types/price-series.d.ts +5 -0
  158. package/lib/types/price-sticks.d.ts +3 -0
  159. package/package.json +155 -4
  160. package/requirements.txt +6 -0
  161. package/screenshots.json +8 -0
  162. package/scripts/bootstrap.sh +5 -0
  163. package/scripts/dsh-bootstrap.mjs +179 -0
  164. package/scripts/dsh-mcp-plugin.mjs +27 -0
  165. package/scripts/run-dsh-kline.mjs +658 -0
  166. package/scripts/run-dsh-kline.sh +5 -0
  167. package/server.py +1755 -0
  168. package/tools/__init__.py +0 -0
  169. package/tools/annotations.py +119 -0
  170. package/tools/automatic_analysis.py +158 -0
  171. package/tools/baostock_source.py +176 -0
  172. package/tools/calc.py +39 -0
  173. package/tools/channel_candidates.py +260 -0
  174. package/tools/channel_preview.py +82 -0
  175. package/tools/channels.py +104 -0
  176. package/tools/chart_applications.py +204 -0
  177. package/tools/chart_context.py +186 -0
  178. package/tools/chart_edits.py +363 -0
  179. package/tools/chart_functions.py +451 -0
  180. package/tools/chart_indicators.py +65 -0
  181. package/tools/chart_measurements.py +84 -0
  182. package/tools/chart_source_status.py +32 -0
  183. package/tools/chart_sources.py +31 -0
  184. package/tools/closed_daily.py +68 -0
  185. package/tools/draw.py +410 -0
  186. package/tools/drawing_feedback.py +45 -0
  187. package/tools/drawing_interaction.py +117 -0
  188. package/tools/drawing_verification.py +141 -0
  189. package/tools/fetch.py +4680 -0
  190. package/tools/fibonacci.py +83 -0
  191. package/tools/foreign_daily.py +185 -0
  192. package/tools/free_sources.py +483 -0
  193. package/tools/lines.py +91 -0
  194. package/tools/nine_count.py +66 -0
  195. package/tools/pattern_groups.py +103 -0
  196. package/tools/pivots.py +60 -0
  197. package/tools/polylines.py +131 -0
  198. package/tools/price_bands.py +165 -0
  199. package/tools/price_patterns.py +311 -0
  200. package/tools/price_series.py +162 -0
  201. package/tools/price_sticks.py +114 -0
  202. package/tools/range_candidates.py +170 -0
  203. package/tools/recent_drawing_candidates.py +123 -0
  204. package/tools/rectangles.py +76 -0
  205. package/tools/regression_channels.py +87 -0
  206. package/tools/ta_functions.py +228 -0
  207. package/tools/trend_lines.py +106 -0
  208. package/tools/watchlist.py +149 -0
  209. package/view/ft-logo.jpg +0 -0
  210. package/view/kline.html +12436 -0
  211. package/view/vendor/klinecharts.min.js +7 -0
@@ -0,0 +1,233 @@
1
+ /** One serial browser publisher per real view; no localStorage/history context fallback. */
2
+ import { createChartApplyController } from "./chart-apply.js";
3
+ import { drawingSourceKey, observationKey } from "../chart-observation.js";
4
+ import { sourceStatus, sanitizeSourceStatus } from "../chart-source-status.js";
5
+ export const CONTEXT_PUBLICATION_TIMEOUT_MS = 8000;
6
+ export function createChartContextPublisher(options) {
7
+ if (!options.conversationId)
8
+ return { notify() { }, retrySource() { }, dispose() { } };
9
+ const viewId = options.viewId ?? btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(24)))).replaceAll('+', '-').replaceAll('/', '_');
10
+ const post = options.transport ?? (async (body, signal) => {
11
+ const result = await fetch('/dsh-kline/context', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal,
12
+ keepalive: body.active === false && body.state === null && !body.receipt && !body.source_receipt });
13
+ const response = await result.json();
14
+ if (!response.ok) {
15
+ const failure = Error('context_publication_failed');
16
+ if (response.error === 'context_state_required')
17
+ failure.code = 'context_state_required';
18
+ throw failure;
19
+ }
20
+ return response;
21
+ });
22
+ const requestedTimeout = options.publicationTimeoutMs;
23
+ const timeout = typeof requestedTimeout === 'number' && Number.isSafeInteger(requestedTimeout) && requestedTimeout > 0
24
+ && requestedTimeout <= CONTEXT_PUBLICATION_TIMEOUT_MS ? requestedTimeout : CONTEXT_PUBLICATION_TIMEOUT_MS;
25
+ const inFlight = new Set();
26
+ function boundedPost(body) {
27
+ return new Promise((resolve, reject) => {
28
+ const controller = new AbortController();
29
+ inFlight.add(controller);
30
+ let settled = false;
31
+ const finish = (done, value) => {
32
+ if (settled)
33
+ return;
34
+ settled = true;
35
+ clearTimeout(timer);
36
+ inFlight.delete(controller);
37
+ controller.signal.removeEventListener('abort', onAbort);
38
+ done(value);
39
+ };
40
+ const onAbort = () => finish(reject, Error('context_publication_interrupted'));
41
+ const timer = setTimeout(() => controller.abort(), timeout);
42
+ controller.signal.addEventListener('abort', onAbort, { once: true });
43
+ // Consume late rejection/fulfilment, but never return a timed-out delivery
44
+ // to the drawing controller, even if a custom transport ignores abort.
45
+ Promise.resolve().then(() => post(body, controller.signal)).then(value => finish(resolve, value), error => finish(reject, error));
46
+ });
47
+ }
48
+ let disposed = false, pageHidden = false, busy = false, pending = false, sequence = 0, lastState = '', lastActive;
49
+ let scheduled = false, sourceRetryPending = false;
50
+ let lastCaptured;
51
+ let receipt;
52
+ let sourceReceipt;
53
+ let blockedSourceState = '', lastSourceStatus = '';
54
+ function reportSourceStatus(value) {
55
+ if (disposed)
56
+ return;
57
+ const cleaned = sanitizeSourceStatus(value), key = JSON.stringify(cleaned);
58
+ if (key !== lastSourceStatus) {
59
+ lastSourceStatus = key;
60
+ try {
61
+ options.onSourceStatus?.(cleaned);
62
+ }
63
+ catch { } // Diagnostics cannot interrupt guarded execution.
64
+ }
65
+ }
66
+ const sourceCapable = Boolean(options.captureSource && options.bindSource && options.confirmSource);
67
+ const applications = options.apply ? createChartApplyController({ ...options, viewId, apply: options.apply,
68
+ isActive: () => !disposed && options.isActive(), confirm: token => { if (!disposed)
69
+ options.confirm?.(token); } }) : undefined;
70
+ async function flush() {
71
+ if (busy) {
72
+ pending = true;
73
+ return;
74
+ }
75
+ busy = true;
76
+ try {
77
+ do {
78
+ pending = false;
79
+ // Consume retries after the older publication settles. Resetting
80
+ // lastState inside retrySource() lets that older reply overwrite it.
81
+ if (sourceRetryPending) {
82
+ sourceRetryPending = false;
83
+ blockedSourceState = '';
84
+ lastState = '';
85
+ }
86
+ const active = !disposed && !pageHidden && options.isActive();
87
+ const state = disposed ? lastCaptured ?? { state: 'empty', candles: [], drawings: [] } : options.capture();
88
+ lastCaptured = state;
89
+ const serialized = JSON.stringify(state);
90
+ const changed = serialized !== lastState;
91
+ let feedback;
92
+ if (!disposed && options.feedback) {
93
+ try {
94
+ feedback = options.feedback();
95
+ }
96
+ catch {
97
+ feedback = { report_status: 'invalid', items: [] };
98
+ }
99
+ }
100
+ const sourcePayload = !disposed && active && changed && sourceCapable && serialized !== blockedSourceState ? options.captureSource?.() : undefined;
101
+ if (sourcePayload || sourceReceipt)
102
+ reportSourceStatus(sourceStatus('source_handoff_pending'));
103
+ const response = await boundedPost({ conversation_id: options.conversationId, view_id: viewId, sequence: ++sequence, active,
104
+ captured_at_ms: Date.now(), application_protocol: applications ? 'guarded-view-v1' : undefined,
105
+ state: changed || lastActive === undefined || receipt || sourceReceipt ? state : null,
106
+ ...(sourceCapable ? { source_protocol: 'browser-source-v1' } : {}),
107
+ ...(sourcePayload ? { source_payload: sourcePayload } : {}), ...(sourceReceipt ? { source_receipt: sourceReceipt } : {}),
108
+ ...(feedback ? { drawing_feedback: feedback } : {}), ...(receipt ? { receipt } : {}) });
109
+ lastState = serialized;
110
+ lastActive = active;
111
+ // Keep the exact reported state beside the receipt. The chart may
112
+ // change while this request is in flight, so a receipt alone is not
113
+ // proof that the currently displayed chart has the same identity.
114
+ if (!disposed)
115
+ try {
116
+ options.onPublished?.({ ...response, observed_source_key: drawingSourceKey(state) });
117
+ }
118
+ catch { } // UI diagnostics never interrupt guarded publication.
119
+ if (!disposed && options.onSourceStatus && JSON.stringify(options.capture()) !== serialized) {
120
+ reportSourceStatus(sourceStatus('source_handoff_pending'));
121
+ pending = true;
122
+ }
123
+ else
124
+ reportSourceStatus(response.source_status);
125
+ if (receipt && response.receipt?.candidate_chart_session === receipt.candidate_chart_session
126
+ && response.receipt.lease_id === receipt.lease_id) {
127
+ applications?.confirm(response.receipt);
128
+ receipt = undefined;
129
+ lastState = ''; // Re-evaluate a deferred source handoff after a terminal application.
130
+ }
131
+ if (response.application) {
132
+ receipt = applications?.consume(response.application, response);
133
+ if (receipt)
134
+ pending = true;
135
+ }
136
+ if (sourceReceipt && response.source_receipt?.chart_session === sourceReceipt.chart_session
137
+ && ['confirmed', 'rejected'].includes(response.source_receipt.status)) {
138
+ if (!disposed)
139
+ options.confirmSource?.(sourceReceipt.chart_session, response.source_receipt.status === 'confirmed');
140
+ if (!disposed && response.source_receipt.status === 'rejected')
141
+ blockedSourceState = JSON.stringify(options.capture());
142
+ sourceReceipt = undefined;
143
+ lastState = '';
144
+ pending = true;
145
+ }
146
+ const offer = response.source_handoff;
147
+ if (offer && sourceCapable && !sourceReceipt && !receipt && !disposed
148
+ && /^[A-Za-z0-9_-]{32}$/.test(offer.chart_session ?? '')) {
149
+ sourceReceipt = { chart_session: offer.chart_session, status: 'rejected' };
150
+ if (options.isActive() && offer.context_ref === response.context_ref && offer.expected_revision === response.revision
151
+ && offer.conversation_id === options.conversationId && offer.view_id === viewId
152
+ && Number.isSafeInteger(offer.expires_at_ms) && offer.expires_at_ms >= Date.now()
153
+ && observationKey(options.capture()) === observationKey(offer.base_state)) {
154
+ options.bindSource?.(offer.chart_session, offer.base_state.source_chart_session);
155
+ sourceReceipt.status = 'bound';
156
+ }
157
+ pending = true;
158
+ }
159
+ } while (pending);
160
+ }
161
+ catch (error) {
162
+ lastState = '';
163
+ lastActive = undefined;
164
+ reportSourceStatus(sourceStatus('context_transport_unavailable'));
165
+ // A restarted host has forgotten this view. Publish its full state now
166
+ // instead of waiting for a throttled background-tab heartbeat.
167
+ if (!disposed && !receipt && !sourceReceipt && error?.code === 'context_state_required')
168
+ pending = true;
169
+ } // Heartbeat/receipt retry never queues a new drawing or refetches data.
170
+ finally {
171
+ busy = false;
172
+ // A pending close must still run when the in-flight request failed.
173
+ // With no newer notification, a failed close simply expires by TTL.
174
+ if (pending) {
175
+ pending = false;
176
+ void flush();
177
+ }
178
+ }
179
+ }
180
+ function notify() {
181
+ if (disposed || scheduled)
182
+ return;
183
+ scheduled = true;
184
+ queueMicrotask(() => { scheduled = false; if (!disposed)
185
+ void flush(); });
186
+ }
187
+ const heartbeat = setInterval(notify, 2000);
188
+ const doc = typeof document === 'undefined' ? undefined : document;
189
+ const win = typeof window === 'undefined' ? undefined : window;
190
+ function pagehide() {
191
+ if (disposed)
192
+ return;
193
+ pageHidden = true;
194
+ // A reloaded page gets a new view ID. Close this view synchronously before
195
+ // the browser can suspend async work; otherwise it remains a false second
196
+ // active chart until the 90-second context lease expires.
197
+ let queued = false;
198
+ try {
199
+ const body = { conversation_id: options.conversationId, view_id: viewId, sequence: ++sequence,
200
+ active: false, captured_at_ms: Date.now(), application_protocol: applications ? 'guarded-view-v1' : undefined,
201
+ state: { state: 'empty', candles: [], drawings: [] } };
202
+ queued = win?.navigator?.sendBeacon?.('/dsh-kline/context', new Blob([JSON.stringify(body)], { type: 'application/json' })) ?? false;
203
+ }
204
+ catch { } // The regular keepalive publication below is a fallback.
205
+ if (!queued)
206
+ notify();
207
+ }
208
+ function pageshow() { pageHidden = false; lastState = ''; lastActive = undefined; notify(); }
209
+ doc?.addEventListener('visibilitychange', notify);
210
+ win?.addEventListener('focus', notify);
211
+ win?.addEventListener('pagehide', pagehide);
212
+ win?.addEventListener('pageshow', pageshow);
213
+ notify();
214
+ return { notify, retrySource() {
215
+ if (disposed)
216
+ return;
217
+ sourceRetryPending = true;
218
+ notify();
219
+ }, dispose() {
220
+ if (disposed)
221
+ return;
222
+ disposed = true;
223
+ clearInterval(heartbeat);
224
+ doc?.removeEventListener('visibilitychange', notify);
225
+ win?.removeEventListener('focus', notify);
226
+ win?.removeEventListener('pagehide', pagehide);
227
+ win?.removeEventListener('pageshow', pageshow);
228
+ for (const controller of inFlight)
229
+ controller.abort();
230
+ // A close queues behind the in-flight sample; sequence ordering prevents late revival.
231
+ void flush();
232
+ } };
233
+ }
@@ -0,0 +1,34 @@
1
+ import { currentConversationId, latestChartFromEvents } from "./conversation.js";
2
+ /** Distinguish live appends from history hydration using the host's delta. */
3
+ export function observeLiveCharts(initial) {
4
+ let revision = initial.revision;
5
+ let previous = latestChartFromEvents(initial.entries);
6
+ return (window) => {
7
+ if (typeof window.revision !== 'number' || !window.change || window.revision === revision)
8
+ return;
9
+ revision = window.revision;
10
+ const next = latestChartFromEvents(window.entries);
11
+ const changed = next && (next.session !== previous?.session || next.order !== previous?.order);
12
+ previous = next;
13
+ return window.change.kind === 'append' && changed ? next : undefined;
14
+ };
15
+ }
16
+ // A newly opened tab mounts after its triggering tool result. Share that live
17
+ // result within this host instance, scoped to its owning conversation. Unlike
18
+ // browser persistence, this cannot promote an old chart after a page reload.
19
+ const liveCharts = new WeakMap();
20
+ export function handoffLiveChart(sessions, conversationId, reference) {
21
+ if (currentConversationId(sessions.list.getSnapshot()) !== conversationId)
22
+ return;
23
+ let charts = liveCharts.get(sessions);
24
+ if (!charts)
25
+ liveCharts.set(sessions, charts = new Map());
26
+ const previous = charts.get(conversationId);
27
+ if (!previous || reference.order >= previous.order)
28
+ charts.set(conversationId, reference);
29
+ }
30
+ export function liveChartFor(sessions, conversationId) {
31
+ if (!conversationId || currentConversationId(sessions.list.getSnapshot()) !== conversationId)
32
+ return;
33
+ return liveCharts.get(sessions)?.get(conversationId);
34
+ }
@@ -0,0 +1,74 @@
1
+ import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
2
+ import { currentConversationId, latestChart, latestChartFromEvents } from './conversation';
3
+ import { handoffLiveChart, observeLiveCharts } from './chart-handoff';
4
+ const EMPTY_CONVERSATION = { nodes: [] };
5
+ const EMPTY_EVENTS = { entries: [] };
6
+ export function useChartReference(sessions, conversationId, onNewChart) {
7
+ const readyForNewCharts = useRef(false);
8
+ const binding = conversationId ? sessions.binding(conversationId) : undefined;
9
+ const face = binding?.eventSource ? undefined : binding?.session;
10
+ const conversation = useSyncExternalStore(listener => face?.subscribe(listener) ?? (() => { }), () => face?.getSnapshot() ?? EMPTY_CONVERSATION);
11
+ const eventSource = binding?.eventSource;
12
+ const liveEvent = useRef();
13
+ const observe = useMemo(() => observeLiveCharts(eventSource?.getSnapshot() ?? EMPTY_EVENTS), [eventSource]);
14
+ const events = useSyncExternalStore(listener => eventSource?.subscribe(() => {
15
+ const next = observe(eventSource.getSnapshot());
16
+ if (next)
17
+ liveEvent.current = next;
18
+ listener();
19
+ }) ?? (() => { }), () => eventSource?.getSnapshot() ?? EMPTY_EVENTS);
20
+ const discovered = useMemo(() => eventSource
21
+ ? latestChartFromEvents(events.entries)
22
+ : latestChart(conversation.nodes ?? []), [eventSource, events.entries, conversation.nodes]);
23
+ // Event timestamps are host-specific and are not guaranteed to use the
24
+ // browser's millisecond clock. Capture the chart already present at mount
25
+ // instead of comparing incompatible timestamps.
26
+ const initialChartSession = useRef(discovered?.session);
27
+ // A chart is authoritative only when it is present in this conversation's
28
+ // live session history. Restoring a browser cache here can make a fresh
29
+ // DSH conversation inherit an old chart, bypassing the Market launcher.
30
+ const [reference, setReference] = useState();
31
+ useEffect(() => {
32
+ // Use only the host's actual active conversation. No browser-cache or
33
+ // global-latest discovery: the server checks a confirmed application.
34
+ if (!conversationId || currentConversationId(sessions.list.getSnapshot()) !== conversationId)
35
+ return;
36
+ const controller = new AbortController();
37
+ void fetch('/dsh-kline/recovery?conversation=' + encodeURIComponent(conversationId), { cache: 'no-store', signal: controller.signal })
38
+ .then(response => response.json()).then(saved => {
39
+ if (controller.signal.aborted || saved?.ok !== true || saved.recovery !== true || saved.conversation_id !== conversationId
40
+ || !/^[A-Za-z0-9_-]{32}$/.test(saved.session) || !Number.isSafeInteger(saved.published_at))
41
+ return;
42
+ if (!Array.isArray(saved.recovery_source_sessions) || saved.recovery_source_sessions.some((token) => typeof token !== 'string' || !/^[A-Za-z0-9_-]{32}$/.test(token)))
43
+ return;
44
+ const next = { session: saved.session, order: 0, recovery: true, recoverySourceSessions: saved.recovery_source_sessions };
45
+ // Host event clocks are not compared with server acknowledgment time.
46
+ setReference(current => !current || next.recoverySourceSessions.includes(current.session) ? next : current);
47
+ }).catch(() => { });
48
+ return () => controller.abort();
49
+ }, [conversationId, sessions]);
50
+ useEffect(() => {
51
+ // Older hosts have no event-delta metadata. Preserve their hydration
52
+ // grace period; modern hosts distinguish history replacements from live
53
+ // appends explicitly and do not discard fast results in this window.
54
+ const timer = window.setTimeout(() => { readyForNewCharts.current = true; }, 350);
55
+ return () => { window.clearTimeout(timer); };
56
+ }, [conversationId]);
57
+ useEffect(() => {
58
+ if (!conversationId || !discovered || (reference && reference.order >= discovered.order))
59
+ return;
60
+ if (reference?.recovery && reference.recoverySourceSessions?.includes(discovered.session))
61
+ return;
62
+ setReference(discovered);
63
+ // Reveal only a result that appeared after this hook mounted. Merely
64
+ // reopening historical messages must not override the Market launcher.
65
+ const explicitLive = liveEvent.current?.session === discovered.session && liveEvent.current?.order === discovered.order;
66
+ const legacyLive = events.revision === undefined && readyForNewCharts.current && discovered.session !== initialChartSession.current;
67
+ if ((explicitLive || legacyLive)
68
+ && currentConversationId(sessions.list.getSnapshot()) === conversationId) {
69
+ handoffLiveChart(sessions, conversationId, discovered);
70
+ onNewChart?.(discovered);
71
+ }
72
+ }, [conversationId, discovered?.session, discovered?.order, reference, onNewChart]);
73
+ return reference;
74
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,88 @@
1
+ /** Resolve one active conversation across the two public DSH session shapes. */
2
+ export function currentConversationId(snapshot) {
3
+ if (typeof snapshot.current === 'string' && snapshot.current.length > 0)
4
+ return snapshot.current;
5
+ const active = Object.entries(snapshot.byId ?? {})
6
+ .filter(([, row]) => typeof row?.retainedBy?.mainView === 'number' && row.retainedBy.mainView > 0)
7
+ .map(([id]) => id);
8
+ // More than one main-view holder is ambiguous: never guess an owner.
9
+ return active.length === 1 ? active[0] : undefined;
10
+ }
11
+ // Harness 0.1.2 moved rendered nodes out of SessionSnapshot. Consume the
12
+ // owning session's public event window, independent of Chat/Trajectory UI.
13
+ // Match results to invocation starts so a slow old call cannot steal the chart.
14
+ export function latestChartFromEvents(entries) {
15
+ const calls = new Map();
16
+ const nodes = [];
17
+ for (const entry of entries) {
18
+ if (entry.type !== 'event')
19
+ continue;
20
+ const event = entry.event;
21
+ const data = event?.data;
22
+ if (event?.type === 'tool/call' && typeof data?.callId === 'string') {
23
+ calls.set(data.callId, { name: data.name, time: event.time });
24
+ }
25
+ else if (event?.type === 'tool/code-dispatch-start' && typeof data?.subCallId === 'string') {
26
+ calls.set(data.subCallId, { name: data.name, time: event.time });
27
+ }
28
+ }
29
+ for (const entry of entries) {
30
+ if (entry.type !== 'event')
31
+ continue;
32
+ const event = entry.event;
33
+ const data = event?.data;
34
+ if (event?.type === 'tool/result') {
35
+ const message = data?.message;
36
+ // DSH 0.2 emits one first-class tool-role message per invocation. The
37
+ // 0.1 adapter below still handles nested tool-result content blocks.
38
+ // In both cases the invocation start supplies the trusted tool name and
39
+ // ordering; result text alone must never claim a chart.
40
+ if (message?.role === 'tool' && typeof message.toolCallId === 'string') {
41
+ const call = calls.get(message.toolCallId);
42
+ if (call)
43
+ nodes.push({ kind: 'tool-result', call, callTime: call.time,
44
+ content: message.content, isError: message.isError || !!data.error });
45
+ continue;
46
+ }
47
+ for (const block of data?.message?.content ?? []) {
48
+ if (block?.type !== 'tool-result')
49
+ continue;
50
+ const call = calls.get(block.toolCallId);
51
+ if (!call)
52
+ continue; // Never guess a truncated call's identity.
53
+ nodes.push({ kind: 'tool-result', call, callTime: call.time, content: block.content, isError: block.isError || !!data.error });
54
+ }
55
+ }
56
+ else if (event?.type === 'tool/code-dispatch') {
57
+ const call = calls.get(data?.subCallId);
58
+ if (!call || call.name !== data.name)
59
+ continue;
60
+ nodes.push({ kind: 'tool-result', call, callTime: call.time, content: data.content, isError: data.isError });
61
+ }
62
+ }
63
+ return latestChart(nodes);
64
+ }
65
+ export function latestChart(nodes) {
66
+ let latest;
67
+ const visit = (node) => {
68
+ for (const child of node.subCalls ?? [])
69
+ visit(child);
70
+ if (node.kind !== 'tool-result' || node.isError)
71
+ return;
72
+ if (!/^mcp__dsh[_-]kline__(?:analyze_kline(?:_rows)?|(?:create|update|delete)_(?:(?:horizontal|trend)_line|channel|rectangle))(?:_[a-f0-9]+)?$/.test(node.call?.name ?? ''))
73
+ return;
74
+ const serialized = JSON.stringify(node.content ?? []);
75
+ const match = serialized.match(/chart_session(?:\\?"\s*:\s*\\?"|=)([A-Za-z0-9_-]{32})/);
76
+ if (!match)
77
+ return;
78
+ const order = Number(node.callTime ?? node.time ?? node.seq ?? 0);
79
+ if (!latest || order >= latest.order)
80
+ latest = { session: match[1], order };
81
+ };
82
+ for (const node of nodes)
83
+ visit(node);
84
+ return latest;
85
+ }
86
+ export function chartStorageKey(conversationId) {
87
+ return `dsh-kline:conversation:${encodeURIComponent(conversationId)}`;
88
+ }
@@ -0,0 +1,83 @@
1
+ import { KLINE_TAB_ID } from "./sidebar-integration.js";
2
+ export const defaultTabKey = (sessionId) => `dsh-kline:default-tab:v1:${sessionId}`;
3
+ // Once per conversation, add an entry without expanding the panel or taking
4
+ // the user's active tab. A persisted receipt also respects later manual close.
5
+ export function installDefaultKlineTabs(service, storage) {
6
+ if (!service.features?.includes('stateSubscription') || typeof service.getSnapshot !== 'function'
7
+ || typeof service.subscribeState !== 'function' || typeof service.activateTab !== 'function'
8
+ || typeof service.isTabEnabled !== 'function')
9
+ return () => { };
10
+ let stopped = false, pending = false;
11
+ const handled = new Set();
12
+ try {
13
+ storage ??= globalThis.localStorage;
14
+ }
15
+ catch { /* In-memory fallback for blocked storage. */ }
16
+ const schedule = () => {
17
+ if (stopped || pending)
18
+ return;
19
+ pending = true;
20
+ queueMicrotask(() => {
21
+ pending = false;
22
+ if (stopped)
23
+ return;
24
+ try {
25
+ const { sessionId, state } = service.getSnapshot();
26
+ if (!sessionId || !state || handled.has(sessionId) || !service.isTabEnabled(KLINE_TAB_ID))
27
+ return;
28
+ const key = defaultTabKey(sessionId);
29
+ try {
30
+ if (storage?.getItem(key) === '1') {
31
+ handled.add(sessionId);
32
+ return;
33
+ }
34
+ }
35
+ catch { }
36
+ // Better Sidebar 0.19 delegates the right sidebar to DSH itself.
37
+ // Plugin tabs now live only in the bottom workbench, so do not read
38
+ // the old private `splits` / `floats` layout fields here.
39
+ const nodes = [state.bottomSplits];
40
+ const seen = new Set();
41
+ let exists = false, previous;
42
+ while (nodes.length) {
43
+ const value = nodes.pop();
44
+ if (!value || typeof value !== 'object' || seen.has(value))
45
+ continue;
46
+ seen.add(value);
47
+ const node = value;
48
+ if (node.kind === 'split' && Array.isArray(node.children))
49
+ nodes.push(...node.children);
50
+ if (!Array.isArray(node.tabs))
51
+ continue;
52
+ exists ||= node.tabs.some((tab) => tab?.type === KLINE_TAB_ID);
53
+ if (node.id === state.activePane && node.tabs.some((tab) => tab?.id === node.active))
54
+ previous = node.active;
55
+ }
56
+ // Mark before notifying the host to avoid re-entrant duplicate opens.
57
+ handled.add(sessionId);
58
+ if (!exists) {
59
+ service.openTab({ type: KLINE_TAB_ID }, { sessionId });
60
+ // Public openTab activates the inserted tab. Restore the prior tab
61
+ // synchronously, before React paints, without touching panel geometry.
62
+ if (previous && service.getSnapshot().sessionId === sessionId)
63
+ service.activateTab(previous, { sessionId });
64
+ }
65
+ try {
66
+ storage?.setItem(key, '1');
67
+ }
68
+ catch { }
69
+ }
70
+ catch { /* Optional default entry must not block chart/plugin startup. */ }
71
+ });
72
+ };
73
+ let unsubscribe;
74
+ try {
75
+ unsubscribe = service.subscribeState(schedule);
76
+ }
77
+ catch { }
78
+ schedule();
79
+ return () => { stopped = true; try {
80
+ unsubscribe?.();
81
+ }
82
+ catch { } };
83
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The host-facing contract of the embeddable chart.
3
+ *
4
+ * Kept free of React and of the generated view so both the component and the
5
+ * tests can rely on it: the sidebar mount passes nothing, and every helper here
6
+ * is a no-op for the defaults.
7
+ */
8
+ /**
9
+ * The attributes an embedded host turns on. The sidebar passes the defaults and
10
+ * gets `{}` — no attribute, so none of the embedding CSS can ever match it.
11
+ */
12
+ export function klineHostDataset({ embedded = false, chrome = 'full' } = {}) {
13
+ const dataset = {};
14
+ if (embedded)
15
+ dataset['data-embedded'] = '';
16
+ if (chrome !== 'full')
17
+ dataset['data-chrome'] = chrome;
18
+ return dataset;
19
+ }
20
+ /** Normalize host identities using the chart's input conventions, retaining the market. */
21
+ export function symbolKey(value) {
22
+ const raw = String(value ?? '').trim().toUpperCase().replace(/\s+/g, '');
23
+ const exchanges = { SH: 'XSHG', SZ: 'XSHE', BJ: 'BJSE' };
24
+ const prefixed = raw.match(/^(SH|SZ|BJ)(\d{6})$/);
25
+ if (prefixed)
26
+ return `${prefixed[2]}.${exchanges[prefixed[1]]}`;
27
+ const suffixed = raw.match(/^(\d{1,6})\.(SH|SZ|BJ|XSHG|XSHE|BJSE|HK|HKG)$/);
28
+ if (suffixed) {
29
+ const market = exchanges[suffixed[2]] || (suffixed[2] === 'HKG' ? 'HK' : suffixed[2]);
30
+ return `${market === 'HK' ? suffixed[1].padStart(5, '0') : suffixed[1]}.${market}`;
31
+ }
32
+ const us = raw.match(/^([A-Z][A-Z0-9._-]{0,15})\.(US|NASDAQ|NYSE)$/);
33
+ if (us)
34
+ return `${us[1]}.US`;
35
+ // Match normalizeSymbolInput in the chart: bare codes use its routing
36
+ // defaults, rather than matching every exchange with the same numeric code.
37
+ if (/^\d{6}$/.test(raw))
38
+ return `${raw}.${raw.startsWith('6') ? 'XSHG' : 'XSHE'}`;
39
+ if (/^\d{1,5}$/.test(raw))
40
+ return `${raw.padStart(5, '0')}.HK`;
41
+ if (/^[A-Z][A-Z0-9_-]{0,15}$/.test(raw))
42
+ return `${raw}.US`;
43
+ return raw;
44
+ }
45
+ /** Only an exact normalized identity is the same instrument; empty never matches. */
46
+ export function sameSymbol(left, right) {
47
+ const a = symbolKey(left);
48
+ const b = symbolKey(right);
49
+ return a !== '' && a === b;
50
+ }