File size: 12,632 Bytes
5448d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// @vitest-environment jsdom
import React from "react";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

vi.mock("next-intl", () => ({
  useTranslations: () => (key: string, values?: Record<string, unknown>) => {
    if (!values) return key;
    return Object.entries(values).reduce(
      (message, [name, value]) => message.replace(`{${name}}`, String(value)),
      key
    );
  },
}));

type FetchCall = {
  url: string;
  method: string;
  body: any;
};

type MockResponse = {
  status?: number;
  body?: unknown;
};

const cleanupCallbacks: Array<() => void> = [];
let fetchCalls: FetchCall[] = [];

function makeContainer(): HTMLElement {
  const container = document.createElement("div");
  document.body.appendChild(container);
  cleanupCallbacks.push(() => {
    container.remove();
  });
  return container;
}

function jsonResponse(body: unknown, status = 200) {
  return {
    ok: status >= 200 && status < 300,
    status,
    json: async () => body,
  } as Response;
}

function parseBody(init?: RequestInit) {
  if (typeof init?.body !== "string") return null;
  try {
    return JSON.parse(init.body);
  } catch {
    return init.body;
  }
}

function installFetchMock(handler: (url: string, init?: RequestInit) => MockResponse) {
  const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
    const url = typeof input === "string" ? input : input.toString();
    const method = String(init?.method || "GET").toUpperCase();
    const body = parseBody(init);
    fetchCalls.push({ url, method, body });
    const response = handler(url, init);
    return jsonResponse(response.body ?? {}, response.status ?? 200);
  });
  vi.stubGlobal("fetch", fetchMock);
  return fetchMock;
}

async function flushEffects() {
  await act(async () => {
    await Promise.resolve();
    await Promise.resolve();
  });
}

async function renderProxyConfigModal(props?: Partial<React.ComponentProps<any>>) {
  const { default: ProxyConfigModal } = await import("@/shared/components/ProxyConfigModal");
  const container = makeContainer();
  const root: Root = createRoot(container);
  cleanupCallbacks.push(() => root.unmount());

  await act(async () => {
    root.render(
      <ProxyConfigModal

        isOpen

        onClose={vi.fn()}

        level="provider"

        levelId="claude"

        levelLabel="Claude"

        onSaved={vi.fn()}

        {...props}

      />
    );
  });
  await waitForModalToLoad(container);
  return { container, root };
}

async function waitForModalToLoad(container: HTMLElement) {
  for (let i = 0; i < 20; i++) {
    await flushEffects();
    if (!container.textContent?.includes("loading")) return;
  }
}

function getInput(container: HTMLElement, placeholder: string) {
  const input = Array.from(container.querySelectorAll("input")).find(
    (item) => item.getAttribute("placeholder") === placeholder
  );
  expect(input).toBeTruthy();
  return input as HTMLInputElement;
}

async function clickButton(container: HTMLElement, text: string) {
  const expected = text.toLowerCase();
  const buttons = Array.from(container.querySelectorAll("button"));
  const getText = (item: HTMLButtonElement) => item.textContent?.trim().toLowerCase() || "";
  const button =
    buttons.find((item) => getText(item) === expected) ||
    buttons.find(
      (item) => getText(item).endsWith(expected) && !getText(item).includes("savedproxy")
    ) ||
    buttons.find((item) => getText(item).includes(expected));
  expect(button).toBeTruthy();
  await act(async () => {
    button?.click();
  });
  await flushEffects();
}

async function waitForCall(predicate: (call: FetchCall) => boolean) {
  for (let i = 0; i < 20; i++) {
    await flushEffects();
    if (fetchCalls.some(predicate)) return;
  }
}

async function setInputValue(input: HTMLInputElement, value: string) {
  await act(async () => {
    const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
    setter?.call(input, value);
    input.dispatchEvent(new Event("input", { bubbles: true }));
    input.dispatchEvent(new Event("change", { bubbles: true }));
  });
  await flushEffects();
}

function defaultProxyConfigResponses(url: string): MockResponse | null {
  if (url === "/api/settings/proxies") {
    return { body: { items: [], total: 0 } };
  }
  if (url.startsWith("/api/settings/proxies/assignments?") && url.includes("scope=provider")) {
    return { body: { items: [], total: 0 } };
  }
  if (url.startsWith("/api/settings/proxy?level=provider")) {
    return { body: { level: "provider", id: "claude", proxy: null } };
  }
  if (url === "/api/settings/proxy") {
    return { body: {} };
  }
  return null;
}

describe("ProxyConfigModal custom registry saves", () => {
  beforeEach(() => {
    (
      globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
    ).IS_REACT_ACT_ENVIRONMENT = true;
    fetchCalls = [];
  });

  afterEach(() => {
    while (cleanupCallbacks.length > 0) {
      cleanupCallbacks.pop()?.();
    }
    document.body.innerHTML = "";
    vi.unstubAllGlobals();
    vi.restoreAllMocks();
  });

  it("creates a dashboard-custom registry proxy, assigns it, and clears matching legacy config", async () => {
    installFetchMock((url, init) => {
      const method = String(init?.method || "GET").toUpperCase();
      const body = parseBody(init);

      if (method === "POST" && url === "/api/settings/proxies") {
        return {
          status: 201,
          body: { id: "custom-proxy-1", ...body, assignment: { proxyId: "custom-proxy-1" } },
        };
      }

      return defaultProxyConfigResponses(url) || { status: 404, body: {} };
    });

    const { container } = await renderProxyConfigModal();

    await setInputValue(getInput(container, "hostPlaceholder"), "custom.local");
    await setInputValue(getInput(container, "8080"), "3128");
    await clickButton(container, "save");
    await waitForCall((call) => call.method === "POST" && call.url === "/api/settings/proxies");

    const createCall = fetchCalls.find(
      (call) => call.method === "POST" && call.url === "/api/settings/proxies"
    );
    expect(createCall?.body).toMatchObject({
      name: "Custom Provider Proxy (Claude)",
      type: "http",
      host: "custom.local",
      port: 3128,
      status: "active",
      source: "dashboard-custom",
      assignment: {
        scope: "provider",
        scopeId: "claude",
      },
    });

    expect(
      fetchCalls.some((call) => call.method === "PUT" && call.url === "/api/settings/proxy")
    ).toBe(false);
    expect(
      fetchCalls.some(
        (call) => call.method === "PUT" && call.url === "/api/settings/proxies/assignments"
      )
    ).toBe(false);
    expect(
      fetchCalls.some(
        (call) =>
          call.method === "DELETE" && call.url === "/api/settings/proxy?level=provider&id=claude"
      )
    ).toBe(false);
  });

  it("updates an existing scope-owned dashboard-custom proxy instead of creating a duplicate", async () => {
    installFetchMock((url, init) => {
      const method = String(init?.method || "GET").toUpperCase();
      const body = parseBody(init);

      if (method === "GET" && url === "/api/settings/proxies") {
        return {
          body: {
            items: [
              {
                id: "custom-proxy-1",
                name: "Custom Provider Proxy (Claude)",
                type: "http",
                host: "old.local",
                port: 8080,
                source: "dashboard-custom",
              },
            ],
            total: 1,
          },
        };
      }
      if (url.startsWith("/api/settings/proxies/assignments?") && url.includes("scope=provider")) {
        return {
          body: {
            items: [
              { proxyId: "other-proxy", scope: "provider", scopeId: "other-provider" },
              { proxyId: "custom-proxy-1", scope: "provider", scopeId: "claude" },
            ],
            total: 1,
          },
        };
      }
      if (url === "/api/settings/proxies?id=custom-proxy-1&whereUsed=1") {
        return {
          body: {
            count: 1,
            assignments: [{ proxyId: "custom-proxy-1", scope: "provider", scopeId: "claude" }],
          },
        };
      }
      if (method === "PATCH" && url === "/api/settings/proxies") {
        return {
          body: { id: "custom-proxy-1", ...body, assignment: { proxyId: "custom-proxy-1" } },
        };
      }

      return defaultProxyConfigResponses(url) || { status: 404, body: {} };
    });

    const { container } = await renderProxyConfigModal();

    await setInputValue(getInput(container, "hostPlaceholder"), "updated.local");
    await clickButton(container, "authOptional");
    await setInputValue(getInput(container, "usernamePlaceholder"), "***");
    await setInputValue(getInput(container, "passwordPlaceholder"), "***");
    await clickButton(container, "save");
    await waitForCall((call) => call.method === "PATCH" && call.url === "/api/settings/proxies");

    expect(
      fetchCalls.some((call) => call.method === "POST" && call.url === "/api/settings/proxies")
    ).toBe(false);

    const updateCall = fetchCalls.find(
      (call) => call.method === "PATCH" && call.url === "/api/settings/proxies"
    );
    expect(updateCall?.body).toMatchObject({
      id: "custom-proxy-1",
      host: "updated.local",
      source: "dashboard-custom",
      assignment: {
        scope: "provider",
        scopeId: "claude",
      },
    });
    expect(updateCall?.body).not.toHaveProperty("username");
    expect(updateCall?.body).not.toHaveProperty("password");
    expect(
      fetchCalls.some(
        (call) => call.method === "PUT" && call.url === "/api/settings/proxies/assignments"
      )
    ).toBe(false);
    expect(
      fetchCalls.some(
        (call) =>
          call.method === "DELETE" && call.url === "/api/settings/proxy?level=provider&id=claude"
      )
    ).toBe(false);
  });

  it("creates a new dashboard-custom proxy when current assignment is a reusable manual proxy", async () => {
    installFetchMock((url, init) => {
      const method = String(init?.method || "GET").toUpperCase();
      const body = parseBody(init);

      if (method === "GET" && url === "/api/settings/proxies") {
        return {
          body: {
            items: [
              {
                id: "manual-proxy-1",
                name: "Shared Manual Proxy",
                type: "http",
                host: "shared.local",
                port: 8080,
                source: "manual",
              },
            ],
            total: 1,
          },
        };
      }
      if (url.startsWith("/api/settings/proxies/assignments?") && url.includes("scope=provider")) {
        return {
          body: {
            items: [{ proxyId: "manual-proxy-1", scope: "provider", scopeId: "claude" }],
            total: 1,
          },
        };
      }
      if (method === "POST" && url === "/api/settings/proxies") {
        return {
          status: 201,
          body: { id: "custom-proxy-2", ...body, assignment: { proxyId: "custom-proxy-2" } },
        };
      }

      return defaultProxyConfigResponses(url) || { status: 404, body: {} };
    });

    const { container } = await renderProxyConfigModal();

    await clickButton(container, "custom");
    await setInputValue(getInput(container, "hostPlaceholder"), "custom.local");
    await clickButton(container, "save");
    await waitForCall((call) => call.method === "POST" && call.url === "/api/settings/proxies");

    expect(
      fetchCalls.some((call) => call.method === "PATCH" && call.url === "/api/settings/proxies")
    ).toBe(false);
    expect(
      fetchCalls.some(
        (call) =>
          call.method === "POST" &&
          call.url === "/api/settings/proxies" &&
          call.body.assignment?.scope === "provider" &&
          call.body.assignment?.scopeId === "claude"
      )
    ).toBe(true);
    expect(
      fetchCalls.some(
        (call) => call.method === "PUT" && call.url === "/api/settings/proxies/assignments"
      )
    ).toBe(false);
  });
});