-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapproval_flow.go
More file actions
1619 lines (1503 loc) · 48.1 KB
/
approval_flow.go
File metadata and controls
1619 lines (1503 loc) · 48.1 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
package agentremote
import (
"context"
"sort"
"strings"
"sync"
"time"
"maunium.net/go/mautrix/bridgev2"
"maunium.net/go/mautrix/bridgev2/networkid"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
)
// ApprovalReactionHandler is the interface used by BaseReactionHandler to
// dispatch reactions to the approval system without knowing the concrete type.
type ApprovalReactionHandler interface {
HandleReaction(ctx context.Context, msg *bridgev2.MatrixReaction) bool
}
// ApprovalReactionRemoveHandler is an optional extension for handling reaction removals.
type ApprovalReactionRemoveHandler interface {
HandleReactionRemove(ctx context.Context, msg *bridgev2.MatrixReactionRemove) bool
}
const approvalWrongTargetMSSMessage = "React to the approval notice message to respond."
const approvalResolvedMSSMessage = "That approval request was already handled and can't be changed."
// ApprovalFlowConfig holds the bridge-specific callbacks for ApprovalFlow.
type ApprovalFlowConfig[D any] struct {
// Login returns the current UserLogin. Required.
Login func() *bridgev2.UserLogin
// Sender returns the EventSender to use for a given portal (e.g. the agent ghost).
Sender func(portal *bridgev2.Portal) bridgev2.EventSender
// BackgroundContext optionally returns a context detached from the request lifecycle.
BackgroundContext func(ctx context.Context) context.Context
// RoomIDFromData extracts the stored room ID from pending data for validation.
// Return "" to skip the room check.
RoomIDFromData func(data D) id.RoomID
// DeliverDecision is called for non-channel flows when a valid reaction resolves
// an approval. The flow has already validated owner, expiration, and room.
// If nil, the flow is channel-based: decisions are delivered via an internal
// channel and retrieved with Wait().
DeliverDecision func(ctx context.Context, portal *bridgev2.Portal, pending *Pending[D], decision ApprovalDecisionPayload) error
// SendNotice sends a system notice to a portal. Used for error toasts.
SendNotice func(ctx context.Context, portal *bridgev2.Portal, msg string)
// DBMetadata produces bridge-specific metadata for the approval prompt message.
// If nil, a default *BaseMessageMetadata is used.
DBMetadata func(prompt ApprovalPromptMessage) any
IDPrefix string
LogKey string
SendTimeout time.Duration
}
// Pending represents a single pending approval.
type Pending[D any] struct {
ExpiresAt time.Time
Data D
ch chan ApprovalDecisionPayload
done chan struct{} // closed when the approval is finalized
}
type resolvedApprovalPrompt struct {
Prompt ApprovalPromptRegistration
Decision ApprovalDecisionPayload
ExpiresAt time.Time
}
// closeDone marks the pending approval as finalized. Safe to call multiple times.
func (p *Pending[D]) closeDone() {
select {
case <-p.done:
default:
close(p.done)
}
}
// ApprovalFlow owns the full lifecycle of approval prompts and pending approvals.
// D is the bridge-specific pending data type.
type ApprovalFlow[D any] struct {
mu sync.Mutex
pending map[string]*Pending[D]
// Prompt store (inlined from ApprovalPromptStore).
promptsByApproval map[string]*ApprovalPromptRegistration
promptsByMsgID map[networkid.MessageID]string
reactionTargetsByMsgID map[networkid.MessageID]string
resolvedByMsgID map[networkid.MessageID]*resolvedApprovalPrompt
resolvedByReactionMsgID map[networkid.MessageID]*resolvedApprovalPrompt
login func() *bridgev2.UserLogin
sender func(portal *bridgev2.Portal) bridgev2.EventSender
backgroundCtx func(ctx context.Context) context.Context
roomIDFromData func(data D) id.RoomID
deliverDecision func(ctx context.Context, portal *bridgev2.Portal, pending *Pending[D], decision ApprovalDecisionPayload) error
sendNotice func(ctx context.Context, portal *bridgev2.Portal, msg string)
dbMetadata func(prompt ApprovalPromptMessage) any
idPrefix string
logKey string
sendTimeout time.Duration
// Reaper goroutine fields.
reaperStop chan struct{}
reaperNotify chan struct{}
// Test hooks (nil in production).
testResolvePortal func(ctx context.Context, login *bridgev2.UserLogin, roomID id.RoomID) (*bridgev2.Portal, error)
testEditPromptToResolvedState func(ctx context.Context, login *bridgev2.UserLogin, portal *bridgev2.Portal, sender bridgev2.EventSender, prompt ApprovalPromptRegistration, decision ApprovalDecisionPayload)
testRedactPromptPlaceholderReacts func(ctx context.Context, login *bridgev2.UserLogin, portal *bridgev2.Portal, sender bridgev2.EventSender, prompt ApprovalPromptRegistration, opts ApprovalPromptReactionCleanupOptions) error
testMirrorRemoteDecisionReaction func(ctx context.Context, login *bridgev2.UserLogin, portal *bridgev2.Portal, sender bridgev2.EventSender, prompt ApprovalPromptRegistration, reactionKey string)
testRedactSingleReaction func(msg *bridgev2.MatrixReaction)
testSendMessageStatus func(ctx context.Context, portal *bridgev2.Portal, evt *event.Event, status bridgev2.MessageStatus)
}
// NewApprovalFlow creates an ApprovalFlow from the given config.
// Call Close() when the flow is no longer needed to stop the reaper goroutine.
func NewApprovalFlow[D any](cfg ApprovalFlowConfig[D]) *ApprovalFlow[D] {
timeout := cfg.SendTimeout
if timeout <= 0 {
timeout = 10 * time.Second
}
f := &ApprovalFlow[D]{
pending: make(map[string]*Pending[D]),
promptsByApproval: make(map[string]*ApprovalPromptRegistration),
promptsByMsgID: make(map[networkid.MessageID]string),
reactionTargetsByMsgID: make(map[networkid.MessageID]string),
resolvedByMsgID: make(map[networkid.MessageID]*resolvedApprovalPrompt),
resolvedByReactionMsgID: make(map[networkid.MessageID]*resolvedApprovalPrompt),
login: cfg.Login,
sender: cfg.Sender,
backgroundCtx: cfg.BackgroundContext,
roomIDFromData: cfg.RoomIDFromData,
deliverDecision: cfg.DeliverDecision,
sendNotice: cfg.SendNotice,
dbMetadata: cfg.DBMetadata,
idPrefix: cfg.IDPrefix,
logKey: cfg.LogKey,
sendTimeout: timeout,
reaperStop: make(chan struct{}),
reaperNotify: make(chan struct{}, 1),
}
go f.runReaper()
return f
}
// Close stops the reaper goroutine. Safe to call multiple times.
func (f *ApprovalFlow[D]) Close() {
if f == nil {
return
}
f.mu.Lock()
defer f.mu.Unlock()
f.closeReaperLocked()
}
func (f *ApprovalFlow[D]) closeReaperLocked() {
select {
case <-f.reaperStop:
default:
close(f.reaperStop)
}
}
func (f *ApprovalFlow[D]) ensureReaperRunning() {
if f == nil {
return
}
f.mu.Lock()
defer f.mu.Unlock()
select {
case <-f.reaperStop:
f.reaperStop = make(chan struct{})
f.reaperNotify = make(chan struct{}, 1)
go f.runReaper()
default:
}
}
func (f *ApprovalFlow[D]) wakeReaper() {
if f == nil {
return
}
select {
case f.reaperNotify <- struct{}{}:
default:
}
}
const reaperMaxInterval = 30 * time.Second
func (f *ApprovalFlow[D]) runReaper() {
timer := time.NewTimer(reaperMaxInterval)
defer timer.Stop()
for {
select {
case <-f.reaperStop:
return
case <-timer.C:
f.reapExpired()
timer.Reset(f.nextReaperDelay())
case <-f.reaperNotify:
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer.Reset(f.nextReaperDelay())
}
}
}
// earliestExpiry returns the earlier of a and b, ignoring zero values.
func earliestExpiry(a, b time.Time) time.Time {
if a.IsZero() {
return b
}
if b.IsZero() || a.Before(b) {
return a
}
return b
}
func approvalPendingResolved[D any](p *Pending[D]) bool {
if p == nil {
return false
}
select {
case <-p.done:
return true
default:
return false
}
}
// nextReaperDelay returns the duration until the earliest pending/prompt expiry,
// capped at reaperMaxInterval.
func (f *ApprovalFlow[D]) nextReaperDelay() time.Duration {
f.mu.Lock()
defer f.mu.Unlock()
earliest := time.Time{}
for _, p := range f.pending {
if approvalPendingResolved(p) {
continue
}
earliest = earliestExpiry(earliest, p.ExpiresAt)
}
for approvalID, entry := range f.promptsByApproval {
if approvalPendingResolved(f.pending[approvalID]) {
continue
}
earliest = earliestExpiry(earliest, entry.ExpiresAt)
}
if earliest.IsZero() {
return reaperMaxInterval
}
delay := time.Until(earliest)
if delay <= 0 {
return time.Millisecond
}
if delay > reaperMaxInterval {
return reaperMaxInterval
}
return delay
}
func (f *ApprovalFlow[D]) reapExpired() {
now := time.Now()
candidates := make(map[string]expiredApprovalCandidate[D])
f.mu.Lock()
// Finalize pending approvals whose own TTL has elapsed.
for aid, p := range f.pending {
if approvalPendingResolved(p) {
continue
}
if !p.ExpiresAt.IsZero() && now.After(p.ExpiresAt) {
candidate := candidates[aid]
candidate.approvalID = aid
candidate.pending = p
candidate.expiredByPending = true
candidates[aid] = candidate
}
}
// Also finalize pending approvals whose associated prompt has expired.
for aid, entry := range f.promptsByApproval {
pending := f.pending[aid]
if approvalPendingResolved(pending) {
continue
}
if !entry.ExpiresAt.IsZero() && now.After(entry.ExpiresAt) {
if pending != nil {
candidate := candidates[aid]
candidate.approvalID = aid
candidate.pending = pending
candidate.prompt = entry
candidate.expiredByPrompt = true
candidates[aid] = candidate
} else {
// Orphan prompt — clean it up.
if entry.PromptMessageID != "" {
delete(f.promptsByMsgID, entry.PromptMessageID)
}
if entry.ReactionTargetMessageID != "" {
delete(f.reactionTargetsByMsgID, entry.ReactionTargetMessageID)
}
delete(f.promptsByApproval, aid)
}
}
}
f.mu.Unlock()
for _, candidate := range candidates {
f.finalizeExpiredCandidate(now, candidate)
}
}
type expiredApprovalCandidate[D any] struct {
approvalID string
pending *Pending[D]
prompt *ApprovalPromptRegistration
expiredByPending bool
expiredByPrompt bool
}
func (f *ApprovalFlow[D]) finalizeExpiredCandidate(now time.Time, candidate expiredApprovalCandidate[D]) {
if candidate.approvalID == "" || candidate.pending == nil {
return
}
var promptVersion uint64
expiredByPending := false
expiredByPrompt := false
f.mu.Lock()
currentPending := f.pending[candidate.approvalID]
if currentPending == candidate.pending && !approvalPendingResolved(currentPending) {
if candidate.expiredByPending && !currentPending.ExpiresAt.IsZero() && now.After(currentPending.ExpiresAt) {
expiredByPending = true
}
if candidate.expiredByPrompt {
currentPrompt := f.promptsByApproval[candidate.approvalID]
if currentPrompt == candidate.prompt && currentPrompt != nil && !currentPrompt.ExpiresAt.IsZero() && now.After(currentPrompt.ExpiresAt) {
expiredByPrompt = true
promptVersion = currentPrompt.PromptVersion
}
}
}
f.mu.Unlock()
switch {
case expiredByPending:
f.finishTimedOutApproval(candidate.approvalID)
case expiredByPrompt:
f.finishTimedOutApprovalWithPromptVersion(candidate.approvalID, promptVersion)
}
}
// ---------------------------------------------------------------------------
// Pending approval store
// ---------------------------------------------------------------------------
// Register adds a new pending approval with the given TTL and bridge-specific data.
// Returns the Pending and true if newly created, or the existing one and false
// if a non-expired approval with the same ID already exists.
func (f *ApprovalFlow[D]) Register(approvalID string, ttl time.Duration, data D) (*Pending[D], bool) {
f.ensureReaperRunning()
approvalID = strings.TrimSpace(approvalID)
if approvalID == "" {
return nil, false
}
if ttl <= 0 {
ttl = 10 * time.Minute
}
f.mu.Lock()
defer f.mu.Unlock()
if existing := f.pending[approvalID]; existing != nil {
if time.Now().Before(existing.ExpiresAt) {
return existing, false
}
delete(f.pending, approvalID)
}
p := &Pending[D]{
ExpiresAt: time.Now().Add(ttl),
Data: data,
ch: make(chan ApprovalDecisionPayload, 1),
done: make(chan struct{}),
}
f.pending[approvalID] = p
f.wakeReaper()
return p, true
}
// Get returns the pending approval for the given id, or nil if not found.
func (f *ApprovalFlow[D]) Get(approvalID string) *Pending[D] {
f.mu.Lock()
defer f.mu.Unlock()
return f.pending[approvalID]
}
// SetData updates the Data field on a pending approval under the lock.
// Returns false if the approval is not found.
func (f *ApprovalFlow[D]) SetData(approvalID string, updater func(D) D) bool {
f.mu.Lock()
defer f.mu.Unlock()
p := f.pending[approvalID]
if p == nil {
return false
}
p.Data = updater(p.Data)
return true
}
// Drop removes a pending approval and its associated prompt from both stores.
func (f *ApprovalFlow[D]) Drop(approvalID string) {
if f == nil {
return
}
f.finalizeWithPromptVersion(approvalID, nil, false, 0)
}
// normalizeDecisionID trims the approvalID and ensures decision.ApprovalID is set.
// Returns the trimmed approvalID and false if it is empty.
func normalizeDecisionID(approvalID string, decision *ApprovalDecisionPayload) (string, bool) {
approvalID = strings.TrimSpace(approvalID)
if approvalID == "" {
return "", false
}
if strings.TrimSpace(decision.ApprovalID) == "" {
decision.ApprovalID = approvalID
}
return approvalID, true
}
// FinishResolved finalizes a terminal approval by editing the approval prompt to
// its final state and cleaning up bridge-authored placeholder reactions.
func (f *ApprovalFlow[D]) FinishResolved(approvalID string, decision ApprovalDecisionPayload) {
if f == nil {
return
}
approvalID, ok := normalizeDecisionID(approvalID, &decision)
if !ok {
return
}
f.finalizeWithPromptVersion(approvalID, &decision, true, 0)
}
// ResolveExternal finalizes a remote allow/deny decision. The bridge declares
// whether the decision originated from the user or the agent/system and the
// shared approval flow manages the terminal Matrix reactions accordingly.
func (f *ApprovalFlow[D]) ResolveExternal(ctx context.Context, approvalID string, decision ApprovalDecisionPayload) {
if f == nil {
return
}
approvalID, ok := normalizeDecisionID(approvalID, &decision)
if !ok {
return
}
if normalizeApprovalResolutionOrigin(decision.ResolvedBy) == "" {
decision.ResolvedBy = ApprovalResolutionOriginAgent
}
prompt, hasPrompt := f.promptRegistration(approvalID)
if err := f.Resolve(approvalID, decision); err != nil {
return
}
if hasPrompt && decision.ResolvedBy == ApprovalResolutionOriginUser {
f.mirrorRemoteDecisionReaction(ctx, prompt, decision)
}
f.FinishResolved(approvalID, decision)
}
// FindByData iterates pending approvals and returns the id of the first one
// for which the predicate returns true. Returns "" if none match.
func (f *ApprovalFlow[D]) FindByData(predicate func(data D) bool) string {
f.mu.Lock()
defer f.mu.Unlock()
for id, p := range f.pending {
if p != nil && predicate(p.Data) {
return id
}
}
return ""
}
func (f *ApprovalFlow[D]) PendingIDs() []string {
f.mu.Lock()
defer f.mu.Unlock()
ids := make([]string, 0, len(f.pending))
for id := range f.pending {
ids = append(ids, id)
}
sort.Strings(ids)
return ids
}
// Resolve programmatically delivers a decision to a pending approval's channel.
// Use this when a decision arrives from an external source (e.g. the upstream
// server or auto-approval) rather than a Matrix reaction.
// Unlike HandleReaction, Resolve does NOT drop the pending entry — the caller
// (typically Wait or an explicit Drop) is responsible for cleanup.
func (f *ApprovalFlow[D]) Resolve(approvalID string, decision ApprovalDecisionPayload) error {
approvalID = strings.TrimSpace(approvalID)
if approvalID == "" {
return ErrApprovalMissingID
}
f.mu.Lock()
p := f.pending[approvalID]
f.mu.Unlock()
if p == nil {
return ErrApprovalUnknown
}
if time.Now().After(p.ExpiresAt) {
f.finishTimedOutApproval(approvalID)
return ErrApprovalExpired
}
select {
case p.ch <- decision:
f.cancelPendingTimeout(approvalID)
return nil
default:
return ErrApprovalAlreadyHandled
}
}
// Wait blocks until a decision arrives via reaction, the approval expires,
// or ctx is cancelled. Only useful for channel-based flows (DeliverDecision is nil).
func (f *ApprovalFlow[D]) Wait(ctx context.Context, approvalID string) (ApprovalDecisionPayload, bool) {
var zero ApprovalDecisionPayload
approvalID = strings.TrimSpace(approvalID)
if approvalID == "" {
return zero, false
}
f.mu.Lock()
p := f.pending[approvalID]
f.mu.Unlock()
if p == nil {
return zero, false
}
select {
case d := <-p.ch:
return d, true
default:
}
timeout := time.Until(p.ExpiresAt)
if timeout <= 0 {
f.finishTimedOutApproval(approvalID)
return zero, false
}
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case d := <-p.ch:
return d, true
case <-timer.C:
f.finishTimedOutApproval(approvalID)
return zero, false
case <-ctx.Done():
return zero, false
}
}
// ---------------------------------------------------------------------------
// Prompt store (inlined)
// ---------------------------------------------------------------------------
// registerPrompt adds or replaces a prompt registration.
// Must be called with f.mu held.
func (f *ApprovalFlow[D]) registerPromptLocked(reg ApprovalPromptRegistration) {
reg.ApprovalID = strings.TrimSpace(reg.ApprovalID)
if reg.ApprovalID == "" {
return
}
reg.ToolCallID = strings.TrimSpace(reg.ToolCallID)
reg.ToolName = strings.TrimSpace(reg.ToolName)
reg.TurnID = strings.TrimSpace(reg.TurnID)
prev := f.promptsByApproval[reg.ApprovalID]
if reg.PromptVersion == 0 && prev != nil {
reg.PromptVersion = prev.PromptVersion
}
if prev != nil && prev.PromptMessageID != "" {
delete(f.promptsByMsgID, prev.PromptMessageID)
}
if prev != nil && prev.ReactionTargetMessageID != "" {
delete(f.reactionTargetsByMsgID, prev.ReactionTargetMessageID)
}
copyReg := reg
f.promptsByApproval[reg.ApprovalID] = ©Reg
if reg.PromptMessageID != "" {
f.promptsByMsgID[reg.PromptMessageID] = reg.ApprovalID
}
if reg.ReactionTargetMessageID != "" {
f.reactionTargetsByMsgID[reg.ReactionTargetMessageID] = reg.ApprovalID
}
}
// bindPromptTargetLocked associates a prompt with its remote message ID. It
// returns the prompt generation that should own any timeout goroutine.
// Must be called with f.mu held.
func (f *ApprovalFlow[D]) bindPromptTargetLocked(approvalID string, messageID networkid.MessageID) (uint64, bool) {
approvalID = strings.TrimSpace(approvalID)
messageID = networkid.MessageID(strings.TrimSpace(string(messageID)))
if approvalID == "" || messageID == "" {
return 0, false
}
entry := f.promptsByApproval[approvalID]
if entry == nil {
return 0, false
}
if entry.PromptMessageID != "" {
delete(f.promptsByMsgID, entry.PromptMessageID)
}
if entry.ReactionTargetMessageID != "" {
f.reactionTargetsByMsgID[entry.ReactionTargetMessageID] = approvalID
}
entry.PromptVersion++
entry.PromptMessageID = messageID
f.promptsByMsgID[messageID] = approvalID
return entry.PromptVersion, true
}
func (f *ApprovalFlow[D]) promptRegistration(approvalID string) (ApprovalPromptRegistration, bool) {
approvalID = strings.TrimSpace(approvalID)
if approvalID == "" {
return ApprovalPromptRegistration{}, false
}
f.mu.Lock()
defer f.mu.Unlock()
entry := f.promptsByApproval[approvalID]
if entry == nil {
return ApprovalPromptRegistration{}, false
}
return *entry, true
}
func (f *ApprovalFlow[D]) resolvedPromptByTarget(targetMessageID networkid.MessageID) (resolvedApprovalPrompt, bool) {
if f == nil {
return resolvedApprovalPrompt{}, false
}
targetMessageID = networkid.MessageID(strings.TrimSpace(string(targetMessageID)))
if targetMessageID == "" {
return resolvedApprovalPrompt{}, false
}
f.mu.Lock()
defer f.mu.Unlock()
f.pruneExpiredResolvedPromptsLocked(time.Now())
if entry := f.resolvedByMsgID[targetMessageID]; entry != nil {
return *entry, true
}
if entry := f.resolvedByReactionMsgID[targetMessageID]; entry != nil {
return *entry, true
}
return resolvedApprovalPrompt{}, false
}
func (f *ApprovalFlow[D]) pruneExpiredResolvedPromptsLocked(now time.Time) {
if now.IsZero() {
now = time.Now()
}
for messageID, entry := range f.resolvedByMsgID {
if entry == nil || entry.ExpiresAt.IsZero() || now.Before(entry.ExpiresAt) {
continue
}
delete(f.resolvedByMsgID, messageID)
}
for messageID, entry := range f.resolvedByReactionMsgID {
if entry == nil || entry.ExpiresAt.IsZero() || now.Before(entry.ExpiresAt) {
continue
}
delete(f.resolvedByReactionMsgID, messageID)
}
}
func (f *ApprovalFlow[D]) rememberResolvedPromptLocked(prompt ApprovalPromptRegistration, decision ApprovalDecisionPayload) {
f.pruneExpiredResolvedPromptsLocked(time.Now())
if prompt.PromptMessageID == "" && prompt.ReactionTargetMessageID == "" {
return
}
resolved := &resolvedApprovalPrompt{
Prompt: prompt,
Decision: decision,
ExpiresAt: prompt.ExpiresAt,
}
if prompt.PromptMessageID != "" {
f.resolvedByMsgID[prompt.PromptMessageID] = resolved
}
if prompt.ReactionTargetMessageID != "" {
f.resolvedByReactionMsgID[prompt.ReactionTargetMessageID] = resolved
}
}
// dropPromptLocked removes a prompt registration.
// Must be called with f.mu held.
func (f *ApprovalFlow[D]) dropPromptLocked(approvalID string) {
approvalID = strings.TrimSpace(approvalID)
if approvalID == "" {
return
}
entry := f.promptsByApproval[approvalID]
if entry != nil && entry.PromptMessageID != "" {
delete(f.promptsByMsgID, entry.PromptMessageID)
}
if entry != nil && entry.ReactionTargetMessageID != "" {
delete(f.reactionTargetsByMsgID, entry.ReactionTargetMessageID)
}
delete(f.promptsByApproval, approvalID)
}
func (f *ApprovalFlow[D]) matchReactionTarget(targetMessageID networkid.MessageID, sender id.UserID, key string, now time.Time) ApprovalPromptReactionMatch {
targetMessageID = networkid.MessageID(strings.TrimSpace(string(targetMessageID)))
key = normalizeReactionKey(key)
if targetMessageID == "" || key == "" {
return ApprovalPromptReactionMatch{}
}
f.mu.Lock()
approvalID := f.promptsByMsgID[targetMessageID]
if approvalID == "" {
approvalID = f.reactionTargetsByMsgID[targetMessageID]
}
entry := f.promptsByApproval[approvalID]
if entry == nil {
f.mu.Unlock()
return ApprovalPromptReactionMatch{}
}
promptCopy := *entry
f.mu.Unlock()
sender = id.UserID(strings.TrimSpace(sender.String()))
match := ApprovalPromptReactionMatch{
KnownPrompt: true,
ApprovalID: approvalID,
Prompt: promptCopy,
}
if promptCopy.OwnerMXID != "" && sender != promptCopy.OwnerMXID {
match.RejectReason = RejectReasonOwnerOnly
return match
}
if !promptCopy.ExpiresAt.IsZero() && !now.IsZero() && now.After(promptCopy.ExpiresAt) {
match.RejectReason = RejectReasonExpired
f.mu.Lock()
f.dropPromptLocked(approvalID)
f.mu.Unlock()
return match
}
for _, opt := range promptCopy.Options {
for _, optKey := range opt.allKeys() {
if key != optKey {
continue
}
match.ShouldResolve = true
match.Decision = ApprovalDecisionPayload{
ApprovalID: promptCopy.ApprovalID,
Approved: opt.Approved,
Always: opt.Always,
Reason: opt.decisionReason(),
ReactionKey: key,
ResolvedBy: ApprovalResolutionOriginUser,
}
return match
}
}
match.RejectReason = RejectReasonInvalidOption
return match
}
// scanPromptsByRoom iterates promptsByApproval under f.mu, filtering for
// entries in the given room that have a pending approval and match the sender
// (or have no owner restriction). Expired prompts are dropped automatically.
// The visit callback is called for each live match and receives the approvalID
// and a copy of the entry; returning false stops the scan early.
//
// Locking: acquires and releases f.mu internally. The visit callback runs
// under f.mu — it must not call methods that acquire the lock.
func (f *ApprovalFlow[D]) scanPromptsByRoom(roomID id.RoomID, sender id.UserID, now time.Time, visit func(approvalID string, entry ApprovalPromptRegistration) bool) {
var expiredIDs []string
f.mu.Lock()
for approvalID, entry := range f.promptsByApproval {
if entry == nil || entry.RoomID != roomID {
continue
}
if _, ok := f.pending[approvalID]; !ok {
continue
}
if entry.OwnerMXID != "" && sender != entry.OwnerMXID {
continue
}
if !entry.ExpiresAt.IsZero() && !now.IsZero() && now.After(entry.ExpiresAt) {
expiredIDs = append(expiredIDs, approvalID)
continue
}
if !visit(approvalID, *entry) {
break
}
}
for _, approvalID := range expiredIDs {
f.dropPromptLocked(approvalID)
}
f.mu.Unlock()
}
func (f *ApprovalFlow[D]) matchFallbackReaction(roomID id.RoomID, sender id.UserID, key string, now time.Time) ApprovalPromptReactionMatch {
roomID = id.RoomID(strings.TrimSpace(roomID.String()))
sender = id.UserID(strings.TrimSpace(sender.String()))
key = normalizeReactionKey(key)
if roomID == "" || sender == "" || key == "" {
return ApprovalPromptReactionMatch{}
}
var (
found int
match ApprovalPromptReactionMatch
)
f.scanPromptsByRoom(roomID, sender, now, func(approvalID string, entry ApprovalPromptRegistration) bool {
var decision ApprovalDecisionPayload
matched := false
for _, opt := range entry.Options {
for _, optKey := range opt.allKeys() {
if key != optKey {
continue
}
matched = true
decision = ApprovalDecisionPayload{
ApprovalID: entry.ApprovalID,
Approved: opt.Approved,
Always: opt.Always,
Reason: opt.decisionReason(),
ReactionKey: key,
ResolvedBy: ApprovalResolutionOriginUser,
}
break
}
if matched {
break
}
}
if !matched {
return true // continue scanning
}
found++
if found > 1 {
match = ApprovalPromptReactionMatch{}
return false // stop scanning
}
match = ApprovalPromptReactionMatch{
KnownPrompt: true,
ShouldResolve: true,
ApprovalID: approvalID,
Decision: decision,
Prompt: entry,
MirrorDecisionReaction: true,
RedactResolvedReaction: true,
}
return true // continue scanning to check for ambiguity
})
if found == 1 {
return match
}
return ApprovalPromptReactionMatch{}
}
func (f *ApprovalFlow[D]) hasPendingApprovalForOwner(roomID id.RoomID, sender id.UserID, now time.Time) bool {
roomID = id.RoomID(strings.TrimSpace(roomID.String()))
sender = id.UserID(strings.TrimSpace(sender.String()))
if roomID == "" || sender == "" {
return false
}
hasPending := false
f.scanPromptsByRoom(roomID, sender, now, func(_ string, _ ApprovalPromptRegistration) bool {
hasPending = true
return false // stop scanning, one match is enough
})
return hasPending
}
// SendPromptParams holds the parameters for sending an approval prompt.
type SendPromptParams struct {
ApprovalPromptMessageParams
RoomID id.RoomID
OwnerMXID id.UserID
}
// ---------------------------------------------------------------------------
// Prompt sending
// ---------------------------------------------------------------------------
// SendPrompt builds an approval prompt message, registers it in the prompt
// store, sends it via the configured sender, binds the prompt identifiers, and
// queues prefill reactions.
func (f *ApprovalFlow[D]) SendPrompt(ctx context.Context, portal *bridgev2.Portal, params SendPromptParams) {
if f == nil || portal == nil || portal.MXID == "" {
return
}
f.ensureReaperRunning()
login := f.loginOrNil()
if login == nil {
return
}
approvalID := strings.TrimSpace(params.ApprovalID)
if approvalID == "" {
return
}
prompt := BuildApprovalPromptMessage(params.ApprovalPromptMessageParams)
sender := f.senderOrEmpty(portal)
reactionTargetMessageID := resolveApprovalReactionTargetMessageID(ctx, login, params.ReplyToEventID)
f.mu.Lock()
var prevPromptCopy ApprovalPromptRegistration
hadPrevPrompt := false
if prev := f.promptsByApproval[approvalID]; prev != nil {
prevPromptCopy = *prev
hadPrevPrompt = true
}
f.registerPromptLocked(ApprovalPromptRegistration{
ApprovalID: approvalID,
RoomID: params.RoomID,
OwnerMXID: params.OwnerMXID,
ToolCallID: strings.TrimSpace(params.ToolCallID),
ToolName: strings.TrimSpace(params.ToolName),
TurnID: strings.TrimSpace(params.TurnID),
Presentation: prompt.Presentation,
ExpiresAt: params.ExpiresAt,
Options: prompt.Options,
ReactionTargetMessageID: reactionTargetMessageID,
PromptSenderID: sender.Sender,
})
f.mu.Unlock()
var dbMeta any
if f.dbMetadata != nil {
dbMeta = f.dbMetadata(prompt)
} else {
dbMeta = &BaseMessageMetadata{
Role: "assistant",
ExcludeFromHistory: true,
}
}
converted := &bridgev2.ConvertedMessage{
Parts: []*bridgev2.ConvertedMessagePart{{
ID: networkid.PartID("0"),
Type: event.EventMessage,
Content: prompt.Content,
Extra: prompt.TopLevelExtra,
DBMetadata: dbMeta,
}},
}
_, msgID, err := f.send(ctx, portal, converted)
if err != nil {
f.mu.Lock()
f.dropPromptLocked(approvalID)
if hadPrevPrompt {
f.registerPromptLocked(prevPromptCopy)
}
f.mu.Unlock()
return
}
f.mu.Lock()
_, bound := f.bindPromptTargetLocked(approvalID, msgID)
if !bound {
f.dropPromptLocked(approvalID)
if hadPrevPrompt {
f.registerPromptLocked(prevPromptCopy)
}
}
f.mu.Unlock()
if !bound {
loggerForLogin(ctx, login).Warn().
Str("approval_msg_id", string(msgID)).
Str("approval_id", approvalID).
Msg("Failed to bind approval prompt message ID")
return
}
f.sendPrefillReactions(ctx, portal, login, approvalReactionTargetMessageID(ApprovalPromptRegistration{
ReactionTargetMessageID: reactionTargetMessageID,
PromptMessageID: msgID,
}), prompt.Options)
f.schedulePromptTimeout(approvalID, params.ExpiresAt)
}
// ---------------------------------------------------------------------------
// Reaction handling (satisfies ApprovalReactionHandler)
// ---------------------------------------------------------------------------