Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
14736 lines (12591 loc) · 438 KB
/
Copy pathbackground.js
File metadata and controls
14736 lines (12591 loc) · 438 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
/* Stream Shell provider registry v2: shared validation for Dashboard and background.
* Custom providers are HTTPS-only basic windows, never injected adapters. */
const STREAM_SHELL_PROVIDER_REGISTRY_KEY = "streamShellProviderRegistry";
const STREAM_SHELL_PROVIDER_BUILTINS = Object.freeze([
{ id: "youtube", name: "YouTube", url: "https://www.youtube.com/" },
{ id: "netflix", name: "Netflix", url: "https://www.netflix.com/browse" },
{ id: "prime", name: "Prime Video", url: "https://www.primevideo.com/" },
{ id: "disney", name: "Disney+", url: "https://www.disneyplus.com/" },
{ id: "crunchyroll", name: "Crunchyroll", url: "https://www.crunchyroll.com/" }
]);
const STREAM_SHELL_PROVIDER_GRID_PATTERNS = Object.freeze({
1: [1], 2: [2], 3: [3], 4: [1, 2, 1],
5: [1, 3, 1], 6: [2, 2, 2], 7: [2, 3, 2]
});
const STREAM_SHELL_BUILTIN_IDS = new Set(STREAM_SHELL_PROVIDER_BUILTINS.map(p => p.id));
function streamShellValidatedCustomUrl(input) {
const raw = typeof input === "string" ? input.trim() : "";
if (!raw || raw.length > 2048 || /[\x00-\x20\x7f]/.test(raw)) return null;
try {
const url = new URL(raw);
if (url.protocol !== "https:" || !url.hostname || url.username || url.password) return null;
return url.href;
} catch {
return null;
}
}
// Local artwork paths are strictly keyed by a user-chosen slug; no arbitrary
// file paths or remote image URLs enter the extension's DOM.
function streamShellValidatedArtworkKey(input) {
const key = typeof input === "string" ? input.trim().toLowerCase() : "";
return /^[a-z0-9][a-z0-9_-]{0,31}$/.test(key) ? key : "";
}
// Empty means: retain the integrated icon palette. Custom fallback defaults
// to a soft neutral accent. A user override is always canonical #RRGGBB.
function streamShellValidatedTitlebarColor(input) {
const raw = typeof input === "string" ? input.trim() : "";
return /^#[0-9a-f]{6}$/i.test(raw) ? raw.toUpperCase() : "";
}
function streamShellNativeCustomIconPath(key) {
const slug = streamShellValidatedArtworkKey(key);
return slug ? `native/titlebar-icons/custom/custom_${slug}.png` : null;
}
function streamShellCustomArtworkPath(key, kind) {
const slug = streamShellValidatedArtworkKey(key);
if (!slug) return null;
if (kind === "wide" || kind === "compact") return `assets/backgrounds/custom_${slug}_${kind}.png`;
if (kind === "icon" || kind === "wordmark") return `assets/providers/custom/custom_${slug}_${kind}.svg`;
return null;
}
function defaultStreamShellProviderRegistry() {
const ids = STREAM_SHELL_PROVIDER_BUILTINS.map(p => p.id);
return {
version: 2,
providers: STREAM_SHELL_PROVIDER_BUILTINS.map(p => ({
...p, kind: "builtin", enabled: true, showOnDashboard: true,
showInTitlebar: true
})),
dashboardOrder: [...ids],
titlebarOrder: [...ids]
};
}
function normalizeStreamShellProviderRegistry(value) {
const defaults = defaultStreamShellProviderRegistry();
if (!value || typeof value !== "object" || Array.isArray(value)) return defaults;
const supplied = Array.isArray(value.providers) ? value.providers : [];
const providers = STREAM_SHELL_PROVIDER_BUILTINS.map((base, index) => {
const incoming = supplied.find(p => p && p.id === base.id);
return {
...defaults.providers[index],
enabled: incoming?.enabled !== false,
showOnDashboard: incoming?.showOnDashboard !== false,
showInTitlebar: incoming?.showInTitlebar !== false,
titlebarColor: streamShellValidatedTitlebarColor(incoming?.titlebarColor)
};
});
const seen = new Set(STREAM_SHELL_BUILTIN_IDS);
for (const item of supplied) {
if (!item || typeof item !== "object" || item.kind !== "custom") continue;
const id = String(item.id || "");
if (!/^custom-[a-z0-9]{8,40}$/.test(id) || seen.has(id)) continue;
const url = streamShellValidatedCustomUrl(item.url);
const name = typeof item.name === "string" ? item.name.trim().slice(0, 48) : "";
if (!url || !name) continue;
seen.add(id);
providers.push({
id, kind: "custom", name, url,
icon: typeof item.icon === "string" ? item.icon.trim().slice(0, 8) : "",
artKey: streamShellValidatedArtworkKey(item.artKey),
titlebarColor: streamShellValidatedTitlebarColor(item.titlebarColor),
enabled: item.enabled !== false,
showOnDashboard: item.showOnDashboard === true,
showInTitlebar: item.showInTitlebar !== false
});
}
const ids = providers.map(p => p.id);
const allowed = new Set(ids);
const order = input => {
const ordered = [], used = new Set();
for (const id of Array.isArray(input) ? input : []) {
if (typeof id === "string" && allowed.has(id) && !used.has(id)) {
used.add(id); ordered.push(id);
}
}
for (const id of ids) if (!used.has(id)) ordered.push(id);
return ordered;
};
const dashboardOrder = order(value.dashboardOrder);
const titlebarOrder = order(value.titlebarOrder);
const pinned = providers.filter(p => p.enabled && p.showOnDashboard);
if (!pinned.length) {
const first = providers.find(p => p.enabled) || providers[0];
first.enabled = true;
first.showOnDashboard = true;
} else if (pinned.length > 7) {
const kept = new Set(dashboardOrder.filter(id => pinned.some(p => p.id === id)).slice(0, 7));
for (const provider of pinned) if (!kept.has(provider.id)) provider.showOnDashboard = false;
}
return { version: 2, providers, dashboardOrder, titlebarOrder };
}
/*
* Shared provider resume URL canonicalization + stable media identity.
* This file is concatenated into both common/shell.js and background.js.
* Keep it dependency-free and DOM-free.
*/
function normalizeProviderResumeUrl(providerName, rawUrl) {
try {
const url = new URL(String(rawUrl || ""));
url.hash = "";
if (providerName === "youtube") {
const videoId = url.searchParams.get("v");
if (videoId) {
const clean = new URL(`${url.origin}/watch`);
clean.searchParams.set("v", videoId);
for (const key of ["list", "index"]) {
const value = url.searchParams.get(key);
if (value) clean.searchParams.set(key, value);
}
return clean.toString();
}
for (const key of ["t", "start", "time_continue"]) {
url.searchParams.delete(key);
}
return url.toString();
}
if (providerName === "netflix") {
const match = url.pathname.match(/^\/watch\/([^/]+)/i);
if (match) url.pathname = `/watch/${match[1]}`;
url.search = "";
return url.toString();
}
if (providerName === "prime") {
const match = url.pathname.match(/^(.*?\/(?:gp\/video\/)?detail\/[^/]+)/i);
if (match) url.pathname = match[1];
url.search = "";
return url.toString();
}
return url.toString();
} catch {
return String(rawUrl || "").split("#")[0];
}
}
function getProviderMediaIdentity(providerName, rawUrl) {
try {
const normalized = normalizeProviderResumeUrl(providerName, rawUrl);
const url = new URL(String(normalized || rawUrl || ""));
const pathname = url.pathname.replace(/\/+$/, "") || "/";
if (providerName === "youtube") {
const videoId = url.searchParams.get("v");
return videoId ? `youtube:${videoId}` : `youtube:${pathname}`;
}
if (providerName === "netflix") {
const match = pathname.match(/^\/watch\/([^/]+)/i);
return match ? `netflix:watch:${match[1]}` : `netflix:${url.origin}${pathname}`;
}
if (providerName === "prime") {
const match = pathname.match(/\/(?:gp\/video\/)?detail\/([^/]+)/i);
return match ? `prime:detail:${match[1]}` : `prime:${url.origin}${pathname}`;
}
if (providerName === "crunchyroll") {
const match = pathname.match(/^\/watch\/([^/]+)/i);
return match ? `crunchyroll:watch:${match[1]}` : `crunchyroll:${url.origin}${pathname}`;
}
return `${providerName}:${url.origin}${pathname}`;
} catch {
return `${providerName}:${String(rawUrl || "").split("#")[0]}`;
}
}
/*
* Resolve a persisted provider media identity back to a provider-owned URL.
* This is intentionally deterministic and network-free: dedicated adapters
* can call it with their current origin, while the service worker uses it as
* a safe fallback when a freshly opened content script is not ready yet.
*/
function isProviderOwnedMediaUrl(providerName, rawUrl) {
try {
const url = new URL(String(rawUrl || ""));
const host = url.hostname.toLowerCase();
switch (providerName) {
case "youtube":
return host === "youtube.com" || host.endsWith(".youtube.com");
case "netflix":
return host === "netflix.com" || host.endsWith(".netflix.com");
case "prime":
return host === "primevideo.com" ||
host.endsWith(".primevideo.com") ||
host === "amazon.de" ||
host.endsWith(".amazon.de");
case "disney":
return host === "disneyplus.com" || host.endsWith(".disneyplus.com");
case "crunchyroll":
return host === "crunchyroll.com" || host.endsWith(".crunchyroll.com");
default:
return false;
}
} catch {
return false;
}
}
function getResolvableProviderIdentity(providerName, rawIdentity, fallbackUrl = "") {
const identity = String(rawIdentity || "").trim();
const fromIdentity = (() => {
if (providerName === "youtube") {
const match = identity.match(/^youtube:([A-Za-z0-9_-]{6,32})$/);
if (match) return { identity, kind: "watch", mediaId: match[1] };
}
if (providerName === "netflix") {
const match = identity.match(/^netflix:watch:([^:/?#]+)$/i);
if (match) return { identity, kind: "watch", mediaId: match[1] };
}
if (providerName === "prime") {
const match = identity.match(/^prime:detail:([^:/?#]+)$/i);
if (match) return { identity, kind: "detail", mediaId: match[1] };
}
if (providerName === "crunchyroll") {
const match = identity.match(/^crunchyroll:watch:([^:/?#]+)$/i);
if (match) return { identity, kind: "watch", mediaId: match[1] };
}
return null;
})();
if (fromIdentity) return fromIdentity;
if (!isProviderOwnedMediaUrl(providerName, fallbackUrl)) return null;
const derived = getProviderMediaIdentity(providerName, fallbackUrl);
if (!derived || derived === identity) return null;
return getResolvableProviderIdentity(providerName, derived, "");
}
function resolveProviderMediaLink(
providerName,
rawIdentity,
fallbackUrl = "",
preferredOrigin = ""
) {
const fallback = isProviderOwnedMediaUrl(providerName, fallbackUrl)
? normalizeProviderResumeUrl(providerName, fallbackUrl)
: "";
const resolvable = getResolvableProviderIdentity(
providerName,
rawIdentity,
fallback
);
let url = "";
let strategy = "canonical-fallback";
if (resolvable?.mediaId) {
const mediaId = encodeURIComponent(resolvable.mediaId);
if (providerName === "youtube") {
const target = new URL("https://www.youtube.com/watch");
target.searchParams.set("v", resolvable.mediaId);
try {
const old = new URL(fallback);
if (
isProviderOwnedMediaUrl("youtube", old.toString()) &&
old.searchParams.get("v") === resolvable.mediaId
) {
for (const key of ["list", "index"]) {
const value = old.searchParams.get(key);
if (value) target.searchParams.set(key, value);
}
}
} catch {
}
url = target.toString();
strategy = "youtube-watch-id";
}
if (providerName === "netflix") {
url = `https://www.netflix.com/watch/${mediaId}`;
strategy = "netflix-watch-id";
}
if (providerName === "prime") {
let origin = "https://www.primevideo.com";
try {
const candidate = new URL(String(preferredOrigin || ""));
if (isProviderOwnedMediaUrl("prime", candidate.toString())) {
origin = candidate.origin;
}
} catch {
}
const host = new URL(origin).hostname.toLowerCase();
url = host === "amazon.de" || host.endsWith(".amazon.de")
? `${origin}/gp/video/detail/${mediaId}`
: `${origin}/detail/${mediaId}`;
strategy = "prime-detail-id";
}
if (providerName === "crunchyroll") {
url = `https://www.crunchyroll.com/watch/${mediaId}`;
strategy = "crunchyroll-watch-id";
}
}
if (!url && fallback) {
url = fallback;
}
if (!url || !isProviderOwnedMediaUrl(providerName, url)) {
return null;
}
const identity = getProviderMediaIdentity(providerName, url);
return {
provider: providerName,
identity,
url: normalizeProviderResumeUrl(providerName, url),
strategy,
reconstructed: Boolean(
resolvable &&
strategy !== "canonical-fallback"
)
};
}
const PROVIDERS = {
youtube: {
label: "YouTube",
url: "https://www.youtube.com/"
},
netflix: {
label: "Netflix",
url: "https://www.netflix.com/browse"
},
prime: {
label: "Prime Video",
url: "https://www.primevideo.com/"
},
disney: {
label: "Disney+",
url: "https://www.disneyplus.com/"
},
crunchyroll: {
label: "Crunchyroll",
url: "https://www.crunchyroll.com/"
}
};
/* The five built-ins keep their specialized adapters. Custom registry entries
* are basic HTTPS targets only and are never registered as content scripts. */
async function refreshStreamShellProviderTargets() {
const stored = await chrome.storage.local.get(STREAM_SHELL_PROVIDER_REGISTRY_KEY);
const registry = normalizeStreamShellProviderRegistry(stored[STREAM_SHELL_PROVIDER_REGISTRY_KEY]);
const valid = new Set(registry.providers.filter(item => item.enabled).map(item => item.id));
for (const id of Object.keys(PROVIDERS)) {
if (!STREAM_SHELL_BUILTIN_IDS.has(id) && !valid.has(id)) delete PROVIDERS[id];
}
for (const provider of registry.providers) {
if (provider.kind === "custom" && provider.enabled) {
PROVIDERS[provider.id] = { label: provider.name, url: provider.url, kind: "custom" };
}
}
return registry;
}
let providerRemovalReconcile = Promise.resolve();
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== "local" || !changes[STREAM_SHELL_PROVIDER_REGISTRY_KEY]) return;
providerRemovalReconcile = providerRemovalReconcile.catch(() => {}).then(async () => {
const oldRegistry = normalizeStreamShellProviderRegistry(changes[STREAM_SHELL_PROVIDER_REGISTRY_KEY].oldValue);
const nextRegistry = await refreshStreamShellProviderTargets();
const ids = new Set(nextRegistry.providers.map(p => p.id));
const removed = oldRegistry.providers.filter(p => p.kind === "custom" && !ids.has(p.id));
if (!removed.length) return;
const state = await chrome.storage.local.get(["activeProvider", "leftMode"]);
if (removed.some(p => p.id === state.leftMode) && !shuttingDown) {
// Preserve rightMode. A removed active provider should never strand a popup.
await switchProvider("youtube");
}
const windows = await getProviderWindows();
for (const removedProvider of removed) {
const windowId = windows[removedProvider.id];
if (Number.isInteger(windowId)) {
await safelyRemoveWindow(windowId);
delete windows[removedProvider.id];
}
}
await saveProviderWindows(windows);
await chrome.storage.local.remove(removed.map(p => `streamShellCustomWindowUrl_${p.id}`));
const after = await chrome.storage.local.get("activeProvider");
if (removed.some(p => p.id === after.activeProvider)) {
await chrome.storage.local.set({ activeProvider: "youtube" });
}
}).catch(error => console.warn("Custom provider cleanup failed:", error));
});
const SUBSCRIPTION_STORAGE_KEY =
"streamShellSubscriptions";
const SUBSCRIPTION_PROVIDERS = [
{
id:
"youtube",
url:
"https://www.youtube.com/paid_memberships"
},
{
id:
"netflix",
url:
"https://www.netflix.com/account"
},
{
id:
"prime",
url:
"https://www.amazon.de/gp/primecentral"
},
{
id:
"disney",
url:
"https://www.disneyplus.com/account"
},
{
id:
"crunchyroll",
url:
"https://www.crunchyroll.com/account/membership"
}
];
const GOOGLE_PLAY_SUBSCRIPTIONS_URL =
"https://play.google.com/store/account/subscriptions";
const PRIME_CENTRAL_URL =
"https://www.amazon.de/gp/primecentral";
const LEFT = {
left: 0,
top: 0,
width: 1920,
height: 1080
};
const RIGHT = {
left: 1920,
top: 0,
width: 1920,
height: 1080
};
const LANDING_URL =
chrome.runtime.getURL(
"landing/landing.html"
);
const DASHBOARD_URL =
chrome.runtime.getURL(
"dashboard/dashboard.html"
);
const TWITCH_HOME_URL =
"https://www.twitch.tv/";
const TWITCH_DROPS_URL =
"https://www.twitch.tv/drops/inventory";
const TWITCH_WINDOW_STORAGE_KEY =
"twitchWindowId";
const TWITCH_SPLIT_LAB_STORAGE_KEY =
"streamShellTwitchSplitLab";
const TWITCH_WORKSPACE_V2_STORAGE_KEY =
"streamShellTwitchWorkspaceV2";
const TWITCH_WORKSPACE_SLOT_URL =
chrome.runtime.getURL("twitch-workspace/slot.html");
const TWITCH_DROPS_WORKER_WINDOW_STORAGE_KEY =
"twitchDropsWorkerWindowId";
const TWITCH_RAID_GUARD_SESSION_KEY =
"streamShellTwitchRaidGuard";
const TWITCH_DROPS_MAINTENANCE_ALARM =
"streamShellTwitchDropsMaintenance";
const POPUP_URL =
chrome.runtime.getURL(
"popup/popup.html"
);
const DISCORD_NATIVE_HOST =
"com.streamshell.discord";
const TITLEBAR_NATIVE_HOST =
"com.streamshell.titlebar";
const TITLEBAR_PROTOCOL_VERSION =
9;
const TITLEBAR_RECONCILE_INTERVAL_MS =
2500;
const DISCORD_EXECUTABLE_PATH =
"";
const providerCreationLocks =
new Map();
let landingCreationLock =
null;
let dashboardCreationLock =
null;
let twitchCreationLock =
null;
let subscriptionSyncLock =
null;
let shuttingDown =
false;
let titlebarPort =
null;
let titlebarConnectPromise =
null;
let titlebarProtocolReady =
false;
let titlebarLastStateKey =
null;
let titlebarSettingsOpen =
false;
let titlebarVolumeActive =
false;
let titlebarFullscreenActive =
false;
let titlebarFullscreenWindowId =
null;
/*
* Managed browser windows can exist before Chromium publishes their first real
* page title. Retry plans are idempotent and may overlap; this generation only
* invalidates all outstanding plans when focus moves to an unmanaged window.
*/
let titlebarClaimRetryGeneration =
0;
let titlebarReconcileTimer =
null;
let titlebarLastNativeStatus =
null;
/*
* Opera window creation/focus is expensive at startup, especially when a left
* provider is activated while the four Twitch surfaces are coming online.
* Only explicit shell-wide transitions share this bounded FIFO. Playback,
* Twitch chat, MoS autojoin, and provider polling NEVER wait on it.
*/
const STREAM_SHELL_TRANSITION_MAX_WAITERS = 2;
let streamShellTransitionTail = Promise.resolve();
let streamShellTransitionWaiters = 0;
let streamShellTransitionActive = null;
/*
* v0.20.9 – Renderer-startup admission control.
* The FIFO only serializes extension calls; chrome.windows.create() returns
* while the new YouTube/Twitch renderer is still loading. On Opera GX,
* starting a different high-cost surface immediately afterwards can saturate
* the browser process (including unrelated Opera windows). A ~5 second gap
* between launches was independently reproducible as the stable path.
*
* This lease is held only for a CROSS-SURFACE handoff, and the wait itself
* occurs inside the existing bounded FIFO. Background chat, MoS autojoin,
* video playback, and all renderer timers never participate in this queue.
*/
const STREAM_SHELL_RENDERER_HANDOFF_GRACE_MS = 5500;
const STREAM_SHELL_RENDERER_HANDOFF_WARM_MS = 3000;
const STREAM_SHELL_RENDERER_WARM_AFTER_MS = 30000;
let streamShellRendererColdUntil = Date.now() + STREAM_SHELL_RENDERER_WARM_AFTER_MS;
let streamShellTransitionVisualSerial = 0;
// UI-only notification; never await renderer acknowledgements while starting windows.
function notifyStreamShellTransitionVisual(event) {
if (shuttingDown) return;
try {
const sent = chrome.runtime.sendMessage({type:'stream-shell-transition-visual', ...event});
if (sent?.catch) sent.catch(() => {});
} catch { /* Dashboard may not be ready yet. */ }
}
function isStreamShellRendererCold(kind, name) {
// A worker wake may briefly have no cache. Prefer the safe startup gap.
if (!shellWideFocusCacheReady) return true;
if (kind === 'twitch') {
const record = shellWideFocusCache[TWITCH_WORKSPACE_V2_STORAGE_KEY];
return !['a','b','c','d'].every(slot =>
Number.isInteger(record?.slots?.[slot]?.windowId));
}
if (kind === 'provider') {
const provider = name.slice('provider:'.length);
return !Number.isInteger(shellWideFocusCache.providerWindows?.[provider]);
}
return false;
}
/* IDs persisted in the focus cache are not proof that Chromium still owns
* those windows. In 0.20.26 four Twitch popups were created even though their
* old IDs made admission classify the launch as warm (3s instead of 5.5s).
* Verify actual window existence before choosing the shorter grace period. */
async function isStreamShellRendererColdVerified(kind, name) {
if (isStreamShellRendererCold(kind, name)) return true;
if (!chrome.windows?.get) return false; // Offline mock without window API.
let windowIds;
if (kind === 'twitch') {
const record = shellWideFocusCache[TWITCH_WORKSPACE_V2_STORAGE_KEY];
windowIds = ['a', 'b', 'c', 'd'].map(slot => record?.slots?.[slot]?.windowId);
} else if (kind === 'provider') {
windowIds = [shellWideFocusCache.providerWindows?.[name.slice('provider:'.length)]];
} else {
return false;
}
const live = await Promise.all(windowIds.map(async windowId => {
if (!Number.isInteger(windowId)) return false;
try { return Number.isInteger((await chrome.windows.get(windowId))?.id); }
catch { return false; }
}));
return !live.every(Boolean);
}
let streamShellLastRendererLaunchKind = null;
let streamShellLastRendererLaunchFinishedAt = 0;
let streamShellRendererLeaseSource = 'memory';
const STREAM_SHELL_RENDERER_LEASE_KEY = 'streamShellRendererHandoffLease';
/* A Chromium MV3 service worker may be evicted/restarted while the browser
* renderer it just launched is still busy. The window-transition FIFO and its
* last-launch timestamp are worker-local; keeping the short handoff lease in
* session storage lets the next worker honor provider -> Twitch (and reverse).
* This is a timestamp, never a durable task or an extra renderer timer. */
async function hydrateStreamShellRendererHandoffLease() {
if (streamShellLastRendererLaunchKind) return;
try {
const stored = (await chrome.storage.session?.get(STREAM_SHELL_RENDERER_LEASE_KEY))
?.[STREAM_SHELL_RENDERER_LEASE_KEY];
const at = Number(stored?.at);
const age = Date.now() - at;
if (!['provider', 'twitch'].includes(stored?.kind) ||
!Number.isFinite(at) || at <= 0 || age < 0 ||
age > STREAM_SHELL_RENDERER_WARM_AFTER_MS) return;
streamShellLastRendererLaunchKind = stored.kind;
streamShellLastRendererLaunchFinishedAt = at;
streamShellRendererLeaseSource = 'session';
} catch { /* Session storage can be unavailable in an old test host. */ }
}
async function rememberStreamShellRendererLaunch(kind) {
const at = Date.now();
streamShellLastRendererLaunchKind = kind;
streamShellLastRendererLaunchFinishedAt = at;
streamShellRendererLeaseSource = 'memory';
try {
await chrome.storage.session?.set({
[STREAM_SHELL_RENDERER_LEASE_KEY]: { kind, at }
});
} catch { /* Retain the same-worker protection if storage fails. */ }
}
function streamShellRendererLaunchKind(name) {
if (name.startsWith('provider:')) return 'provider';
if (name.startsWith('twitch:')) return 'twitch';
return null;
}
async function waitForStreamShellRendererHandoff(name, verifiedCold = null) {
const kind = streamShellRendererLaunchKind(name);
if (!kind || !streamShellLastRendererLaunchKind ||
streamShellLastRendererLaunchKind === kind) return 0;
const cold = Date.now() < streamShellRendererColdUntil ||
(verifiedCold === null
? await isStreamShellRendererColdVerified(kind, name)
: verifiedCold);
const graceMs = cold
? STREAM_SHELL_RENDERER_HANDOFF_GRACE_MS
: STREAM_SHELL_RENDERER_HANDOFF_WARM_MS;
const remaining = graceMs - (Date.now() - streamShellLastRendererLaunchFinishedAt);
if (remaining <= 0) return 0;
await new Promise(resolve => setTimeout(resolve, remaining));
recordFlightEvent({
category: 'window-transition', action: 'renderer-handoff-staggered',
detail: { from: streamShellLastRendererLaunchKind, to: kind,
delayMs: remaining, graceMs, cold,
leaseSource: streamShellRendererLeaseSource }
}).catch(() => {});
return remaining;
}
/* Diagnostics only: timestamp expensive steps without changing their order. */
async function measureShellWindowStep(name, task) {
const startedAt = Date.now();
try {
return await task();
} finally {
const durationMs = Date.now() - startedAt;
if (durationMs >= 350) {
recordFlightEvent({
category: "window-transition", action: "step-timing",
level: durationMs > 1500 ? "warn" : "info",
detail: { name, durationMs }
}).catch(() => {});
}
}
}
function runStreamShellWindowTransition(name, operation) {
if (shuttingDown) return Promise.reject(new Error("Stream Shell is shutting down."));
if (streamShellTransitionWaiters >= STREAM_SHELL_TRANSITION_MAX_WAITERS) {
return Promise.reject(new Error("Stream Shell is busy switching windows; try again shortly."));
}
const queuedAt = Date.now();
streamShellTransitionWaiters += 1;
const execute = async () => {
streamShellTransitionWaiters -= 1;
if (shuttingDown) throw new Error("Stream Shell is shutting down.");
const startedAt = Date.now();
streamShellTransitionActive = name;
const kind = streamShellRendererLaunchKind(name);
const visualId = ++streamShellTransitionVisualSerial;
let showTwitchLoading = false;
try {
// Read any outstanding lease before deciding that a freshly
// restarted worker can launch Twitch without a provider cooldown.
if (kind) await hydrateStreamShellRendererHandoffLease();
// Verify Twitch windows on first admission, or the target provider
// during a Twitch -> provider handoff. Ordinary provider changes
// and non-renderer FIFO commands need no cold/window API probes.
const shouldVerifyCold = kind === 'twitch' &&
streamShellLastRendererLaunchKind !== 'twitch' ||
kind === 'provider' && streamShellLastRendererLaunchKind === 'twitch';
const verifiedCold = shouldVerifyCold
? await isStreamShellRendererColdVerified(kind, name)
: kind === 'twitch' ? isStreamShellRendererCold(kind, name) : false;
showTwitchLoading = kind === 'twitch' &&
(verifiedCold ||
(streamShellLastRendererLaunchKind === 'provider' &&
Date.now() - streamShellLastRendererLaunchFinishedAt < STREAM_SHELL_RENDERER_HANDOFF_GRACE_MS));
if (showTwitchLoading) notifyStreamShellTransitionVisual({
surface:'twitch', stage:'waiting', id:visualId
});
// Explicit commands stay ordered, but renderer initialization
// must also be given room to settle before crossing surfaces.
const delayMs = await waitForStreamShellRendererHandoff(name, verifiedCold);
if (shuttingDown) throw new Error("Stream Shell is shutting down.");
if (showTwitchLoading) notifyStreamShellTransitionVisual({
surface:'twitch', stage:'creating', id:visualId,
delayMs
});
const result = await operation();
if (kind) await rememberStreamShellRendererLaunch(kind);
if (showTwitchLoading) notifyStreamShellTransitionVisual({
surface:'twitch', stage:'done', id:visualId
});
return result;
} catch (error) {
if (showTwitchLoading) notifyStreamShellTransitionVisual({
surface:'twitch', stage:'failed', id:visualId
});
recordFlightEvent({
category: "window-transition", action: "failed", level: "error",
detail: { name, message: String(error?.message || error).slice(0, 160) }
}).catch(() => {});
throw error;
} finally {
streamShellTransitionActive = null;
const durationMs = Date.now() - startedAt;
if (durationMs > 1500 || startedAt - queuedAt > 200) {
recordFlightEvent({
category: "window-transition", action: "timing",
level: durationMs > 5000 ? "warn" : "info",
detail: { name, durationMs, waitMs: startedAt - queuedAt }
}).catch(() => {});
}
}
};
const result = streamShellTransitionTail.then(execute, execute);
// A failed operation must never poison or indefinitely grow the queue.
streamShellTransitionTail = result.then(() => undefined, () => undefined);
return result;
}
function openShellHome() {
return runStreamShellWindowTransition("open-home", _openShellHome);
}
async function _openShellHome() {
if (
shuttingDown
) {
return;
}
let displayProfile = null;
try {
displayProfile = await refreshStreamShellDisplayProfile(
"shell-open"
);
} catch {
/* Legacy 0,0 geometry remains available if display discovery fails. */
}
const compact = displayProfile?.mode === "compact";
titlebarFullscreenActive = false;
titlebarFullscreenWindowId = null;
await deactivateTwitchForRightSurface({
forceMinimize: compact
});
await stopVolumeCaptureForProviderChange(
compact ? "dashboard" : "landing"
);
let landingId = null;
if (!compact) {
landingId = await ensureLandingWindow();
if (shuttingDown) return;
} else {
/* A pre-existing Wide Landing must never leak into Compact. */
const storedLanding = await chrome.storage.local.get("landingWindowId");
if (Number.isInteger(storedLanding.landingWindowId)) {
await safelyRemoveWindow(storedLanding.landingWindowId);
await chrome.storage.local.remove("landingWindowId");
}
}
const dashboardId = await ensureDashboardWindow();
if (shuttingDown) return;
const providerWindows = await getProviderWindows();
const providerEntries = Object.entries(providerWindows);
await Promise.all(
providerEntries.map(([providerName, windowId]) =>
pauseProviderWindowPlayback(
windowId,
providerName,
"shell-home"
)
)
);
for (const [providerName, windowId] of providerEntries) {
await setWindowMuted(windowId, true);
if (compact) {
await parkWindowOffscreenAndMinimize(windowId, LEFT);
} else {
await safelyMinimizeWindow(windowId);
await parkWindowOffscreen(windowId, LEFT);
}
await chrome.storage.local.remove(`streamShellNowPlaying_${providerName}`);
}
if (shuttingDown) return;
/*
* Publish the intended shell surfaces before restoring/focusing them. Native
* claims validate this intent and never infer ownership from geometry alone.
*/
await chrome.storage.local.set({
leftMode: compact ? "dashboard" : "landing",
rightMode: "dashboard",
twitchTarget: "resume"
});
await ensureTitlebarNative();
if (!compact) {
await restoreWindow(landingId, LEFT, true);
if (shuttingDown) return;
/* Wide can resolve a managed left surface by the extension-provided
* title fingerprint + left-pane geometry even after Dashboard receives
* focus a moment later. */
await claimFocusedTitlebarSurface(landingId);
scheduleTitlebarClaimRetries(landingId);
await restoreWindow(dashboardId, RIGHT, true);
if (shuttingDown) return;
await claimFocusedTitlebarSurface(dashboardId);
scheduleTitlebarClaimRetries(dashboardId);
} else {
await restoreWindow(dashboardId, LEFT, true);
if (shuttingDown) return;
await claimFocusedTitlebarSurface(dashboardId);
scheduleTitlebarClaimRetries(dashboardId);
}
runStreamShellLaunchSelfTest()
.catch(() => {});
await broadcastState();
}
function openShellWarmLastProvider() {
return runStreamShellWindowTransition("startup-warm", _openShellWarmLastProvider);
}
async function _openShellWarmLastProvider() {
await refreshStreamShellProviderTargets();
const stored =
await chrome.storage.local.get(
"activeProvider"
);
const providerName =
stored.activeProvider;