File size: 8,665 Bytes
1dd9186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaaa6c
 
1dd9186
cfaaa6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dd9186
cfaaa6c
 
 
 
 
 
 
1dd9186
 
 
 
 
cfaaa6c
 
 
 
 
 
 
1dd9186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaaa6c
1dd9186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfaaa6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useCallback, useEffect, useRef, useState } from 'react';

const PANEL_HEIGHT_STORAGE_KEY = 'nodes_ui_flow_interactive_panel_height';
const DEFAULT_PANEL_HEIGHT = 320;
const MIN_PANEL_HEIGHT = 250;
const TOOLBAR_FALLBACK_HEIGHT = 72;
const MAX_PANEL_TOP_GAP = 8;

function getMaxPanelHeight() {
  if (typeof window === 'undefined') {
    return DEFAULT_PANEL_HEIGHT;
  }

  const toolbarHeight = document.querySelector('.toolbar')?.getBoundingClientRect().height || TOOLBAR_FALLBACK_HEIGHT;
  return Math.max(MIN_PANEL_HEIGHT, window.innerHeight - toolbarHeight - MAX_PANEL_TOP_GAP);
}

function readInitialPanelHeight() {
  if (typeof window === 'undefined') {
    return DEFAULT_PANEL_HEIGHT;
  }

  const savedHeight = Number(window.localStorage.getItem(PANEL_HEIGHT_STORAGE_KEY));
  if (!Number.isFinite(savedHeight)) {
    return DEFAULT_PANEL_HEIGHT;
  }

  return Math.min(Math.max(savedHeight, MIN_PANEL_HEIGHT), getMaxPanelHeight());
}

export default function InteractivePanel({
  isDemo,
  pendingQuestion,
  transcript,
  inputValue,
  isBusy,
  llmProvider,
  llmAutoAnswer,
  writeTranscriptLogs,
  llmRolePrompt,
  onInputChange,
  onLlmAutoAnswerChange,
  onWriteTranscriptLogsChange,
  onLlmRolePromptChange,
  onSubmitAnswer,
  onSimulateAnswer,
  onSaveSessionLog,
}) {
  const [panelHeight, setPanelHeight] = useState(readInitialPanelHeight);
  const canAnswer = Boolean(pendingQuestion) && !isBusy && inputValue.trim().length > 0;
  const canSimulate = Boolean(pendingQuestion) && !isBusy && llmRolePrompt.trim().length > 0;
  const providerLabel = {
    deepinfra: 'DeepInfra',
    ollama: 'Ollama',
  }[llmProvider] || llmProvider;
  const transcriptRef = useRef(null);
  const resizeRef = useRef(null);

  const clampPanelHeight = useCallback((height) => (
    Math.min(Math.max(Math.round(height), MIN_PANEL_HEIGHT), getMaxPanelHeight())
  ), []);

  useEffect(() => {
    if (transcriptRef.current) {
      transcriptRef.current.scrollTop = transcriptRef.current.scrollHeight;
    }
  }, [transcript]);

  useEffect(() => {
    if (isDemo) {
      return;
    }

    window.localStorage.setItem(PANEL_HEIGHT_STORAGE_KEY, String(panelHeight));
  }, [isDemo, panelHeight]);

  useEffect(() => {
    if (isDemo) {
      return undefined;
    }

    const handleResize = () => {
      setPanelHeight((currentHeight) => clampPanelHeight(currentHeight));
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [clampPanelHeight, isDemo]);

  useEffect(() => () => {
    document.body.classList.remove('is-resizing-interactive-panel');
  }, []);

  const stopResize = useCallback((event) => {
    const resizeState = resizeRef.current;
    if (!resizeState || resizeState.pointerId !== event.pointerId) {
      return;
    }

    resizeRef.current = null;
    if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
      event.currentTarget.releasePointerCapture(event.pointerId);
    }
    document.body.classList.remove('is-resizing-interactive-panel');
  }, []);

  const handleResizeStart = useCallback((event) => {
    if (isDemo) {
      return;
    }

    if (event.button !== 0) {
      return;
    }

    event.preventDefault();
    resizeRef.current = {
      pointerId: event.pointerId,
      startY: event.clientY,
      startHeight: panelHeight,
    };
    event.currentTarget.setPointerCapture?.(event.pointerId);
    document.body.classList.add('is-resizing-interactive-panel');
  }, [isDemo, panelHeight]);

  const handleResizeMove = useCallback((event) => {
    if (isDemo) {
      return;
    }

    const resizeState = resizeRef.current;
    if (!resizeState || resizeState.pointerId !== event.pointerId) {
      return;
    }

    const nextHeight = resizeState.startHeight + resizeState.startY - event.clientY;
    setPanelHeight(clampPanelHeight(nextHeight));
  }, [clampPanelHeight, isDemo]);

  const handleResizeKeyDown = useCallback((event) => {
    if (isDemo) {
      return;
    }

    if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {
      return;
    }

    event.preventDefault();
    const step = event.shiftKey ? 80 : 24;
    setPanelHeight((currentHeight) => (
      clampPanelHeight(currentHeight + (event.key === 'ArrowUp' ? step : -step))
    ));
  }, [clampPanelHeight, isDemo]);

  return (
    <section
      className={`interactive-panel ${isDemo ? 'interactive-panel--demo' : ''}`}
      style={isDemo ? undefined : { '--interactive-panel-height': `${panelHeight}px` }}
    >
      {!isDemo ? (
        <div
          className="interactive-panel__resize-handle"
          role="separator"
          aria-label="Изменить высоту интерактивной панели"
          aria-orientation="horizontal"
          tabIndex={0}
          onKeyDown={handleResizeKeyDown}
          onPointerDown={handleResizeStart}
          onPointerMove={handleResizeMove}
          onPointerUp={stopResize}
          onPointerCancel={stopResize}
        />
      ) : null}

      <div className="interactive-panel__main">
        <div className="interactive-panel__header">
          <div>
            <div className="interactive-panel__eyebrow">Интерактивный прогон</div>
            <div className="interactive-panel__title">
              {pendingQuestion ? pendingQuestion.question : 'Запустите сценарий, чтобы дойти до следующего вопроса.'}
            </div>
          </div>
          <div className={`interactive-panel__state ${pendingQuestion ? 'is-waiting' : ''}`}>
            {isBusy ? 'идет' : pendingQuestion ? 'ждем ответ' : 'готово'}
          </div>
        </div>

        <div className="interactive-panel__transcript" ref={transcriptRef}>
          {transcript.length === 0 ? (
            <div className="interactive-panel__empty">Диалог появится здесь во время интерактивного прогона.</div>
          ) : (
            transcript.map((message) => (
              <div key={message.id} className={`interactive-message interactive-message--${message.role}`}>
                <span>{message.role === 'assistant' ? 'Ассистент' : 'Пользователь'}</span>
                <p>{message.text}</p>
              </div>
            ))
          )}
        </div>

        <form className="interactive-panel__answer" onSubmit={onSubmitAnswer}>
          <input
            className="interactive-panel__input"
            type="text"
            value={inputValue}
            placeholder={pendingQuestion ? 'Введите ответ пользователя...' : 'Запустите сценарий до вопроса'}
            disabled={!pendingQuestion || isBusy}
            onChange={(event) => onInputChange(event.target.value)}
          />
          <button type="submit" className="toolbar__button toolbar__button--primary" disabled={!canAnswer}>
            Ответить
          </button>
        </form>
      </div>

      <aside className="interactive-panel__side">
        <button
          type="button"
          className="toolbar__button toolbar__button--primary interactive-panel__save-log"
          onClick={onSaveSessionLog}
        >
          Сохранить лог сессии
        </button>

        <div className="interactive-panel__tools">
          <button type="button" className="toolbar__button" disabled={!canSimulate} onClick={onSimulateAnswer}>
            Ответ LLM · {providerLabel}
          </button>
        </div>

        <div className="interactive-panel__tools">
          <label className="field-row">
            <input
              type="checkbox"
              checked={llmAutoAnswer}
              disabled={!llmRolePrompt.trim()}
              onChange={(event) => onLlmAutoAnswerChange(event.target.checked)}
            />
            <span>Автоответ LLM</span>
          </label>
          <label className="field-row">
            <input
              type="checkbox"
              checked={writeTranscriptLogs}
              onChange={(event) => onWriteTranscriptLogsChange(event.target.checked)}
            />
            <span>Писать txt-лог</span>
          </label>
        </div>

        <textarea
          className="interactive-panel__role"
          value={llmRolePrompt}
          disabled={isBusy}
          placeholder="Роль тестового пользователя..."
          onChange={(event) => onLlmRolePromptChange(event.target.value)}
        />
      </aside>
    </section>
  );
}