-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoDjPanel.tish
More file actions
1132 lines (1116 loc) · 45.4 KB
/
Copy pathCoDjPanel.tish
File metadata and controls
1132 lines (1116 loc) · 45.4 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
// Co-DJ WebSocket client: actor receives deck.block from other actors.
import { h, Fragment, useState } from '@tishlang/lattish'
import { applyCoDjTplSource } from '../codj/Merge.tish'
import { bumpAllRev } from '../core/Ingest.tish'
import { coDjClearOverlays } from '../codj/Overlay.tish'
import { coDjHandleIncomingTplBlock } from '../codj/Schedule.tish'
import { applyLaunchLinesFromSource } from '../codj/Launch.tish'
import { coDjShouldFollow, coDjOwnDeckLetter } from '../codj/Transport.tish'
import { channelDeck } from '../model/DeckRouting.tish'
import { createTplLineStream, tplLineStreamPush } from '../deckfile/Stream.tish'
import { emitProject, deckMixLine } from '../deckfile/Emit.tish'
import { loadProjectFromTpl } from '../model/ProjectLoad.tish'
import { ensureCoDjMeta, setTrackOwner } from '../codj/CoDjMeta.tish'
import { projectEligibleToContribute, rehomeJoinerChannels, projectHasActorPrefixedTracks } from '../codj/DeckJoin.tish'
import { IkSelect } from './InstrumentKit.tish'
// Default gateway URL. Locally that's the dev gateway on 35987; when served from a real host (the DigitalOcean
// deploy) the gateway rides the SAME origin behind the `/codj` ingress route, so connect same-origin over
// ws/wss. The user can still override via the WS field (rt.coDjWsUrl). globalThis.location is a member read
// (undefined off-browser, no `typeof` throw).
fn defaultWsUrl() {
let loc = globalThis.location
if (loc !== null && loc.hostname !== null && loc.hostname !== "" && loc.hostname !== "localhost" && loc.hostname !== "127.0.0.1") {
let proto = loc.protocol === "https:" ? "wss:" : "ws:"
return proto + "//" + loc.host + "/codj"
}
return "ws://127.0.0.1:35987"
}
export fn CoDjPanel(project, setProject, tplMirrorFlush, rt) {
let [poll, setPoll] = useState(0)
if (rt) {
rt.coDjBumpUi = () => {
setPoll((p) => p + 1)
}
if (!rt.coDjCodjPollIv) {
rt.coDjCodjPollIv = setInterval(() => {
if (rt.coDjLogDirty || rt.coDjStreamDirty || rt.coDjLocalStreamDirty || rt.coDjPairingDirty) {
rt.coDjLogDirty = false
rt.coDjStreamDirty = false
rt.coDjLocalStreamDirty = false
rt.coDjPairingDirty = false
setPoll((p) => p + 1)
}
}, 350)
}
if (rt.coDjLog.length === 0 && !rt.coDjLogSeeded) {
rt.coDjLogSeeded = true
rt.coDjLog.push(String(Date.now()).slice(-8) + " Co-DJ: Connect to gateway")
rt.coDjLogDirty = true
}
}
fn pushLog(s) {
if (!rt) {
return
}
rt.coDjLog.push(String(Date.now()).slice(-8) + " " + s)
while (rt.coDjLog.length > 36) {
rt.coDjLog.shift()
}
rt.coDjLogDirty = true
}
// Force a full app re-render (App.setProjectFromUI → bumpAllRev) when available, else the plain setter.
// Used on connect/disconnect/merge so memo'd panels (e.g. the deck-routing lock) reflect the new state.
fn rerenderAll(p) {
if (rt && rt.setProjectFromUI) {
rt.setProjectFromUI(p)
} else {
setProject(p)
}
}
if (rt) {
rt.coDjPushLog = pushLog
rt.coDjApplyScheduledTpl = (tpl, actorId, authorId, perfStep, skillIds) => {
let p = rt.project
if (!p) {
return
}
let step = perfStep
if (step === null) {
step = typeof rt.perfStep === "number" ? rt.perfStep : 0
}
// Session-control directives (@ launch / @ transport) mutate shared runtime arming — apply them
// here (we have rt) and merge only the remaining project lines through the master-gated path.
let s = applyLaunchLinesFromSource(p, rt, tpl, actorId, skillIds)
if (s.indexOf("tpl ") !== 0) {
s = "deck 1\n" + s
}
applyCoDjTplSource(p, s, actorId, authorId, step, skillIds)
}
rt.coDjAfterScheduled = () => {
if (rt.setProject && rt.project) {
rt.setProject(rt.project)
}
if (rt.coDjTplMirrorFlush) {
rt.coDjTplMirrorFlush()
}
}
rt.coDjTplMirrorFlush = tplMirrorFlush
// Push the current project to peers on any local change (edit, deck load/add), even while stopped. Host =
// authority (full gen-versioned snapshot). Follower = ONE atomic deck.put of its own deck (peers fold it).
rt.coDjBroadcastNow = () => {
if (!(rt.coDjWs && rt.coDjWs.readyState === 1)) {
return
}
if (rt.coDjIsHost === true) {
sendStateSnapshot()
} else {
sendDeckPut()
}
}
rt.coDjNotifyPlaying = (playing) => {
let ws = rt.coDjWs
let wsOk = ws && ws.readyState === 1
let aid = rt.coDjActorId ? rt.coDjActorId : (rt.coDjClientId ? rt.coDjClientId : "actor-unknown")
let ps = typeof rt.perfStep === "number" ? rt.perfStep : 0
if (!playing) {
if (wsOk) {
let payload = JSON.stringify({ type: "control", op: "playing_stop", actorId: aid, authorId: aid })
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ UI] OUTPUT wsSend:", payload)
}
ws.send(payload)
}
rt.coDjLocalStreamPreview = ""
rt.coDjLocalStreamLane = ""
rt.coDjLocalStreamDirty = true
if (rt.coDjBumpUi) {
rt.coDjBumpUi()
}
return
}
let p = rt.project
if (!p) {
return
}
let text = emitProject(p)
rt.coDjLocalStreamLane = (rt.coDjActorId || "actor") + (wsOk ? "→hub" : " · offline (connect to send)")
rt.coDjLocalStreamPreview = text.slice(0, 900)
rt.coDjLocalStreamDirty = true
if (rt.coDjBumpUi) {
rt.coDjBumpUi()
}
if (!wsOk) {
return
}
let startPayload = JSON.stringify({ type: "control", op: "playing_start", actorId: aid, authorId: aid, perfStep: ps, playMode: rt.playMode === "sequence" ? "sequence" : "song" })
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ UI] OUTPUT wsSend:", startPayload)
}
// TRANSPORT CHANNEL ONLY — exactly one control frame. No project content rides the play trigger; the
// shared document travels on the deck-sync channel (deck.put / state.snapshot), position on control:clock.
ws.send(startPayload)
}
}
fn ingestCoDjMsg(msg) {
fn bumpHubInboundBlockPreview(fromActor, linesArr) {
if (!rt) {
return
}
let from = fromActor ? String(fromActor) : "?"
let body = linesArr.join("\n")
if (body.length > 900) {
body = body.substring(0, 900) + "\n…"
}
rt.coDjStreamPreview = (rt.coDjStreamPreview + "[deck.block " + from + "]\n" + body + "\n\n").slice(-14000)
rt.coDjStreamLane = from + " deck.block"
rt.coDjStreamDirty = true
if (rt.coDjBumpUi) {
rt.coDjBumpUi()
}
}
let t = msg.type
if (t === "presence") {
if (rt) {
rt.coDjActors = msg.actors ? msg.actors : []
// Only (re)resolve role on a CONCRETE hostActorId. A transient null (host died, gateway mid-reassign)
// is IGNORED — never demote the real host on a momentary null, which would drop its transport.
if (msg.hostActorId !== null) {
rt.coDjHostActorId = msg.hostActorId
rt.coDjIsHost = rt.coDjActorId !== null && msg.hostActorId === rt.coDjActorId
}
syncPlayerRoster()
let al = rt.coDjActors
let s = "presence: actors " + (al.length > 0 ? al.join(",") : "none")
pushLog(s)
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ] " + s + " session=" + (msg.sessionId || ""))
}
rt.coDjPairingDirty = true
// Host (re-)election can change whether THIS client is a follower → re-render the app so the
// transport's host-only Play gating updates.
rerenderAll(rt && rt.project ? rt.project : project)
}
return
}
if (t === "deck.put") {
// THE deck-sync apply: a peer's WHOLE deck arrives as ONE frame and is folded in ONE atomic
// applyCoDjTplSource call — owner-gated, so the contributor's actorId-prefixed tracks land owned by them
// (→ their deck) and are idempotently replaced on a re-send. No per-line stream, no interleave, no
// partial deck. Every peer applies it (host included → its snapshot stays complete for late joiners);
// the sender is excluded by the gateway, so this never echoes. NOT tied to transport — applies whether
// playing or stopped, and never triggers a snapshot, so it can't disturb the bar clock.
let fromId = msg.actorId ? msg.actorId : (msg.laneId ? msg.laneId : "?")
let dlines = msg.lines
if (rt && Array.isArray(dlines) && dlines.length > 0 && fromId !== "?" && fromId !== rt.coDjActorId) {
let p = rt && rt.project ? rt.project : project
let ps = typeof rt.perfStep === "number" ? rt.perfStep : 0
// REPLACE-MY-DECK semantics: a deck.put always carries the sender's WHOLE current deck (ownTrackLines).
// So any track I currently hold that's OWNED BY THE SENDER but absent from this frame is stale — it was
// removed on their side (e.g. a song load drop-and-replaced their deck). Prepend remove_track for each so
// the sender's deck on every peer MATCHES theirs (add new + drop gone), not just accumulates. Without this
// a client loading a new song would leave its old tracks orphaned on the host.
let keep = deckPutKeepIds(dlines)
let rmLines = staleOwnedRemoveLines(p, fromId, keep)
let src = "deck 1\n" + rmLines.concat(dlines).join("\n") + "\n"
applyCoDjTplSource(p, src, fromId, fromId, ps, msg.skillIds)
// Bump the per-slice rev counters so the memo'd panels re-render on a remote edit to an EXISTING track
// (a name/knob change keeps the channel count the same → channelsRev wouldn't move without this, and
// the instrument input/waveform would show stale values). New tracks already move it; this covers edits.
bumpAllRev(p)
setProject(p)
// A new track needs an audio bus, and a remove_track splice misaligns the index-keyed bus array — rebuild
// both. Skip mid-playback (a resync mid-bar glitches the graph); it reconciles on the next stop/play.
if (rt.resyncAudio && rt.playing !== true) {
rt.resyncAudio()
}
// If the deck.put carried a deck_mix (a follower's owned-deck booth EQ/volume — folded only on the host,
// since it's master-gated), recompute per-channel eq + repaint the booth strip.
if (rt.reconcileDeckMix) {
rt.reconcileDeckMix()
}
bumpHubInboundBlockPreview(fromId, dlines)
pushLog("deck.put ◂ " + fromId + " (" + String(dlines.length) + " lines)")
if (rt.coDjBumpUi) {
rt.coDjBumpUi()
}
}
return
}
if (t === "deck.block") {
let actorId = msg.actorId ? msg.actorId : (msg.laneId ? msg.laneId : "actor-1")
let authorId = msg.authorId ? msg.authorId : actorId
let lines = msg.lines
if (!lines || lines.length === 0) {
return
}
let src = lines.join("\n")
if (src.indexOf("tpl ") !== 0) {
src = "deck 1\n" + src
}
let r = coDjHandleIncomingTplBlock(
src,
actorId,
authorId,
msg.effectivePerfStep,
msg.submitDeadlinePerfStep,
msg.asap,
pushLog,
rt,
msg.skillIds
)
if (r.status === "late") {
return
}
if (r.status === "queued") {
let effStep = msg.effectivePerfStep
if (effStep === null) {
effStep = rt && typeof rt.perfStep === "number" ? rt.perfStep : 0
}
if (rt && rt.appendStreamedBlock) {
rt.appendStreamedBlock(lines, effStep)
rt.coDjStreamDirty = true
}
bumpHubInboundBlockPreview(actorId, lines)
pushLog("apply " + actorId + " queued @" + String(effStep))
return
}
if (rt) {
rt.coDjStreamDirty = true
}
let p = rt && rt.project ? rt.project : project
let effStep = msg.effectivePerfStep
if (effStep === null) {
effStep = rt && typeof rt.perfStep === "number" ? rt.perfStep : 0
}
// Apply session-control directives to shared arming, merge the rest through the gated path.
let applySrc = applyLaunchLinesFromSource(p, rt, r.tpl, actorId, msg.skillIds)
if (applySrc.indexOf("tpl ") !== 0) {
applySrc = "deck 1\n" + applySrc
}
applyCoDjTplSource(p, applySrc, actorId, authorId, effStep, msg.skillIds)
setProject(p)
if (rt && rt.appendStreamedBlock) {
rt.appendStreamedBlock(lines, effStep)
}
let inStreamMode =
rt && rt.coDjWs && rt.coDjWs.readyState === 1 && Array.isArray(rt.tplSessionStream)
if (tplMirrorFlush && !inStreamMode) {
tplMirrorFlush()
}
bumpHubInboundBlockPreview(actorId, lines)
pushLog("apply " + actorId + " " + String(lines.length) + "L")
// NB: no host re-snapshot here — deck.block is the LIVE-playback stream (coDjPushLive), not deck
// contribution. Deck convergence is driven from the deck.line apply path (and gated to stopped only).
return
}
if (t === "deck.stream_chunk") {
let ch = msg.chunk ? String(msg.chunk) : ""
let from = msg.actorId ? msg.actorId : (msg.laneId ? msg.laneId : "?")
if (rt) {
rt.coDjStreamPreview = (rt.coDjStreamPreview + ch).slice(-1200)
rt.coDjStreamLane = from
rt.coDjStreamDirty = true
if (rt.coDjBumpUi) {
rt.coDjBumpUi()
}
}
return
}
if (t === "deck.line") {
let ln = msg.line !== null ? String(msg.line) : ""
let fromId = msg.actorId ? msg.actorId : (msg.laneId ? msg.laneId : "?")
let authorId = msg.authorId ? msg.authorId : fromId
// Live token-line preview (read-only "Hub → you" pane).
if (rt) {
rt.coDjStreamPreview = (rt.coDjStreamPreview + ln + "\n").slice(-14000)
rt.coDjStreamLane = fromId
rt.coDjStreamDirty = true
}
// Incremental decode: apply each streamed line into the live project as it arrives,
// so a remote actor's stems appear progressively (track header → pattern fills in).
let p = rt && rt.project ? rt.project : project
if (rt && p && fromId !== "?" && fromId !== rt.coDjActorId) {
if (!rt.coDjLineStreams) {
rt.coDjLineStreams = {}
}
let strm = rt.coDjLineStreams[fromId]
if (!strm) {
strm = createTplLineStream(fromId, authorId, msg.skillIds)
rt.coDjLineStreams[fromId] = strm
} else {
strm.skillIds = msg.skillIds
strm.authorId = authorId
}
let ps = typeof rt.perfStep === "number" ? rt.perfStep : 0
let res = tplLineStreamPush(strm, ln, p, ps)
if (res.applied) {
setProject(p)
let inStreamMode =
rt.coDjWs && rt.coDjWs.readyState === 1 && Array.isArray(rt.tplSessionStream)
if (tplMirrorFlush && !inStreamMode) {
tplMirrorFlush()
}
if (res.opened) {
pushLog("stream " + fromId + " ◂ " + ln)
}
} else if (res.denied) {
pushLog("skill-deny " + fromId + ": " + ln)
}
}
if (rt && rt.coDjBumpUi) {
rt.coDjBumpUi()
}
return
}
if (t === "direct") {
pushLog("direct→" + (msg.targetActorId ? msg.targetActorId : "?"))
return
}
if (t === "control" && msg.op === "clear_overlay") {
coDjClearOverlays(project)
setProject(project)
}
// Shared transport: the host is the clock master. A follower slaves its playhead to the host so the
// whole room is on the same bar/step — the point of the deck session. (Skipped when this client IS
// the host, or the user switched to independent mode.)
if (t === "control" && msg.op === "playing_start" && rt && coDjShouldFollow(rt)) {
rt.coDjHostPlaying = true
let hs = msg.perfStep !== null ? Math.floor(Number(msg.perfStep)) : 0
if (rt.coDjFollowStart) {
rt.coDjFollowStart(hs, msg.playMode)
}
pushLog("follow host play @" + String(hs))
return
}
if (t === "control" && msg.op === "playing_stop" && rt && coDjShouldFollow(rt)) {
rt.coDjHostPlaying = false
if (rt.coDjFollowStop) {
rt.coDjFollowStop()
}
pushLog("follow host stop")
return
}
if (t === "control" && msg.op === "clock" && rt && coDjShouldFollow(rt)) {
rt.coDjHostPlaying = true
let hs2 = msg.perfStep !== null ? Math.floor(Number(msg.perfStep)) : 0
if (!rt.playing && rt.coDjFollowStart) {
rt.coDjFollowStart(hs2, msg.playMode)
} else if (rt.coDjApplyClock) {
rt.coDjApplyClock(hs2)
}
return
}
}
// Stamp the room roster onto the project so deck routing can place up to 4 players in 2 decks
// (P1=host A-top, P2=B-top, P3=A-bottom, P4=B-bottom). Player order = [host, …others sorted].
fn syncPlayerRoster() {
if (!rt || !rt.project) {
return
}
let host = rt.coDjHostActorId !== null ? rt.coDjHostActorId : null
let actors = Array.isArray(rt.coDjActors) ? rt.coDjActors : []
let players = []
if (host !== null && host !== "") {
players.push(host)
}
let sorted = actors.slice().sort()
let i = 0
while (i < sorted.length && players.length < 4) {
if (sorted[i] !== host) {
players.push(sorted[i])
}
i = i + 1
}
rt.project.coDjSelfActorId = rt.coDjActorId !== null ? rt.coDjActorId : ""
rt.project.coDjHostActorId = host
rt.project.coDjIsHost = rt.coDjIsHost === true
rt.project.coDjPlayers = players
}
// Host: push the authoritative full project as a state.snapshot (seeds the gateway cache + clobbers
// every follower's local default). Sent on connect when designated host, and on gateway request.
fn sendStateSnapshot() {
if (!(rt && rt.coDjWs && rt.coDjWs.readyState === 1)) {
return
}
let p = rt.project ? rt.project : project
let lines = emitProject(p).split("\n")
let aid = rt.coDjActorId ? rt.coDjActorId : ""
// Carry per-track ownership so followers reconstruct the right decks (host's tracks → Deck A, each
// agent on its own lane). The host's own locally-authored ("human") tracks are attributed to it.
let owners = {}
if (p.coDjMeta && p.coDjMeta.tracks) {
let ci = 0
while (ci < p.channels.length) {
let cid = p.channels[ci].id
let m = p.coDjMeta.tracks[cid]
let ow = m && m.ownerActorId ? String(m.ownerActorId) : "human"
owners[cid] = ow === "human" ? aid : ow
ci = ci + 1
}
}
// Monotonic generation: every snapshot carries the next gen so receivers (and the gateway cache) can
// discard a stale/out-of-order one (newer-wins). This makes the connect-time cached+fresh double snapshot
// and any re-order harmless.
let g = (typeof rt.coDjSnapGen === "number" ? rt.coDjSnapGen : 0) + 1
rt.coDjSnapGen = g
rt.coDjWs.send(JSON.stringify({ type: "state.snapshot", actorId: aid, authorId: aid, lines: lines, owners: owners, gen: g }))
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ UI] OUTPUT state.snapshot (" + String(lines.length) + " lines, gen " + String(g) + ")")
}
pushLog("pushed host snapshot (" + String(p.channels.length) + " tracks, gen " + String(g) + ")")
}
// The set of track ids carried in a deck.put frame (the positional id token before " gen " in each header).
fn deckPutKeepIds(dlines) {
let keep = {}
let i = 0
while (i < dlines.length) {
let ln = dlines[i]
let isIndented = ln.length > 0 && (ln.charAt(0) === " " || ln.charAt(0) === "\t")
if (!isIndented && ln.trim().indexOf("track ") === 0) {
let genIdx = ln.indexOf(" gen ")
if (genIdx >= 0) {
let head = ln.substring(0, genIdx)
let lastSp = head.lastIndexOf(" ")
if (lastSp >= 0) {
keep[head.substring(lastSp + 1)] = true
}
}
}
i = i + 1
}
return keep
}
// remove_track lines for every channel I currently hold that is OWNED BY `fromId` but ABSENT from this deck.put.
// A deck.put is the sender's whole deck, so a sender-owned track not in it was dropped on their side (a song
// load replaces the deck) and must be dropped here too — otherwise it lingers orphaned (the host's stale-track bug).
fn staleOwnedRemoveLines(p, fromId, keep) {
let out = []
if (!p || !p.coDjMeta || !p.coDjMeta.tracks || !Array.isArray(p.channels)) {
return out
}
let ci = 0
while (ci < p.channels.length) {
let ch = p.channels[ci]
let cid = String(ch.id)
let m = p.coDjMeta.tracks[cid]
let owner = m && m.ownerActorId ? String(m.ownerActorId) : ""
if (owner === String(fromId) && keep[cid] !== true) {
out.push("remove_track " + cid)
}
ci = ci + 1
}
return out
}
// From a live project, return the track blocks (header + indented body, deck-line dropped) for the tracks
// routed to MY deck (channelDeck) — robust to every id shape (re-homed, deck-prefixed, +TRACK). Used to send
// my current deck on an edit.
fn ownTrackLines(p, myDeck) {
// The tracks I own = every channel routed to MY deck (channelDeck), regardless of its id SHAPE. This is the
// robust selector: it catches the initial actor-prefixed re-home (actorId_c0), a song loaded onto my deck
// (deck-prefixed b_kick), AND a +TRACK (actorId_c8) alike — anything earlier prefix-only matching missed,
// which is why a client's song loads / added instruments never reached the host. Build the id set first.
let mineIds = {}
if (myDeck !== null) {
let ci = 0
while (ci < p.channels.length) {
let ch = p.channels[ci]
if (channelDeck(p, ch) === myDeck) {
mineIds[String(ch.id)] = true
}
ci = ci + 1
}
}
let all = emitProject(p).split("\n")
let out = []
let inMine = false
let i = 0
while (i < all.length) {
let ln = all[i]
let isIndented = ln.length > 0 && (ln.charAt(0) === " " || ln.charAt(0) === "\t")
if (!isIndented) {
if (ln.trim().indexOf("track ") === 0) {
let genIdx = ln.indexOf(" gen ")
let mine = false
if (genIdx >= 0) {
let head = ln.substring(0, genIdx)
let lastSp = head.lastIndexOf(" ")
if (lastSp >= 0) {
let id = head.substring(lastSp + 1)
mine = mineIds[id] === true
}
}
inMine = mine
if (inMine) {
out.push(ln)
}
} else {
inMine = false
}
} else if (inMine) {
// Drop the per-track `deck … slot …` line — ownership routes my track to my deck on the host.
if (ln.trim().indexOf("deck ") !== 0) {
out.push(ln)
}
}
i = i + 1
}
return out
}
// THE single deck-contribution wire: send MY whole deck to the room as ONE atomic deck.put frame. Every peer
// folds it in one applyCoDjTplSource call (no per-line stream, no interleave, no partial). Prefers my
// already-re-homed live tracks (ownTrackLines); before the first adopt re-homes them they don't exist yet in
// the live project, so it falls back to re-homing my captured deck (rehomedSelfTrackLines of coDjPendingSelfTpl).
// Idempotent: same actorId-prefixed ids → peers replace, never duplicate.
fn sendDeckPut() {
let ws = rt && rt.coDjWs
if (!ws || ws.readyState !== 1) {
return
}
if (rt.coDjIsHost === true) {
return
}
let aid = rt.coDjActorId ? String(rt.coDjActorId) : ""
if (aid.length === 0) {
return
}
let p = rt && rt.project ? rt.project : project
let myDeck = coDjOwnDeckLetter(rt)
// Send EVERY track routed to my deck — instruments added via +TRACK and songs loaded onto my deck included,
// not just the initial re-homed loop. (Pre-adopt my deck doesn't exist yet → fall back to the captured deck.)
let lines = ownTrackLines(p, myDeck)
if (lines.length === 0 && rt.coDjPendingSelfTpl && rt.coDjPendingSelfTpl.length > 0) {
lines = rehomedSelfTrackLines(rt.coDjPendingSelfTpl, aid).lines
}
if (lines.length === 0) {
pushLog("deck.put: no tracks to send")
return
}
// Append my OWN deck's booth EQ/volume (deck_mix) so a follower's deck is fully expressed — the host folds
// it (master-gated) and re-snapshots, so every client sees my booth. Same serializer the host snapshot uses.
if (myDeck !== null) {
let dml = deckMixLine(p, myDeck)
if (dml.length > 0) {
lines = lines.concat([dml])
}
}
ws.send(JSON.stringify({ type: "deck.put", actorId: aid, lines: lines }))
pushLog("deck.put → room (" + String(lines.length) + " lines)")
}
// Re-home a `track <name> id <id> gen <gen> …` header by id-prefixing with my actorId (collision-free,
// and exactly what routes the track to MY deck once the host owns it to me). The id is the single token
// immediately before " gen " — extracted positionally so multi-word names (`MOS 6581`) are safe.
fn rehomeTrackHeaderLine(line, aid) {
let genIdx = line.indexOf(" gen ")
if (genIdx < 0) {
return line
}
let head = line.substring(0, genIdx)
let lastSp = head.lastIndexOf(" ")
if (lastSp < 0) {
return line
}
let id = head.substring(lastSp + 1)
if (id.length === 0) {
return line
}
let prefix = head.substring(0, lastSp + 1)
return prefix + aid + "_" + id + line.substring(genIdx)
}
// From a raw deck string, build ONLY the re-homed `track` block lines (header + indented body), dropping
// globals (bpm / master_mix / session / clip) and any per-track `deck … slot …` line. PURE STRING — no
// loadProjectFromTpl round-trip, so it can't be defeated by patch/macro content that fails to re-parse.
fn rehomedSelfTrackLines(tplStr, aid) {
let all = tplStr.split("\n")
let out = []
let inTrack = false
let count = 0
let i = 0
while (i < all.length) {
let ln = all[i]
let isIndented = ln.length > 0 && (ln.charAt(0) === " " || ln.charAt(0) === "\t")
if (!isIndented) {
let trimmed = ln.trim()
if (trimmed.indexOf("track ") === 0) {
inTrack = true
out.push(rehomeTrackHeaderLine(ln, aid))
count = count + 1
} else {
inTrack = false
}
} else if (inTrack) {
// Drop the deck line so OWNERSHIP routes the track to my deck (a stale `deck local slot 0` would
// otherwise try to pin it to the host's Deck A).
if (ln.trim().indexOf("deck ") !== 0) {
out.push(ln)
}
}
i = i + 1
}
return { lines: out, count: count }
}
// Does the host carry instruments on decks B/C/D (deckSlot 1..3)? On connect we offer to merge them onto
// Deck A so each remote player cleanly owns one deck — or leave them for more local control.
fn hostHasMultiDeckContent() {
let p = rt && rt.project ? rt.project : project
if (!p || !Array.isArray(p.channels)) {
return false
}
let i = 0
while (i < p.channels.length) {
let s = p.channels[i].deckSlot
if (s !== null) {
let n = Math.floor(Number(s))
if (n >= 1 && n <= 3 && n === n) {
return true
}
}
i = i + 1
}
return false
}
// Host chose "Merge into Deck A": collapse every channel onto Deck A (deckSlot 0) and re-broadcast the
// authoritative state so followers' decks B/C/D are clear.
fn mergeHostDecksToA() {
let p = rt && rt.project ? rt.project : project
if (p && Array.isArray(p.channels)) {
let i = 0
while (i < p.channels.length) {
p.channels[i].deckSlot = 0
p.channels[i].actorLane = ""
i = i + 1
}
}
if (rt) {
rt.coDjHostDeckPrompt = false
}
rerenderAll(p)
if (rt && rt.resyncAudio) {
rt.resyncAudio()
}
sendStateSnapshot()
pushLog("merged decks B/C/D into Deck A")
if (rt && rt.coDjBumpUi) {
rt.coDjBumpUi()
}
}
// A joiner that arrives with its OWN content shouldn't lose it to the host's snapshot. We captured that
// content at connect (rt.coDjPendingSelfTpl, before any clobber). Here we re-home it INTO the adopted
// snapshot via rehomeJoinerChannels (prefix + own by my actorId → routes to my deck). Returns true if
// anything was merged, so the caller can broadcast it up to the host and fold it into the shared deck.
//
// The pending capture is held across snapshots (NOT consumed on the first merge) until a snapshot actually
// carries my contributed tracks back. This defends against the connect-time DOUBLE snapshot: the gateway
// hands a joiner a CACHED snapshot AND asks the host for a FRESH one (request.snapshot). The fresh one is
// generated before my just-broadcast tracks land on the host, so a one-shot consume would let that 2nd
// snapshot permanently wipe my deck. Re-homing is idempotent because each adopt rebuilds np fresh and the
// id prefix is deterministic; once the shared snapshot includes my prefix, we stop and clear pending.
fn mergePendingSelfInto(np) {
let tpl = rt ? rt.coDjPendingSelfTpl : null
if (!tpl || tpl.length === 0 || !np || !Array.isArray(np.channels)) {
return false
}
let aid = rt && rt.coDjActorId ? String(rt.coDjActorId) : ""
if (aid.length === 0) {
return false
}
// Round-trip confirmed? If the adopted snapshot already carries any track id-prefixed with my actorId,
// my contribution is in the shared deck — stop re-homing and release the capture.
if (projectHasActorPrefixedTracks(np, aid)) {
rt.coDjPendingSelfTpl = null
return false
}
let res = loadProjectFromTpl(tpl)
if (!res || !res.project || !Array.isArray(res.project.channels) || res.project.channels.length === 0) {
return false
}
let added = rehomeJoinerChannels(np, res.project.channels, aid)
if (added > 0) {
pushLog("re-homed " + String(added) + " of my track(s) onto my deck")
}
return added > 0
}
// This client's OWN deck letter (A/B/C/D) = its slot in the shared roster. Used to land a follower's view
// on its own deck after it connects.
fn selfDeckLetter(p) {
let players = p && p.coDjPlayers ? p.coDjPlayers : null
let self = p && p.coDjSelfActorId ? String(p.coDjSelfActorId) : ""
if (Array.isArray(players) && self.length > 0) {
let i = 0
while (i < players.length && i < 4) {
if (String(players[i]) === self) {
return i === 1 ? "B" : (i === 2 ? "C" : (i === 3 ? "D" : "A"))
}
i = i + 1
}
}
return "A"
}
// Follower: adopt the host's authoritative state, then re-home any content I joined with onto my deck so it
// joins the one shared deck (instead of being silently clobbered).
fn applyHostSnapshot(lines, owners, fromHost, gen) {
if (!Array.isArray(lines) || lines.length === 0) {
return
}
// Newer-wins: discard a stale/out-of-order snapshot (the connect-time cached+fresh double, any re-order).
let g = (typeof gen === "number") ? Math.floor(gen) : 0
let last = (rt && (rt.coDjLastSnapshotGen !== null)) ? rt.coDjLastSnapshotGen : -1
if (g <= last) {
return
}
let res = loadProjectFromTpl(lines.join("\n"))
if (!res || !res.project) {
return
}
let np = res.project
// Reconstruct ownership so decks survive the clobber: the host's tracks → Deck A, agents on their
// own lanes. Without this every track would default to "human" and collapse onto Deck A.
ensureCoDjMeta(np)
if (owners !== null) {
let ci = 0
while (ci < np.channels.length) {
let cid = np.channels[ci].id
if (owners[cid] !== null) {
setTrackOwner(np, cid, owners[cid], owners[cid])
}
ci = ci + 1
}
}
// Best-effort: re-home my captured deck INTO the adopted snapshot so I see my own loop immediately (the
// authoritative copy also arrives once the host folds my deck.put into a later snapshot, which clears the
// pending capture). This is DISPLAY only — the contribution to the room is the atomic deck.put, not here.
mergePendingSelfInto(np)
rt.project = np
if (rt) {
rt.coDjLastSnapshotGen = g
}
syncPlayerRoster()
// Bump every per-slice rev counter so the memo'd panels (instrument knobs, deck mixer, sequencer) actually
// re-render against the adopted document. Without this, a host's param edit to an EXISTING track lands in
// the project but the UI keeps showing stale values (the "host KICK punch/volume never appears" bug).
bumpAllRev(np)
setProject(np)
// Recompute per-channel eq from the adopted deck_mix + repaint the booth strip (its memo keys on deckMixRev,
// not the bumpAllRev slice counters), so a host's deck volume/EQ change reconciles here.
if (rt.reconcileDeckMix) {
rt.reconcileDeckMix()
}
// Mid-playback: update the shared DOCUMENT but do NOT rebuild the audio graph — a resync mid-bar glitches
// the shared clock and is exactly how deck-sync used to break play/stop. Rebuild only while stopped.
if (rt.resyncAudio && rt.playing !== true) {
rt.resyncAudio()
}
// First adoption only: land a FOLLOWER's view on its OWN deck (B/C/D) so it sees its own loop rather than
// the host's Deck A. Once only — don't yank the view back if the player later navigates decks themselves.
if (rt && rt.coDjIsHost !== true && rt.coDjViewLandedDeck !== true && rt.setActiveDeck) {
rt.setActiveDeck(selfDeckLetter(np))
rt.coDjViewLandedDeck = true
}
pushLog("adopted host state (" + String(np.channels.length) + " tracks, gen " + String(g) + ")")
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ UI] applied host snapshot -> " + String(np.channels.length) + " tracks gen " + String(g))
}
// Do NOT re-contribute here — that would loop (adopt → send → host fold → snapshot → adopt → …). The deck
// is contributed ONCE on join and on each local edit (deck.put). Adoption is purely receive-side.
}
fn handleWsMessage(ev) {
let raw = ev.data
let msg = null
try {
msg = JSON.parse(raw)
} catch (e) {
return
}
if (msg !== null && msg.type === "ping") {
return
}
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ UI] INPUT raw:", typeof raw === "string" && raw.length > 300 ? (raw.substring(0, 300) + "...") : raw)
}
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ UI] INPUT parsed type=" + (msg.type || "?") + " keys=" + JSON.stringify(Object.keys(msg)))
}
let t = msg.type
if (t === "joined") {
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ] joined", msg.you, "actors=", msg.actors)
}
if (rt) {
if (msg.you) {
if (msg.you.clientId) {
rt.coDjClientId = msg.you.clientId
}
if (msg.you.actorId) {
rt.coDjActorId = msg.you.actorId
}
}
rt.coDjActors = msg.actors ? msg.actors : []
rt.coDjHostActorId = msg.hostActorId !== null ? msg.hostActorId : null
rt.coDjIsHost = rt.coDjActorId !== null && msg.hostActorId === rt.coDjActorId
syncPlayerRoster()
rt.coDjPairingDirty = true
}
pushLog(
"joined actor=" +
(msg.you && msg.you.actorId ? String(msg.you.actorId).slice(0, 16) : "?") +
(rt && rt.coDjIsHost ? " [HOST]" : " [follower]") +
" actors=" +
(msg.actors && msg.actors.length > 0 ? msg.actors.join(",") : "none")
)
// Host seeds the gateway cache immediately so any follower already waiting gets the real project.
if (rt && rt.coDjIsHost) {
// The host IS the authority — its own content is already the shared deck, nothing to re-contribute.
rt.coDjPendingSelfTpl = null
// If the host carries instruments on decks B/C/D, offer to merge them onto Deck A (or keep them).
rt.coDjHostDeckPrompt = hostHasMultiDeckContent()
sendStateSnapshot()
} else if (rt && rt.coDjPendingSelfTpl) {
// FOLLOWER: contribute my whole deck to the room as ONE atomic deck.put, exactly once on join.
// (Edits afterward re-send via coDjBroadcastNow → sendDeckPut.) No timer, no pump, no dual trigger.
sendDeckPut()
}
// Re-render the whole app so the deck-routing lock reflects the now-connected state.
rerenderAll(rt && rt.project ? rt.project : project)
return
}
if (t === "request.snapshot") {
// The gateway asks the host to push fresh state for a new joiner.
if (rt && rt.coDjIsHost) {
sendStateSnapshot()
}
return
}
if (t === "state.snapshot") {
// Follower: adopt the host's authoritative project, clobbering the local default.
applyHostSnapshot(msg.lines, msg.owners, msg.fromHost, msg.gen)
return
}
if (t === "error") {
pushLog("error " + (msg.message ? msg.message : ""))
return
}
ingestCoDjMsg(msg)
}
fn connectWs() {
let sock = null
let base = defaultWsUrl()
let sess = "default"
let actorId = "actor-" + Date.now() + "-" + (Math.random() * 1000000000 | 0)
if (rt) {
if (rt.coDjWsUrl && rt.coDjWsUrl.length > 0) {
base = rt.coDjWsUrl
}
if (rt.coDjSessionId && rt.coDjSessionId.length > 0) {
sess = rt.coDjSessionId
}
if (rt.coDjActorId) {
actorId = rt.coDjActorId
}
}
// Resolve identity BEFORE first send: write the actorId to rt so role-resolution + deck.put use the same
// id (no divergent local var). Reset the adopted-snapshot generation so this fresh session re-adopts.
if (rt) {
rt.coDjActorId = actorId
rt.coDjLastSnapshotGen = -1
}
// Snapshot my own deck content NOW, before any host snapshot can clobber it. On join it is re-homed onto
// my own deck and sent to the room as ONE atomic deck.put. A host or a pristine-default joiner captures
// nothing. (Display copy is folded in by mergePendingSelfInto on the first snapshot adopt.)
if (rt) {
rt.coDjPendingSelfTpl = null
let selfP = rt.project ? rt.project : project
if (projectEligibleToContribute(selfP)) {
rt.coDjPendingSelfTpl = emitProject(selfP)
pushLog("captured my deck content to contribute on join")
}
}
let path = base
while (path.length > 0 && path.charAt(path.length - 1) === "/") {
path = path.substring(0, path.length - 1)
}
pushLog("connecting to " + path)
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ] connecting", path)
}
sock = Reflect.construct(WebSocket, [path])
if (rt) {
rt.coDjWs = sock
}
sock.onopen = () => {
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ] ws onopen")
}
pushLog("ws open (handshake OK)")
if (rt && !Array.isArray(rt.tplSessionStream)) {
rt.tplSessionStream = []
}
if (rt) {
rt.coDjLineStreams = {}
}
if (sock && sock.send) {
let joinPayload = JSON.stringify({
type: "join",
sessionId: sess,
actorId: actorId,
channelIds: ["default"],
skillIds: ["add_track", "adjust_instrument", "pattern_steps", "pattern_piano", "channel_mix", "master_mixer"]
})
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ UI] OUTPUT wsSend join:", joinPayload)
}
sock.send(joinPayload)
}
}
sock.onmessage = handleWsMessage
sock.onerror = () => {
if (typeof console !== "undefined" && console.log) {
console.log("[Co-DJ] ws error")
}
pushLog("ws error")
}
sock.onclose = (ev) => {
if (typeof console !== "undefined" && console.log) {
let code = ev && ev.code !== null ? ev.code : "?"
let reason = ev && ev.reason ? ev.reason : ""
console.log("[Co-DJ] ws closed", code, reason)
}
pushLog("closed")
}
}
fn disconnectWs() {
if (!rt) {
return
}
if (rt.coDjPlayResyncIv) {
clearInterval(rt.coDjPlayResyncIv)