@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +601 -0
- package/LICENSE +21 -0
- package/PROVENANCE.md +13 -0
- package/README.en.md +116 -0
- package/README.md +115 -2
- package/chart_service.py +687 -0
- package/config/basic-symbols.json +570 -0
- package/config/dsh-kline.patch.yml +4 -0
- package/config/dsh-tool-catalog.json +3875 -0
- package/cordis.patch.yml +33 -0
- package/core/__init__.py +0 -0
- package/core/adjustment.py +16 -0
- package/core/calc.py +691 -0
- package/core/rows.py +228 -0
- package/core/ta_engine.py +99 -0
- package/docs/anonymous-market-support.md +33 -0
- package/docs/automatic-drawing.md +24 -0
- package/docs/chart-functions.md +136 -0
- package/docs/drawing-examples.en.md +13 -0
- package/docs/drawing-examples.md +13 -0
- package/docs/embedding.md +43 -0
- package/docs/fixtures/price-pattern-real-v1.json +1 -0
- package/docs/free-foreign-daily.md +44 -0
- package/docs/guide.en.md +232 -0
- package/docs/guide.md +248 -0
- package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
- package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
- package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
- package/docs/images/dsh-kline-tab-workspace.png +0 -0
- package/docs/images/dsh-market.png +0 -0
- package/docs/images/kline-news.png +0 -0
- package/docs/images/kline-range-stats.png +0 -0
- package/docs/images/kline-support.png +0 -0
- package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
- package/docs/images/market-overview-v0.6.9.png +0 -0
- package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
- package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
- package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
- package/docs/npm-release.md +33 -0
- package/docs/price-pattern-rules-v1.md +40 -0
- package/docs/price-pattern-samples-v1.md +42 -0
- package/docs/provider-adaptation.md +73 -0
- package/docs/release-acceptance-v0.4.0.md +46 -0
- package/docs/release-acceptance-v0.4.1.md +43 -0
- package/docs/release-acceptance-v0.5.0.md +40 -0
- package/docs/release-acceptance-v0.6.0.md +33 -0
- package/docs/release-acceptance-v0.6.1.md +19 -0
- package/docs/release-acceptance-v0.6.10.md +21 -0
- package/docs/release-acceptance-v0.6.2.md +31 -0
- package/docs/release-acceptance-v0.6.3.md +25 -0
- package/docs/release-acceptance-v0.6.4.md +24 -0
- package/docs/release-acceptance-v0.6.5.md +21 -0
- package/docs/release-acceptance-v0.6.6.md +21 -0
- package/docs/release-acceptance-v0.6.7.md +18 -0
- package/docs/release-acceptance-v0.6.8.md +18 -0
- package/docs/release-acceptance-v0.6.9.md +98 -0
- package/docs/release-notes-v0.5.0.md +23 -0
- package/docs/release-notes-v0.6.0.md +11 -0
- package/docs/release-notes-v0.6.1.md +20 -0
- package/docs/release-notes-v0.6.10.md +11 -0
- package/docs/release-notes-v0.6.2.md +14 -0
- package/docs/release-notes-v0.6.3.md +26 -0
- package/docs/release-notes-v0.6.4.md +12 -0
- package/docs/release-notes-v0.6.5.md +13 -0
- package/docs/release-notes-v0.6.6.md +13 -0
- package/docs/release-notes-v0.6.7.md +17 -0
- package/docs/release-notes-v0.6.8.md +10 -0
- package/docs/release-notes-v0.6.9.md +16 -0
- package/lib/candle-sequence.js +15 -0
- package/lib/chart-adjustment.js +7 -0
- package/lib/chart-annotations.js +33 -0
- package/lib/chart-applications.js +171 -0
- package/lib/chart-context.js +164 -0
- package/lib/chart-observation.js +251 -0
- package/lib/chart-service-status.js +82 -0
- package/lib/chart-source-status.js +39 -0
- package/lib/chart-sources.js +354 -0
- package/lib/client/BetterSidebarTab.js +70 -0
- package/lib/client/ClassicShell.js +254 -0
- package/lib/client/KlineContent.js +155 -0
- package/lib/client/chart-apply.js +73 -0
- package/lib/client/chart-context.js +233 -0
- package/lib/client/chart-handoff.js +34 -0
- package/lib/client/chart-session-resolver.js +74 -0
- package/lib/client/client-context.js +1 -0
- package/lib/client/conversation.js +88 -0
- package/lib/client/default-tab.js +83 -0
- package/lib/client/embed.js +50 -0
- package/lib/client/generated-view.js +12983 -0
- package/lib/client/horizontal-lines.js +19 -0
- package/lib/client/index.js +62 -0
- package/lib/client/mode-preferences.js +28 -0
- package/lib/client/native-sidebar-contract.js +45 -0
- package/lib/client/native-sidebar-register.js +133 -0
- package/lib/client/native-sidebar-services.js +1 -0
- package/lib/client/native-sidebar.js +96 -0
- package/lib/client/sidebar-integration.js +93 -0
- package/lib/client/ui-onboarding.js +42 -0
- package/lib/client/version.js +14 -0
- package/lib/client.js +17382 -0
- package/lib/client.js.map +1 -0
- package/lib/drawing-feedback.js +284 -0
- package/lib/fibonacci.js +18 -0
- package/lib/ftshare-settings-bridge.js +159 -0
- package/lib/index.js +279 -0
- package/lib/labeled-polyline.js +17 -0
- package/lib/pattern-groups.js +91 -0
- package/lib/price-bands.js +55 -0
- package/lib/price-series.js +47 -0
- package/lib/price-sticks.js +32 -0
- package/lib/types/candle-sequence.d.ts +2 -0
- package/lib/types/chart-adjustment.d.ts +2 -0
- package/lib/types/chart-annotations.d.ts +4 -0
- package/lib/types/chart-applications.d.ts +26 -0
- package/lib/types/chart-context.d.ts +14 -0
- package/lib/types/chart-observation.d.ts +8 -0
- package/lib/types/chart-service-status.d.ts +22 -0
- package/lib/types/chart-source-status.d.ts +47 -0
- package/lib/types/chart-sources.d.ts +25 -0
- package/lib/types/client/BetterSidebarTab.d.ts +12 -0
- package/lib/types/client/ClassicShell.d.ts +4 -0
- package/lib/types/client/KlineContent.d.ts +37 -0
- package/lib/types/client/chart-apply.d.ts +13 -0
- package/lib/types/client/chart-context.d.ts +23 -0
- package/lib/types/client/chart-handoff.d.ts +5 -0
- package/lib/types/client/chart-session-resolver.d.ts +2 -0
- package/lib/types/client/client-context.d.ts +14 -0
- package/lib/types/client/conversation.d.ts +43 -0
- package/lib/types/client/default-tab.d.ts +3 -0
- package/lib/types/client/embed.d.ts +37 -0
- package/lib/types/client/generated-view.d.ts +2 -0
- package/lib/types/client/horizontal-lines.d.ts +1 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/mode-preferences.d.ts +13 -0
- package/lib/types/client/native-sidebar-contract.d.ts +52 -0
- package/lib/types/client/native-sidebar-register.d.ts +46 -0
- package/lib/types/client/native-sidebar-services.d.ts +45 -0
- package/lib/types/client/native-sidebar.d.ts +47 -0
- package/lib/types/client/sidebar-integration.d.ts +12 -0
- package/lib/types/client/ui-onboarding.d.ts +6 -0
- package/lib/types/client/version.d.ts +1 -0
- package/lib/types/drawing-feedback.d.ts +5 -0
- package/lib/types/fibonacci.d.ts +5 -0
- package/lib/types/ftshare-settings-bridge.d.ts +50 -0
- package/lib/types/index.d.ts +26 -0
- package/lib/types/labeled-polyline.d.ts +11 -0
- package/lib/types/pattern-groups.d.ts +2 -0
- package/lib/types/price-bands.d.ts +3 -0
- package/lib/types/price-series.d.ts +5 -0
- package/lib/types/price-sticks.d.ts +3 -0
- package/package.json +153 -4
- package/requirements.txt +6 -0
- package/screenshots.json +11 -0
- package/scripts/bootstrap.sh +5 -0
- package/scripts/dsh-bootstrap.mjs +179 -0
- package/scripts/dsh-mcp-plugin.mjs +27 -0
- package/scripts/run-dsh-kline.mjs +658 -0
- package/scripts/run-dsh-kline.sh +5 -0
- package/server.py +1755 -0
- package/tools/__init__.py +0 -0
- package/tools/annotations.py +119 -0
- package/tools/automatic_analysis.py +158 -0
- package/tools/baostock_source.py +176 -0
- package/tools/calc.py +39 -0
- package/tools/channel_candidates.py +260 -0
- package/tools/channel_preview.py +82 -0
- package/tools/channels.py +104 -0
- package/tools/chart_applications.py +204 -0
- package/tools/chart_context.py +186 -0
- package/tools/chart_edits.py +363 -0
- package/tools/chart_functions.py +451 -0
- package/tools/chart_indicators.py +65 -0
- package/tools/chart_measurements.py +84 -0
- package/tools/chart_source_status.py +32 -0
- package/tools/chart_sources.py +31 -0
- package/tools/closed_daily.py +68 -0
- package/tools/draw.py +410 -0
- package/tools/drawing_feedback.py +45 -0
- package/tools/drawing_interaction.py +117 -0
- package/tools/drawing_verification.py +141 -0
- package/tools/fetch.py +4680 -0
- package/tools/fibonacci.py +83 -0
- package/tools/foreign_daily.py +185 -0
- package/tools/free_sources.py +483 -0
- package/tools/lines.py +91 -0
- package/tools/nine_count.py +66 -0
- package/tools/pattern_groups.py +103 -0
- package/tools/pivots.py +60 -0
- package/tools/polylines.py +131 -0
- package/tools/price_bands.py +165 -0
- package/tools/price_patterns.py +311 -0
- package/tools/price_series.py +162 -0
- package/tools/price_sticks.py +114 -0
- package/tools/range_candidates.py +170 -0
- package/tools/recent_drawing_candidates.py +123 -0
- package/tools/rectangles.py +76 -0
- package/tools/regression_channels.py +87 -0
- package/tools/ta_functions.py +228 -0
- package/tools/trend_lines.py +106 -0
- package/tools/watchlist.py +149 -0
- package/view/ft-logo.jpg +0 -0
- package/view/kline.html +12436 -0
- 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
|
+
}
|