-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebEditor.cpp
More file actions
945 lines (891 loc) · 49.8 KB
/
Copy pathWebEditor.cpp
File metadata and controls
945 lines (891 loc) · 49.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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
// WebEditor.cpp — see WebEditor.h for the design overview.
#include "WebEditor.h"
#include "DevLog.h"
#include "BridgeProtocol.h"
#include "BridgeShim.h"
#include "AppSettings.h"
#include "WebAssets.h"
#include "Prompt.h"
#include "LlmClient.h"
#include "AccountPanel.h"
using juce::var;
using VarArray = juce::Array<juce::var>;
using Completion = juce::WebBrowserComponent::NativeFunctionCompletion;
namespace
{
// The GUI bridge shim + withBridge + toBytes now live in BridgeShim.h so the
// locked product editor (LockedEditor) injects byte-identical JS. Bring the two
// we use here into scope so the rest of this file reads unchanged.
using vstai::shim::toBytes;
using vstai::shim::withBridge;
// {ok, message} result object returned to a JS promise.
var result (bool ok, const juce::String& message)
{
auto* o = new juce::DynamicObject();
o->setProperty ("ok", ok);
o->setProperty ("message", message);
return var (o);
}
var modelEntry (const char* provider, const char* id, const char* label, const char* group)
{
auto* o = new juce::DynamicObject();
o->setProperty ("provider", juce::String::fromUTF8 (provider));
o->setProperty ("id", juce::String::fromUTF8 (id));
o->setProperty ("label", juce::String::fromUTF8 (label)); // labels contain "·"
o->setProperty ("group", juce::String::fromUTF8 (group));
return var (o);
}
// The selectable model catalogue (mirrors the legacy rebuildModelBox), plus any
// locally-discovered Ollama models appended at the end.
var modelCatalog (const juce::StringArray& ollama)
{
juce::Array<var> a;
a.add (modelEntry ("anthropic", "claude-fable-5", "Fable 5 (most capable, 2\xC3\x97 price)", "Anthropic (your key)"));
a.add (modelEntry ("anthropic", "claude-opus-5", "Opus 5 (best value)", "Anthropic (your key)"));
a.add (modelEntry ("anthropic", "claude-sonnet-4-6", "Sonnet 4.6 (cheaper)", "Anthropic (your key)"));
// GLM / Z.ai and local Ollama models are temporarily hidden from the dropdown
// (Anthropic-only for now). The backend still supports them — re-add to restore.
// a.add (modelEntry ("glm", "glm-5.2", "GLM-5.2", "GLM / Z.ai (your key)"));
// a.add (modelEntry ("glm", "glm-4.6", "GLM-4.6", "GLM / Z.ai (your key)"));
// a.add (modelEntry ("cloud", "glm-5.2", "Cloud · GLM-5.2 (cheapest)", "VibePlugin Cloud (credits)"));
a.add (modelEntry ("cloud", "claude-haiku-4-5", "Cloud · Haiku 4.5", "VibePlugin Cloud (credits)"));
a.add (modelEntry ("cloud", "claude-sonnet-4-6", "Cloud · Sonnet 4.6", "VibePlugin Cloud (credits)"));
a.add (modelEntry ("cloud", "claude-opus-4-8", "Cloud · Opus 4.8 (best)", "VibePlugin Cloud (credits)"));
// for (const auto& m : ollama)
// {
// auto* o = new juce::DynamicObject();
// o->setProperty ("provider", "ollama");
// o->setProperty ("id", m);
// o->setProperty ("label", m);
// o->setProperty ("group", "Ollama (local, no key)");
// a.add (var (o));
// }
juce::ignoreUnused (ollama);
return a;
}
juce::String argStr (const VarArray& args, int i)
{
return i < args.size() ? args[i].toString() : juce::String();
}
}
WebEditor::WebEditor (VstaiAudioProcessor& p)
: AudioProcessorEditor (&p), processor (p)
{
cacheToken = juce::String ((juce::int64) juce::Time::currentTimeMillis());
juce::Component::SafePointer<WebEditor> safe (this);
auto options = juce::WebBrowserComponent::Options{}
.withNativeIntegrationEnabled()
.withKeepPageLoadedWhenBrowserIsHidden()
// Windows needs BOTH of the following, or the GUI renders an Internet
// Explorer error page instead of the SPA:
//
// - withBackend(webview2): JUCE's Backend::defaultBackend means *IE* on
// Windows, and createAndInitPlatformDependentPart only builds a WebView2
// when the backend is explicitly webview2 — otherwise it silently falls
// back to Win32WebView. IE cannot serve a resource provider, so the
// navigation is simply cancelled. Compiling with NEEDS_WEBVIEW2 is not
// enough; the backend has to be requested at runtime too.
// - withUserDataFolder: WebView2 otherwise puts its user-data folder next
// to the *host* exe, and DAWs live under C:\Program Files, which isn't
// user-writable — the environment then fails to create. JUCE documents
// this as a plugin-specific gotcha.
#if JUCE_WINDOWS
.withBackend (juce::WebBrowserComponent::Options::Backend::webview2)
.withWinWebView2Options (juce::WebBrowserComponent::Options::WinWebView2{}
.withUserDataFolder (juce::File::getSpecialLocation (juce::File::tempDirectory)))
#endif
.withResourceProvider ([safe] (const auto& url) -> std::optional<juce::WebBrowserComponent::Resource>
{
if (safe == nullptr) return std::nullopt;
return safe->provideResource (url);
})
// ---- read-only / quick state ------------------------------------
.withNativeFunction ("getState", [safe] (const VarArray&, Completion complete)
{
complete (safe != nullptr ? safe->currentState() : var());
})
// The SPA calls this once its JUCE bridge (window.__JUCE__.backend) is up;
// until then C++ must not emit events (they'd hit an undefined backend).
.withNativeFunction ("ready", [safe] (const VarArray&, Completion complete)
{
// Logged because it's the last line of the SPA's init(): seeing it
// confirms the whole shell.js ran (imports + Monaco + bridge are OK).
VSTAI_LOG ("WebEditor: SPA bridge ready");
if (safe != nullptr) safe->pageReady = true;
complete (safe != nullptr ? safe->currentState() : var());
})
.withNativeFunction ("setModel", [safe] (const VarArray& a, Completion complete)
{
if (safe != nullptr)
{
safe->processor.setGenerationProvider (argStr (a, 0));
safe->processor.setGenerationModel (argStr (a, 1));
}
complete (safe != nullptr ? safe->currentState() : var());
})
.withNativeFunction ("setEffort", [safe] (const VarArray& a, Completion complete)
{
if (safe != nullptr) safe->processor.setGenerationEffort (argStr (a, 0));
complete (var());
})
.withNativeFunction ("setThinking", [safe] (const VarArray& a, Completion complete)
{
if (safe != nullptr) safe->processor.setGenerationThinking (a.size() > 0 && (bool) a[0]);
complete (var());
})
// ---- generation -------------------------------------------------
.withNativeFunction ("generate", [safe] (const VarArray& a, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
const auto prompt = argStr (a, 0).trim();
if (prompt.isEmpty()) { complete (result (false, "Type a prompt first.")); return; }
safe->processor.requestBuild (prompt,
[safe] (const juce::String& stage) { if (safe) safe->emitEvent ("stage", stage); },
[safe, complete] (bool ok, juce::String message) { complete (result (ok, message)); });
})
.withNativeFunction ("buildManualPrompt", [safe] (const VarArray& a, Completion complete)
{
if (safe == nullptr) { complete (var()); return; }
const auto& d = safe->processor.getDocument();
complete (vstai::buildManualPrompt (argStr (a, 0), d.assembly, d.html,
safe->processor.isInstrument(),
vstai::appsettings::selectedDesignName(),
vstai::appsettings::selectedDesignPrinciples()));
})
// Short follow-up prompt for iterating in the SAME chat (no re-paste of the
// system rules or current code — the chat already holds them).
.withNativeFunction ("buildManualUpdatePrompt", [] (const VarArray& a, Completion complete)
{
complete (vstai::buildManualUpdatePrompt (argStr (a, 0)));
})
// Publish the compiled plugin to the configured web catalogue. Prompts for a
// name, bakes it into the document, then POSTs the .vstai JSON (html + wasm +
// params) to <publishUrl>/api/publish; the server serves a browser player that
// runs the WASM DSP live.
.withNativeFunction ("publish", [safe] (const VarArray&, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
const auto base = vstai::appsettings::publishUrl().trim();
if (base.isEmpty()) { complete (result (false, "Set a Publish server URL first — open Keys…")); return; }
if (! safe->processor.getDocument().hasPlugin())
{ complete (result (false, "Generate or compile a plugin first.")); return; }
// Ask for the name to publish under (defaults to the current name). The
// chosen name is baked into the document so the catalogue entry carries it.
const auto current = safe->processor.getDocument().name;
auto* aw = new juce::AlertWindow ("Publish to the catalogue",
"Name this creation — it's how players will find it in the web catalogue.",
juce::MessageBoxIconType::NoIcon);
aw->addTextEditor ("name", current == "Untitled" ? juce::String() : current, "Name");
aw->addButton ("Publish", 1, juce::KeyPress (juce::KeyPress::returnKey));
aw->addButton ("Cancel", 0, juce::KeyPress (juce::KeyPress::escapeKey));
aw->enterModalState (true, juce::ModalCallbackFunction::create ([safe, aw, complete, base] (int r)
{
// If the editor is gone the WebView bridge behind `complete` is dead too,
// and `aw` is being torn down with us — bail before touching either.
if (safe == nullptr) return;
if (r != 1) { complete (result (false, "Cancelled.")); return; }
const auto name = aw->getTextEditorContents ("name").trim();
if (name.isEmpty()) { complete (result (false, "Give it a name first.")); return; }
safe->processor.setDocumentName (name);
const juce::String payload = safe->processor.getDocument().toJsonString();
juce::Component::SafePointer<WebEditor> s2 (safe);
std::thread ([s2, base, payload, name, complete]() mutable
{
juce::String endpoint = base;
while (endpoint.endsWithChar ('/')) endpoint = endpoint.dropLastCharacters (1);
endpoint += "/api/publish";
int status = 0; juce::String resp;
auto opts = juce::URL::InputStreamOptions (juce::URL::ParameterHandling::inPostData)
.withExtraHeaders ("Content-Type: application/json")
.withConnectionTimeoutMs (15000)
.withStatusCode (&status);
if (auto in = juce::URL (endpoint).withPOSTData (payload).createInputStream (opts))
resp = in->readEntireStreamAsString();
const bool ok = (status >= 200 && status < 300);
juce::String link;
if (auto* o = juce::JSON::parse (resp).getDynamicObject()) link = o->getProperty ("url").toString();
juce::MessageManager::callAsync ([s2, complete, ok, name, status, link, base]() mutable
{
if (s2 == nullptr) return;
// On success, open the PR so the submitter can track review/publish status.
if (ok && link.isNotEmpty()) juce::URL (link).launchInDefaultBrowser();
complete (result (ok,
ok ? ("Submitted “" + name + "” — it will be tested & reviewed before publishing."
+ (link.isNotEmpty() ? " Tracking the PR in your browser." : juce::String()))
: ("Publish failed (HTTP " + juce::String (status)
+ "). Is the publish proxy reachable at " + base + "?")));
});
}).detach();
}), true);
safe->trackDialog (aw);
})
.withNativeFunction ("manualFixPrompt", [] (const VarArray& a, Completion complete)
{
// Fix request to paste back into the chatbot: failed AssemblyScript + the
// compiler diagnostics, in the same fenced-block reply format.
complete (vstai::buildManualFixPrompt (argStr (a, 0), argStr (a, 1)));
})
.withNativeFunction ("applyManualReply", [safe] (const VarArray& a, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
juce::var artifact; juce::String err;
if (! vstai::parseManualReply (argStr (a, 0), artifact, err)) { complete (result (false, err)); return; }
safe->processor.requestBuildFromArtifact (argStr (a, 1), artifact,
[safe] (const juce::String& stage) { if (safe) safe->emitEvent ("stage", stage); },
[safe, complete] (bool ok, juce::String message) { complete (result (ok, message)); });
})
.withNativeFunction ("applyManualParts", [safe] (const VarArray& a, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
const auto asmSrc = argStr (a, 0).trim();
const auto htmlSrc = argStr (a, 1).trim();
const auto jsonSrc = argStr (a, 2).trim();
const auto prompt = argStr (a, 3);
if (asmSrc.isEmpty()) { complete (result (false, "Paste the AssemblyScript first.")); return; }
// Optional params/explanation from the pasted JSON block (either the
// {params,explanation} object or a bare params array).
juce::var params; juce::String explanation;
if (jsonSrc.isNotEmpty())
{
const auto meta = juce::JSON::parse (jsonSrc);
if (auto* mo = meta.getDynamicObject())
{
params = mo->getProperty ("params");
explanation = mo->getProperty ("explanation").toString();
}
else if (meta.isArray()) { params = meta; }
}
auto* o = new juce::DynamicObject();
o->setProperty ("assembly", asmSrc);
o->setProperty ("html", htmlSrc);
o->setProperty ("params", params.isArray() ? params : juce::var (juce::Array<juce::var>()));
o->setProperty ("explanation", explanation.isNotEmpty() ? explanation
: juce::String ("Built from pasted parts."));
safe->processor.requestBuildFromArtifact (prompt, juce::var (o),
[safe] (const juce::String& stage) { if (safe) safe->emitEvent ("stage", stage); },
[safe, complete] (bool ok, juce::String message) { complete (result (ok, message)); });
})
.withNativeFunction ("newDoc", [safe] (const VarArray&, Completion complete)
{
if (safe != nullptr) safe->processor.newPlugin();
complete (safe != nullptr ? safe->currentState() : var());
})
// ---- code tabs --------------------------------------------------
.withNativeFunction ("compile", [safe] (const VarArray& a, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
const auto asmSrc = argStr (a, 0), htmlSrc = argStr (a, 1);
if (asmSrc.trim().isEmpty()) { complete (result (false, "The DSP (AssemblyScript) tab is empty.")); return; }
safe->processor.requestRecompile (asmSrc, htmlSrc,
[safe] (const juce::String& stage) { if (safe) safe->emitEvent ("stage", stage); },
[safe, complete] (bool ok, juce::String diagnostics)
{
complete (result (ok, ok ? juce::String ("Compiled successfully.") : diagnostics));
});
})
.withNativeFunction ("fixWithAI", [safe] (const VarArray& a, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
const auto asmSrc = argStr (a, 0), htmlSrc = argStr (a, 1);
if (asmSrc.trim().isEmpty()) { complete (result (false, "Write or generate some DSP first.")); return; }
safe->processor.applyEditedSource (asmSrc, htmlSrc);
const bool hasDiag = a.size() > 2 && argStr (a, 2).isNotEmpty();
juce::String prompt = hasDiag
? ("The current DSP does not compile. Fix the AssemblyScript so it compiles cleanly; keep the "
"behaviour, the HTML GUI and the parameter indices stable unless the fix requires changing "
"them.\n\n=== COMPILER OUTPUT ===\n" + argStr (a, 2))
: juce::String ("Review the current DSP and GUI for bugs and fix any issues you find, keeping "
"the plugin's behaviour and parameter layout stable.");
safe->processor.requestBuild (prompt,
[safe] (const juce::String& stage) { if (safe) safe->emitEvent ("stage", stage); },
[safe, complete] (bool ok, juce::String message) { complete (result (ok, message)); });
})
// ---- native file dialogs ---------------------------------------
.withNativeFunction ("save", [safe] (const VarArray&, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
safe->chooser = std::make_unique<juce::FileChooser> (
"Save plugin as .vstai",
juce::File::getSpecialLocation (juce::File::userDocumentsDirectory)
.getChildFile (safe->processor.getDocument().name + ".vstai"),
"*.vstai");
safe->chooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles,
[safe, complete] (const juce::FileChooser& fc)
{
auto file = fc.getResult();
if (file == juce::File() || safe == nullptr) { complete (result (false, "Cancelled.")); return; }
if (file.getFileExtension().isEmpty()) file = file.withFileExtension ("vstai");
juce::String err;
const bool ok = safe->processor.saveDocument (file, err);
complete (result (ok, ok ? ("Saved " + file.getFileName()) : ("Save failed: " + err)));
});
})
.withNativeFunction ("load", [safe] (const VarArray&, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
safe->chooser = std::make_unique<juce::FileChooser> (
"Open a .vstai plugin",
juce::File::getSpecialLocation (juce::File::userDocumentsDirectory), "*.vstai");
safe->chooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
[safe, complete] (const juce::FileChooser& fc)
{
auto file = fc.getResult();
if (file == juce::File() || safe == nullptr) { complete (result (false, "Cancelled.")); return; }
juce::String err;
const bool ok = safe->processor.loadDocument (file, err);
complete (result (ok, ok ? ("Loaded " + file.getFileName()) : ("Load failed: " + err)));
});
})
// ---- browse the public GitHub gallery and load examples on the fly ----
// Fetch happens in C++ (no browser CORS) against the Pages-hosted catalogue.
.withNativeFunction ("galleryIndex", [safe] (const VarArray&, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
juce::Component::SafePointer<WebEditor> s2 (safe);
std::thread ([s2, complete]() mutable
{
const juce::String url = "https://k1ln.github.io/VibePlugin/gallery/data/index.json";
int status = 0; juce::String body;
auto opts = juce::URL::InputStreamOptions (juce::URL::ParameterHandling::inAddress)
.withConnectionTimeoutMs (15000).withStatusCode (&status);
if (auto in = juce::URL (url).createInputStream (opts))
body = in->readEntireStreamAsString();
const bool ok = (status >= 200 && status < 300) && body.isNotEmpty();
auto items = ok ? juce::JSON::parse (body) : juce::var();
juce::MessageManager::callAsync ([s2, complete, ok, items, status]() mutable
{
if (s2 == nullptr) return;
auto* o = new juce::DynamicObject();
o->setProperty ("ok", ok);
if (ok) o->setProperty ("items", items);
else o->setProperty ("message", "Could not reach the gallery (HTTP " + juce::String (status) + ").");
complete (juce::var (o));
});
}).detach();
})
.withNativeFunction ("galleryLoad", [safe] (const VarArray& a, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
const juce::String slug = argStr (a, 0).trim();
if (slug.isEmpty()) { complete (result (false, "No plugin chosen.")); return; }
juce::Component::SafePointer<WebEditor> s2 (safe);
std::thread ([s2, slug, complete]() mutable
{
const juce::String url = "https://k1ln.github.io/VibePlugin/gallery/data/"
+ juce::URL::addEscapeChars (slug, false) + ".vstai";
int status = 0; juce::String body;
auto opts = juce::URL::InputStreamOptions (juce::URL::ParameterHandling::inAddress)
.withConnectionTimeoutMs (20000).withStatusCode (&status);
if (auto in = juce::URL (url).createInputStream (opts))
body = in->readEntireStreamAsString();
const bool got = (status >= 200 && status < 300) && body.isNotEmpty();
juce::MessageManager::callAsync ([s2, complete, got, body, status]() mutable
{
if (s2 == nullptr) return;
if (! got) { complete (result (false, "Download failed (HTTP " + juce::String (status) + ").")); return; }
juce::String err;
const bool ok = s2->processor.loadDocumentFromJson (body, err);
complete (result (ok, ok ? ("Loaded " + s2->processor.getDocument().name)
: ("Load failed: " + err)));
});
}).detach();
})
// ---- export as a standalone, locked whitelabel plugin ----------
.withNativeFunction ("exportPlugin", [safe] (const VarArray&, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
if (! safe->processor.getDocument().hasPlugin())
{
complete (result (false, "Generate a plugin first, then export it."));
return;
}
const auto suggested = safe->processor.getDocument().name;
safe->chooser = std::make_unique<juce::FileChooser> (
"Export as a standalone, locked plugin (.vst3)",
juce::File::getSpecialLocation (juce::File::userDesktopDirectory)
.getChildFile ((suggested.isNotEmpty() && suggested != "Untitled" ? suggested
: juce::String ("My Plugin")) + ".vst3"),
"*.vst3");
safe->chooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles,
[safe, complete] (const juce::FileChooser& fc)
{
auto file = fc.getResult();
if (file == juce::File() || safe == nullptr) { complete (result (false, "Cancelled.")); return; }
if (! file.getFileName().endsWithIgnoreCase (".vst3"))
file = file.getSiblingFile (file.getFileName() + ".vst3");
const auto productName = file.getFileNameWithoutExtension();
// Copy + bake + re-sign shells out to ditto/codesign and can take a
// few seconds — run it off the message thread. Capture the processor
// (it outlives the editor) rather than dereferencing the editor there.
auto* proc = &safe->processor;
std::thread ([proc, safe, file, productName, complete]
{
// Surface each stage (copy / sign / notarize / staple) in the
// status line — notarization alone can take a few minutes.
auto progress = [safe] (const juce::String& s)
{
juce::MessageManager::callAsync ([safe, s]
{ if (safe != nullptr) safe->emitEvent ("stage", s); });
};
juce::String message;
const bool ok = proc->exportToBundle (file, productName, progress, message);
const juce::String msg = ok ? message : ("Export failed: " + message);
juce::MessageManager::callAsync ([complete, ok, msg] { complete (result (ok, msg)); });
}).detach();
});
})
// ---- standard UI editor ----------------------------------------
.withNativeFunction ("getStandardUi", [] (const VarArray&, Completion complete)
{
complete (vstai::appsettings::standardUi());
})
.withNativeFunction ("saveStandardUi", [safe] (const VarArray& a, Completion complete)
{
vstai::appsettings::setStandardUi (argStr (a, 0));
// If no plugin is generated yet, the preview shows the standard kit —
// refresh it so the edit is visible immediately.
if (safe != nullptr && ! safe->processor.getDocument().hasPlugin())
safe->emitEvent ("documentChanged", safe->currentState());
complete (result (true, "Standard UI saved — it's now the house style for new generations."));
})
.withNativeFunction ("resetStandardUi", [] (const VarArray&, Completion complete)
{
vstai::appsettings::resetStandardUi();
complete (vstai::appsettings::standardUi());
})
// ---- settings + design schools ---------------------------------
// Diagnostics: the in-memory log ring plus the technical facts you would
// otherwise have to dig out of a log file on disk. A DAW gives the user no
// stdout, so the plugin has to be able to show its own state.
.withNativeFunction ("getDiagnostics", [safe] (const VarArray&, Completion complete)
{
auto* o = new juce::DynamicObject();
o->setProperty ("log", vstai::dev::ring().text());
#ifdef VSTAI_BUILD_ID
o->setProperty ("build", VSTAI_BUILD_ID);
#else
o->setProperty ("build", "(unknown)");
#endif
o->setProperty ("devMode", vstai::dev::enabled);
o->setProperty ("logFile", vstai::dev::logFilePath());
o->setProperty ("juce", juce::SystemStats::getJUCEVersion());
o->setProperty ("os", juce::SystemStats::getOperatingSystemName());
o->setProperty ("cpu", juce::SystemStats::getNumCpus());
if (safe != nullptr)
{
auto& p = safe->processor;
o->setProperty ("kind", p.isInstrument() ? "instrument" : "effect");
o->setProperty ("provider", p.getGenerationProvider());
o->setProperty ("model", p.getGenerationModel());
o->setProperty ("effort", p.getGenerationEffort());
o->setProperty ("thinking", p.getGenerationThinking());
o->setProperty ("asmChars", p.getDocument().assembly.length());
o->setProperty ("htmlChars", p.getDocument().html.length());
o->setProperty ("wasmBytes", (int) p.getDocument().wasm.size());
}
auto res = juce::File::getSpecialLocation (juce::File::currentExecutableFile)
.getParentDirectory().getParentDirectory().getChildFile ("Resources");
o->setProperty ("resourceDir", res.getFullPathName());
o->setProperty ("uiFound", res.getChildFile ("ui/shell.html").existsAsFile());
o->setProperty ("compilerFound", res.getChildFile ("asc-bundle.mjs").existsAsFile());
complete (var (o));
})
.withNativeFunction ("clearDiagnostics", [] (const VarArray&, Completion complete)
{
vstai::dev::ring().clear();
VSTAI_LOG ("diagnostics log cleared by user");
complete (var());
})
.withNativeFunction ("getSettings", [] (const VarArray&, Completion complete)
{
auto* o = new juce::DynamicObject();
o->setProperty ("anthropicKey", vstai::appsettings::rawAnthropicKey());
o->setProperty ("publishUrl", vstai::appsettings::rawPublishUrl());
o->setProperty ("notaryProfile", vstai::appsettings::notaryProfile());
o->setProperty ("designId", vstai::appsettings::selectedDesignId());
o->setProperty ("designTheme",
vstai::appsettings::designMeta (vstai::appsettings::selectedDesignId()).theme);
complete (var (o));
})
.withNativeFunction ("saveSettings", [] (const VarArray& a, Completion complete)
{
auto parsed = juce::JSON::parse (argStr (a, 0));
if (auto* o = parsed.getDynamicObject())
{
vstai::appsettings::setAnthropicKey (o->getProperty ("anthropicKey").toString().trim());
vstai::appsettings::setPublishUrl (o->getProperty ("publishUrl").toString().trim());
vstai::appsettings::setNotaryProfile (o->getProperty ("notaryProfile").toString().trim());
}
complete (result (true, "Settings saved."));
})
.withNativeFunction ("getDesigns", [] (const VarArray&, Completion complete)
{
const auto sel = vstai::appsettings::selectedDesignId();
juce::Array<var> rows;
auto add = [&rows, &sel] (const vstai::designs::DesignMeta& m)
{
auto* o = new juce::DynamicObject();
o->setProperty ("id", m.id);
o->setProperty ("name", m.name);
o->setProperty ("blurb", m.blurb);
o->setProperty ("builtin", m.builtin);
o->setProperty ("selected", m.id == sel);
o->setProperty ("theme", m.theme);
rows.add (var (o));
};
for (auto& id : vstai::designs::builtinIds())
add (vstai::appsettings::designMeta (id));
for (auto& v : vstai::appsettings::customDesignArray())
if (auto* o = v.getDynamicObject())
add (vstai::appsettings::designMeta (o->getProperty ("id").toString()));
complete (rows);
})
.withNativeFunction ("setDesign", [safe] (const VarArray& a, Completion complete)
{
const auto id = argStr (a, 0);
if (id.isNotEmpty()) vstai::appsettings::setSelectedDesignId (id);
// No plugin yet? The preview shows the standard kit — reseed it so the
// newly-selected design is visible immediately.
if (safe != nullptr && ! safe->processor.getDocument().hasPlugin())
safe->emitEvent ("documentChanged", safe->currentState());
complete (result (true, "Design: " + vstai::appsettings::selectedDesignName()));
})
.withNativeFunction ("removeDesign", [safe] (const VarArray& a, Completion complete)
{
const auto id = argStr (a, 0);
if (id.isNotEmpty()) vstai::appsettings::removeCustomDesign (id);
if (safe != nullptr && ! safe->processor.getDocument().hasPlugin())
safe->emitEvent ("documentChanged", safe->currentState());
complete (result (true, "Removed."));
})
.withNativeFunction ("exportDesign", [safe] (const VarArray& a, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
const auto id = argStr (a, 0).isNotEmpty() ? argStr (a, 0)
: vstai::appsettings::selectedDesignId();
const auto html = vstai::appsettings::designKitHtml (id);
safe->chooser = std::make_unique<juce::FileChooser> (
"Export design",
juce::File::getSpecialLocation (juce::File::userDocumentsDirectory)
.getChildFile (id + ".vibedesign.html"),
"*.html");
safe->chooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles,
[html, complete] (const juce::FileChooser& fc)
{
auto file = fc.getResult();
if (file == juce::File()) { complete (result (false, "Cancelled.")); return; }
if (file.getFileExtension().isEmpty()) file = file.withFileExtension ("html");
const bool ok = file.replaceWithText (html);
complete (result (ok, ok ? ("Exported " + file.getFileName()) : juce::String ("Export failed.")));
});
})
.withNativeFunction ("importDesign", [safe] (const VarArray&, Completion complete)
{
if (safe == nullptr) { complete (result (false, "Editor closed.")); return; }
safe->chooser = std::make_unique<juce::FileChooser> (
"Import a design (.html)",
juce::File::getSpecialLocation (juce::File::userDocumentsDirectory), "*.html");
safe->chooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
[safe, complete] (const juce::FileChooser& fc)
{
auto file = fc.getResult();
if (file == juce::File() || safe == nullptr) { complete (result (false, "Cancelled.")); return; }
const auto html = file.loadFileAsString();
if (html.isEmpty()) { complete (result (false, "Empty or unreadable file.")); return; }
auto meta = vstai::designs::parseMeta (html, file.getFileNameWithoutExtension());
// Never clobber a built-in id; give imports their own namespace.
if (meta.id.isEmpty() || vstai::designs::isBuiltin (meta.id))
meta.id = "custom-" + juce::Uuid().toString().substring (0, 8);
meta.builtin = false;
vstai::appsettings::upsertCustomDesign (meta, html);
vstai::appsettings::setSelectedDesignId (meta.id);
if (! safe->processor.getDocument().hasPlugin())
safe->emitEvent ("documentChanged", safe->currentState());
complete (result (true, "Imported \"" + meta.name + "\"."));
});
})
// ---- prompt history --------------------------------------------
.withNativeFunction ("getHistory", [safe] (const VarArray&, Completion complete)
{
juce::Array<var> rows;
if (safe != nullptr)
{
const auto& d = safe->processor.getDocument();
// newest first
for (auto it = d.revisions.rbegin(); it != d.revisions.rend(); ++it)
{
auto* o = new juce::DynamicObject();
o->setProperty ("id", it->id);
o->setProperty ("prompt", it->prompt.isNotEmpty() ? it->prompt : juce::String ("(no label)"));
o->setProperty ("model", it->model);
o->setProperty ("active", it->id == d.activeRevision);
o->setProperty ("timestamp", (juce::int64) it->timestamp);
rows.add (var (o));
}
}
complete (rows);
})
.withNativeFunction ("restoreRevision", [safe] (const VarArray& a, Completion complete)
{
if (safe != nullptr && a.size() > 0) safe->processor.restoreRevision ((int) a[0]);
complete (safe != nullptr ? safe->currentState() : var());
})
// ---- native dialogs (reused) -----------------------------------
.withNativeFunction ("openAccount", [safe] (const VarArray&, Completion complete)
{
if (safe != nullptr)
{
auto panel = std::make_unique<AccountPanel>();
juce::DialogWindow::LaunchOptions o;
o.content.setOwned (panel.release());
o.dialogTitle = "VibePlugin Cloud credits";
o.dialogBackgroundColour = juce::Colour (0xff141a24);
o.escapeKeyTriggersCloseButton = true;
o.useNativeTitleBar = true;
safe->trackDialog (o.launchAsync());
}
complete (var());
})
.withNativeFunction ("openKeys", [safe] (const VarArray&, Completion complete)
{
if (safe == nullptr) { complete (var()); return; }
auto* aw = new juce::AlertWindow ("API keys",
"Leave a field blank to fall back to the compiled-in / environment value.",
juce::MessageBoxIconType::NoIcon);
aw->addTextEditor ("anthropic", vstai::appsettings::rawAnthropicKey(), "Anthropic API key", true);
// GLM / Z.ai and Ollama fields are temporarily hidden (Anthropic-only for now).
// The backend still supports them — re-add these editors and their setters to restore.
// aw->addTextEditor ("glm", vstai::appsettings::rawGlmKey(), "GLM (Z.ai) API key", true);
// aw->addTextEditor ("glmurl", vstai::appsettings::rawGlmUrl(), "GLM URL (blank = Z.ai)");
// aw->addTextEditor ("ollama", vstai::appsettings::ollamaBaseUrl(), "Ollama URL");
aw->addTextEditor ("publish", vstai::appsettings::rawPublishUrl(), "Publish server URL (blank = default proxy)");
aw->addButton ("Save", 1, juce::KeyPress (juce::KeyPress::returnKey));
aw->addButton ("Cancel", 0, juce::KeyPress (juce::KeyPress::escapeKey));
aw->enterModalState (true, juce::ModalCallbackFunction::create ([safe, aw, complete] (int r)
{
// If the editor is gone the WebView bridge behind `complete` is dead too —
// invoking it (or reading `aw`, which we're being torn down with) would crash.
if (safe == nullptr) return;
if (r == 1)
{
vstai::appsettings::setAnthropicKey (aw->getTextEditorContents ("anthropic").trim());
// GLM / Ollama fields hidden — leave their stored values untouched.
// vstai::appsettings::setGlmKey (aw->getTextEditorContents ("glm").trim());
// vstai::appsettings::setGlmUrl (aw->getTextEditorContents ("glmurl").trim());
// vstai::appsettings::setOllamaUrl (aw->getTextEditorContents ("ollama").trim());
vstai::appsettings::setPublishUrl (aw->getTextEditorContents ("publish").trim());
}
complete (result (r == 1, r == 1 ? "Settings saved." : "Cancelled."));
}), true);
safe->trackDialog (aw);
});
web = std::make_unique<juce::WebBrowserComponent> (options);
addAndMakeVisible (*web);
#if JUCE_MAC
// Keyups the WKWebView swallows: re-inject into the page (GUI key handlers)
// and hand them back to the host window (FL typing-piano note-off) — see
// MacKeyUpMonitor.h.
keyUpMonitor = MacKeyUpMonitor::install (
[safe] (const std::string& key, const std::string& code)
{
if (safe != nullptr && safe->web != nullptr)
safe->web->evaluateJavascript (vstai::shim::syntheticKeyUpJs (key, code));
},
[safe]() -> void*
{
if (safe == nullptr) return nullptr;
if (auto* peer = safe->getPeer()) return peer->getNativeHandle();
return nullptr;
});
#endif
resetParamReflection();
// Stream document / build / reasoning changes into the SPA.
processor.onDocumentChanged = [safe]
{
if (safe == nullptr) return;
safe->resetParamReflection(); // new plugin: re-send all param positions
safe->emitEvent ("documentChanged", safe->currentState());
};
processor.onBuildStateChanged = [safe]
{
if (safe == nullptr) return;
auto* o = new juce::DynamicObject();
o->setProperty ("building", safe->processor.isBuilding());
o->setProperty ("stage", safe->processor.getBuildStage());
safe->emitEvent ("buildState", var (o));
};
processor.onThinkingDelta = [safe] (const juce::String& delta)
{
if (safe == nullptr) return;
auto& buf = safe->thinkingBuffer;
buf += delta;
constexpr int kMax = 16000;
if (buf.length() > kMax) buf = buf.substring (buf.length() - kMax);
safe->thinkingDirty = true;
};
startTimerHz (30); // reasoning repaint throttle + param reflection
setResizable (true, true);
setSize (980, 720);
web->goToURL (juce::WebBrowserComponent::getResourceProviderRoot());
refreshOllamaModelsAsync();
}
WebEditor::~WebEditor()
{
stopTimer();
#if JUCE_MAC
keyUpMonitor.reset(); // stop forwarding before `web` goes away
#endif
processor.onDocumentChanged = nullptr;
processor.onThinkingDelta = nullptr;
processor.onBuildStateChanged = nullptr;
// Close any still-open native dialog before `web` and this editor are gone.
// Deleting a modal AlertWindow fires its callback asynchronously with a 0
// ("cancelled") result; those callbacks guard on this editor's SafePointer
// (null by then) so they never touch the destroyed WebBrowser bridge.
for (auto& d : openDialogs)
if (auto* c = d.getComponent())
delete c;
openDialogs.clear();
}
void WebEditor::trackDialog (juce::Component* c)
{
if (c != nullptr)
openDialogs.add (c);
}
void WebEditor::resized()
{
if (web != nullptr) web->setBounds (getLocalBounds());
}
void WebEditor::timerCallback()
{
reflectParamsToGui();
if (! thinkingDirty) return;
thinkingDirty = false;
// Send only the tail so the SPA stays light.
auto lines = juce::StringArray::fromLines (thinkingBuffer);
while (lines.size() > 60) lines.remove (0);
emitEvent ("thinking", lines.joinIntoString ("\n"));
}
void WebEditor::resetParamReflection()
{
// Sentinel so the next poll re-sends every current value (GUI matches state).
for (auto& v : lastSentParam) v = -1.0e30f;
}
void WebEditor::reflectParamsToGui()
{
if (web == nullptr || ! pageReady) return;
juce::var values (new juce::DynamicObject());
auto* vo = values.getDynamicObject();
bool any = false;
for (const auto& p : processor.getDocument().params)
{
const int i = p.index;
if (i < 0 || i >= vstai::kMaxParams) continue;
const float v = processor.getParamValue (i);
// Relative epsilon so tiny float noise doesn't spam the GUI.
if (std::abs (v - lastSentParam[i]) > 1.0e-5f * (1.0f + std::abs (v)))
{
lastSentParam[i] = v;
vo->setProperty (juce::String (i), v);
any = true;
}
}
if (any)
{
auto* o = new juce::DynamicObject();
o->setProperty ("values", values);
emitEvent ("paramUpdate", juce::var (o));
}
}
void WebEditor::emitEvent (const juce::Identifier& id, const var& payload)
{
if (web != nullptr && pageReady) web->emitEventIfBrowserIsVisible (id, payload);
}
void WebEditor::refreshOllamaModelsAsync()
{
const juce::String baseUrl = vstai::appsettings::ollamaBaseUrl();
juce::Component::SafePointer<WebEditor> safe (this);
std::thread ([safe, baseUrl]
{
juce::String err;
auto models = LlmClient::listOllamaModels (baseUrl, err);
juce::MessageManager::callAsync ([safe, models]
{
if (safe == nullptr || safe->ollamaModels == models) return;
safe->ollamaModels = models;
safe->emitEvent ("modelsChanged", safe->currentState()); // SPA rebuilds the select
});
}).detach();
}
juce::var WebEditor::currentState() const
{
const auto& d = processor.getDocument();
auto* o = new juce::DynamicObject();
o->setProperty ("provider", processor.getGenerationProvider());
o->setProperty ("model", processor.getGenerationModel());
o->setProperty ("effort", processor.getGenerationEffort());
o->setProperty ("thinking", processor.getGenerationThinking());
o->setProperty ("models", modelCatalog (ollamaModels));
o->setProperty ("isInstrument", processor.isInstrument());
o->setProperty ("hasPlugin", d.hasPlugin());
o->setProperty ("name", d.name);
o->setProperty ("assembly", d.assembly);
o->setProperty ("html", d.html.isNotEmpty() ? d.html : processor.getDisplayHtml());
o->setProperty ("signedIn", vstai::appsettings::isSignedIn());
o->setProperty ("building", processor.isBuilding());
o->setProperty ("stage", processor.getBuildStage());
o->setProperty ("designId", vstai::appsettings::selectedDesignId());
// The selected design's chrome palette, so the shell re-skins to match the
// generated GUI on every state refresh (incl. live design switches).
o->setProperty ("designTheme",
vstai::appsettings::designMeta (vstai::appsettings::selectedDesignId()).theme);
return var (o);
}
std::optional<juce::WebBrowserComponent::Resource>
WebEditor::provideResource (const juce::String& rawUrl)
{
const juce::String url = rawUrl.startsWith ("/") ? rawUrl : ("/" + rawUrl);
// ---- param / note / sample bridge from the /preview iframe --------------
if (auto r = vstai::shim::handleBridgeFetch (processor, url))
return r;
// ---- the sandboxed generated GUI ---------------------------------------
// Pass the current param values so the injected bridge stops the GUI's boot from
// resetting them to defaults — keeps your sound on reopen (see BridgeShim.h).
if (url == "/preview" || url.endsWithIgnoreCase ("/preview"))
return juce::WebBrowserComponent::Resource {
toBytes (withBridge (processor.getDisplayHtml(), vstai::shim::restoredValuesJson (processor))),
"text/html;charset=UTF-8" };
// ---- the SPA shell -----------------------------------------------------
if (url == "/" || url.endsWithIgnoreCase ("/index.html"))
{
auto html = vstai::webassets::readText ("shell.html");
if (html.isEmpty()) html = "<!doctype html><meta charset=utf-8><body style='font:14px sans-serif;color:#fff;background:#0c0f16;padding:24px'>"
"shell.html not found in Resources/ui. Rebuild to ship the UI assets.</body>";
// Cache-bust the shell's own resources so a host WebView can never serve a
// stale shell.js/css from a previous (possibly broken) load.
const juce::String v = "?v=" + cacheToken;
html = html.replace ("\"shell.css\"", "\"shell.css" + v + "\"")
.replace ("\"shell.js\"", "\"shell.js" + v + "\"")
.replace ("\"vendor/monaco/vs/loader.js\"", "\"vendor/monaco/vs/loader.js" + v + "\"");
// Stamp the header with the build this binary came from. DAWs cache plugin
// binaries, so without this there is no way to tell from the GUI whether a
// rebuild actually got loaded or the host is still running the old one.
#ifdef VSTAI_BUILD_ID
html = html.replace ("__VSTAI_BUILD__", VSTAI_BUILD_ID);
#else
html = html.replace ("__VSTAI_BUILD__", "dev");
#endif
return juce::WebBrowserComponent::Resource { toBytes (html), "text/html;charset=UTF-8" };
}
// ---- any other ui/ asset (css, js, Monaco, fonts) ----------------------
// Strip any ?v=… cache-buster (and other query) before hitting the disk.
const auto rel = url.substring (1).upToFirstOccurrenceOf ("?", false, false);
auto file = vstai::webassets::resolve (rel);
if (file.existsAsFile())
{
juce::MemoryBlock mb;
if (file.loadFileAsData (mb))
return juce::WebBrowserComponent::Resource { toBytes (mb), vstai::webassets::mimeFor (rel) };
}
return std::nullopt;
}