File size: 26,923 Bytes
79b2fcc
d7637ba
 
 
 
 
 
 
 
 
 
 
 
2b4c539
d7637ba
2b4c539
d7637ba
3ce798d
79b2fcc
219e6a7
2b4c539
 
c9a83ae
ff8c636
540437a
092f909
5db99fa
 
9c72f5f
5db99fa
 
 
 
79b2fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db99fa
540437a
 
 
 
 
 
 
 
79b2fcc
9c72f5f
5af3ab5
79b2fcc
3eec386
79b2fcc
 
 
9c72f5f
 
 
 
 
 
 
5db99fa
 
 
 
 
 
 
5af3ab5
0a9e96d
 
f0db8ab
0a9e96d
 
79b2fcc
 
0a9e96d
 
f0db8ab
0a9e96d
 
79b2fcc
1b922dd
 
 
 
 
 
 
79b2fcc
 
9c72f5f
 
 
 
 
 
 
5db99fa
9c72f5f
 
 
 
 
 
 
 
 
 
 
092f909
 
 
 
9c72f5f
79b2fcc
67b16c6
d7637ba
 
 
 
 
 
 
 
 
 
 
 
 
67b16c6
bf564b6
092f909
67b16c6
ecbfd3c
2b4c539
ecbfd3c
67b16c6
79b2fcc
c9a83ae
 
67b16c6
 
2b4c539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3eec386
5db99fa
540437a
2b4c539
 
 
 
 
 
 
 
 
 
c9a83ae
67b16c6
79b2fcc
2b4c539
5db99fa
 
 
092f909
 
 
79b2fcc
ff8c636
 
092f909
bed4e38
d7637ba
2b4c539
 
 
 
 
79b2fcc
5db99fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c72f5f
5db99fa
 
 
 
 
 
 
 
 
 
 
 
 
 
bf564b6
 
79b2fcc
bf564b6
 
 
79b2fcc
 
bf564b6
 
5db99fa
bf564b6
092f909
79b2fcc
 
 
bf564b6
092f909
79b2fcc
5db99fa
79b2fcc
ecbfd3c
79b2fcc
ecbfd3c
79b2fcc
 
ecbfd3c
67b16c6
 
2b4c539
67b16c6
 
 
2b4c539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b16c6
2b4c539
 
 
 
 
 
 
 
 
 
 
 
540437a
 
 
 
 
 
 
67b16c6
 
 
 
 
 
 
 
 
 
79b2fcc
 
82c186c
79b2fcc
 
 
 
 
 
 
 
bf564b6
79b2fcc
bf564b6
79b2fcc
 
 
092f909
 
 
d7637ba
 
092f909
d7637ba
 
 
 
79b2fcc
 
ff8c636
 
bed4e38
ff8c636
 
 
bed4e38
ff8c636
 
 
 
bed4e38
ff8c636
 
 
 
 
 
bed4e38
 
 
 
 
 
 
 
 
ff8c636
bed4e38
 
 
 
 
 
 
 
 
 
 
 
ff8c636
82c186c
5db99fa
82c186c
 
 
 
 
 
540437a
 
67b16c6
 
 
79b2fcc
 
3ce798d
 
67b16c6
 
79b2fcc
3ce798d
c1f951a
67b16c6
2b4c539
 
 
 
 
 
79b2fcc
c1f951a
 
79b2fcc
c1f951a
 
 
 
 
67b16c6
 
3ce798d
 
 
 
 
 
 
79b2fcc
ecbfd3c
c1f951a
79b2fcc
c1f951a
 
 
 
 
 
 
 
79b2fcc
c1f951a
 
 
3ce798d
2b4c539
c1f951a
 
 
 
 
 
 
 
3ce798d
 
2b4c539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecbfd3c
 
 
 
2b4c539
 
 
219e6a7
ecbfd3c
219e6a7
ecbfd3c
219e6a7
ecbfd3c
 
219e6a7
ecbfd3c
 
 
219e6a7
 
 
 
ecbfd3c
 
 
 
2b4c539
ecbfd3c
2b4c539
 
 
ecbfd3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ce798d
2b4c539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79b2fcc
c1f951a
79b2fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1f951a
 
 
79b2fcc
 
 
 
 
c1f951a
79b2fcc
c1f951a
79b2fcc
c1f951a
79b2fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db99fa
79b2fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5db99fa
540437a
5db99fa
540437a
 
 
 
 
 
 
 
 
 
79b2fcc
 
 
 
 
 
 
 
 
 
540437a
ff8c636
 
 
bed4e38
ff8c636
 
bed4e38
540437a
d7637ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b16c6
 
 
 
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
import { useState, useCallback, useEffect, useRef, KeyboardEvent } from 'react';
import {
  Alert,
  Box,
  TextField,
  IconButton,
  CircularProgress,
  Typography,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
  Chip,
  LinearProgress,
  Snackbar,
  Tooltip,
} from '@mui/material';
import ArrowUpwardIcon from '@mui/icons-material/ArrowUpward';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import StopIcon from '@mui/icons-material/Stop';
import AddIcon from '@mui/icons-material/Add';
import { apiFetch, apiUpload } from '@/utils/api';
import type { UserQuota } from '@/hooks/useUserQuota';
import JobsUpgradeDialog from '@/components/JobsUpgradeDialog';
import { useAgentStore } from '@/store/agentStore';
import { useSessionStore } from '@/store/sessionStore';
import {
  CLAUDE_MODEL_PATH,
  CLAUDE_OPUS_48_MODEL_PATH,
  GPT_55_MODEL_PATH,
  isClaudePath,
  isPremiumPath,
} from '@/utils/model';

// Model configuration
interface ModelOption {
  id: string;
  name: string;
  description: string;
  modelPath: string;
  avatarUrl: string;
  recommended?: boolean;
}

const getHfAvatarUrl = (modelId: string) => {
  const org = modelId.split('/')[0];
  return `https://huggingface.co/api/avatars/${org}`;
};

const DEFAULT_MODEL_OPTIONS: ModelOption[] = [
  {
    id: 'kimi-k2.6',
    name: 'Kimi K2.6',
    description: 'Novita',
    modelPath: 'moonshotai/Kimi-K2.6',
    avatarUrl: getHfAvatarUrl('moonshotai/Kimi-K2.6'),
    recommended: true,
  },
  {
    id: 'claude-opus-4-6',
    name: 'Claude Opus 4.6',
    description: 'Anthropic',
    modelPath: CLAUDE_MODEL_PATH,
    avatarUrl: 'https://huggingface.co/api/avatars/Anthropic',
    recommended: true,
  },
  {
    id: 'claude-opus-4-8',
    name: 'Claude Opus 4.8',
    description: 'Anthropic',
    modelPath: CLAUDE_OPUS_48_MODEL_PATH,
    avatarUrl: 'https://huggingface.co/api/avatars/Anthropic',
  },
  {
    id: 'gpt-5.5',
    name: 'GPT-5.5',
    description: 'OpenAI',
    modelPath: GPT_55_MODEL_PATH,
    avatarUrl: 'https://huggingface.co/api/avatars/openai',
  },
  {
    id: 'minimax-m2.7',
    name: 'MiniMax M2.7',
    description: 'Novita',
    modelPath: 'MiniMaxAI/MiniMax-M2.7',
    avatarUrl: getHfAvatarUrl('MiniMaxAI/MiniMax-M2.7'),
  },
  {
    id: 'glm-5.1',
    name: 'GLM 5.1',
    description: 'Together',
    modelPath: 'zai-org/GLM-5.1',
    avatarUrl: getHfAvatarUrl('zai-org/GLM-5.1'),
  },
  {
    id: 'deepseek-v4-pro',
    name: 'DeepSeek V4 Pro',
    description: 'DeepInfra',
    modelPath: 'deepseek-ai/DeepSeek-V4-Pro:deepinfra',
    avatarUrl: getHfAvatarUrl('deepseek-ai/DeepSeek-V4-Pro'),
  },
];

const normalizeModelPath = (path: string | undefined) => (
  (path ?? '')
    .toLowerCase()
    .replace(/^huggingface\//, '')
    .replace(/claude-opus-4\.(\d)/g, 'claude-opus-4-$1')
);

const findModelByPath = (path: string, options: ModelOption[]): ModelOption | undefined => {
  const normalizedPath = normalizeModelPath(path);
  const matched = options.find((m) => {
    const normalizedModelPath = normalizeModelPath(m.modelPath);
    const normalizedId = normalizeModelPath(m.id);
    return (
      m.modelPath === path ||
      normalizedModelPath === normalizedPath ||
      normalizedPath.includes(normalizedId)
    );
  });
  if (matched) return matched;
  if (isClaudePath(path)) {
    const claude = options.find(isClaudeModel);
    if (claude) return claude;
  }
  return undefined;
};

const readApiErrorMessage = async (res: Response, fallback: string): Promise<string> => {
  try {
    const data = await res.json();
    const detail = data?.detail;
    if (typeof detail === 'string') return detail;
    if (detail && typeof detail.message === 'string') return detail.message;
    if (detail && typeof detail.error === 'string') return detail.error;
  } catch {
    /* ignore malformed error bodies */
  }
  return fallback;
};

interface ChatInputProps {
  sessionId?: string;
  initialModelPath?: string | null;
  onSend: (text: string) => void;
  onStop?: () => void;
  onDatasetUploaded?: () => Promise<boolean> | boolean;
  isProcessing?: boolean;
  disabled?: boolean;
  placeholder?: string;
  quota: UserQuota | null;
  refreshQuota: () => Promise<void> | void;
}

interface DatasetUploadResponse {
  session_id: string;
  repo_id: string;
  repo_type: 'dataset';
  private: true;
  upload_id: string;
  config_name: string;
  filename: string;
  path_in_repo: string;
  size_bytes: number;
  format: 'csv' | 'json' | 'jsonl';
  hub_url: string;
  load_dataset_snippet: string;
}

const MAX_DATASET_UPLOAD_BYTES = 100 * 1024 * 1024;
const DATASET_UPLOAD_ACCEPT = '.csv,.json,.jsonl';
const DATASET_UPLOAD_EXTENSIONS = new Set(['csv', 'json', 'jsonl']);

const isClaudeModel = (m: ModelOption) => isClaudePath(m.modelPath);
const isPremiumModel = (m: ModelOption) => isPremiumPath(m.modelPath);

const formatBytes = (bytes: number) => {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
};

const datasetRepoUrl = (repoId: string) => (
  `https://huggingface.co/datasets/${repoId.split('/').map(encodeURIComponent).join('/')}`
);

export default function ChatInput({ sessionId, initialModelPath, onSend, onStop, onDatasetUploaded, isProcessing = false, disabled = false, placeholder = 'Ask anything...', quota, refreshQuota }: ChatInputProps) {
  const [input, setInput] = useState('');
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [modelOptions, setModelOptions] = useState<ModelOption[]>(DEFAULT_MODEL_OPTIONS);
  const modelOptionsRef = useRef<ModelOption[]>(DEFAULT_MODEL_OPTIONS);
  const sessionIdRef = useRef<string | undefined>(sessionId);
  const [selectedModelId, setSelectedModelId] = useState<string>(
    () => findModelByPath(initialModelPath ?? '', DEFAULT_MODEL_OPTIONS)?.id ?? DEFAULT_MODEL_OPTIONS[0].id,
  );
  const [modelAnchorEl, setModelAnchorEl] = useState<null | HTMLElement>(null);
  const jobsUpgradeRequired = useAgentStore((s) => s.jobsUpgradeRequired);
  const setJobsUpgradeRequired = useAgentStore((s) => s.setJobsUpgradeRequired);
  const updateSessionModel = useSessionStore((s) => s.updateSessionModel);
  const [awaitingTopUp, setAwaitingTopUp] = useState(false);
  const [modelSwitchError, setModelSwitchError] = useState<string | null>(null);
  const [datasetUploadError, setDatasetUploadError] = useState<string | null>(null);
  const [datasetUploadSuccess, setDatasetUploadSuccess] = useState<string | null>(null);
  const [uploadedDatasets, setUploadedDatasets] = useState<DatasetUploadResponse[]>([]);
  const [isUploadingDataset, setIsUploadingDataset] = useState(false);
  const [datasetUploadProgress, setDatasetUploadProgress] = useState<number | null>(null);

  useEffect(() => {
    modelOptionsRef.current = modelOptions;
  }, [modelOptions]);

  useEffect(() => {
    sessionIdRef.current = sessionId;
  }, [sessionId]);

  useEffect(() => {
    let cancelled = false;
    apiFetch('/api/config/model')
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (cancelled || !data?.available) return;
        const claude = data.available.find((m: { provider?: string; id?: string }) => (
          m.provider === 'anthropic' && m.id
        ));
        if (!claude?.id) return;

        const next = DEFAULT_MODEL_OPTIONS.map((option) => (
          option.id === 'claude-opus-4-6'
            ? { ...option, modelPath: claude.id, name: claude.label ?? option.name }
            : option
        ));
        modelOptionsRef.current = next;
        setModelOptions(next);
        if (!sessionIdRef.current) {
          const current = data.current ? findModelByPath(data.current, next) : null;
          if (current) setSelectedModelId(current.id);
        }
      })
      .catch(() => { /* ignore */ });
    return () => { cancelled = true; };
  }, []);

  // Model is per-session: fetch this tab's current model every time the
  // session changes. Other tabs keep their own selections independently.
  useEffect(() => {
    if (!sessionId) return;
    let cancelled = false;
    apiFetch(`/api/session/${sessionId}`)
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (cancelled) return;
        if (data?.model) {
          const model = findModelByPath(data.model, modelOptionsRef.current);
          if (model) setSelectedModelId(model.id);
          updateSessionModel(sessionId, data.model);
        }
      })
      .catch(() => { /* ignore */ });
    return () => { cancelled = true; };
  }, [sessionId, updateSessionModel]);

  const selectedModel = modelOptions.find(m => m.id === selectedModelId) || modelOptions[0];

  // Auto-focus the textarea when the session becomes ready
  useEffect(() => {
    if (!disabled && !isProcessing && inputRef.current) {
      inputRef.current.focus();
    }
  }, [disabled, isProcessing]);

  const handleSend = useCallback(() => {
    if (input.trim() && !disabled && !isUploadingDataset) {
      onSend(input);
      setInput('');
    }
  }, [input, disabled, isUploadingDataset, onSend]);

  const handleDatasetUploadClick = useCallback(() => {
    fileInputRef.current?.click();
  }, []);

  const handleDatasetFileChange = useCallback(
    async (event: React.ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files?.[0];
      event.target.value = '';
      if (!file) return;

      if (!sessionId) {
        setDatasetUploadError('Start a session before uploading a dataset.');
        return;
      }

      const extension = file.name.split('.').pop()?.toLowerCase() || '';
      if (!DATASET_UPLOAD_EXTENSIONS.has(extension)) {
        setDatasetUploadError('Only CSV, JSON, and JSONL dataset files are supported.');
        return;
      }
      if (file.size > MAX_DATASET_UPLOAD_BYTES) {
        setDatasetUploadError(
          `Dataset files must be 100 MB or smaller. ${file.name} is ${formatBytes(file.size)}.`
        );
        return;
      }
      if (file.size === 0) {
        setDatasetUploadError('Uploaded dataset file is empty.');
        return;
      }

      const formData = new FormData();
      formData.append('file', file);
      setIsUploadingDataset(true);
      setDatasetUploadProgress(0);
      setDatasetUploadError(null);
      setDatasetUploadSuccess(null);
      try {
        const res = await apiUpload(`/api/session/${sessionId}/datasets`, formData, {
          onProgress: ({ percent }) => {
            setDatasetUploadProgress(percent !== null && percent < 100 ? percent : null);
          },
        });
        if (!res.ok) {
          setDatasetUploadError(await readApiErrorMessage(res, 'Dataset upload failed.'));
          return;
        }
        const payload = await res.json() as DatasetUploadResponse;
        setUploadedDatasets((previous) => [payload, ...previous]);
        setDatasetUploadSuccess(`Uploaded ${payload.filename} to ${payload.repo_id}`);
        await onDatasetUploaded?.();
      } catch (error) {
        setDatasetUploadError(
          error instanceof Error ? error.message : 'Dataset upload failed.'
        );
      } finally {
        setIsUploadingDataset(false);
        setDatasetUploadProgress(null);
      }
    },
    [sessionId, onDatasetUploaded],
  );

  useEffect(() => {
    if (!datasetUploadError) return;
    const timeout = window.setTimeout(() => setDatasetUploadError(null), 7000);
    return () => window.clearTimeout(timeout);
  }, [datasetUploadError]);

  useEffect(() => {
    if (!datasetUploadSuccess) return;
    const timeout = window.setTimeout(() => setDatasetUploadSuccess(null), 5000);
    return () => window.clearTimeout(timeout);
  }, [datasetUploadSuccess]);

  // Refresh the quota display whenever the session changes (user might
  // have started another tab that spent quota).
  useEffect(() => {
    if (sessionId) refreshQuota();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionId]);

  const handleKeyDown = useCallback(
    (e: KeyboardEvent<HTMLDivElement>) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        handleSend();
      }
    },
    [handleSend]
  );

  const handleModelClick = (event: React.MouseEvent<HTMLElement>) => {
    setModelAnchorEl(event.currentTarget);
    void refreshQuota();
  };

  const handleModelClose = () => {
    setModelAnchorEl(null);
  };

  const handleSelectModel = async (model: ModelOption) => {
    handleModelClose();
    if (!sessionId) return;
    try {
      const res = await apiFetch(`/api/session/${sessionId}/model`, {
        method: 'POST',
        body: JSON.stringify({ model: model.modelPath }),
      });
      if (res.ok) {
        setSelectedModelId(model.id);
        updateSessionModel(sessionId, model.modelPath);
        setModelSwitchError(null);
        return;
      }
      setModelSwitchError(await readApiErrorMessage(res, 'Could not switch model.'));
    } catch (error) {
      setModelSwitchError(error instanceof Error ? error.message : 'Could not switch model.');
    }
  };

  const handleJobsUpgradeClose = useCallback(() => {
    setJobsUpgradeRequired(null);
    setAwaitingTopUp(false);
  }, [setJobsUpgradeRequired]);

  const handleJobsUpgradeClick = useCallback(async () => {
    setAwaitingTopUp(true);
    if (!sessionId || !jobsUpgradeRequired) return;
    try {
      await apiFetch(`/api/pro-click/${sessionId}`, {
        method: 'POST',
        body: JSON.stringify({ source: 'hf_jobs_billing_dialog', target: 'hf_billing' }),
      });
    } catch {
      /* tracking is best-effort */
    }
  }, [sessionId, jobsUpgradeRequired]);

  const handleJobsRetry = useCallback(() => {
    const namespace = jobsUpgradeRequired?.namespace;
    setJobsUpgradeRequired(null);
    setAwaitingTopUp(false);
    const msg = namespace
      ? `I just added credits to the \`${namespace}\` namespace. Please retry the previous job.`
      : "I just added credits. Please retry the previous job.";
    onSend(msg);
  }, [jobsUpgradeRequired, setJobsUpgradeRequired, onSend]);

  // Auto-retry when the user comes back to this tab after clicking "Add credits".
  // Browsers fire visibilitychange when the tab regains focus from a sibling tab.
  useEffect(() => {
    if (!awaitingTopUp || !jobsUpgradeRequired) return;
    const onVisible = () => {
      if (document.visibilityState === 'visible') {
        handleJobsRetry();
      }
    };
    document.addEventListener('visibilitychange', onVisible);
    return () => document.removeEventListener('visibilitychange', onVisible);
  }, [awaitingTopUp, jobsUpgradeRequired, handleJobsRetry]);

  // Show the remaining subsidized premium-session allowance for today.
  const premiumChip = (() => {
    if (!quota) return null;
    const remaining = Math.max(0, quota.premiumRemaining);
    if (remaining === 0) {
      return quota.plan === 'pro' ? '0 left – using HF billing' : '0 left – enable billing';
    }
    return `${remaining} left today`;
  })();

  return (
    <Box
      sx={{
        pb: { xs: 2, md: 4 },
        pt: { xs: 1, md: 2 },
        position: 'relative',
        zIndex: 10,
      }}
    >
      <Box sx={{ maxWidth: '880px', mx: 'auto', width: '100%', px: { xs: 0, sm: 1, md: 2 } }}>
        <Box
          className="composer"
          sx={{
            display: 'grid',
            gridTemplateColumns: 'auto 1fr auto',
            gridTemplateRows: 'auto auto',
            columnGap: '10px',
            rowGap: '4px',
            alignItems: 'end',
            bgcolor: 'var(--composer-bg)',
            borderRadius: 'var(--radius-md)',
            p: '12px',
            border: '1px solid var(--border)',
            transition: 'box-shadow 0.2s ease, border-color 0.2s ease',
            '&:focus-within': {
                borderColor: 'var(--accent-yellow)',
                boxShadow: 'var(--focus)',
            }
          }}
        >
          <TextField
            fullWidth
            multiline
            maxRows={6}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={placeholder}
            disabled={disabled || isProcessing}
            variant="standard"
            inputRef={inputRef}
            InputProps={{
                disableUnderline: true,
                sx: {
                    color: 'var(--text)',
                    fontSize: '15px',
                    fontFamily: 'inherit',
                    padding: 0,
                    lineHeight: 1.5,
                    minHeight: { xs: '44px', md: '56px' },
                    alignItems: 'flex-start',
                }
            }}
            sx={{
                gridColumn: '1 / -1',
                '& .MuiInputBase-root': {
                    p: 0,
                    backgroundColor: 'transparent',
                },
                '& textarea': {
                    resize: 'none',
                    padding: '0 !important',
                }
            }}
          />
          <input
            ref={fileInputRef}
            type="file"
            accept={DATASET_UPLOAD_ACCEPT}
            onChange={handleDatasetFileChange}
            style={{ display: 'none' }}
          />
          <Box sx={{ gridColumn: '1', gridRow: '2', display: 'flex' }}>
            <Tooltip title="Upload dataset">
              <span>
                <IconButton
                  onClick={handleDatasetUploadClick}
                  disabled={disabled || isProcessing || isUploadingDataset || !sessionId}
                  sx={{
                    p: 1,
                    borderRadius: '50%',
                    color: uploadedDatasets.length ? 'var(--accent-yellow)' : 'var(--muted-text)',
                    transition: 'all 0.2s',
                    '&:hover': {
                      color: 'var(--accent-yellow)',
                      bgcolor: 'var(--hover-bg)',
                    },
                    '&.Mui-disabled': {
                      opacity: 0.3,
                    },
                  }}
                  aria-label="Upload dataset"
                >
                  <AddIcon fontSize="small" />
                </IconButton>
              </span>
            </Tooltip>
          </Box>
          {isProcessing ? (
            <IconButton
              onClick={onStop}
              sx={{
                gridColumn: '3',
                gridRow: '2',
                justifySelf: 'end',
                p: 1.5,
                borderRadius: '10px',
                color: 'var(--muted-text)',
                transition: 'all 0.2s',
                position: 'relative',
                '&:hover': {
                  bgcolor: 'var(--hover-bg)',
                  color: 'var(--accent-red)',
                },
              }}
            >
              <Box sx={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <CircularProgress size={28} thickness={3} sx={{ color: 'inherit', position: 'absolute' }} />
                <StopIcon sx={{ fontSize: 16 }} />
              </Box>
            </IconButton>
          ) : (
            <IconButton
              onClick={handleSend}
              disabled={disabled || isUploadingDataset || !input.trim()}
              sx={{
                gridColumn: '3',
                gridRow: '2',
                justifySelf: 'end',
                p: 1,
                borderRadius: '10px',
                color: 'var(--muted-text)',
                transition: 'all 0.2s',
                '&:hover': {
                  color: 'var(--accent-yellow)',
                  bgcolor: 'var(--hover-bg)',
                },
                '&.Mui-disabled': {
                  opacity: 0.3,
                },
              }}
            >
              <ArrowUpwardIcon fontSize="small" />
            </IconButton>
          )}
        </Box>
        {isUploadingDataset && (
          <Box sx={{ mt: 1, px: 0.5 }}>
            <LinearProgress
              variant={datasetUploadProgress === null ? 'indeterminate' : 'determinate'}
              value={datasetUploadProgress ?? 0}
              aria-label="Dataset upload progress"
              sx={{
                height: 4,
                borderRadius: 999,
                bgcolor: 'rgba(255,255,255,0.08)',
                '& .MuiLinearProgress-bar': {
                  borderRadius: 999,
                  bgcolor: 'var(--accent-yellow)',
                },
              }}
            />
          </Box>
        )}
        {(datasetUploadError || datasetUploadSuccess) && (
          <Box sx={{ display: 'flex', justifyContent: 'center', mt: 1 }}>
            <Alert
              severity={datasetUploadError ? 'error' : 'success'}
              variant="filled"
              onClose={() => {
                setDatasetUploadError(null);
                setDatasetUploadSuccess(null);
              }}
              sx={{ fontSize: '0.8rem', maxWidth: 520, width: '100%' }}
            >
              {datasetUploadError ?? datasetUploadSuccess}
            </Alert>
          </Box>
        )}
        {uploadedDatasets.length > 0 && (
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.75, justifyContent: 'center', mt: 1 }}>
            {uploadedDatasets.map((dataset) => (
              <Chip
                key={dataset.upload_id}
                size="small"
                label={`Dataset: ${dataset.filename}`}
                component="a"
                href={datasetRepoUrl(dataset.repo_id)}
                target="_blank"
                rel="noreferrer"
                clickable
                sx={{
                  maxWidth: '100%',
                  bgcolor: 'rgba(255,255,255,0.08)',
                  color: 'var(--text)',
                  border: '1px solid var(--divider)',
                  '& .MuiChip-label': {
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                  },
                }}
              />
            ))}
          </Box>
        )}

        {/* Powered By Badge */}
        <Box
          onClick={handleModelClick}
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            mt: 1.5,
            gap: 0.8,
            opacity: 0.6,
            cursor: 'pointer',
            transition: 'opacity 0.2s',
            '&:hover': {
              opacity: 1
            }
          }}
        >
          <Typography variant="caption" sx={{ fontSize: '10px', color: 'var(--muted-text)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 500 }}>
            powered by
          </Typography>
          <img
            src={selectedModel.avatarUrl}
            alt={selectedModel.name}
            style={{ height: '14px', width: '14px', objectFit: 'contain', borderRadius: '2px' }}
          />
          <Typography variant="caption" sx={{ fontSize: '10px', color: 'var(--text)', fontWeight: 600, letterSpacing: '0.02em' }}>
            {selectedModel.name}
          </Typography>
          <ArrowDropDownIcon sx={{ fontSize: '14px', color: 'var(--muted-text)' }} />
        </Box>

        {/* Model Selection Menu */}
        <Menu
          anchorEl={modelAnchorEl}
          open={Boolean(modelAnchorEl)}
          onClose={handleModelClose}
          anchorOrigin={{
            vertical: 'top',
            horizontal: 'center',
          }}
          transformOrigin={{
            vertical: 'bottom',
            horizontal: 'center',
          }}
          slotProps={{
            paper: {
              sx: {
                bgcolor: 'var(--panel)',
                border: '1px solid var(--divider)',
                mb: 1,
                maxHeight: '400px',
              }
            }
          }}
        >
          {modelOptions.map((model) => (
            <MenuItem
              key={model.id}
              onClick={() => handleSelectModel(model)}
              selected={selectedModelId === model.id}
              sx={{
                py: 1.5,
                '&.Mui-selected': {
                  bgcolor: 'rgba(255,255,255,0.05)',
                }
              }}
            >
              <ListItemIcon>
                <img
                  src={model.avatarUrl}
                  alt={model.name}
                  style={{ width: 24, height: 24, borderRadius: '4px', objectFit: 'cover' }}
                />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    {model.name}
                    {model.recommended && (
                      <Chip
                        label="Recommended"
                        size="small"
                        sx={{
                          height: '18px',
                          fontSize: '10px',
                          bgcolor: 'var(--accent-yellow)',
                          color: '#000',
                          fontWeight: 600,
                        }}
                      />
                    )}
                    {isPremiumModel(model) && premiumChip && (
                      <Chip
                        label={premiumChip}
                        size="small"
                        sx={{
                          height: '18px',
                          fontSize: '10px',
                          bgcolor: 'rgba(255,255,255,0.08)',
                          color: 'var(--muted-text)',
                          fontWeight: 600,
                        }}
                      />
                    )}
                  </Box>
                }
                secondary={model.description}
                secondaryTypographyProps={{
                  sx: { fontSize: '12px', color: 'var(--muted-text)' }
                }}
              />
            </MenuItem>
          ))}
        </Menu>

        <JobsUpgradeDialog
          open={!!jobsUpgradeRequired}
          message={jobsUpgradeRequired?.message || ''}
          awaitingTopUp={awaitingTopUp}
          onClose={handleJobsUpgradeClose}
          onUpgrade={handleJobsUpgradeClick}
          onRetry={handleJobsRetry}
        />
        <Snackbar
          open={!!modelSwitchError}
          anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
          onClose={() => setModelSwitchError(null)}
          autoHideDuration={6000}
        >
          <Alert
            severity="error"
            variant="filled"
            onClose={() => setModelSwitchError(null)}
            sx={{ fontSize: '0.8rem', maxWidth: 480 }}
          >
            {modelSwitchError}
          </Alert>
        </Snackbar>
      </Box>
    </Box>
  );
}