File size: 9,410 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { CLI_TOOLS } from "@/shared/constants/cliTools";
import { PROVIDER_ID_TO_ALIAS, getModelsByProviderId } from "@/shared/constants/models";
import {
  AntigravityToolCard,
  ClaudeToolCard,
  ClineToolCard,
  CodexToolCard,
  CopilotToolCard,
  CustomCliCard,
  DefaultToolCard,
  DroidToolCard,
  HermesAgentToolCard,
  KiloToolCard,
  OpenClawToolCard,
} from "./index";

export interface ToolDetailClientProps {
  toolId: string;
  category: "code" | "agent";
}

const CLOUD_URL = process.env.NEXT_PUBLIC_CLOUD_URL;

export default function ToolDetailClient({ toolId, category }: ToolDetailClientProps) {
  const tool = CLI_TOOLS[toolId];

  const [connections, setConnections] = useState<any[]>([]);
  const [apiKeys, setApiKeys] = useState<any[]>([]);
  const [cloudEnabled, setCloudEnabled] = useState(false);
  const [dynamicModels, setDynamicModels] = useState<any[]>([]);
  const [modelMappings, setModelMappings] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(true);

  const fetchConnections = useCallback(async () => {
    try {
      const res = await fetch("/api/providers");
      if (res.ok) {
        const data = await res.json();
        setConnections(data.connections || []);
      }
    } catch (error) {
      console.log("Error fetching connections:", error);
    }
  }, []);

  const fetchApiKeys = useCallback(async () => {
    try {
      const res = await fetch("/api/cli-tools/keys");
      if (res.ok) {
        const data = await res.json();
        setApiKeys(data.keys || []);
      }
    } catch (error) {
      console.log("Error fetching API keys:", error);
    }
  }, []);

  const fetchCloudSettings = useCallback(async () => {
    try {
      const res = await fetch("/api/settings");
      if (res.ok) {
        const data = await res.json();
        setCloudEnabled(data.cloudEnabled || false);
      }
    } catch (error) {
      console.log("Error loading cloud settings:", error);
    }
  }, []);

  const fetchDynamicModels = useCallback(async () => {
    try {
      const res = await fetch("/v1/models");
      if (res.ok) {
        const data = await res.json();
        setDynamicModels(data?.data || []);
      }
    } catch (error) {
      console.log("Error fetching dynamic models:", error);
    }
  }, []);

  useEffect(() => {
    let cancelled = false;
    // "Load data on mount" pattern: fetch* callbacks call setState internally
    // after async resolution. The cancelled flag prevents setState after unmount.
    // The react-hooks/set-state-in-effect rule flags this pattern conservatively
    // (it cannot distinguish sync vs async setState), but this is the canonical
    // way to load remote data on mount until we migrate to use()/Suspense.
    /* eslint-disable react-hooks/set-state-in-effect */
    Promise.all([
      fetchConnections(),
      fetchApiKeys(),
      fetchCloudSettings(),
      fetchDynamicModels(),
    ]).finally(() => {
      if (!cancelled) setLoading(false);
    });
    /* eslint-enable react-hooks/set-state-in-effect */
    return () => {
      cancelled = true;
    };
  }, [fetchConnections, fetchApiKeys, fetchCloudSettings, fetchDynamicModels]);

  const getActiveProviders = useCallback(() => {
    return connections.filter((c) => c.isActive !== false);
  }, [connections]);

  const getAllAvailableModels = useCallback(() => {
    const activeProviders = getActiveProviders();
    const models: any[] = [];
    const seenModels = new Set<string>();

    activeProviders.forEach((conn) => {
      const alias = PROVIDER_ID_TO_ALIAS[conn.provider] || conn.provider;
      const providerModels = getModelsByProviderId(conn.provider);
      providerModels.forEach((m: any) => {
        const modelValue = `${alias}/${m.id}`;
        if (!seenModels.has(modelValue)) {
          seenModels.add(modelValue);
          models.push({
            value: modelValue,
            label: `${alias}/${m.id}`,
            provider: conn.provider,
            alias,
            connectionName: conn.name,
            modelId: m.id,
          });
        }
      });
    });

    const activeAliases = new Set(
      activeProviders.map((c) => PROVIDER_ID_TO_ALIAS[c.provider] || c.provider)
    );
    const activeProviderIds = new Set(activeProviders.map((c) => c.provider));
    dynamicModels.forEach((dm) => {
      const rawId = dm?.id ?? dm;
      const modelId = typeof rawId === "string" ? rawId : "";
      if (!modelId || seenModels.has(modelId)) return;
      const slashIdx = modelId.indexOf("/");
      if (slashIdx === -1) return;
      const alias = modelId.substring(0, slashIdx);
      const bareModel = modelId.substring(slashIdx + 1);
      if (!activeAliases.has(alias) && !activeProviderIds.has(alias)) return;
      seenModels.add(modelId);
      models.push({
        value: modelId,
        label: modelId,
        provider: alias,
        alias,
        connectionName: "",
        modelId: bareModel,
      });
    });

    return models;
  }, [getActiveProviders, dynamicModels]);

  const handleModelMappingChange = useCallback((alias: string, targetModel: string) => {
    setModelMappings((prev) => {
      if (prev[alias] === targetModel) return prev;
      return { ...prev, [alias]: targetModel };
    });
  }, []);

  const getBaseUrl = useCallback(() => {
    if (cloudEnabled && CLOUD_URL) return CLOUD_URL;
    if (typeof window !== "undefined") return window.location.origin;
    return "";
  }, [cloudEnabled]);

  if (!tool) return null;

  const activeProviders = getActiveProviders();
  const availableModels = getAllAvailableModels();
  const hasActiveProviders = availableModels.length > 0;

  const backCategory = category === "code" ? "/dashboard/cli-code" : "/dashboard/cli-agents";

  // Common props passed to every specialized card.
  // isExpanded is always true in the detail page (D23).
  const cardProps: any = {
    tool,
    isExpanded: true,
    onToggle: () => {},
    baseUrl: getBaseUrl(),
    apiKeys,
    batchStatus: null,
    lastConfiguredAt: null,
    activeProviders,
    hasActiveProviders,
    cloudEnabled,
    availableModels,
  };

  const renderCard = () => {
    switch (toolId) {
      case "claude":
        return (
          <ClaudeToolCard

            {...cardProps}

            modelMappings={modelMappings}

            onModelMappingChange={handleModelMappingChange}

          />
        );
      case "codex":
        return <CodexToolCard {...cardProps} />;
      case "droid":
        return <DroidToolCard {...cardProps} />;
      case "openclaw":
        return <OpenClawToolCard {...cardProps} />;
      case "cline":
        return <ClineToolCard {...cardProps} />;
      case "kilo":
        return <KiloToolCard {...cardProps} />;
      case "copilot":
        return <CopilotToolCard {...cardProps} />;
      case "hermes-agent":
        return <HermesAgentToolCard {...cardProps} />;
      case "antigravity":
        return <AntigravityToolCard {...cardProps} />;
      case "custom":
        return <CustomCliCard {...cardProps} />;
      default:
        if (tool.configType === "mitm") {
          return <AntigravityToolCard {...cardProps} />;
        }
        return <DefaultToolCard toolId={toolId} {...cardProps} />;
    }
  };

  return (
    <div className="flex flex-col gap-4">

      {/* Back navigation */}

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

        <Link

          href={backCategory}

          className="inline-flex items-center gap-1.5 text-sm text-text-muted hover:text-primary transition-colors"

        >

          <span className="material-symbols-outlined text-[16px]">arrow_back</span>

          {category === "code" ? "CLI Code" : "CLI Agents"}

        </Link>

        <span className="text-text-muted">/</span>

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

      </div>



      {/* Tool header */}

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

        {tool.vendor && (

          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-surface border border-border text-text-muted">

            {tool.vendor}

          </span>

        )}

        <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-primary/10 text-primary">

          {category}

        </span>

        {tool.baseUrlSupport && tool.baseUrlSupport !== "none" && (

          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-500/10 text-green-600 dark:text-green-400">

            <span className="material-symbols-outlined text-[12px]">link</span>

            {tool.baseUrlSupport === "full" ? "Full base URL" : "Partial base URL"}

          </span>

        )}

      </div>



      {/* Specialized card — always expanded */}

      {loading ? (

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

          <div className="h-24 rounded-xl bg-surface animate-pulse" />

        </div>

      ) : (

        renderCard()

      )}

    </div>
  );
}