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
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
"use client";

import { useState, useEffect } from "react";
import { Card, Button } from "@/shared/components";
import Image from "next/image";
import { useTranslations } from "next-intl";
import { matchesSearch } from "@/shared/utils/turkishText";

/**

 * GitHub Copilot Configuration Generator

 *

 * Generates the chatLanguageModels.json block for VS Code GitHub Copilot

 * using the Azure vendor pattern as required by Copilot's architecture.

 *

 * Feature request: https://github.com/diegosouzapw/OmniRoute/issues/142

 */
export default function CopilotToolCard({

  tool,

  isExpanded = false,

  onToggle = () => {},

  baseUrl,

  apiKeys,

  activeProviders = [],

  hasActiveProviders = false,

  cloudEnabled = false,

  batchStatus,

}) {
  const t = useTranslations("cliTools");
  const [copiedField, setCopiedField] = useState<string | null>(null);
  const [selectedModels, setSelectedModels] = useState<Set<string>>(() => {
    if (typeof window === "undefined") return new Set<string>();
    try {
      const saved = localStorage.getItem("omniroute-copilot-selected-models");
      return saved ? new Set<string>(JSON.parse(saved)) : new Set<string>();
    } catch {
      return new Set<string>();
    }
  });
  const [selectedApiKeyId, setSelectedApiKeyId] = useState(() => {
    if (typeof window !== "undefined") {
      const savedKey = localStorage.getItem("omniroute-cli-key-copilot");
      if (savedKey && apiKeys?.some((k: any) => k.id === savedKey)) return savedKey;
    }
    return apiKeys?.length > 0 ? apiKeys[0].id : "";
  });
  const [maxInputTokens, setMaxInputTokens] = useState(128000);
  const [maxOutputTokens, setMaxOutputTokens] = useState(16000);
  const [toolCalling, setToolCalling] = useState(true);
  const [vision, setVision] = useState(false);
  const [allModels, setAllModels] = useState<Array<{ value: string; label: string }>>([]);
  const [modelsLoaded, setModelsLoaded] = useState(false);
  const [searchFilter, setSearchFilter] = useState("");

  // Fetch ALL models dynamically from /v1/models (includes combos, custom, aliased)
  // Per @alpgul feedback: /api/models/alias doesn't include combo definitions
  useEffect(() => {
    if (!isExpanded || modelsLoaded) return;
    let cancelled = false;
    fetch("/v1/models")
      .then((res) => res.json())
      .then((data) => {
        if (cancelled) return;
        const modelList = (data.data || [])
          .filter((m: any) => m && !m.type && !m.parent && m.id) // Only chat models with valid IDs
          .map((m: any) => ({
            value: m.id,
            label: m.id,
          }));
        setAllModels(modelList);
        setModelsLoaded(true);
      })
      .catch(() => {
        if (!cancelled) setModelsLoaded(true);
      });
    return () => {
      cancelled = true;
    };
  }, [isExpanded, modelsLoaded]);

  // Filter models by search
  const availableModels = searchFilter
    ? allModels.filter((m) => matchesSearch(m.label, searchFilter))
    : allModels;

  // Persist selection
  useEffect(() => {
    if (selectedModels.size > 0) {
      localStorage.setItem(
        "omniroute-copilot-selected-models",
        JSON.stringify([...selectedModels])
      );
    }
  }, [selectedModels]);

  const toggleModel = (modelValue: string) => {
    setSelectedModels((prev) => {
      const next = new Set(prev);
      if (next.has(modelValue)) {
        next.delete(modelValue);
      } else {
        next.add(modelValue);
      }
      return next;
    });
  };

  const selectAll = () => {
    setSelectedModels(new Set(allModels.map((m) => m.value)));
  };

  const deselectAll = () => {
    setSelectedModels(new Set());
  };

  const getBaseUrlForConfig = () => {
    const url = baseUrl;
    return `${url}/v1/chat/completions`;
  };

  // Generate the Copilot chatLanguageModels.json config
  const generateConfig = () => {
    const models = [...selectedModels].map((modelId) => ({
      id: modelId,
      name: modelId,
      url: `${getBaseUrlForConfig()}#models.ai.azure.com`,
      toolCalling,
      vision,
      maxInputTokens,
      maxOutputTokens,
    }));

    const responseModels = [...selectedModels].map((modelId) => ({
      id: modelId,
      name: modelId,
      url: `${baseUrl}/v1/responses#models.ai.azure.com`,
      supportsReasoningEffort: ["none", "low", "medium", "high", "xhigh"],
      zeroDataRetentionEnabled: true,
      toolCalling,
      vision,
      maxInputTokens,
      maxOutputTokens,
    }));

    const config = {
      name: "OmniRoute",
      vendor: "azure",
      apiKey: `\${input:chat.lm.secret.omniroute}`,
      models,
    };

    const responsesConfig = {
      name: "OmniRoute-responses",
      vendor: "azure",
      apiKey: `\${input:chat.lm.secret.omniroute}`,
      models: responseModels,
    };

    return [config, responsesConfig].map((entry) => JSON.stringify(entry, null, 2)).join(",\n");
  };

  const handleCopy = async (text: string, field: string) => {
    await navigator.clipboard.writeText(text);
    setCopiedField(field);
    setTimeout(() => setCopiedField(null), 2000);
  };

  const handleApiKeyChange = (value: string) => {
    setSelectedApiKeyId(value);
    if (value) localStorage.setItem("omniroute-cli-key-copilot", value);
  };

  return (
    <Card padding="sm" className="overflow-hidden">

      {/* Header */}

      <div className="flex items-center justify-between hover:cursor-pointer" onClick={onToggle}>

        <div className="flex items-center gap-3">

          <div className="size-8 rounded-lg flex items-center justify-center shrink-0">

            <Image

              src={tool.image || "/providers/copilot.png"}

              alt={tool.name}

              width={32}

              height={32}

              className="size-8 object-contain rounded-lg"

              sizes="32px"

              onError={(e) => {

                (e.currentTarget as HTMLElement).style.display = "none";

              }}

            />

          </div>

          <div className="min-w-0">

            <div className="flex items-center gap-2">

              <h3 className="font-medium text-sm">{tool.name}</h3>

              <span className="inline-flex items-center gap-1.5 px-2 py-0.5 text-[11px] font-medium rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400">

                <span className="size-1.5 rounded-full bg-blue-500" />

                {t("guide")}

              </span>

            </div>

            <p className="text-xs text-text-muted truncate">{tool.description}</p>

          </div>

        </div>

        <span

          className={`material-symbols-outlined text-text-muted text-[20px] transition-transform ${isExpanded ? "rotate-180" : ""}`}

        >

          expand_more

        </span>

      </div>



      {/* Expanded content */}

      {isExpanded && (

        <div className="mt-6 pt-6 border-t border-border">

          <div className="flex flex-col gap-5">

            {/* Info box */}

            <div className="flex items-start gap-3 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg">

              <span className="material-symbols-outlined text-blue-500 text-lg">info</span>

              <div className="text-sm text-blue-700 dark:text-blue-300">

                <p className="font-medium">{t("copilotConfigGenerator")}</p>

                <p className="mt-1 text-xs opacity-80">

                  Generates the{" "}

                  <code className="px-1 py-0.5 rounded bg-black/5 dark:bg-white/10">

                    chatLanguageModels.json

                  </code>{" "}

                  block for VS Code GitHub Copilot using the Azure vendor pattern. Select the models

                  you want, then copy the JSON into your config file.

                </p>

              </div>

            </div>



            {/* Version compatibility warning */}

            <div className="flex items-start gap-3 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">

              <span className="material-symbols-outlined text-yellow-500 text-lg">warning</span>

              <p className="text-xs text-yellow-600 dark:text-yellow-400">

                This configuration uses the Azure vendor workaround for custom model lists. Tested

                with <strong>VS Code ≥ 1.109</strong> and{" "}

                <strong>GitHub Copilot Chat ≥ v0.37</strong>. Future extension updates may change

                this behavior.

              </p>

            </div>



            {/* Step 2: API Key (if cloud enabled) */}

            {cloudEnabled && apiKeys?.length > 0 && (

              <div>

                <div className="flex items-center gap-2 mb-2">

                  <div

                    className="size-6 rounded-full flex items-center justify-center text-xs font-semibold text-white"

                    style={{ backgroundColor: tool.color }}

                  >

                    1

                  </div>

                  <span className="font-medium text-sm">{t("copilotApiKey")}</span>

                </div>

                <select

                  value={selectedApiKeyId}

                  onChange={(e) => handleApiKeyChange(e.target.value)}

                  className="w-full px-3 py-2 bg-bg-secondary rounded-lg text-sm border border-border focus:outline-none focus:ring-1 focus:ring-primary/50"

                >

                  {apiKeys.map((key: any) => (

                    <option key={key.id} value={key.id}>

                      {key.key}

                    </option>

                  ))}

                </select>

              </div>

            )}



            {/* Step 3: Model Selection */}

            <div>

              <div className="flex items-center justify-between mb-2">

                <div className="flex items-center gap-2">

                  <div

                    className="size-6 rounded-full flex items-center justify-center text-xs font-semibold text-white"

                    style={{ backgroundColor: tool.color }}

                  >

                    {cloudEnabled && apiKeys?.length > 0 ? "2" : "1"}

                  </div>

                  <span className="font-medium text-sm">

                    Select Models ({selectedModels.size}/{availableModels.length})

                  </span>

                </div>

                <div className="flex gap-2">

                  <button

                    onClick={selectAll}

                    className="px-2 py-1 text-xs bg-bg-secondary hover:bg-bg-tertiary rounded border border-border transition-colors"

                  >

                    Select All

                  </button>

                  <button

                    onClick={deselectAll}

                    className="px-2 py-1 text-xs bg-bg-secondary hover:bg-bg-tertiary rounded border border-border transition-colors"

                  >

                    Clear

                  </button>

                </div>

              </div>



              {/* Search filter */}

              <div className="mb-2">

                <input

                  type="text"

                  value={searchFilter}

                  onChange={(e) => setSearchFilter(e.target.value)}

                  placeholder={t("copilotFilterModelsPlaceholder")}

                  className="w-full px-3 py-1.5 bg-bg-secondary rounded-lg text-sm border border-border focus:outline-none focus:ring-1 focus:ring-primary/50"

                />

              </div>



              {!modelsLoaded && allModels.length === 0 ? (

                <div className="flex items-center gap-2 p-3 text-text-muted text-sm">

                  <span className="material-symbols-outlined animate-spin text-base">

                    progress_activity

                  </span>

                  <span>Loading models...</span>

                </div>

              ) : availableModels.length === 0 && allModels.length === 0 ? (

                <div className="flex items-center gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">

                  <span className="material-symbols-outlined text-yellow-500 text-lg">warning</span>

                  <p className="text-sm text-yellow-600 dark:text-yellow-400">

                    {t("noActiveProviders")}

                  </p>

                </div>

              ) : (

                <div className="max-h-64 overflow-y-auto rounded-lg border border-border bg-bg-secondary">

                  {availableModels.map((model) => (

                    <label

                      key={model.value}

                      className="flex items-center gap-3 px-3 py-2 hover:bg-bg-tertiary cursor-pointer border-b border-border last:border-0 transition-colors"

                    >

                      <input

                        type="checkbox"

                        checked={selectedModels.has(model.value)}

                        onChange={() => toggleModel(model.value)}

                        className="rounded border-border text-primary accent-[#1F6FEB]"

                      />

                      <span className="text-sm font-mono truncate">{model.label}</span>

                    </label>

                  ))}

                </div>

              )}

            </div>



            {/* Step 4: Advanced options (collapsible) */}

            <details className="group">

              <summary className="flex items-center gap-2 cursor-pointer text-sm text-text-muted hover:text-text-main transition-colors">

                <span className="material-symbols-outlined text-base group-open:rotate-90 transition-transform">

                  chevron_right

                </span>

                Advanced Options

              </summary>

              <div className="mt-3 grid grid-cols-2 gap-3 pl-6">

                <div>

                  <label className="text-xs text-text-muted block mb-1">

                    {t("copilotMaxInputTokens")}

                  </label>

                  <input

                    type="number"

                    value={maxInputTokens}

                    onChange={(e) => setMaxInputTokens(Number(e.target.value) || 128000)}

                    className="w-full px-3 py-1.5 bg-bg-secondary rounded-lg text-sm border border-border focus:outline-none focus:ring-1 focus:ring-primary/50"

                  />

                </div>

                <div>

                  <label className="text-xs text-text-muted block mb-1">

                    {t("copilotMaxOutputTokens")}

                  </label>

                  <input

                    type="number"

                    value={maxOutputTokens}

                    onChange={(e) => setMaxOutputTokens(Number(e.target.value) || 16000)}

                    className="w-full px-3 py-1.5 bg-bg-secondary rounded-lg text-sm border border-border focus:outline-none focus:ring-1 focus:ring-primary/50"

                  />

                </div>

                <label className="flex items-center gap-2 cursor-pointer">

                  <input

                    type="checkbox"

                    checked={toolCalling}

                    onChange={(e) => setToolCalling(e.target.checked)}

                    className="rounded border-border accent-[#1F6FEB]"

                  />

                  <span className="text-sm">{t("copilotToolCalling")}</span>

                </label>

                <label className="flex items-center gap-2 cursor-pointer">

                  <input

                    type="checkbox"

                    checked={vision}

                    onChange={(e) => setVision(e.target.checked)}

                    className="rounded border-border accent-[#1F6FEB]"

                  />

                  <span className="text-sm">Vision</span>

                </label>

              </div>

            </details>



            {/* Step 5: Generated config */}

            {selectedModels.size > 0 && (

              <div>

                <div className="flex items-center justify-between mb-2">

                  <div className="flex items-center gap-2">

                    <div

                      className="size-6 rounded-full flex items-center justify-center text-xs font-semibold text-white"

                      style={{ backgroundColor: tool.color }}

                    >

                      {cloudEnabled && apiKeys?.length > 0 ? "3" : "2"}

                    </div>

                    <span className="font-medium text-sm">

                      Copy Config ({selectedModels.size} model{selectedModels.size !== 1 ? "s" : ""}

                      )

                    </span>

                  </div>

                  <Button

                    variant="primary"

                    size="sm"

                    onClick={() => handleCopy(generateConfig(), "config")}

                  >

                    <span className="material-symbols-outlined text-[14px] mr-1">

                      {copiedField === "config" ? "check" : "content_copy"}

                    </span>

                    {copiedField === "config" ? t("copied") : t("copyConfig")}

                  </Button>

                </div>

                <pre className="p-4 bg-bg-secondary rounded-lg border border-border overflow-x-auto max-h-80">

                  <code className="text-xs font-mono whitespace-pre text-text-main">

                    {generateConfig()}

                  </code>

                </pre>



                {/* Usage instructions */}

                <div className="mt-3 p-3 bg-bg-secondary rounded-lg border border-border">

                  <p className="text-xs text-text-muted">

                    <span className="font-medium text-text-main">{t("copilotPasteInto")} </span>

                    <code className="px-1 py-0.5 rounded bg-black/5 dark:bg-white/10">

                      ~/.config/Code/User/chatLanguageModels.json

                    </code>

                  </p>

                  <p className="text-xs text-text-muted mt-1">

                    Then reload VS Code and set the API key in the input prompt.

                  </p>

                </div>

              </div>

            )}

          </div>

        </div>

      )}

    </Card>
  );
}