-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBridge.lua
More file actions
1672 lines (1527 loc) · 82.2 KB
/
Copy pathBridge.lua
File metadata and controls
1672 lines (1527 loc) · 82.2 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
-- ============================================================
-- Bridge.lua — MBOT bridge / playerbot protocol layer.
--
-- Owns the handshake, debounced sync, no-bridge whisper discovery,
-- linked-account fetch, inventory fetch, quest fetch, the event
-- handler that parses ROSTER~ / DETAIL~ / STATE~ / INV_* / QUESTS_*
-- addon messages plus the co?/nc? whisper replies, and the item-link
-- cleaning helper used before sending links over bot commands.
-- ============================================================
local NS = CleanBotNS
-- URL-decode a percent-encoded string (e.g. quest names from the bridge).
-- Converts %XX hex sequences to their ASCII characters.
---@param s string Percent-encoded string.
---@return string The decoded string.
local function CB_UrlDecode(s)
return (s:gsub("%%(%x%x)", function(hex) return string.char(tonumber(hex, 16)) end))
end
-- Returns the clean API item link for a raw item link (which may carry color
-- codes and extra enchant/gem fields that confuse the server-side parser).
-- Strips to the item ID and re-fetches a canonical link from the client cache via
-- GetItemInfo, falling back to the raw link on a cache miss.
-- Use this before sending any item link over a bot command (give/equip/etc.).
---@param rawLink string The raw item link (may carry extra fields).
---@return string The canonical client-cache link, or rawLink on a cache miss.
NS.CB_CleanItemLink = function(rawLink)
local itemId = strmatch(rawLink, "item:(%d+)")
local _, apiLink = GetItemInfo(tonumber(itemId) or 0)
return apiLink or rawLink
end
-- ============================================================
-- Bot discovery / roster helpers
-- These support bot identification and class resolution during the
-- handshake and STATE~ packet handling below, so they live alongside the
-- discovery state and probing logic. Called at event time, so they may
-- reference helpers defined in earlier-loading files (CB_GroupInfo).
-- ============================================================
-- Tests whether a unit token belongs to a tracked playerbot.
---@param unit string Unit token to test (e.g. "party1").
---@return boolean Whether the unit is a tracked playerbot.
NS.CleanBot_IsBot = function(unit)
local name = UnitName(unit)
if not name then return false end
if CleanBot_PartyBots[strlower(name)] then return true end
return false
end
-- Returns the group unit id ("partyN" or "raidN") whose name matches, or nil.
-- Walks the raid roster when in a raid, the party roster otherwise.
---@param name string Character name to locate in the party/raid.
---@return string|nil The matching unit token (e.g. "party2" / "raid5"), or nil.
NS.CB_FindPartyUnit = function(name)
local prefix, n = NS.CB_GroupInfo()
for i = 1, n do
local unit = prefix .. i
if UnitName(unit) == name then return unit end
end
return nil
end
-- Resolves a bot's class token from the live party roster (authoritative),
-- falling back to the supplied value (or WARRIOR) when the unit isn't found.
---@param name string Character name to resolve the class for.
---@param fallback string? Class token to return when resolution fails.
---@return string|nil The resolved class token, or fallback.
NS.CB_ResolveClass = function(name, fallback)
local unit = NS.CB_FindPartyUnit(name)
if unit then
local _, class = UnitClass(unit)
if class then return class end
end
return fallback or "WARRIOR"
end
-- ============================================================
-- Bridge / handshake state
-- ============================================================
NS.lastRawStates = nil
NS.lastHelloAck = nil
NS.bridgeReady = false
-- Bridge availability: "unknown" until detection resolves, then "present"
-- (HELLO_ACK received) or "absent" (detection timed out). Drives whether
-- strategy reads use GET~STATES (bridge) or co?/nc? whispers (no bridge).
NS.bridgeState = "unknown"
NS.probed = {} -- name-key -> true: party member already probed for bot-hood
NS.awaitingProbe = {} -- name-key -> true: probe co? sent, awaiting a "Strategies:" reply
-- Debug overrides — both are nil/false by default and are toggled via /cbdebug.
-- nil = auto (follow real handshake); "present" or "absent" = forced override.
NS.debugBridgeOverride = nil ---@type string|nil
-- When true, CB_SendBotCommand prints commands to chat instead of sending them.
NS.debugSimulate = false ---@type boolean
-- When true, strategy toggles log any optimistic-vs-actual mismatch after the
-- authoritative state comes back (see CB_SendStrategyToggle / CB_VerifyStrategyExpect).
NS.debugVerify = false ---@type boolean
-- No-bridge login gating: on a fresh login (not a /reload) bots may not be
-- online yet, so we block CB_ProbePartyForBots until bridge detection resolves.
-- Once it does, the probe sweep runs and a not-yet-ready bot is caught later via
-- its readiness whisper (see NS.joinCandidates).
NS.loginPhaseActive = false -- true only on fresh login, cleared when detection resolves
-- Re-probe candidates: members CB_ProbePartyForBots has probed but not yet confirmed. If that
-- probe goes unanswered because the bot was still loading, its later readiness whisper re-probes
-- it (the greeting branch in CHAT_MSG_WHISPER). The fast path there uses a LIVE group check plus
-- "not probed", so the first greeting from a freshly-joined member triggers immediately without
-- any pre-set flag; this set only covers the re-probe-after-unanswered case. Cleared on the
-- re-probe / on confirmation / on leaving, so a chatty human gets at most one stray probe.
NS.joinCandidates = {} -- name-key -> display-name: probed, awaiting a re-probe if unanswered
-- ============================================================
-- Linked accounts (populated by .playerbots account linkedAccounts)
-- ============================================================
NS.linkedAccounts = {}
NS.awaitingLinkedAccounts = false -- true = waiting for "Linked accounts:" header
NS.collectingLinkedAccounts = false -- true = reading "- NAME" lines
NS.CleanBot_FetchLinkedAccounts = function()
NS.linkedAccounts = {}
NS.awaitingLinkedAccounts = true
NS.collectingLinkedAccounts = false
SendChatMessage(".playerbots account linkedAccounts", "SAY")
end
-- ============================================================
-- Debounced bridge sync + UI refresh
-- ============================================================
NS.syncPending = false
-- No-bridge discovery: whisper "co ?" to each group member (party or raid)
-- exactly once. Only members that reply with a "Strategies: " line are treated
-- as bots (handled in the CHAT_MSG_WHISPER branch). Humans never respond, so
-- they are probed a single time and then ignored. Each probed member is flagged as a
-- joinCandidate so that, if this probe goes unanswered because the bot was still loading,
-- its later readiness whisper re-probes it (see the CHAT_MSG_WHISPER greeting branch).
-- Skipped during loginPhaseActive — bots may not be online yet on fresh
-- login; probing waits until detection resolves, then this sweep runs.
local function CB_ProbePartyForBots()
if NS.loginPhaseActive then return end
-- Forget probe records for members who have left, so a rejoin re-probes.
local present = {}
NS.CB_ForEachGroupMember(function(unit, nm)
if nm then present[strlower(nm)] = true end
end)
for k in pairs(NS.probed) do
if not present[k] then
NS.probed[k] = nil; NS.awaitingProbe[k] = nil; NS.joinCandidates[k] = nil
end
end
NS.CB_ForEachGroupMember(function(unit, nm)
if nm and UnitIsPlayer(unit) then
local key = strlower(nm)
if not CleanBot_PartyBots[key] and not NS.probed[key] then
NS.probed[key] = true
NS.awaitingProbe[key] = true
NS.joinCandidates[key] = nm -- re-probe target if this probe goes unanswered
NS.CB_SendBotCommand(nm, "co ?")
end
end
end)
end
-- ============================================================
-- Self-bot management
-- ============================================================
-- mod-playerbots can register the player's own character as a bot. The authoritative
-- live signal is the server's "Enable/Disable player botAI" system message (parsed in
-- the CHAT_MSG_SYSTEM handler), which fires however the toggle happens — addon, login
-- auto-enable, or a manually typed `.playerbot bot self`. CB_SetSelfBotActive applies
-- that live state on the addon side; it never sends the toggle command itself (that is
-- a pure server toggle, sent only once on a fresh login — see PLAYER_ENTERING_WORLD).
--
-- NS.selfBotActive = live state (driven by the messages; persisted only for reload).
-- NS.manageSelf = auto-enable-on-login preference (Settings checkbox / first-time popup).
--- Applies the player's live self-bot state on the addon side (no command is sent).
--- active=true seeds the player as a known bot, reads real strategies, and surfaces them
--- in the lists; active=false drops them. Persists the state for /reload recovery.
---@param active boolean Whether the player is currently a self-bot.
NS.CB_SetSelfBotActive = function(active)
active = active and true or false
NS.selfBotActive = active
if CleanBot_SavedVars then CleanBot_SavedVars.selfBotActive = active end
local name = UnitName("player")
local key = name and strlower(name)
if active and key then
-- Seed a known-bot entry (same shape as the ROSTER~ handler) so the player counts
-- as a bot regardless of bridge state. Class comes from the client (always known).
if not CleanBot_PartyBots[key] then
local _, class = UnitClass("player")
class = class or "WARRIOR"
CleanBot_PartyBots[key] = {
name = name,
class = class,
combat = NS.CB_DefaultCombat(),
nonCombat = NS.CB_DefaultNonCombat(),
classData = NS.CB_DefaultClassData(class),
}
end
-- Now that we're a live self-bot, resolve the bridge if it hasn't yet (the gate
-- keys off NS.selfBotActive, so a self-whisper handshake can run solo).
if NS.bridgeState == "unknown" and NS.CB_StartBridgeDetection then
NS.CB_StartBridgeDetection()
end
-- Read the player's actual strategies. A bare "co ?" (awaitingCo, NOT coVerifyOnly)
-- stores the combat reply then chains "nc ?" — a full read, same as the probe path.
-- Always whispers (queries are never bridged), and self-whisper works here.
local entry = CleanBot_PartyBots[key]
if entry then
entry.awaitingCo = true
NS.CB_SendBotCommand(name, "co ?")
end
elseif key then
CleanBot_PartyBots[key] = nil
end
if CleanBotFrame:IsShown() and NS.CleanBot_RefreshTabs then
NS.CleanBot_RefreshTabs()
end
end
-- ============================================================
-- Bridge allowlists — mirror of MultiBotBridge.cpp IsAllowed*()
-- Source: https://github.com/Wishmaster117/mod-multibot-bridge/blob/main/src/MultiBotBridge.cpp
-- Keep in sync with the server when the bridge is updated.
-- ============================================================
-- RUN~COMBAT — IsAllowedCombatCommand()
local BRIDGE_COMBAT_CMDS = {
["CO +FOCUS"] = true,
["CO -FOCUS"] = true,
["CO +DPS ASSIST"] = true,
["CO -DPS ASSIST"] = true,
["CO +AOE"] = true,
["CO -AOE"] = true,
["CO +DPS AOE"] = true,
["CO -DPS AOE"] = true,
["CO +TANK ASSIST"] = true,
["CO -TANK ASSIST"] = true,
["CO +AVOID AOE"] = true,
["CO -AVOID AOE"] = true,
["CO +SAVE MANA"] = true,
["CO -SAVE MANA"] = true,
["CO +THREAT"] = true,
["CO -THREAT"] = true,
["CO +BEHIND"] = true,
["CO -BEHIND"] = true,
["CO +WAIT FOR ATTACK"] = true,
["CO -WAIT FOR ATTACK"] = true,
-- "wait for attack time N" (N = 0–60) handled via pattern below
}
-- RUN~LOOT — IsAllowedLootCommand() (case-sensitive after trim)
local BRIDGE_LOOT_CMDS = {
["nc +loot"] = true,
["nc -loot"] = true,
["ll all"] = true,
["ll normal"] = true,
["ll gray"] = true,
["ll quest"] = true,
["ll skill"] = true,
}
-- RUN~RTI — IsAllowedRTIIcon()
local BRIDGE_RTI_ICONS = {
["STAR"] = true,
["CIRCLE"] = true,
["DIAMOND"] = true,
["TRIANGLE"] = true,
["MOON"] = true,
["SQUARE"] = true,
["CROSS"] = true,
["SKULL"] = true,
}
---@param command string The bot command being routed.
---@return string|nil The bridge opcode ("COMBAT"/"POSITION"/"LOOT"/"RTI") or nil to whisper.
local function CB_GetBridgeOpcode(command)
-- COMBAT: static set
if BRIDGE_COMBAT_CMDS[strupper(command)] then return "COMBAT" end
-- COMBAT: "wait for attack time N" — no "co" prefix, N must be 0–60
local n = strmatch(command, "^[Ww][Aa][Ii][Tt]%s+[Ff][Oo][Rr]%s+[Aa][Tt][Tt][Aa][Cc][Kk]%s+[Tt][Ii][Mm][Ee]%s+(%d+)$")
if n and tonumber(n) <= 60 then return "COMBAT" end
-- POSITION: "disperse disable" or "disperse set N" (0 < N ≤ 100)
local lower = strlower(command)
if lower == "disperse disable" then return "POSITION" end
local dval = strmatch(lower, "^disperse set%s+(.+)$")
if dval then
local v = tonumber(dval)
if v and v > 0 and v <= 100 then return "POSITION" end
end
-- LOOT: static set (case-sensitive)
if BRIDGE_LOOT_CMDS[command] then return "LOOT" end
-- RTI: "attack/pull rti target", "rti <icon>", "rti cc <icon>"
local upper = strupper(command)
if upper == "ATTACK RTI TARGET" or upper == "PULL RTI TARGET" then return "RTI" end
local rtiIcon = strmatch(upper, "^RTI%s+(%S+)$")
if rtiIcon and BRIDGE_RTI_ICONS[rtiIcon] then return "RTI" end
local rtiCCIcon = strmatch(upper, "^RTI%s+CC%s+(%S+)$")
if rtiCCIcon and BRIDGE_RTI_ICONS[rtiCCIcon] then return "RTI" end
return nil
end
-- Returns the effective bridge state, respecting NS.debugBridgeOverride.
-- Use this instead of reading NS.bridgeState directly inside CB_SendBotCommand
-- so that /cbdebug bridge on/off can exercise both code paths without a real bridge.
local function CB_EffectiveBridgeState()
return NS.debugBridgeOverride or NS.bridgeState
end
-- Sends a bridge addon packet on the correct channel:
-- • In a raid → "RAID" ("PARTY" does not reach raid members)
-- • In a party → "PARTY"
-- • Solo + self-management on → "WHISPER" to self. The server bridge replies directly
-- to the sender (player->SendDirectMessage in MultiBotBridge.cpp) and its chat hook
-- fires on the whisper overload regardless of recipient, so a self-whisper completes
-- the handshake and carries all GET~/RUN~ traffic with no group present.
-- • Solo without self-management → no bots to talk to, so this no-ops.
local function CB_SendBridge(msg)
if GetNumRaidMembers() > 0 then
SendAddonMessage("MBOT", msg, "RAID")
elseif GetNumPartyMembers() > 0 then
SendAddonMessage("MBOT", msg, "PARTY")
elseif NS.selfBotActive then
SendAddonMessage("MBOT", msg, "WHISPER", UnitName("player"))
end
end
-- Command-reply window: bots confirm nearly every command with a whisper — a one-line ack
-- ("Picking ...", "Wait for attack time set to ...") or a multi-line dump (items/quests/spec).
-- Rather than enumerate every reply string, we open a per-bot window the instant we whisper a
-- command; ChatFilter.lua suppresses that bot's whispers while the window is open and slides it
-- forward as each reply line arrives, so the window brackets the whole burst and closes after
-- WHISPER_SILENCE of quiet (the same silence basis the collection flags use). Keyed by
-- lowercased name so it also covers discovery probes to not-yet-cached members.
NS.botReplyWindow = NS.botReplyWindow or {} -- [lowername] = GetTime() deadline
---@param botName string The bot we just whispered a command/query to.
local function CB_MarkExpectReply(botName)
if botName and botName ~= "" then
NS.botReplyWindow[strlower(botName)] = GetTime() + NS.WHISPER_SILENCE
end
end
-- Exposed so broadcast (party/raid) commands can open reply windows for the bots
-- they reach, letting ChatFilter hide their whispered replies (CommandControls.lua).
NS.CB_MarkExpectReply = CB_MarkExpectReply
-- Outgoing whisper provenance: CHAT_MSG_WHISPER_INFORM can't tell an addon-sent command from
-- one the user typed by hand, so we tag each command whisper we send. ChatFilter.lua hides only
-- the tagged ones, leaving manually typed whispers to a bot visible. Keyed by recipient+text,
-- holding a short list of send timestamps (a list, not a flag, so two identical commands in a
-- row each get their own tag); ChatFilter consumes one per matching INFORM and expires stale
-- tags (a failed send fires no INFORM, so its tag must not linger and hide a later manual one).
NS.selfWhispers = NS.selfWhispers or {} -- ["lowerRecipient\0text"] = { GetTime(), ... }
---@param recipient string Whisper target (bot name).
---@param text string Exact whisper text the addon is sending.
local function CB_TagSelfWhisper(recipient, text)
if not recipient or recipient == "" then return end
local k = strlower(recipient) .. "\0" .. (text or "")
local list = NS.selfWhispers[k]
if not list then list = {}; NS.selfWhispers[k] = list end
list[#list + 1] = GetTime()
end
-- Same provenance problem for broadcast commands: the player's own party/raid echo
-- (CHAT_MSG_PARTY/RAID, sender = the player) is indistinguishable from a manually typed line, so we
-- tag each broadcast CleanBot sends. Keyed by text only (sender is always the player); ChatFilter
-- consumes one tag per matching echo and expires stale ones.
NS.selfGroupMessages = NS.selfGroupMessages or {} -- [text] = { GetTime(), ... }
---@param text string Exact party/raid message the addon is broadcasting.
local function CB_TagSelfGroup(text)
if not text or text == "" then return end
local list = NS.selfGroupMessages[text]
if not list then list = {}; NS.selfGroupMessages[text] = list end
list[#list + 1] = GetTime()
end
NS.CB_TagSelfGroup = CB_TagSelfGroup
-- Raw dispatch: the actual bridge-or-whisper send. Routes through the bridge (silent) when
-- present and the command is allowlisted; otherwise whispers. Honors the debugSimulate and
-- debugBridgeOverride toggles. Called by the serial queue (for whispers) and directly for
-- bridge/simulated commands — NOT to be called directly for ad-hoc whispers; use
-- CB_SendBotCommand so they serialize.
---@param botName string Target bot's name (whisper recipient / bridge BOT field).
---@param command string The command text to run.
local function CB_SendBotCommandRaw(botName, command)
if NS.debugSimulate then
NS.CB_Print("|cff888888[simulate]|r → " .. botName .. ": " .. command)
return
end
if CB_EffectiveBridgeState() == "present" then
local opcode = CB_GetBridgeOpcode(command)
if opcode then
CB_SendBridge("RUN~" .. opcode .. "~BOT~" .. botName .. "~~" .. command)
return
end
end
CB_MarkExpectReply(botName)
CB_TagSelfWhisper(botName, command)
SendChatMessage(command, "WHISPER", nil, botName)
end
NS.CB_SendBotCommandRaw = CB_SendBotCommandRaw -- for queued fetch/move sends (avoids re-enqueue)
-- Sends a command to a bot. WHISPER commands are serialized through the bot's request queue
-- so their (possibly multi-line, link-bearing) replies never interleave with another reply
-- stream and corrupt our parsing. Bridge commands (structured addon messages, no whisper
-- reply) and simulated commands bypass the queue so they stay snappy.
NS.CB_SendBotCommand = function(botName, command)
-- Simulate prints, no reply; bridge is a fast addon message with no whisper stream.
if NS.debugSimulate
or (CB_EffectiveBridgeState() == "present" and CB_GetBridgeOpcode(command)) then
CB_SendBotCommandRaw(botName, command)
return
end
NS.CB_EnqueueRequest(strlower(botName), function() CB_SendBotCommandRaw(botName, command) end)
end
NS.CB_RequestSync = function()
if NS.syncPending then return end
NS.syncPending = true
NS.CB_After(0.5, function()
NS.syncPending = false
if CB_EffectiveBridgeState() == "present" then
CB_SendBridge("GET~ROSTER")
CB_SendBridge("GET~DETAILS")
CB_SendBridge("GET~STATES")
elseif CB_EffectiveBridgeState() == "absent" then
CB_ProbePartyForBots()
end
if CleanBotFrame:IsShown() then
NS.CleanBot_RefreshTabs()
end
end)
end
--- Convenience wrapper: kicks off a debounced roster/details/states sync.
NS.CB_RequestRosterThenRefresh = function()
NS.CB_RequestSync()
end
-- Lightweight, debounced strategy-state re-sync (bridge path). Unlike
-- CB_RequestSync it sends ONLY GET~STATES — no ROSTER/DETAILS and no RefreshTabs —
-- so it reconciles strategy flags (via the STATE~ handler → CB_StoreCombat/
-- CB_StoreNonCombat → CB_UpdateTabData) without tab/inspect churn. Used to verify a
-- strategy toggle silently after sending it over the bridge.
NS.statesPending = false
NS.CB_RequestStates = function()
if NS.statesPending then return end
NS.statesPending = true
NS.CB_After(0.4, function()
NS.statesPending = false
if CB_EffectiveBridgeState() == "present" then
CB_SendBridge("GET~STATES")
end
end)
end
-- Authoritative per-bot re-read of strategies + formation + loot — used to VERIFY/reconcile after a
-- command that optimistically rewrites a bot's whole state (e.g. the Individual tab's "reset botAI",
-- applied optimistically by Overhear). Unlike CB_RequestSync this targets one ALREADY-KNOWN bot —
-- CB_RequestSync's no-bridge probe (CB_ProbePartyForBots) skips known bots, so it can't re-read here.
-- "co ?" needs awaitingCo set so its reply is parsed and chains "nc ?" (mirrors CB_SetSelfBotActive);
-- the formation/loot replies match by prefix and need no flag. All three are whispered queries (never
-- bridged) and queue in order BEHIND the triggering command, so they read the post-command state; each
-- reply repaints via CB_UpdateTabData, overwriting the optimistic guess with the bot's real values.
---@param key string Bot name-key (CleanBot_PartyBots index).
---@param botName string The bot's name (whisper recipient).
NS.CB_RereadBotState = function(key, botName)
local entry = key and CleanBot_PartyBots[key]
if not (entry and botName) then return end
entry.awaitingCo = true
NS.CB_SendBotCommand(botName, "co ?")
NS.CB_SendBotCommand(botName, "formation ?")
NS.CB_SendBotCommand(botName, "ll ?")
end
-- Sends a combat/non-combat strategy toggle, then arranges an authoritative
-- re-read so the optimistic UI converges to the bot's real state (self-healing).
-- Path-aware to avoid reintroducing bridge whisper spam:
-- bridge present → send the toggle as usual (allowlisted singles stay silent),
-- then a silent debounced GET~STATES (CB_RequestStates).
-- no bridge → send the atomic combined form "<prefix> <toggle>,?" so the
-- bot's "Strategies:" reply (still via CHAT_MSG_WHISPER) reflects
-- the post-set state; arm awaitingCo/awaitingNc to consume it.
-- expectMap = { [field] = bool } of the toggled strategies; recorded for the
-- /cbdebug verify mismatch check (only when NS.debugVerify is on).
---@param slot table The bound slot (resolves the live bot via slot.key/.name).
---@param prefix string "co" or "nc".
---@param toggleStr string Toggle body, e.g. "+focus", "-aoe", "+arms,-fury,-prot".
---@param expectMap table? field→expected-bool map for the debug mismatch check.
NS.CB_SendStrategyToggle = function(slot, prefix, toggleStr, expectMap)
local entry = CleanBot_PartyBots[slot.key]
if entry and NS.debugVerify and expectMap then
local section = (prefix == "co") and "combat" or "nonCombat"
entry.stratExpect = entry.stratExpect or {}
local acc = entry.stratExpect[section] or {}
for f, v in pairs(expectMap) do acc[f] = v end -- merge so rapid toggles all check
entry.stratExpect[section] = acc
end
if CB_EffectiveBridgeState() == "present" then
NS.CB_SendBotCommand(slot.name, prefix .. " " .. toggleStr)
NS.CB_RequestStates()
else
NS.CB_SendBotCommand(slot.name, prefix .. " " .. toggleStr .. ",?")
if entry then
if prefix == "co" then
entry.awaitingCo = true
entry.coVerifyOnly = true -- parse the combat reply but don't chain "nc ?"
else
entry.awaitingNc = true
end
end
end
end
-- Finalizes a whisper-path quest collection: swaps the staged quests into the
-- live list and re-renders if the bot's quest frame is open. Shared by the
-- summary-line terminator and the silence-timeout fallback below.
---@param key string Bot name-key.
---@param entry table The bot roster entry being finalized.
local function CB_FinalizeQuestCollection(key, entry)
entry.awaitingQuests = false
entry.questTimeout = 0
entry.quests = entry.questStaging or {}
entry.questStaging = nil
local f = NS.botQuestFrames and NS.botQuestFrames[key]
if f and f:IsShown() and NS.CB_RenderQuests then NS.CB_RenderQuests(key) end
end
-- ============================================================
-- Premade talent-spec list cache (per class, in-memory)
-- "talents spec list" replies one line per premade: "1. arms pve (51-0-20)"
-- where the name is the exact "talents spec <name>" argument (== dropdown cmd)
-- and (t1-t2-t3) is the per-tree point spread. CB_SyncTalentSpec matches the
-- inspected bot's tree totals against these spreads to identify its premade.
-- ============================================================
NS.premadeSpecs = {} -- [class] = { { name = "arms pve", t = {51,0,20} }, ... }
NS.premadeSpecsFetching = {} -- [class] = true while a list fetch is in flight
-- Whispers "talents spec list" to one bot of the class and arms collection.
-- One fetch per class per session; the reply lines are collected in the
-- CHAT_MSG_WHISPER handler and finalized on 2s silence in invTickFrame.
---@param key string Bot name-key of the bot to query.
---@param entry table The bot roster entry (provides name/class).
NS.CB_FetchSpecList = function(key, entry)
if not entry or not entry.class then return end
if NS.premadeSpecs[entry.class] or NS.premadeSpecsFetching[entry.class] then return end
NS.premadeSpecsFetching[entry.class] = true
-- Enqueue: the silence timer (specListTimeout) must start at SEND time, not now, or a
-- deferred send behind other requests would finalize before the reply arrives.
NS.CB_EnqueueRequest(key, function()
entry.awaitingSpecList = true
entry.specListTimeout = 0
entry.specListStaging = {}
NS.CB_SendBotCommandRaw(entry.name, "talents spec list")
end)
end
-- Publishes a collected spec list to the per-class cache and re-runs the
-- pending talent sync that requested it.
---@param key string Bot name-key.
---@param entry table The bot roster entry being finalized.
local function CB_FinalizeSpecList(key, entry)
entry.awaitingSpecList = false
entry.specListTimeout = 0
if entry.class then
NS.premadeSpecsFetching[entry.class] = nil
-- Publish even an empty list so a server with no premades doesn't refetch
-- on every inspect; the sync just falls back to tree-name display.
NS.premadeSpecs[entry.class] = entry.specListStaging or {}
end
entry.specListStaging = nil
if NS.CB_SyncTalentSpec then NS.CB_SyncTalentSpec(key) end
end
-- How long a whisper collection waits in SILENCE before declaring itself done.
-- The clock resets on every line received, so this must cover (a) the bot's
-- time-to-first-reply after our query and (b) the max gap between burst lines —
-- NOT the total reply length. Bots reply fast on a healthy server; favor snappy
-- UX when things run smoothly over graceful degradation under lag.
-- Tune with /cbtiming (measures both first-reply latency and inter-line gaps).
-- 0.5 chosen from /cbtiming measurements on a healthy server (2026-06).
NS.WHISPER_SILENCE = 0.5
-- ── Per-bot serial whisper queue ─────────────────────────────────────────
-- A bot's reply (items / bank / stats list, a "Strategies:" line, a "put X to bank"
-- confirmation, …) is a whisper that can span many lines and may echo item links. Sending
-- another whisper before it finishes interleaves the replies and corrupts our parsing
-- (duplicate items, items snapping back). So EVERY whisper to a bot is queued and sent ONE
-- AT A TIME. The queue owns a single generic busy flag (wqBusy): set when a request is sent,
-- and cleared once the bot's reply has gone silent (each incoming whisper resets the timer in
-- CHAT_MSG_WHISPER). Typed flags like awaitingInventory still drive parsing/finalize/lock, but
-- the queue's advancement is governed solely by wqBusy, so it works uniformly for every kind
-- of request. Bridge/simulated commands don't whisper and bypass the queue (see CB_SendBotCommand).
---@param key string Bot name-key.
local function CB_PumpQueue(key)
local entry = CleanBot_PartyBots[key]
if not entry or not entry.reqQueue or entry.wqBusy then return end
local send = table.remove(entry.reqQueue, 1)
if send then
entry.wqBusy = true -- held until the reply goes silent (tick below)
entry.wqTimeout = 0
send()
end
end
-- Enqueues a whisper request (`send` performs the actual raw whisper). Runs immediately when
-- the bot is idle, else after the in-flight request's reply completes.
---@param key string Bot name-key.
---@param send fun() Performs the raw whisper send.
NS.CB_EnqueueRequest = function(key, send)
local entry = CleanBot_PartyBots[key]
if not entry then
-- No per-bot entry to serialize against — e.g. a no-bridge discovery probe
-- ("co ?") to a member not yet known to be a bot. There is no reply stream to
-- interleave with, so send immediately rather than dropping it.
send()
return
end
entry.reqQueue = entry.reqQueue or {}
entry.reqQueue[#entry.reqQueue + 1] = send
CB_PumpQueue(key)
end
-- Tick inventory, money, quest, and spec-list timeouts for the whisper path
-- (silence = collection done), then drain the serial request queue as bots go idle.
local invTickFrame = CreateFrame("Frame")
invTickFrame:SetScript("OnUpdate", function(self, dt)
for key, entry in pairs(CleanBot_PartyBots) do
if entry.awaitingSpecList then
entry.specListTimeout = (entry.specListTimeout or 0) + dt
if entry.specListTimeout >= NS.WHISPER_SILENCE then
CB_FinalizeSpecList(key, entry)
end
end
if entry.awaitingQuests then
entry.questTimeout = (entry.questTimeout or 0) + dt
if entry.questTimeout >= NS.WHISPER_SILENCE then
CB_FinalizeQuestCollection(key, entry)
end
end
if entry.awaitingInventory then
entry.invTimeout = (entry.invTimeout or 0) + dt
if entry.invTimeout >= NS.WHISPER_SILENCE then
entry.awaitingInventory = false
entry.invTimeout = 0
-- Whisper path only (marked by invStaging): atomically swap the
-- freshly-staged items in (replacing the preserved stale set) so
-- a refresh updates cleanly, then fetch money/bag separately so
-- its reply arrives on its own and isn't swallowed here.
-- On the bridge path invStaging is nil and INV_END has normally
-- already rendered; this branch is just a safety-net flag clear.
-- Only swap when the reply actually arrived: a lost/late reply times
-- out with empty staging, and overwriting would wipe a good list.
if entry.invStaging then
if entry.invReplyArrived and entry.inventory then
entry.inventory.items = entry.invStaging
-- Inventory just changed (e.g. Sell Trash) — force past the TTL so the
-- bag/money totals reflect the new state (in-flight dedup still applies).
NS.CB_FetchStats(entry, true)
end
entry.invStaging = nil
entry.invReplyArrived = nil
entry.curItemSection = nil
end
local f = NS.botInventoryFrames and NS.botInventoryFrames[key]
if f and f:IsShown() then
NS.CB_RenderInventory(key)
elseif f and NS.CB_SetInventoryLoading then
NS.CB_SetInventoryLoading(f, false)
end
end
end
if entry.awaitingBank then
entry.bankTimeout = (entry.bankTimeout or 0) + dt
if entry.bankTimeout >= NS.WHISPER_SILENCE then
entry.awaitingBank = false
entry.bankTimeout = 0
-- Whisper-only (bankStaging marker): swap the freshly-staged bank items
-- in atomically, replacing the preserved stale set so a refresh updates
-- cleanly. No money/bag fetch — the bank reply carries no summary.
-- Only swap when the reply actually arrived (else keep the stale list,
-- so a lost/late reply doesn't wipe the bank to empty).
if entry.bankStaging then
if entry.bankReplyArrived and entry.bank then
entry.bank.items = entry.bankStaging
end
entry.bankStaging = nil
entry.bankReplyArrived = nil
end
entry.curItemSection = nil
local f = NS.botBankFrames and NS.botBankFrames[key]
if f and f:IsShown() then
NS.CB_RenderBank(key)
elseif f and NS.CB_SetInventoryLoading then
NS.CB_SetInventoryLoading(f, false)
end
end
end
if entry.awaitingMoney then
entry.moneyTimeout = (entry.moneyTimeout or 0) + dt
if entry.moneyTimeout >= NS.WHISPER_SILENCE then
entry.awaitingMoney = false
entry.moneyTimeout = 0
end
end
-- Deposit/withdraw ("bank <link>") completion: arms the no-banker popup for the op
-- window; cleared after silence (timer reset on each whisper from this bot, below).
if entry.awaitingBankOp then
entry.bankOpTimeout = (entry.bankOpTimeout or 0) + dt
if entry.bankOpTimeout >= NS.WHISPER_SILENCE then
entry.awaitingBankOp = false
entry.bankOpTimeout = 0
end
end
-- Serial-queue completion: the in-flight request is done once the bot's reply stream
-- goes silent. Runs AFTER the typed finalizes above (which parse/render this reply),
-- so the next request is sent only once the current one is fully handled.
if entry.wqBusy then
entry.wqTimeout = (entry.wqTimeout or 0) + dt
if entry.wqTimeout >= NS.WHISPER_SILENCE then
entry.wqBusy = false
end
end
-- Drain the serial whisper queue as the bot returns to idle.
if entry.reqQueue and #entry.reqQueue > 0 and not entry.wqBusy then
CB_PumpQueue(key)
end
end
end)
-- Performs the actual inventory fetch (sets the busy flag + sends). Runs from the serial
-- queue so it never overlaps another reply stream. Bridge path is instant; whisper path
-- streams the "items" reply, collected via invStaging and finalized on silence.
---@param key string Bot name-key (lowercased lookup key).
---@param botName string Bot's display name (whisper/bridge target).
local function CB_DoFetchInventory(key, botName)
local entry = CleanBot_PartyBots[key]
if not entry then return end
-- Preserve existing inventory while the fresh fetch is in flight so the
-- frame can display stale-but-correct data instead of going blank.
entry.inventory = entry.inventory or { items = {} }
local useBridge = CB_EffectiveBridgeState() == "present"
-- In-flight flag drives the loading overlay AND the interaction lock; cleared in
-- CB_RenderInventory when data lands (or by the silence-timeout tick as a safety net).
entry.awaitingInventory = true
entry.invTimeout = 0
entry.curItemSection = nil -- reset header-routed staging for the new collection
entry.invReplyArrived = false -- set true when the reply (header/item) actually lands
-- Overlay policy: always for a first (empty) load, but for a refresh of an
-- already-rendered grid only on the whisper path — bridge refreshes are
-- near-instant, so a "Refreshing..." flash there is distracting noise.
local invF = NS.botInventoryFrames and NS.botInventoryFrames[key]
entry.invOverlay = (not (invF and invF.rendered)) or not useBridge
if invF and invF:IsShown() and entry.invOverlay and NS.CB_SetInventoryLoading then
NS.CB_SetInventoryLoading(invF, true)
end
if useBridge then
CB_SendBridge("GET~INVENTORY~" .. botName .. "~inv")
else
-- invStaging is the whisper-path marker: its presence tells the tick to run the
-- whisper finalize (swap + stats fetch). Fresh replies are collected here and only
-- swapped into entry.inventory.items atomically once collection completes.
-- Raw send: this already runs from the queue (CB_FetchInventory enqueued it).
entry.invStaging = {}
CB_SendBotCommandRaw(botName, "items")
end
end
-- Enqueues an inventory fetch onto the bot's serial whisper queue (see CB_EnqueueRequest).
---@param key string Bot name-key (lowercased lookup key).
---@param botName string Bot's display name (whisper/bridge target).
NS.CB_FetchInventory = function(key, botName)
NS.CB_EnqueueRequest(key, function() CB_DoFetchInventory(key, botName) end)
end
-- How long a fetched "stats" reply is considered fresh. Re-selecting a bot within this
-- window reuses the cached money/XP/durability instead of re-whispering; older revisits
-- refetch so the values stay reasonably current.
NS.STATS_TTL = 30 -- seconds
-- Fetches a bot's "stats" reply (money, bag totals, durability, XP). The reply is
-- parsed in the awaitingMoney branch of CHAT_MSG_WHISPER (below). "stats" is a query,
-- so it always whispers (never allowlisted) and the reply returns via CHAT_MSG_WHISPER
-- regardless of CB_EffectiveBridgeState() — no override gating needed. This is the
-- single source of truth for the "stats" whisper: the inventory-finalize tick and the
-- on-demand XP-bar fetch both route through here.
--
-- Two guards keep this from spamming a bot (mirrors CB_FetchSpecList's guard pattern):
-- • in-flight dedup — never stack a second "stats" while one is awaiting a reply, so the
-- post-login RefreshTabs→SelectBot burst can't hammer the first bot once per frame.
-- • TTL freshness — skip the refetch when the cached reply is younger than STATS_TTL,
-- so re-selecting a recently-viewed bot reuses the cache. Pass force=true to bypass
-- the TTL (e.g. after an inventory change that may have altered bag/money); the
-- in-flight dedup still applies.
---@param entry table The CleanBot_PartyBots entry to refresh.
---@param force boolean? Bypass the TTL freshness check (still respects in-flight dedup).
NS.CB_FetchStats = function(entry, force)
if not entry or not entry.name then return end
if entry.awaitingMoney then return end
if not force and entry.statsAt and (GetTime() - entry.statsAt) < NS.STATS_TTL then
return
end
-- Enqueue so the "stats" reply doesn't overlap an items/bank stream.
NS.CB_EnqueueRequest(strlower(entry.name), function()
entry.awaitingMoney = true
entry.moneyTimeout = 0
CB_MarkExpectReply(entry.name)
CB_TagSelfWhisper(entry.name, "stats")
SendChatMessage("stats", "WHISPER", nil, entry.name)
end)
end
-- Queries a bot's current movement formation ("formation ?"). The reply
-- ("Formation: <name>") is parsed in the CHAT_MSG_WHISPER handler into entry.formation.
-- Cached: skips when entry.formation is already known unless `force` is set. Routes
-- through CB_SendBotCommand so it serializes and the reply is hidden.
---@param entry table The CleanBot_PartyBots entry to query.
---@param force boolean? Re-query even when a formation is already cached.
NS.CB_FetchFormation = function(entry, force)
if not entry or not entry.name then return end
if entry.formation and not force then return end
NS.CB_SendBotCommand(entry.name, "formation ?")
end
-- Queries a bot's current loot-quality strategy ("ll ?"). The reply
-- ("Loot strategy: <mode>") is parsed in the CHAT_MSG_WHISPER handler into entry.lootStrategy.
-- Cached: skips when entry.lootStrategy is already known unless `force` is set. Routes through
-- CB_SendBotCommand so it serializes and the reply is hidden (same as CB_FetchFormation).
---@param entry table The CleanBot_PartyBots entry to query.
---@param force boolean? Re-query even when a loot strategy is already cached.
NS.CB_FetchLootStrategy = function(entry, force)
if not entry or not entry.name then return end
if entry.lootStrategy and not force then return end
NS.CB_SendBotCommand(entry.name, "ll ?")
end
-- Fetches a bot's bank contents. Whisper-only — bank has no bridge packet, and the
-- reply (header "=== Bank ===" then item lines) is collected via the header-routed
-- staging branch in CHAT_MSG_WHISPER and finalized by the silence tick. The reply
-- carries no money/slot summary, so there is no stats fetch. Needs a banker NPC near
-- the bot; otherwise the bot replies "Cannot find banker nearby" (handled as a popup).
-- Performs the actual bank fetch (sets the busy flag + sends "bank"). Runs from the serial
-- queue so the multi-line reply never overlaps another stream.
---@param key string Bot name-key (lowercased lookup key).
---@param botName string Bot's display name (whisper target).
local function CB_DoFetchBank(key, botName)
local entry = CleanBot_PartyBots[key]
if not entry then return end
-- Preserve existing bank items while the fresh fetch is in flight (stale display).
entry.bank = entry.bank or { items = {} }
entry.awaitingBank = true
entry.bankTimeout = 0
entry.curItemSection = nil
entry.bankReplyArrived = false -- set true when the reply (header/item) actually lands
-- Bank is always whisper-only (replies trickle in over ~0.5s+), so always show
-- the overlay — "Loading..." on a first fetch, "Refreshing..." over rendered data.
entry.bankOverlay = true
local bf = NS.botBankFrames and NS.botBankFrames[key]
if bf and bf:IsShown() and NS.CB_SetInventoryLoading then
NS.CB_SetInventoryLoading(bf, true)
end
-- bankStaging is the whisper-path marker the silence tick keys off to finalize.
-- Raw send: this already runs from the queue (CB_FetchBank enqueued it).
entry.bankStaging = {}
CB_SendBotCommandRaw(botName, "bank")
end
-- Enqueues a bank fetch onto the bot's serial whisper queue (see CB_EnqueueRequest).
---@param key string Bot name-key (lowercased lookup key).
---@param botName string Bot's display name (whisper target).
NS.CB_FetchBank = function(key, botName)
NS.CB_EnqueueRequest(key, function() CB_DoFetchBank(key, botName) end)
end
-- Debounced post-action reconcile. A burst of optimistic item moves (deposit/withdraw,
-- use, sell) bumps a per-entry token; the actual refetch fires once the user stops (token
-- still current) and only for the currently-open frames. The eager optimistic display
-- carries the UI in the meantime, and the refetch is enqueued so it is serialized behind
-- the move commands (no interleaving). Coalescing avoids one slow round-trip per move.
NS.RECONCILE_DELAY = 1.0
---@param key string Bot name-key.
---@param botName string Bot's display name (fetch target).
NS.CB_ScheduleReconcile = function(key, botName)
local entry = CleanBot_PartyBots[key]
if not entry then return end
entry.reconcileGen = (entry.reconcileGen or 0) + 1
local gen = entry.reconcileGen
NS.CB_After(NS.RECONCILE_DELAY, function()
local e = CleanBot_PartyBots[key]
if not e or e.reconcileGen ~= gen then return end -- superseded by a newer action
local invF = NS.botInventoryFrames and NS.botInventoryFrames[key]
local bankF = NS.botBankFrames and NS.botBankFrames[key]
-- Enqueued (not sent inline): the queue runs these after the move commands' replies
-- complete, so the list query reflects the finished moves and never interleaves.
if invF and invF:IsShown() then NS.CB_FetchInventory(key, botName) end
if bankF and bankF:IsShown() then NS.CB_FetchBank(key, botName) end
end)
end
-- Overheard inventory/bank/equip command (Overhear.lua) → re-sync any open window for that bot.
-- Reuses the coalesced reconcile (inventory + bank, each gated on its window being shown). For the
-- currently-viewed bot also refresh the equipment inspect, mirroring the UNIT_INVENTORY_CHANGED path.
NS.CB_On(NS.EV.BOT_INVENTORY_DIRTY, function(key)
local entry = CleanBot_PartyBots[key]
if not entry then return end
NS.CB_ScheduleReconcile(key, entry.name)
if key == NS.selectedBotKey and NS.tabList and NS.CB_QueueEquipRefresh then
for _, info in ipairs(NS.tabList) do
if info.key == key and info.unit then
NS.CB_QueueEquipRefresh({ { key = key, unit = info.unit } })
break
end
end
end
end)
---@param key string Bot name-key (lowercased lookup key).
---@param botName string Bot's display name (whisper/bridge target).
---@param anchor table|string? Placement forwarded to CB_ToggleInventory ("CENTER", a frame, or nil).
NS.CB_RequestInventory = function(key, botName, anchor)
NS.CB_FetchInventory(key, botName)
NS.CB_ToggleInventory(key, botName, anchor)
end
-- Fetches the quest log for a bot. Bridge path sends a structured GET~QUESTS
-- request; the QUESTS_BEGIN/ITEM/END packets are handled below in the
-- CHAT_MSG_ADDON block. Whisper fallback sends "quests" and parses the reply
-- lines in the CHAT_MSG_WHISPER handler into the same { {id, status} } shape.
-- The live entry.quests is intentionally NOT cleared here: the bridge path
-- resets it on QUESTS_BEGIN, and the whisper path swaps fresh data in on
-- finalize (CB_FinalizeQuestCollection) — so the last render survives on screen
-- until the new list is ready.
---@param key string Bot name-key (lowercased lookup key).
---@param botName string Bot's display name (whisper/bridge target).
NS.CB_FetchQuests = function(key, botName)
local entry = CleanBot_PartyBots[key]
if not entry then return end
if CB_EffectiveBridgeState() == "present" then
CB_SendBridge("GET~QUESTS~ALL~" .. botName .. "~quests")
else
-- Whisper path: enqueue so the multi-line "quests all" reply is serialized; the typed
-- flags are set at SEND time (the queued function) so the silence timer starts then.
-- Lines are collected into staging keyed by section header (Incompleted/Completed) and
-- swapped in on the summary line or after silence (invTickFrame).
NS.CB_EnqueueRequest(key, function()
entry.awaitingQuests = true
entry.questTimeout = 0
entry.questStatus = "I" -- current section; flipped by reply headers
entry.questStaging = {}
-- "quests all" (not bare "quests", which only prints the summary) makes the
-- bot stream the per-quest lines + section headers we parse — mirrors the
-- bridge's GET~QUESTS~ALL mode.
NS.CB_SendBotCommandRaw(botName, "quests all")
end)
end
end
-- ============================================================
-- Bridge handshake