4
File size: 6,050 Bytes
abab9e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import re
from typing import Any


PATCH_SCRIPT = r"""
<script>
(function () {
  if (window.__dvncFlipPatchLoaded) return;
  window.__dvncFlipPatchLoaded = true;

  function findByFragment(fragment) {
    return document.getElementById(fragment) || document.querySelector('[id*="' + fragment + '"]');
  }

  function getInteractiveNode(root) {
    if (!root) return null;
    return root.matches?.('textarea,input,button') ? root : root.querySelector?.('textarea,input,button');
  }

  function triggerRouteSwapPatched(idx) {
    try {
      const payloadRoot = findByFragment('route_swap_payload');
      const payload = getInteractiveNode(payloadRoot);
      if (!payload) {
        console.warn('[DVNC patch] route_swap_payload not found');
        return;
      }

      payload.focus?.();
      payload.value = String(idx);

      ['input', 'change'].forEach(function (name) {
        payload.dispatchEvent(new Event(name, { bubbles: true }));
      });

      window.setTimeout(function () {
        const applyRoot = findByFragment('route_swap_apply');
        const applyBtn = getInteractiveNode(applyRoot) || applyRoot;
        if (!applyBtn) {
          console.warn('[DVNC patch] route_swap_apply not found');
          return;
        }
        applyBtn.click?.();
      }, 180);
    } catch (err) {
      console.error('[DVNC patch] triggerRouteSwap failed', err);
    }
  }

  window.triggerRouteSwap = triggerRouteSwapPatched;

  document.addEventListener('click', function (e) {
    const mini = e.target.closest('.candidate-back .mini');
    if (mini) return;

    const card = e.target.closest('.candidate-card');
    if (!card) return;

    card.classList.toggle('flipped');
  }, true);

  document.addEventListener('keydown', function (e) {
    const target = e.target;
    if (!target || !target.closest) return;

    const card = target.closest('.candidate-card');
    if (!card) return;

    if (e.key === 'Enter' || e.key === ' ') {
      if (target.closest('.candidate-back .mini')) return;
      e.preventDefault();
      card.classList.toggle('flipped');
    }
  }, true);
})();
</script>
"""

PATCH_STYLE = r"""
<style>
.candidate-card { cursor: pointer; }
.candidate-card.flipped .candidate-card-inner { transform: rotateY(180deg) !important; }
.candidate-card:hover .candidate-card-inner,
.candidate-card:focus .candidate-card-inner,
.candidate-card:focus-within .candidate-card-inner { transform: none !important; }
.candidate-back .mini { position: relative; z-index: 5; }
</style>
"""


def _inject_assets(head: str) -> str:
    if "__dvncFlipPatchLoaded" in head:
        return head
    return head + "\n" + PATCH_STYLE + "\n" + PATCH_SCRIPT


def _patch_head(module: Any) -> None:
    for attr in ("HEAD", "head", "CUSTOM_HEAD"):
        if hasattr(module, attr):
            value = getattr(module, attr)
            if isinstance(value, str):
                setattr(module, attr, _inject_assets(value))
                return


def _patch_cards_builder(module: Any) -> None:
    if not hasattr(module, "build_cards_html"):
        return

    original = module.build_cards_html

    def wrapped(*args, **kwargs):
        out = original(*args, **kwargs)
        if not isinstance(out, str):
            return out
        if "candidate-card" not in out:
            return out

        out = re.sub(
            r'(<div\s+class="candidate-card"\b)',
            r'\1 tabindex="0" role="button" aria-label="Flip insight card"',
            out,
        )
        return out

    module.build_cards_html = wrapped


def _build_timeline_from_state(module: Any, route_state: Any):
    if route_state is None:
        return None

    builder = getattr(module, "build_agent_route_cards_html", None)
    if not callable(builder):
        return None

    try:
        variants = route_state.get("variants") if isinstance(route_state, dict) else None
        active_idx = route_state.get("active_variant", 0) if isinstance(route_state, dict) else 0
        if not variants or active_idx >= len(variants):
            return None

        variant = variants[active_idx] or {}
        steps = variant.get("steps") or variant.get("route") or []
        if not steps:
            return None

        normalized = []
        for i, step in enumerate(steps):
            if isinstance(step, dict):
                normalized.append({
                    "step": step.get("step", i + 1),
                    "agent": step.get("agent", f"Step {i+1}"),
                    "tag": step.get("tag", step.get("mode", "")),
                    "summary": step.get("summary", step.get("description", "")),
                })
            else:
                normalized.append({
                    "step": i + 1,
                    "agent": f"Step {i+1}",
                    "tag": "",
                    "summary": str(step),
                })

        return builder(normalized)
    except Exception:
        return None


def _patch_apply_route_swap(module: Any) -> None:
    if not hasattr(module, "apply_route_swap"):
        return

    original = module.apply_route_swap

    def wrapped(*args, **kwargs):
        result = original(*args, **kwargs)
        if not isinstance(result, tuple):
            return result

        if len(result) == 5:
            chat_html, connectome_html, timeline_value, hypothesis_md, route_state = result
            rebuilt = _build_timeline_from_state(module, route_state)
            if rebuilt is not None:
                gr = getattr(module, "gr", None)
                if gr is not None and hasattr(gr, "update"):
                    timeline_value = gr.update(value=rebuilt)
                else:
                    timeline_value = rebuilt
            return chat_html, connectome_html, timeline_value, hypothesis_md, route_state

        return result

    module.apply_route_swap = wrapped


def apply_patch(module: Any) -> Any:
    _patch_head(module)
    _patch_cards_builder(module)
    _patch_apply_route_swap(module)
    return module