Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
815 lines (708 loc) · 22.8 KB
/
Copy pathindex.ts
File metadata and controls
815 lines (708 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import type { Plugin } from "@opencode-ai/plugin";
import { tool } from "@opencode-ai/plugin";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { open } from "glimpseui";
import { AVAILABLE_MODULES, getGuidelines } from "./lib/guidelines.js";
import { SVG_STYLES } from "./lib/svg-styles.js";
type WidgetWindow = ReturnType<typeof open>;
const require = createRequire(import.meta.url);
const MORPHDOM_SOURCE = readFileSync(require.resolve("morphdom/dist/morphdom-umd.min.js"), "utf8");
const loadedModulesBySession = new Map<string, Set<string>>();
const activeWindowsBySession = new Map<string, Set<WidgetWindow>>();
function trackWindow(sessionID: string, win: WidgetWindow) {
let windows = activeWindowsBySession.get(sessionID);
if (!windows) {
windows = new Set();
activeWindowsBySession.set(sessionID, windows);
}
windows.add(win);
}
function untrackWindow(sessionID: string, win: WidgetWindow) {
const windows = activeWindowsBySession.get(sessionID);
if (!windows) return;
windows.delete(win);
if (windows.size === 0) {
activeWindowsBySession.delete(sessionID);
}
}
function closeSessionWindows(sessionID: string) {
const windows = activeWindowsBySession.get(sessionID);
if (!windows) return;
for (const win of windows) {
try {
win.close();
} catch {}
}
activeWindowsBySession.delete(sessionID);
}
function closeAllWindows() {
for (const sessionID of Array.from(activeWindowsBySession.keys())) {
closeSessionWindows(sessionID);
}
}
function rememberModules(sessionID: string, modules: string[]) {
let seen = loadedModulesBySession.get(sessionID);
if (!seen) {
seen = new Set();
loadedModulesBySession.set(sessionID, seen);
}
for (const moduleName of modules) {
seen.add(moduleName);
}
}
function hasLoadedGuidelines(sessionID: string) {
return (loadedModulesBySession.get(sessionID)?.size ?? 0) > 0;
}
function clearSessionState(sessionID: string) {
loadedModulesBySession.delete(sessionID);
closeSessionWindows(sessionID);
}
const WIDGET_SHELL_STYLES = `
#oc-shell {
position: relative;
width: 100vw;
height: 100vh;
overflow: hidden;
background: #1a1a1a;
color: #e0e0e0;
}
#oc-viewport {
position: absolute;
inset: 0;
overflow: hidden;
user-select: none;
}
#oc-stage {
position: absolute;
left: 0;
top: 0;
transform-origin: 0 0;
will-change: transform;
}
#oc-content {
position: relative;
}
body.oc-html #oc-content {
padding: 16px;
}
body.oc-svg #oc-content {
padding: 0;
}
body.oc-svg #oc-content > svg {
display: block;
}
#oc-toolbar {
position: absolute;
top: 12px;
right: 12px;
display: flex;
align-items: center;
gap: 8px;
padding: 8px;
border: 0.5px solid rgba(255, 255, 255, 0.18);
border-radius: 12px;
background: rgba(17, 17, 17, 0.88);
backdrop-filter: blur(10px);
z-index: 1000;
}
#oc-toolbar button {
min-width: 34px;
height: 34px;
padding: 0 10px;
border-radius: 8px;
font-size: 13px;
line-height: 1;
}
#oc-zoom-value {
min-width: 52px;
text-align: center;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
color: #a0a0a0;
}
#oc-hint {
position: absolute;
left: 12px;
bottom: 12px;
max-width: min(560px, calc(100vw - 24px));
padding: 10px 12px;
border: 0.5px solid rgba(255, 255, 255, 0.14);
border-radius: 12px;
background: rgba(17, 17, 17, 0.8);
backdrop-filter: blur(10px);
font-size: 12px;
line-height: 1.45;
color: #a0a0a0;
z-index: 1000;
pointer-events: none;
}
#oc-shell.oc-space-ready,
#oc-shell.oc-panning {
cursor: grab;
}
#oc-shell.oc-panning {
cursor: grabbing;
}
@keyframes _fadeIn {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: none; }
}
`;
const WIDGET_SHELL_SCRIPT = String.raw`(() => {
const MIN_SCALE = 0.2;
const MAX_SCALE = 4;
const ZOOM_STEP = 1.15;
const PAN_STEP = 60;
const shell = document.getElementById('oc-shell');
const viewport = document.getElementById('oc-viewport');
const stage = document.getElementById('oc-stage');
const content = document.getElementById('oc-content');
const zoomValue = document.getElementById('oc-zoom-value');
const zoomInButton = document.getElementById('oc-zoom-in');
const zoomOutButton = document.getElementById('oc-zoom-out');
const fitButton = document.getElementById('oc-fit');
const resetButton = document.getElementById('oc-reset');
const declaredSVG = shell?.dataset.kind === 'svg';
if (!shell || !viewport || !stage || !content || !zoomValue) return;
let scale = 1;
let tx = 0;
let ty = 0;
let defaultScale = 1;
let defaultTx = 0;
let defaultTy = 0;
let spacePressed = false;
let panning = false;
let panPointerId = null;
let panStartX = 0;
let panStartY = 0;
let panStartTx = 0;
let panStartTy = 0;
let gestureScaleStart = null;
let gestureAnchor = null;
let svgEl = null;
let svgBaseWidth = 0;
let svgBaseHeight = 0;
const isEditableTarget = (target) => {
if (!(target instanceof Element)) return false;
return Boolean(target.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""]'));
};
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
const syncSVG = () => {
const candidate = content.querySelector('svg');
if (!(candidate instanceof SVGSVGElement)) {
svgEl = null;
return false;
}
if (svgEl !== candidate) {
svgEl = candidate;
const viewBox = svgEl.viewBox?.baseVal;
let width = viewBox && viewBox.width > 0 ? viewBox.width : Number.parseFloat(svgEl.getAttribute('width') || '');
let height = viewBox && viewBox.height > 0 ? viewBox.height : Number.parseFloat(svgEl.getAttribute('height') || '');
if (!(width > 0) || !(height > 0)) {
const rect = svgEl.getBoundingClientRect();
width = rect.width;
height = rect.height;
}
if (!(width > 0) || !(height > 0)) {
width = 680;
height = 420;
}
svgBaseWidth = width;
svgBaseHeight = height;
svgEl.style.display = 'block';
svgEl.style.maxWidth = 'none';
svgEl.style.maxHeight = 'none';
if (!svgEl.getAttribute('preserveAspectRatio')) {
svgEl.setAttribute('preserveAspectRatio', 'xMidYMid meet');
}
}
return true;
};
const usesNativeSVGZoom = () => {
if (!syncSVG()) return false;
if (declaredSVG) return true;
return !content.querySelector('input, button, select, textarea, [contenteditable="true"], [contenteditable=""]');
};
const measureContent = () => {
if (usesNativeSVGZoom()) {
return {
width: Math.max(svgBaseWidth, 1),
height: Math.max(svgBaseHeight, 1),
};
}
const width = Math.max(content.scrollWidth, content.offsetWidth, content.clientWidth);
const height = Math.max(content.scrollHeight, content.offsetHeight, content.clientHeight);
return {
width: Math.max(width, 1),
height: Math.max(height, 1),
};
};
const updateZoomLabel = () => {
zoomValue.textContent = Math.round(scale * 100) + '%';
};
const render = () => {
if (usesNativeSVGZoom() && svgEl) {
stage.style.transform = 'translate(' + tx + 'px, ' + ty + 'px)';
svgEl.style.width = svgBaseWidth * scale + 'px';
svgEl.style.height = svgBaseHeight * scale + 'px';
} else {
if (svgEl) {
svgEl.style.width = '';
svgEl.style.height = '';
}
stage.style.transform = 'translate(' + tx + 'px, ' + ty + 'px) scale(' + scale + ')';
}
updateZoomLabel();
};
const defaultPositionFor = (nextScale) => {
const viewportRect = viewport.getBoundingClientRect();
const size = measureContent();
const scaledWidth = size.width * nextScale;
const scaledHeight = size.height * nextScale;
const centerX = (viewportRect.width - scaledWidth) / 2;
const centerY = (viewportRect.height - scaledHeight) / 2;
return {
x: isSVG ? centerX : Math.max(24, centerX),
y: isSVG ? centerY : Math.max(24, centerY),
};
};
const setDefaultView = (nextScale) => {
scale = nextScale;
const position = defaultPositionFor(nextScale);
tx = position.x;
ty = position.y;
defaultScale = scale;
defaultTx = tx;
defaultTy = ty;
render();
};
const fitView = () => {
const viewportRect = viewport.getBoundingClientRect();
const size = measureContent();
const fitScale = clamp(
Math.min((viewportRect.width - 40) / size.width, (viewportRect.height - 40) / size.height),
MIN_SCALE,
MAX_SCALE,
);
setDefaultView(fitScale);
};
const resetView = () => {
scale = defaultScale;
tx = defaultTx;
ty = defaultTy;
render();
};
const zoomAt = (nextScale, clientX, clientY) => {
const bounded = clamp(nextScale, MIN_SCALE, MAX_SCALE);
const viewportRect = viewport.getBoundingClientRect();
const pointX = clientX - viewportRect.left;
const pointY = clientY - viewportRect.top;
const contentX = (pointX - tx) / scale;
const contentY = (pointY - ty) / scale;
scale = bounded;
tx = pointX - contentX * scale;
ty = pointY - contentY * scale;
render();
};
const zoomBy = (factor, clientX, clientY) => {
const viewportRect = viewport.getBoundingClientRect();
zoomAt(
scale * factor,
clientX ?? viewportRect.left + viewportRect.width / 2,
clientY ?? viewportRect.top + viewportRect.height / 2,
);
};
const beginPan = (pointerId, clientX, clientY) => {
panning = true;
panPointerId = pointerId;
panStartX = clientX;
panStartY = clientY;
panStartTx = tx;
panStartTy = ty;
shell.classList.add('oc-panning');
};
const endPan = () => {
panning = false;
panPointerId = null;
shell.classList.remove('oc-panning');
};
viewport.addEventListener('wheel', (event) => {
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
const factor = event.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP;
zoomBy(factor, event.clientX, event.clientY);
}
}, { passive: false });
viewport.addEventListener('pointerdown', (event) => {
if (event.button === 1 || (spacePressed && event.button === 0)) {
event.preventDefault();
viewport.setPointerCapture(event.pointerId);
beginPan(event.pointerId, event.clientX, event.clientY);
}
});
viewport.addEventListener('pointermove', (event) => {
if (!panning || event.pointerId !== panPointerId) return;
event.preventDefault();
tx = panStartTx + (event.clientX - panStartX);
ty = panStartTy + (event.clientY - panStartY);
render();
});
viewport.addEventListener('pointerup', (event) => {
if (event.pointerId === panPointerId) {
endPan();
}
});
viewport.addEventListener('pointercancel', (event) => {
if (event.pointerId === panPointerId) {
endPan();
}
});
viewport.addEventListener('gesturestart', (event) => {
event.preventDefault();
gestureScaleStart = scale;
gestureAnchor = { x: event.clientX, y: event.clientY };
});
viewport.addEventListener('gesturechange', (event) => {
if (gestureScaleStart == null || !gestureAnchor) return;
event.preventDefault();
zoomAt(gestureScaleStart * event.scale, gestureAnchor.x, gestureAnchor.y);
});
viewport.addEventListener('gestureend', () => {
gestureScaleStart = null;
gestureAnchor = null;
});
window.addEventListener('keydown', (event) => {
if (event.code === 'Space' && !isEditableTarget(event.target)) {
event.preventDefault();
spacePressed = true;
shell.classList.add('oc-space-ready');
return;
}
if (isEditableTarget(event.target)) return;
const viewportRect = viewport.getBoundingClientRect();
const centerX = viewportRect.left + viewportRect.width / 2;
const centerY = viewportRect.top + viewportRect.height / 2;
if (event.key === '+' || event.key === '=') {
event.preventDefault();
zoomBy(ZOOM_STEP, centerX, centerY);
return;
}
if (event.key === '-') {
event.preventDefault();
zoomBy(1 / ZOOM_STEP, centerX, centerY);
return;
}
if (event.key === '0') {
event.preventDefault();
resetView();
return;
}
if (event.key === 'f' || event.key === 'F') {
event.preventDefault();
fitView();
return;
}
if (event.key === 'ArrowLeft') {
event.preventDefault();
tx += PAN_STEP;
render();
return;
}
if (event.key === 'ArrowRight') {
event.preventDefault();
tx -= PAN_STEP;
render();
return;
}
if (event.key === 'ArrowUp') {
event.preventDefault();
ty += PAN_STEP;
render();
return;
}
if (event.key === 'ArrowDown') {
event.preventDefault();
ty -= PAN_STEP;
render();
}
});
window.addEventListener('keyup', (event) => {
if (event.code === 'Space') {
spacePressed = false;
shell.classList.remove('oc-space-ready');
}
});
zoomInButton?.addEventListener('click', () => {
const viewportRect = viewport.getBoundingClientRect();
zoomBy(ZOOM_STEP, viewportRect.left + viewportRect.width / 2, viewportRect.top + viewportRect.height / 2);
});
zoomOutButton?.addEventListener('click', () => {
const viewportRect = viewport.getBoundingClientRect();
zoomBy(1 / ZOOM_STEP, viewportRect.left + viewportRect.width / 2, viewportRect.top + viewportRect.height / 2);
});
fitButton?.addEventListener('click', fitView);
resetButton?.addEventListener('click', resetView);
window.addEventListener('resize', () => {
if (scale === defaultScale && tx === defaultTx && ty === defaultTy) {
setDefaultView(defaultScale);
return;
}
render();
});
let hasInitialView = false;
const refreshLayout = () => {
if (!hasInitialView) {
hasInitialView = true;
if (usesNativeSVGZoom()) {
fitView();
return;
}
setDefaultView(1);
return;
}
render();
};
window._ocRefresh = refreshLayout;
updateZoomLabel();
})();`;
function escapeJS(s: string): string {
return s
.replace(/\\/g, "\\\\")
.replace(/'/g, "\\'")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/<\/script>/gi, "<\\/script>");
}
function shellHTML(code: string, isSVG = false): string {
const bodyClass = isSVG ? "oc-svg" : "oc-html";
const bodyKind = isSVG ? "svg" : "html";
const hint = isSVG
? "Pinch or Cmd/Ctrl + wheel to zoom. Pan with middle-drag, Space + drag, or arrow keys."
: "Zoom with pinch or Cmd/Ctrl + wheel. Pan with middle-drag, Space + drag, or arrow keys without breaking widget controls.";
const escapedCode = escapeJS(code);
return `<!DOCTYPE html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
*{box-sizing:border-box}
html,body{margin:0;width:100%;height:100%;overflow:hidden}
body{font-family:system-ui,-apple-system,sans-serif;background:#1a1a1a;color:#e0e0e0}
${SVG_STYLES}
${WIDGET_SHELL_STYLES}
</style>
</head><body class="${bodyClass}">
<div id="oc-shell" data-kind="${bodyKind}">
<div id="oc-viewport">
<div id="oc-stage">
<div id="oc-content"></div>
</div>
</div>
<div id="oc-toolbar" aria-label="Widget controls">
<button id="oc-zoom-out" type="button" title="Zoom out (-)">-</button>
<div id="oc-zoom-value">100%</div>
<button id="oc-zoom-in" type="button" title="Zoom in (+)">+</button>
<button id="oc-fit" type="button" title="Fit to viewport (F)">Fit</button>
<button id="oc-reset" type="button" title="Reset view (0)">Reset</button>
</div>
<div id="oc-hint">${hint}</div>
</div>
<script>${MORPHDOM_SOURCE}</script>
<script>
window._setContent = function(html) {
var root = document.getElementById('oc-content');
var target = document.createElement('div');
target.id = 'oc-content';
target.innerHTML = html;
morphdom(root, target, {
onBeforeElUpdated: function(from, to) {
if (from.isEqualNode(to)) return false;
return true;
},
onNodeAdded: function(node) {
if (node.nodeType === 1 && node.tagName !== 'STYLE' && node.tagName !== 'SCRIPT') {
node.style.animation = '_fadeIn 0.3s ease both';
}
return node;
}
});
if (window._ocRefresh) window._ocRefresh();
};
window._runScripts = function() {
document.querySelectorAll('#oc-content script').forEach(function(old) {
var s = document.createElement('script');
Array.from(old.attributes).forEach(function(attr) {
s.setAttribute(attr.name, attr.value);
});
if (old.src) {
s.src = old.src;
} else {
s.textContent = old.textContent;
}
old.parentNode.replaceChild(s, old);
});
var refresh = function() {
if (window._ocRefresh) window._ocRefresh();
};
requestAnimationFrame(refresh);
setTimeout(refresh, 0);
setTimeout(refresh, 60);
};
window._setContent('${escapedCode}');
window._runScripts();
</script>
<script>${WIDGET_SHELL_SCRIPT}</script>
</body></html>`;
}
function normalizeTitle(title: string): string {
const normalized = title.replace(/_/g, " ").trim();
return normalized || "Widget";
}
function getGlimpseSetupHint(err: unknown): string {
const message = err instanceof Error ? err.message : String(err);
return [
`Failed to open the Glimpse widget window: ${message}`,
"Ensure plugin dependencies are installed.",
"If Bun blocked lifecycle scripts, run `bun pm trust glimpseui` in the plugin directory or OpenCode config directory.",
"If the native build still fails, update your Xcode Command Line Tools / Swift toolchain or point GLIMPSE_BINARY_PATH at an existing Glimpse binary.",
].join(" ");
}
const visualizeReadMe = tool({
description:
"Returns design guidelines for show_widget (CSS patterns, colors, typography, layout rules, examples). " +
"Call once before your first show_widget call. Do not mention this call to the user.",
args: {
modules: tool.schema
.array(tool.schema.string())
.min(1)
.describe(`Which module(s) to load. Pick from: ${AVAILABLE_MODULES.join(", ")}.`),
},
async execute(args, context) {
const invalid = args.modules.filter((moduleName) => !AVAILABLE_MODULES.includes(moduleName));
if (invalid.length > 0) {
throw new Error(`Unknown module(s): ${invalid.join(", ")}. Available modules: ${AVAILABLE_MODULES.join(", ")}.`);
}
rememberModules(context.sessionID, args.modules);
context.metadata({
title: "Read Guidelines",
metadata: { modules: args.modules },
});
return getGuidelines(args.modules);
},
});
const showWidget = tool({
description:
"Show visual content in a native window using HTML or SVG. Use for charts, diagrams, dashboards, calculators, mockups, and interactive explainers. " +
"Always call visualize_read_me first in the current session.",
args: {
i_have_seen_read_me: tool.schema
.boolean()
.describe("Confirm that visualize_read_me was already called in this session."),
title: tool.schema.string().min(1).describe("Short snake_case identifier for this widget."),
widget_code: tool.schema
.string()
.min(1)
.describe("HTML fragment or raw SVG. For HTML, do not include a full HTML document."),
width: tool.schema.number().int().positive().optional().describe("Window width in pixels. Default: 800."),
height: tool.schema.number().int().positive().optional().describe("Window height in pixels. Default: 600."),
floating: tool.schema.boolean().optional().describe("Keep the window always on top. Default: false."),
},
async execute(args, context) {
if (!args.i_have_seen_read_me || !hasLoadedGuidelines(context.sessionID)) {
throw new Error("You must call visualize_read_me before show_widget. Set i_have_seen_read_me: true after doing so.");
}
const code = args.widget_code;
const isSVG = code.trimStart().startsWith("<svg");
const title = normalizeTitle(args.title);
const width = args.width ?? 800;
const height = args.height ?? 600;
context.metadata({
title: `Show Widget: ${title}`,
metadata: {
title: args.title,
width,
height,
isSVG,
},
});
let win: WidgetWindow;
try {
win = open(shellHTML(code, isSVG), {
width,
height,
title,
floating: args.floating ?? false,
});
} catch (err) {
throw new Error(getGlimpseSetupHint(err));
}
trackWindow(context.sessionID, win);
return await new Promise<string>((resolve) => {
let resolved = false;
let messageData: unknown;
const finish = (reason: string) => {
if (resolved) return;
resolved = true;
if (messageData !== undefined) {
resolve(`Widget rendered. User interaction data: ${JSON.stringify(messageData)}`);
return;
}
resolve(`Widget \"${title}\" rendered and shown to the user (${width}x${height}). ${reason}`);
};
win.on("message", (data: unknown) => {
messageData = data;
finish("User sent data from widget.");
});
win.on("closed", () => {
untrackWindow(context.sessionID, win);
finish("Window closed by user.");
});
win.on("error", (err: Error) => {
untrackWindow(context.sessionID, win);
finish(`Error: ${err.message}`);
});
context.abort.addEventListener(
"abort",
() => {
try {
win.close();
} catch {}
finish("Aborted.");
},
{ once: true },
);
setTimeout(() => {
finish("Widget still open (timed out waiting for interaction).");
}, 120_000);
});
},
});
const SYSTEM_GUIDANCE = [
"Use show_widget when the user asks for visual content such as charts, diagrams, dashboards, SVG illustrations, mockups, or interactive explainers.",
"Always call visualize_read_me once before the first show_widget call in a session, then set i_have_seen_read_me: true.",
"For HTML widgets, provide a fragment only. Do not include DOCTYPE, html, head, or body tags.",
"For SVG widgets, start widget_code with <svg>.",
"If the user may zoom in or inspect labels closely, prefer pure SVG or HTML that renders to a single inline SVG. Avoid canvas unless the interaction genuinely needs it.",
"Keep widgets focused and appropriately sized. Default size is 800x600 unless the content needs another size.",
].join("\n");
let registeredExitHandler = false;
export const GenerativeUIPlugin: Plugin = async () => {
if (!registeredExitHandler) {
registeredExitHandler = true;
process.on("exit", closeAllWindows);
}
return {
tool: {
visualize_read_me: visualizeReadMe,
show_widget: showWidget,
},
event: async ({ event }) => {
if (event.type === "session.deleted") {
clearSessionState(event.properties.info.id);
}
},
"experimental.chat.system.transform": async (_input, output) => {
output.system.push(SYSTEM_GUIDANCE);
},
};
};
export default GenerativeUIPlugin;