-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.ts
More file actions
1641 lines (1557 loc) · 70.5 KB
/
Copy pathmain.ts
File metadata and controls
1641 lines (1557 loc) · 70.5 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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import "./style.css";
import {
BrowserOpenURL,
EventsOn,
Quit,
WindowMinimise,
WindowToggleMaximise,
} from "../wailsjs/runtime/runtime";
import {
AddFleetDevice,
BackgroundHelperStatus,
InstallBackgroundHelper,
RemoveBackgroundHelper,
CheckRuntime,
CollectService,
CompleteOnboarding,
DeployService,
GetAppState,
GetCredentials,
GetFleetState,
GetLogs,
GetRuntimeGuides,
GetSettingsState,
RemoveFleetDevice,
RefreshDeployments,
RemoveService,
SaveSettings,
SaveCredentials,
StartService,
StopService,
} from "../wailsjs/go/main/App";
import type { AppState, BackgroundStatus, DailyPoint, Deployment, FleetState, HealthScore, InstallGuide, MystNode, PointsBalance, Service, ServiceEarning, SettingsState } from "./wails";
let state: AppState | null = null;
let selectedService: Service | null = null;
let onboardingStep: "welcome" | "runtime" = "welcome";
type View = "dashboard" | "wizard" | "catalog" | "settings" | "fleet";
let activeView: View = "dashboard";
let wizardStep = 1;
let wizardCategories: string[] = [];
let wizardSelected: string[] = [];
let catalogFilter = "all";
let catalogSearch = "";
let resetScrollAfterRender = false;
const root = document.querySelector<HTMLDivElement>("#app")!;
async function boot() {
try {
state = await GetAppState();
render();
wireBackendEvents();
} catch (error) {
renderError(error);
}
}
let eventRefreshInFlight = false;
// The Go backend emits these after background collection cycles and deployment
// changes. Refresh state so passive earnings appear without the user navigating.
function wireBackendEvents() {
EventsOn("earnings:changed", () => void onBackendEvent());
EventsOn("deployment:changed", () => void onBackendEvent());
// Background/startup failures the Go side reports via app:error had no listener,
// so ~every background error was silently dropped. Surface them to the user.
EventsOn("app:error", (payload) => showErrorToast(payload));
EventsOn("app:notice", (payload) => showInfoToast(payload));
}
async function onBackendEvent() {
if (eventRefreshInFlight) return;
if (!state || !state.config.firstRunComplete) return;
eventRefreshInFlight = true;
try {
state = await GetAppState();
// Only re-render on the dashboard; other views own an in-progress form, so
// update state silently and let them pick it up on their next natural render.
if (activeView === "dashboard") render();
} catch {
// transient background refresh failure — ignore; next event/read recovers
} finally {
eventRefreshInFlight = false;
}
}
function render() {
if (!state) return;
if (!state.config.firstRunComplete) {
renderOnboarding(state);
return;
}
if (activeView === "wizard") {
renderSetupWizard(state);
return;
}
if (activeView === "catalog") {
renderCatalog(state);
return;
}
if (activeView === "settings") {
void renderSettings(state);
return;
}
if (activeView === "fleet") {
void renderFleet(state);
return;
}
renderDashboard(state);
}
function renderOnboarding(current: AppState) {
if (onboardingStep === "welcome") {
renderWelcome();
return;
}
const runtime = current.runtime;
// Onboarding proceeds on EITHER runtime: Docker (runs every service) OR the
// always-on native runtime (runs services that ship a native app, no Docker
// needed). Native-only is a READY state, not a warning — only "neither" warns.
const dockerReady = runtime.available;
const runtimeReady = runtime.available || runtime.nativeAvailable;
const runtimeTitle = dockerReady
? "Runtime ready"
: runtime.nativeAvailable
? "Native mode ready — no Docker needed"
: "Runtime setup needed";
// Docker/neither show the backend's (Docker-centric) message, escaped; native-only
// shows honest static copy instead of the alarming "choose a runtime" Docker text.
const runtimeBody = !dockerReady && runtime.nativeAvailable
? "You can run services that ship a native app right away. A few container-only services would additionally need Docker."
: escapeHtml(runtime.message);
root.innerHTML = `
${titlebar()}
${synthwaveBackground()}
<main class="onboarding">
<section class="onboarding-card">
<p class="eyebrow">CashPilot Desktop</p>
<h1>Put your idle machine to work</h1>
<p class="subtitle">Share spare bandwidth, storage, CPU, RAM, or GPU with real networks, then track what each service earns from one place.</p>
<div class="runtime-card ${runtimeReady ? "ok" : "warn"}">
<strong>${runtimeTitle}</strong>
<span>${runtimeBody}</span>
${runtime.context ? `<small>Docker context: ${escapeHtml(runtime.context)}</small>` : ""}
</div>
<div class="actions">
<button class="primary" id="continue-btn" ${runtimeReady ? "" : "disabled"}>Open Dashboard</button>
<button class="secondary" id="refresh-runtime">Check Again</button>
</div>
<div id="install-guides" class="guide-grid"></div>
</section>
</main>
`;
wireChrome();
document.querySelector("#continue-btn")?.addEventListener("click", async () => {
await CompleteOnboarding();
state = await GetAppState();
render();
});
document.querySelector("#refresh-runtime")?.addEventListener("click", async () => {
const updated = await CheckRuntime();
state = {...current, runtime: updated, guides: await GetRuntimeGuides()};
render();
});
renderGuides(current.guides || []);
}
function renderWelcome() {
root.innerHTML = `
${titlebar()}
${synthwaveBackground()}
<main class="welcome-screen">
<section class="welcome-copy">
<p class="eyebrow">CashPilot Desktop</p>
<h1>Welcome to CashPilot</h1>
<p class="subtitle">Let your spare resources earn in the background while CashPilot handles setup, monitoring, and payouts from one place.</p>
<button class="primary" id="get-started">Get Started</button>
</section>
</main>
`;
wireChrome();
document.querySelector("#get-started")?.addEventListener("click", () => {
onboardingStep = "runtime";
render();
});
}
function renderGuides(guides: InstallGuide[]) {
const holder = document.querySelector<HTMLDivElement>("#install-guides");
if (!holder) return;
holder.innerHTML = guides.map((guide) => `
<article class="guide">
<h3>${escapeHtml(guide.name)}</h3>
<p>${escapeHtml(guide.description)}</p>
<button class="guide-link" data-url="${escapeHtml(guide.url)}">Open install guide</button>
${(guide.commands || []).map((cmd) => `<code>${escapeHtml(cmd)}</code>`).join("")}
${(guide.notes || []).map((note) => `<small>${escapeHtml(note)}</small>`).join("")}
</article>
`).join("");
holder.querySelectorAll<HTMLButtonElement>("[data-url]").forEach((button) => {
button.addEventListener("click", () => {
const url = button.dataset.url;
if (url) BrowserOpenURL(url);
});
});
}
function renderDashboard(current: AppState) {
const services = current.services || [];
const deployments = current.deployments || [];
const earnings = current.earnings || [];
const summary = current.summary;
const disp = summary?.displayCurrency || current.config.displayCurrency || "USD";
const runningCount = deployments.filter((dep) => dep.status === "running").length;
const total = summary?.total ?? 0;
const daily = summary?.daily || [];
const breakdown = summary?.breakdown || [];
const points = summary?.points || [];
root.innerHTML = `
${titlebar()}
<div class="app-layout">
${appSidebar("dashboard")}
<div class="main-content">
${topbar("Dashboard", total, current)}
<main class="page-content">
<section class="stats-grid">
${metricCard("Total Balance", formatBalance(total, disp), summary?.ratesStale ? "Rates may be stale" : "Across convertible services")}
${metricCard("Today", formatBalance(summary?.today ?? 0, disp), changeCaption(summary?.todayChange ?? 0, "vs yesterday"))}
${metricCard("This Month", formatBalance(summary?.month ?? 0, disp), summary?.monthChange ? changeCaption(summary.monthChange, "vs last month") : "So far this month")}
${metricCard("Active Services", `${runningCount}`, "Containers currently running")}
</section>
<section class="card earnings-panel">
<div class="card-header">
<div>
<span class="card-title">Earnings</span>
<p class="muted compact-copy">Daily earnings in ${escapeHtml(disp)}.${summary?.ratesStale ? ` <span class="badge warn">rates stale</span>` : ""}</p>
</div>
<div class="tab-strip">
<button class="tab-btn active">30 days</button>
</div>
</div>
${renderEarningsChart(daily, disp)}
<div class="earnings-breakdown">
${breakdown.length ? breakdown.map((item) => renderEarningBreakdown(item, disp)).join("") : `<p class="muted">No earnings yet. Deploy a service, add credentials, then collect earnings.</p>`}
</div>
</section>
${points.length ? renderPointsSection(points) : ""}
<section class="card dashboard-panel">
<div class="card-header">
<span class="card-title">Deployed Services</span>
<div class="header-actions">
<button class="secondary compact-btn" id="refresh">Refresh</button>
<button class="primary compact-btn" id="open-wizard">+ Add Service</button>
</div>
</div>
<div class="services-table-wrap">
${renderServicesTable(services, deployments, earnings, current.health, current.serviceDetails, current.outdatedServices)}
</div>
</section>
<pre id="service-output" class="output dashboard-output"></pre>
</main>
</div>
</div>
`;
wireChrome();
wireShellNav();
maybeResetScroll();
document.querySelector("#refresh")?.addEventListener("click", refreshState);
document.querySelector("#refresh-services")?.addEventListener("click", refreshState);
document.querySelector("#open-wizard")?.addEventListener("click", openWizard);
document.querySelector("#open-wizard-empty")?.addEventListener("click", openWizard);
document.querySelectorAll<HTMLButtonElement>("[data-row-action]").forEach((button) => {
button.addEventListener("click", () => {
const slug = button.dataset.slug || "";
const action = button.dataset.rowAction || "";
void runServiceAction(slug, action);
});
});
document.querySelectorAll<HTMLButtonElement>("[data-url]").forEach((button) => {
button.addEventListener("click", () => {
const url = button.dataset.url;
if (url) BrowserOpenURL(url);
});
});
}
function metricCard(label: string, value: string, caption: string) {
return `
<article class="metric-card">
<span>${escapeHtml(label)}</span>
<strong>${escapeHtml(value)}</strong>
<small>${escapeHtml(caption)}</small>
</article>
`;
}
function appSidebar(active: View) {
return `
<aside class="cp-sidebar">
<div class="sidebar-brand">
${officialLogoMark()}
CashPilot
</div>
<nav class="sidebar-nav">
${navButton("dashboard", "Dashboard", active)}
${navButton("wizard", "Setup Wizard", active)}
${navButton("catalog", "Service Catalog", active)}
${navButton("settings", "Settings", active)}
${navButton("fleet", "Fleet", active)}
</nav>
<div class="sidebar-footer">
<div class="footer-links">
<button class="footer-link" data-url="https://github.com/GeiserX/CashPilot-Desktop" title="GitHub">GitHub</button>
<button class="footer-link" data-url="https://github.com/sponsors/GeiserX" title="Sponsor">Sponsor</button>
</div>
<span>Desktop v${__APP_VERSION__}</span>
</div>
</aside>
`;
}
function officialLogoMark() {
return `
<svg class="brand-logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true">
<defs>
<linearGradient id="brand-sun-gradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#FFD54F"/>
<stop offset="35%" stop-color="#FF9800"/>
<stop offset="65%" stop-color="#E91E63"/>
<stop offset="100%" stop-color="#7B1FA2"/>
</linearGradient>
<clipPath id="brand-sun-clip"><circle cx="16" cy="16" r="11"/></clipPath>
</defs>
<circle cx="16" cy="16" r="11" fill="url(#brand-sun-gradient)"/>
<g clip-path="url(#brand-sun-clip)">
<rect x="4" y="16" width="24" height="1.2" fill="#0A0A1A" opacity="0.85"/>
<rect x="4" y="18.5" width="24" height="1.5" fill="#0A0A1A" opacity="0.85"/>
<rect x="4" y="21.5" width="24" height="2" fill="#0A0A1A" opacity="0.85"/>
<rect x="4" y="25" width="24" height="3" fill="#0A0A1A" opacity="0.85"/>
<g transform="translate(16,12) rotate(30) scale(0.4)">
<path d="M0,-28 L2.5,-6 L30,2 L3,5 L4,12 L0,8 L-4,12 L-3,5 L-30,2 L-2.5,-6 Z" fill="#0A0A1A" opacity="0.65"/>
</g>
</g>
</svg>
`;
}
function navButton(view: View, label: string, active: string) {
return `<button class="sidebar-link ${active === view ? "active" : ""}" data-view="${view}">${escapeHtml(label)}</button>`;
}
function topbar(title: string, totalBalance: number, current: AppState) {
const notifications = current.notifications || [];
return `
<header class="topbar">
<div class="topbar-left">
<span class="topbar-title">${escapeHtml(title)}</span>
</div>
<div class="topbar-right">
<span class="runtime-dot ${current.runtime.available || current.runtime.nativeAvailable ? "ok" : "warn"}"></span>
<span class="topbar-runtime">${current.runtime.available ? "Runtime ready" : current.runtime.nativeAvailable ? "Native mode" : "Runtime offline"}</span>
<span class="topbar-earnings">${formatBalance(totalBalance, current.config.displayCurrency || "USD")}</span>
<select class="currency-select" id="currency-select" title="Display currency">
${(current.currencies || ["USD", "EUR"]).map((currency) => `<option value="${currency}" ${currency === current.config.displayCurrency ? "selected" : ""}>${currency}</option>`).join("")}
</select>
<details class="notification-menu">
<summary aria-label="Notifications">Alerts <span class="notify-badge">${notifications.length}</span></summary>
<div class="notification-popover">
<strong>Notifications</strong>
${notifications.length ? notifications.map((item) => `
<div class="notification-item ${escapeHtml(item.level)}">
<span>${escapeHtml(item.title)}</span>
<small>${escapeHtml(item.message)}</small>
</div>
`).join("") : `<p class="muted">No alerts right now.</p>`}
</div>
</details>
</div>
</header>
`;
}
function wireShellNav() {
document.querySelectorAll<HTMLButtonElement>("[data-view]").forEach((button) => {
button.addEventListener("click", () => {
const next = button.dataset.view;
if (next === "dashboard" || next === "wizard" || next === "catalog" || next === "settings" || next === "fleet") {
activeView = next;
if (next === "wizard") {
wizardStep = 1;
}
resetScrollAfterRender = true;
render();
}
});
});
document.querySelectorAll<HTMLButtonElement>("[data-url]").forEach((button) => {
button.addEventListener("click", () => {
const url = button.dataset.url;
if (url) BrowserOpenURL(url);
});
});
document.querySelector<HTMLSelectElement>("#currency-select")?.addEventListener("change", async (event) => {
const currency = (event.target as HTMLSelectElement).value;
await SaveSettings({displayCurrency: currency});
state = await GetAppState();
render();
});
}
function renderCatalog(current: AppState) {
const total = totalBalance(current);
const services = (current.services || []).filter((service) => {
const matchesCategory = catalogFilter === "all" || service.category === catalogFilter;
const haystack = `${service.name} ${service.shortDescription} ${service.description}`.toLowerCase();
return matchesCategory && haystack.includes(catalogSearch.toLowerCase());
});
const categories = ["all", "bandwidth", "depin", "storage", "compute"];
root.innerHTML = `
${titlebar()}
<div class="app-layout">
${appSidebar("catalog")}
<div class="main-content">
${topbar("Service Catalog", total, current)}
<main class="page-content">
<section class="card">
<div class="card-header">
<span class="card-title">Available Services</span>
<input class="catalog-search" id="catalog-search" type="search" placeholder="Search services..." value="${escapeHtml(catalogSearch)}" />
</div>
<div class="filter-tabs">
${categories.map((category) => `<button class="filter-tab ${catalogFilter === category ? "active" : ""}" data-filter="${category}">${escapeHtml(capitalize(category))}</button>`).join("")}
</div>
<div class="catalog-grid">
${services.map((service) => renderCatalogCard(service, current.deployments || [], current.outdatedServices)).join("")}
</div>
</section>
</main>
</div>
</div>
`;
wireChrome();
wireShellNav();
maybeResetScroll();
document.querySelector<HTMLInputElement>("#catalog-search")?.addEventListener("input", (event) => {
catalogSearch = (event.target as HTMLInputElement).value;
render();
});
document.querySelectorAll<HTMLButtonElement>("[data-filter]").forEach((button) => {
button.addEventListener("click", () => {
catalogFilter = button.dataset.filter || "all";
render();
});
});
document.querySelectorAll<HTMLButtonElement>("[data-service]").forEach((button) => {
button.addEventListener("click", () => openWizard(button.dataset.service));
});
document.querySelectorAll<HTMLButtonElement>("[data-url]").forEach((button) => {
button.addEventListener("click", () => {
const url = button.dataset.url;
if (url) BrowserOpenURL(url);
});
});
}
function renderCatalogCard(service: Service, deployments: Deployment[], outdated: string[] | null) {
const deployed = deployments.some((deployment) => deployment.slug === service.slug);
const isOutdated = deployed && (outdated || []).includes(service.slug);
const signupUrl = service.referral?.signupUrl || service.website;
return `
<article class="catalog-card">
<div class="service-card-header">
<div class="service-icon">${escapeHtml(service.name[0] || "?")}</div>
<div>
<strong>${escapeHtml(service.name)}</strong>
<div class="badge-row">
<span class="badge">${escapeHtml(service.category)}</span>
<span class="badge ${deployed ? "success" : ""}">${deployed ? "Deployed" : service.manualOnly ? "Manual" : "Available"}</span>
${isOutdated ? `<span class="badge warn" title="The provider changed this service's image. Re-deploy from the catalog to keep earning.">update available</span>` : ""}
</div>
</div>
</div>
<p>${escapeHtml(service.shortDescription || service.description)}</p>
<div class="card-actions">
${service.manualOnly && signupUrl ? `<button class="primary compact-btn" data-url="${escapeHtml(signupUrl)}">Visit</button>` : `<button class="primary compact-btn" data-service="${escapeHtml(service.slug)}">${deployed ? "Manage" : "Deploy"}</button>`}
${signupUrl ? `<button class="secondary compact-btn" data-url="${escapeHtml(signupUrl)}">Sign Up</button>` : ""}
</div>
</article>
`;
}
async function renderSettings(current: AppState) {
let settings: SettingsState;
try {
settings = await GetSettingsState();
} catch (error) {
showErrorToast({scope: "settings", error: String(error)});
return;
}
const total = totalBalance(current);
// Background-helper state is derived live from the OS (not a stored preference):
// installed = a login agent is registered, running = the service manager reports it
// alive. Reject only if the app isn't ready yet, in which case the toggle is disabled.
let background: BackgroundStatus | null = null;
let backgroundError = "";
try {
background = await BackgroundHelperStatus();
} catch (error) {
backgroundError = String(error);
}
root.innerHTML = `
${titlebar()}
<div class="app-layout">
${appSidebar("settings")}
<div class="main-content">
${topbar("Settings", total, current)}
<main class="page-content">
<section class="card">
<div class="card-header">
<div>
<span class="card-title">Environment Variables</span>
<p class="muted compact-copy">Variables that affect this desktop node. Locked values are controlled by the app or OS.</p>
</div>
<button class="primary compact-btn" id="save-settings">Save Variables</button>
</div>
<div class="settings-list">
${settings.environment.map(renderEnvSetting).join("")}
</div>
</section>
<section class="card">
<div class="card-header">
<div>
<span class="card-title">Earnings Collection</span>
<p class="muted compact-copy">Credentials for automated earnings tracking. Manual/mobile-first services can be tracked without deploying a container.</p>
</div>
</div>
<div class="collector-grid">
${settings.collectors.map(renderCollectorSetting).join("")}
</div>
</section>
${renderBackgroundCard(background, backgroundError)}
</main>
</div>
</div>
`;
wireChrome();
wireShellNav();
maybeResetScroll();
document.querySelector("#save-settings")?.addEventListener("click", () => void saveSettingsFromForm());
document.querySelector<HTMLInputElement>("#bg-helper-toggle")?.addEventListener("change", (event) => void toggleBackgroundHelper(event));
document.querySelectorAll<HTMLButtonElement>("[data-service]").forEach((button) => {
button.addEventListener("click", () => openWizard(button.dataset.service));
});
}
function renderEnvSetting(item: SettingsState["environment"][number]) {
const editableKey = envInputName(item.key);
return `
<label class="setting-row">
<span>
<strong>${escapeHtml(item.label)}</strong>
<small>${escapeHtml(item.key)} · ${escapeHtml(item.source)}</small>
</span>
<input data-setting="${editableKey}" value="${escapeHtml(item.value)}" ${item.readOnly ? "readonly" : ""} />
<small>${escapeHtml(item.help)}</small>
</label>
`;
}
function renderCollectorSetting(item: SettingsState["collectors"][number]) {
return `
<button class="collector-row" data-service="${escapeHtml(item.slug)}">
<span>${escapeHtml(item.name)}</span>
<small>${escapeHtml(item.collector || "manual")}</small>
<strong class="${item.configured ? "configured" : ""}">${item.configured ? "Configured" : "Not configured"}</strong>
</button>
`;
}
async function saveSettingsFromForm() {
const values: Record<string, string> = {};
document.querySelectorAll<HTMLInputElement>("[data-setting]").forEach((input) => {
if (!input.readOnly) values[input.dataset.setting || ""] = input.value;
});
try {
await SaveSettings(values);
state = await GetAppState();
render();
} catch (error) {
showErrorToast({scope: "settings", error: String(error)});
}
}
// renderBackgroundCard renders the "Background Earning" settings card. The toggle
// reflects the live OS state (background.installed); when the status call rejected
// (app not ready), the toggle is disabled and the reason is shown.
function renderBackgroundCard(background: BackgroundStatus | null, backgroundError: string) {
const unavailable = background === null;
const on = Boolean(background?.installed);
const running = Boolean(background?.running);
let title: string;
let detail: string;
if (unavailable) {
title = "Background earning unavailable";
detail = backgroundError || "The background helper can't be reached right now.";
} else if (on && running) {
title = "Earning in the background";
detail = "CashPilot keeps your earners running after you close the window, and starts them automatically when you sign in.";
} else if (on) {
title = "Starting in the background…";
detail = "The helper is registered with your operating system and will start momentarily.";
} else {
title = "Off — earners stop when you quit";
detail = "Turn on to keep earning after you close CashPilot. Registers a per-user helper the OS keeps alive and restarts — no admin required.";
}
const statusClass = unavailable ? "is-unavailable" : on && running ? "is-on" : "";
return `
<section class="card">
<div class="card-header">
<div>
<span class="card-title">Background Earning</span>
<p class="muted compact-copy">Keep earning when CashPilot is closed. Your operating system keeps a per-user helper running and restarts it automatically — no admin rights, no separate service to manage.</p>
</div>
</div>
<div class="bg-toggle-row">
<label class="switch" title="Keep earning in the background">
<input type="checkbox" id="bg-helper-toggle" role="switch" ${on ? "checked" : ""} ${unavailable ? "disabled" : ""} aria-label="Keep earning in the background" />
<span class="switch-track"><span class="switch-thumb"></span></span>
</label>
<div class="bg-toggle-status ${statusClass}">
<strong>${escapeHtml(title)}</strong>
<small>${escapeHtml(detail)}</small>
</div>
</div>
</section>
`;
}
// toggleBackgroundHelper installs or removes the OS login agent when the switch is
// flipped, then re-renders Settings so the card reflects the true OS state. On failure
// the switch is reverted and the error surfaced.
async function toggleBackgroundHelper(event: Event) {
const input = event.target as HTMLInputElement;
const enable = input.checked;
input.disabled = true;
try {
if (enable) {
await InstallBackgroundHelper();
showInfoToast({scope: "background", message: "Earning will continue after you close CashPilot."});
} else {
await RemoveBackgroundHelper();
showInfoToast({scope: "background", message: "Background earning turned off."});
}
// Re-render the active (Settings) view so the card reflects fresh OS state;
// render() null-guards module state, then re-invokes renderSettings.
render();
} catch (error) {
input.checked = !enable;
input.disabled = false;
showErrorToast({scope: "background", error: String(error)});
}
}
function envInputName(key: string) {
const names: Record<string, string> = {
CASHPILOT_HOSTNAME_PREFIX: "hostnamePrefix",
CASHPILOT_COLLECT_INTERVAL: "collectIntervalMinutes",
CASHPILOT_DISPLAY_CURRENCY: "displayCurrency",
CASHPILOT_FLEET_BIND: "fleetBindAddress",
CASHPILOT_FLEET_PORT: "fleetPort",
TZ: "timezone",
};
return names[key] || key;
}
async function renderFleet(current: AppState) {
let fleet: FleetState;
try {
fleet = await GetFleetState();
} catch (error) {
showErrorToast({scope: "fleet", error: String(error)});
return;
}
const total = totalBalance(current);
root.innerHTML = `
${titlebar()}
<div class="app-layout">
${appSidebar("fleet")}
<div class="main-content">
${topbar("Fleet Management", total, current)}
<main class="page-content">
<section class="stats-grid">
${metricCard("Workers", `${fleet.workers}`, "Desktop and server workers")}
${metricCard("Mobiles", `${fleet.mobiles}`, "Registered mobile devices")}
${metricCard("Online", `${fleet.online}`, "Devices currently reachable")}
${metricCard("Services", `${fleet.services}`, "Available providers")}
</section>
<section class="card">
<div class="card-header">
<span class="card-title">Add Worker or Mobile</span>
</div>
<p class="muted">Point CashPilot workers, mobile companions, or another machine on your LAN at this desktop API. The API listens for authenticated heartbeats and registers devices automatically.</p>
<div class="connection-grid">
${detailStat("UI URL", fleet.uiUrl)}
${detailStat("Local API", fleet.localApiUrl)}
${detailStat("API Key", fleet.apiKey ? "Generated" : "Missing")}
${detailStat("Listener", fleet.apiListening ? "Listening" : "Offline")}
</div>
<div class="fleet-snippets">
<div>
<div class="snippet-header"><strong>Docker worker</strong><button class="secondary compact-btn" data-copy="${escapeHtml(fleet.workerSnippet)}">Copy</button></div>
<code>${escapeHtml(fleet.workerSnippet)}</code>
</div>
<div>
<div class="snippet-header"><strong>Mobile / companion</strong><button class="secondary compact-btn" data-copy="${escapeHtml(fleet.mobileSnippet)}">Copy</button></div>
<code>${escapeHtml(fleet.mobileSnippet)}</code>
</div>
</div>
<div class="fleet-form">
<input id="fleet-name" placeholder="Device name" />
<select id="fleet-kind">
<option value="worker">Worker</option>
<option value="mobile">Mobile</option>
</select>
<input id="fleet-endpoint" placeholder="Endpoint or device note" />
<input id="fleet-services" placeholder="Services, comma-separated" />
<button class="primary compact-btn" id="add-fleet-device">Register</button>
</div>
</section>
<section class="card">
<div class="card-header">
<span class="card-title">Devices</span>
</div>
<div class="fleet-list">
${fleet.devices.map(renderFleetDevice).join("")}
</div>
</section>
</main>
</div>
</div>
`;
wireChrome();
wireShellNav();
maybeResetScroll();
document.querySelector("#add-fleet-device")?.addEventListener("click", () => void addFleetDevice());
document.querySelectorAll<HTMLButtonElement>("[data-remove-device]").forEach((button) => {
button.addEventListener("click", () => void removeFleetDevice(Number(button.dataset.removeDevice || 0)));
});
document.querySelectorAll<HTMLButtonElement>("[data-copy]").forEach((button) => {
button.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(button.dataset.copy || "");
button.textContent = "Copied";
} catch (error) {
showErrorToast({scope: "clipboard", error: String(error)});
}
});
});
}
function renderFleetDevice(device: FleetState["devices"][number]) {
return `
<article class="fleet-device ${device.kind}">
<div class="split">
<div>
<strong><span class="runtime-dot ${device.status === "online" ? "ok" : "warn"}"></span> ${escapeHtml(device.name)}</strong>
<p class="muted compact-copy">${escapeHtml(device.endpoint || "No endpoint")} · ${escapeHtml(device.os || "unknown")} ${escapeHtml(device.arch || "")} · ${escapeHtml(device.lastSeen || "never seen")}</p>
</div>
<div class="device-actions">
<span class="badge">${escapeHtml(device.kind)}</span>
${device.id > 0 ? `<button class="danger compact-btn" data-remove-device="${device.id}">Remove</button>` : ""}
</div>
</div>
<div class="badge-row">${(device.services || []).map((service) => `<span class="badge success">${escapeHtml(service)}</span>`).join("") || `<span class="badge">No services yet</span>`}</div>
</article>
`;
}
async function addFleetDevice() {
const values = {
name: valueOf("#fleet-name"),
kind: valueOf("#fleet-kind"),
endpoint: valueOf("#fleet-endpoint"),
services: valueOf("#fleet-services"),
};
try {
await AddFleetDevice(values);
render();
} catch (error) {
showErrorToast({scope: "fleet", error: String(error)});
}
}
async function removeFleetDevice(id: number) {
if (!confirm("Remove this fleet device from CashPilot Desktop?")) return;
try {
await RemoveFleetDevice(id);
render();
} catch (error) {
showErrorToast({scope: "fleet", error: String(error)});
}
}
function totalBalance(current: AppState) {
return current.summary?.total ?? 0;
}
function valueOf(selector: string) {
return document.querySelector<HTMLInputElement | HTMLSelectElement>(selector)?.value || "";
}
function maybeResetScroll() {
if (!resetScrollAfterRender) return;
resetScrollAfterRender = false;
requestAnimationFrame(() => window.scrollTo({top: 0, left: 0}));
}
function renderEarningsChart(points: DailyPoint[], displayCurrency: string) {
const data = (points || []).filter((point) => Number.isFinite(point.amount));
if (data.length === 0 || !data.some((point) => point.amount > 0)) {
return `
<div class="chart-empty">
<strong>No earnings collected yet</strong>
<span>Once collectors run, daily earnings in ${escapeHtml(displayCurrency)} appear here.</span>
</div>
`;
}
const width = 720;
const height = 240;
const max = Math.max(...data.map((point) => point.amount), 1);
const step = data.length > 1 ? width / (data.length - 1) : width;
const labelEvery = Math.max(1, Math.ceil(data.length / 6));
const coords = data.map((point, index) => {
const x = data.length > 1 ? index * step : width / 2;
const y = height - (point.amount / max) * 180 - 30;
return `${x.toFixed(1)},${y.toFixed(1)}`;
}).join(" ");
return `
<div class="chart-shell">
<svg class="earnings-chart" viewBox="0 0 ${width} ${height}" role="img" aria-label="Daily earnings chart">
<defs>
<linearGradient id="chart-fill" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#fb7185" stop-opacity="0.32"/>
<stop offset="100%" stop-color="#fb7185" stop-opacity="0"/>
</linearGradient>
</defs>
${[40, 80, 120, 160, 200].map((y) => `<line x1="0" y1="${y}" x2="${width}" y2="${y}" />`).join("")}
<polyline points="${coords}" fill="none" stroke="#fb7185" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
<polygon points="0,${height} ${coords} ${width},${height}" fill="url(#chart-fill)"/>
${data.map((point, index) => {
const x = data.length > 1 ? index * step : width / 2;
const y = height - (point.amount / max) * 180 - 30;
const label = index % labelEvery === 0 ? `<text x="${x.toFixed(1)}" y="232">${escapeHtml(point.day)}</text>` : "";
return `<circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="4"><title>${escapeHtml(point.day)}: ${escapeHtml(formatBalance(point.amount, displayCurrency))}</title></circle>${label}`;
}).join("")}
</svg>
</div>
`;
}
function changeCaption(pct: number, suffix: string) {
if (!pct || !Number.isFinite(pct)) return `No change ${suffix}`;
const arrow = pct > 0 ? "▲" : "▼";
return `${arrow} ${Math.abs(pct).toFixed(1)}% ${suffix}`;
}
function renderPointsSection(points: PointsBalance[]) {
return `
<section class="card points-panel">
<div class="card-header">
<div>
<span class="card-title">Points / rewards</span>
<p class="muted compact-copy">Not included in totals — these rewards have no market price yet.</p>
</div>
</div>
<div class="earnings-breakdown">
${points.map((item) => `
<div class="earning-chip points" title="${escapeHtml(formatBalance(item.balance, item.currency))}">
<span>${escapeHtml(item.name || item.platform)}</span>
<strong>${escapeHtml(formatBalance(item.balance, item.currency))}</strong>
<small>${escapeHtml(item.currency)}</small>
</div>
`).join("")}
</div>
</section>
`;
}
function renderEarningBreakdown(item: ServiceEarning, displayCurrency: string) {
const native = `${item.balance.toFixed(2)} ${item.currency}`;
// When a service is convertible but its display balance is 0 the live rate is
// missing, so show the native `balance currency` instead of a misleading
// display-currency 0.
const primary = item.error
? "Needs attention"
: item.convertible && item.balanceDisplay !== 0
? formatBalance(item.balanceDisplay, displayCurrency)
: formatBalance(item.balance, item.currency);
const cashout = item.cashout;
const showBar = !item.error && cashout.comparable && cashout.minAmount > 0;
const pct = Math.max(0, Math.min(100, cashout.percent || 0));
const sub = item.error
? escapeHtml(item.error)
: item.convertible
? `${escapeHtml(native)}${cashout.eligible ? " · ready to cash out" : ""}`
: `${escapeHtml(item.currency)} · not converted`;
return `
<div class="earning-chip ${item.error ? "error" : ""}" title="${escapeHtml(native)}">
<span>${escapeHtml(item.name || item.platform)}</span>
<strong>${escapeHtml(primary)}</strong>
<small>${sub}</small>
${showBar ? `
<div class="payout-progress" title="${pct.toFixed(0)}% of ${escapeHtml(formatBalance(cashout.minAmount, cashout.currency))} minimum">
<div class="payout-progress-bar" style="width: ${pct.toFixed(1)}%"></div>
</div>
` : ""}
</div>
`;
}
// renderHealthBadge renders a compact, color-coded pill for a deployed service's
// rolling health: the 0-100 score plus uptime%. Colour tracks the score — green
// >= 80, amber 50-79, red < 50 — reusing the theme's own status variables. A
// service with no health entry yet (nothing scored) renders nothing rather than a
// misleading 0/NaN badge. The title surfaces the raw lifecycle counts behind it.
function renderHealthBadge(health: HealthScore | undefined): string {
if (!health) return "";
const score = Math.round(health.score);
const uptime = Math.round(health.uptimePercent);
const crashes = health.crashes;
// "Unstable" surfaces the crash accounting the native supervisor now records (Phase C1):
// a service that has crashed repeatedly in the health window. It reads off the same 7-day
// aggregate the score does, so it flags sustained crashing rather than an instantaneous
// loop — hence the honest "unstable" label. Unstable always shows the error tone.
const unstable = crashes >= 3;
const tone = unstable || score < 50
? "color: var(--error); background: rgba(248, 113, 113, 0.14); border-color: rgba(248, 113, 113, 0.32);"
: score < 80
? "color: var(--warning); background: rgba(245, 158, 11, 0.14); border-color: rgba(245, 158, 11, 0.32);"
: "color: var(--success); background: rgba(34, 197, 94, 0.12); border-color: rgba(34, 197, 94, 0.32);";
const title = `Health ${score}/100 · ${uptime}% uptime · ${health.restarts} restarts · ${crashes} crashes · ${health.stops} stops`;
// Surface crashes in the visible pill (previously only in the tooltip) so a crash-looping
// earner is legible at a glance, not just via hover.
const crashNote = crashes > 0 ? ` · ${crashes} crash${crashes === 1 ? "" : "es"}` : "";
const label = unstable ? `unstable · ${uptime}% up${crashNote}` : `${score} · ${uptime}% up${crashNote}`;
return `<span class="badge" style="margin-left: 6px; text-transform: none; ${tone}" title="${escapeHtml(title)}">${escapeHtml(label)}</span>`;
}
// renderMystNodes turns the Mysterium per-node earnings blob — a JSON array of
// MystNode the backend stashes under serviceDetails["mysterium"] — into a
// compact per-node list: each node's name (or a shortened identity), an
// online/offline dot in the theme's success/muted colours, and its 30-day and
// lifetime MYST. It returns "" when the blob is missing, unparseable, or not a
// non-empty array, so a Mysterium row with no per-node detail renders nothing
// extra rather than an empty header or a NaN.
function renderMystNodes(json: string | undefined): string {
if (!json) return "";
let nodes: MystNode[];
try {
const parsed: unknown = JSON.parse(json);
if (!Array.isArray(parsed) || parsed.length === 0) return "";
nodes = parsed as MystNode[];
} catch {
return "";
}
const items = nodes.map((node) => {
const label = (node.name || "").trim() || shortenIdentity(node.identity);
const dotColor = node.online ? "var(--success)" : "var(--text-muted)";
const dot = `<span title="${node.online ? "online" : "offline"}" style="display:inline-block;width:8px;height:8px;border-radius:50%;flex:0 0 auto;background:${dotColor};"></span>`;
return `
<div style="display:flex;align-items:center;gap:0.6rem;font-size:0.82rem;padding:0.15rem 0;">
<span style="display:flex;align-items:center;gap:0.4rem;flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-secondary);">${dot}${escapeHtml(label)}</span>
<span style="flex:0 0 auto;color:var(--text-muted);" title="Last 30 days">${escapeHtml(formatMyst(node.earnings30dMyst))} · 30d</span>
<span style="flex:0 0 auto;color:var(--text-secondary);" title="Lifetime">${escapeHtml(formatMyst(node.lifetimeMyst))} lifetime</span>
</div>
`;
}).join("");
return `
<div style="display:flex;flex-direction:column;gap:0.1rem;">
<span style="font-size:0.72rem;letter-spacing:0.06em;text-transform:uppercase;color:var(--text-muted);margin-bottom:0.2rem;">Per-node earnings</span>
${items}
</div>
`;
}
function renderServicesTable(services: Service[], deployments: Deployment[], earnings: {platform: string; balance: number; currency: string; error?: string}[], health: Record<string, HealthScore> | null, serviceDetails: Record<string, string> | null, outdated: string[] | null) {
if (deployments.length === 0) {
return `
<div class="empty-state">
<strong>No services deployed yet</strong>