Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 编辑自定义端点时同步模型路由 #4927 (#4934)
DavidShenXD92294b7ead54
diff --git a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsxindex daf8209064..a6f908a138 100644--- a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx@@ -2,7 +2,8 @@ import { providerEndpointBindings, canonicalProviderEndpoint, BUNDLED_CATALOG, c/*** Connection credentials and advanced routing only. Model capabilities are imported into the* shared catalog and edited through standard model settings. Stored per-runtime credentials,- * OAuth definitions, explicit routes and user overrides remain unchanged when saving.+ * OAuth definitions and user overrides are preserved. Model routes follow endpoint+ * edits while retaining their independent protocol and path overrides.*/import * as Dialog from '@radix-ui/react-dialog';@@ -55,6 +56,7 @@ import {} from '@/lib/customProviders';import type { CodexImageGenerationRestartPolicy } from '@/../shared/customProviderUpdate';import { uniqueCustomProviderId } from '@/lib/customProviderId';+import { modelsAfterProviderEndpointEdit } from '@/lib/customProviderEndpointEdit';import {areProviderRequestUrlsAllowed,canSendHydratedApiKey,@@ -191,6 +193,8 @@ interface HeaderRow {}interface RuntimeFields extends RuntimeFillDraft {models: ModelRow[];+ /** Draft-only provenance: model routes may come from a preset or another runtime. */+ modelRouteBaseUrl?: string;headers: HeaderRow[];/** 隐藏字段:列模型端点(预设 / 已存配置快照进来),「获取模型列表」用;不在表单展示。 */modelsUrl: string;@@ -201,6 +205,14 @@ interface RuntimeFields extends RuntimeFillDraft {supportsImageGeneration: boolean;}+function runtimeProbeFields(agent: DialogAgentKind, runtime: RuntimeFields): RuntimeFields {+ return {+ ...runtime,+ requestPath: agent === 'pi' ? '' : runtime.requestPath,+ models: modelsAfterProviderEndpointEdit(runtime.models, runtime.modelRouteBaseUrl, runtime.baseUrl),+ };+}+function canRuntimeUseNativeImageGeneration(runtime: RuntimeFields): boolean {return (runtime.wireProtocol === 'openai-responses' ||@@ -261,6 +273,7 @@ function initRuntimes(initial?: CustomProviderConfig): Record<DialogAgentKind, Rif (!rc) continue;out[a] = normalizeRuntimeImageGenerationCapability(a, {baseUrl: rc.baseUrl,+ modelRouteBaseUrl: rc.baseUrl,requestPath: a === 'pi' ? '' : (rc.requestPath ?? ''),apiKey: '',wireProtocol: rc.wireProtocol ?? defaultWireFor(a),@@ -848,6 +861,7 @@ export function ProviderConnectionDialog({}next[a] = {baseUrl: rc.baseUrl,+ modelRouteBaseUrl: rc.baseUrl,requestPath: a === 'pi' ? '' : (rc.requestPath ?? ''),apiKey: prev[a].apiKey, // 已填的 key 保留wireProtocol: rc.wireProtocol ?? defaultWireFor(a),@@ -998,7 +1012,13 @@ export function ProviderConnectionDialog({const includeApiKey = usesApiKey;const oauthPiUnavailable = authModeRef.current === 'oauth' && source !== 'pi';- const sourceDraft = cloneRuntimeFillDraft(rtRef.current[source]);+ const sourceFields = rtRef.current[source];+ const sourceDraft = cloneRuntimeFillDraft({+ ...sourceFields,+ models: modelsAfterProviderEndpointEdit(+ sourceFields.models, sourceFields.modelRouteBaseUrl, sourceFields.baseUrl,+ ),+ });const allTargets = runtimeFillTargetAgents(source, {includePi: authModeRef.current !== 'oauth',}).map((agent) => ({@@ -1121,6 +1141,9 @@ export function ProviderConnectionDialog({const restored = restoreHydratedKey(target.agent, {...prev[target.agent],...endpointSafeFilled,+ ...(selectedFields.includes('models')+ ? { modelRouteBaseUrl: runtimeFill.sourceDraft.baseUrl }+ : {}),});next[target.agent] = restored;}@@ -1211,7 +1234,7 @@ export function ProviderConnectionDialog({const handleTest = useCallback(async () => {const agent = activeTab;const rf = rt[agent];- const probeFields = agent === 'pi' ? { ...rf, requestPath: '' } : rf;+ const probeFields = runtimeProbeFields(agent, rf);const defaultBaseUrl = rf.baseUrl.trim();const firstModelConfig = firstProviderChatModel(rf.models);const firstModel = firstModelConfig?.id.trim();@@ -1281,7 +1304,7 @@ export function ProviderConnectionDialog({);if (providerConnectionTestRequestSignature(- agent === 'pi' ? { ...rtRef.current[agent], requestPath: '' } : rtRef.current[agent],+ runtimeProbeFields(agent, rtRef.current[agent]),authModeRef.current,) !== requestSig)@@ -1295,7 +1318,7 @@ export function ProviderConnectionDialog({} catch (e) {if (providerConnectionTestRequestSignature(- agent === 'pi' ? { ...rtRef.current[agent], requestPath: '' } : rtRef.current[agent],+ runtimeProbeFields(agent, rtRef.current[agent]),authModeRef.current,) !== requestSig)@@ -1632,7 +1655,7 @@ export function ProviderConnectionDialog({reportFieldError(`${a}:baseUrl`, t('settings.providers.custom.errors.baseUrlInvalid'));return;}- const models = rf.models+ const models = modelsAfterProviderEndpointEdit(rf.models, rf.modelRouteBaseUrl, rf.baseUrl).map((m) => ({id: m.id.trim(),name: m.name.trim(),diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsxindex 1b179e5a3f..5c0b3ee2e4 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx@@ -208,6 +208,242 @@ async function renderNewImageGenerationReloadConfirmation(onSaved = vi.fn(), onC}describe('ProviderConnectionDialog accessibility', () => {+ it.each(['claude-code', 'codex', 'pi'] as const)(+ 'preserves existing %s configuration when saving unchanged or renaming', async agent => {+ const initial: CustomProviderConfig = {+ id: 'existing-connection', name: 'Existing connection',+ runtimes: { [agent]: {+ baseUrl: 'https://existing.example.test/v1', wireProtocol: 'openai-chat',+ modelsUrl: 'https://existing.example.test/catalog',+ headers: { 'x-custom-option': 'existing-option' },+ ...(agent === 'pi' ? { piCatalogProviderId: 'openai' } : {}),+ ...(agent === 'codex' ? { supportsImageGeneration: true } : {}),+ models: [{ id: 'custom-chat', name: 'User chosen name', contextWindow: 64000,+ api: 'openai-responses', mode: 'chat',+ modalities: { input: ['text', 'image'], output: ['text'] },+ officialDocs: 'https://existing.example.test/docs',+ discoveredMetadata: { contextWindow: 128000, supportsImageInput: true },+ discoveredCost: { input: 2, output: 8, cacheRead: 0.2 },+ defaultEnabled: false, supportsImageInput: false, reasoning: true,+ reasoningEfforts: ['low', 'high'], reasoningDefaultEffort: 'high', nameExplicit: true,+ ...(agent === 'pi' ? { piApi: 'openai-responses' } : {}),+ route: { baseUrl: 'https://existing.example.test/independent?version=1',+ wireProtocol: 'openai-responses', requestPath: '/responses' } },+ { id: 'inherited-model', name: 'Inherited model' }],+ } },+ };+ const before = structuredClone(initial);+ customProviderMocks.readCustomProviderKey.mockResolvedValue('qa-invalid-saved-key');+ // Keep the draft open after the first attempt so the same fixture can exercise renaming.+ customProviderMocks.updateCustomProvider.mockRejectedValueOnce(new Error('Save failed'));+ const user = userEvent.setup();+ render(<ProviderConnectionDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);+ await waitForInitialDialogFocus();+ await screen.findByText('settings.providers.custom.fields.apiKeySaved');+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await waitFor(() => expect(window.electronAPI.maker.testProviderConnection).toHaveBeenCalledWith({+ kind: 'saved', providerId: initial.id, agent,+ }));+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());+ const nameInput = screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder');+ await user.clear(nameInput);+ await user.type(nameInput, 'Renamed connection');+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledTimes(2));+ for (const [config, keys] of customProviderMocks.updateCustomProvider.mock.calls) {+ expect(config.runtimes).toEqual(initial.runtimes);+ expect(keys).toEqual({});+ expect(JSON.stringify(config)).not.toContain('modelRouteBaseUrl');+ }+ expect(customProviderMocks.updateCustomProvider.mock.calls[1][0].name).toBe('Renamed connection');+ expect(initial).toEqual(before);+ },+ );++ it.each(['claude', 'codex'] as const)('preserves existing native %s configuration when renaming', async native => {+ const initial: CustomProviderConfig = {+ id: 'existing-native', name: 'Existing native', auth: { method: 'oauth', native },+ runtimes: native === 'claude'+ ? { 'claude-code': { baseUrl: 'https://api.anthropic.com', models: [] } }+ : { codex: { baseUrl: 'https://chatgpt.com/backend-api/codex', models: [] } },+ };+ const user = userEvent.setup();+ render(<ProviderConnectionDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);+ await waitForInitialDialogFocus();+ const nameInput = screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder');+ await user.clear(nameInput);+ await user.type(nameInput, 'Renamed native');+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledWith(+ { ...initial, name: 'Renamed native' }, {},+ ));+ });++ it('leaves existing configuration untouched when an endpoint edit is cancelled', async () => {+ const initial = modelRoutedCodexProvider();+ const before = structuredClone(initial);+ const onClose = vi.fn();+ customProviderMocks.readCustomProviderKey.mockResolvedValue('qa-invalid-saved-key');+ const user = userEvent.setup();+ render(<ProviderConnectionDialog initial={initial} onSaved={vi.fn()} onClose={onClose} />);+ await waitForInitialDialogFocus();+ expect(customProviderMocks.updateCustomProvider).not.toHaveBeenCalled();+ await user.clear(screen.getByLabelText('settings.providers.custom.fields.baseUrl'));+ await user.type(screen.getByLabelText('settings.providers.custom.fields.baseUrl'), 'http://127.0.0.1:8000/v2');+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.cancel' }));+ expect(onClose).toHaveBeenCalledOnce();+ expect(customProviderMocks.updateCustomProvider).not.toHaveBeenCalled();+ expect(customProviderMocks.createCustomProvider).not.toHaveBeenCalled();+ expect(initial).toEqual(before);+ });++ it.each(['claude-code', 'codex', 'pi'] as const)(+ 'rebases saved %s model routes for both testing and saving an edited HTTP endpoint', async agent => {+ const initial: CustomProviderConfig = {+ id: 'edited-endpoint', name: 'Edited endpoint', auth: { method: 'apiKey' },+ runtimes: { [agent]: {+ baseUrl: 'https://old.example.test/v1', wireProtocol: 'openai-chat',+ models: [{ id: 'test-model', name: 'Test Model',+ route: { baseUrl: 'https://old.example.test/v1', wireProtocol: 'openai-chat' } },+ { id: 'special-model', name: 'Special Model',+ route: { baseUrl: 'https://old.example.test/special', wireProtocol: 'anthropic-messages', requestPath: '/messages' } }],+ } },+ };+ customProviderMocks.readCustomProviderKey.mockResolvedValue('old-key');+ const user = userEvent.setup();+ render(<ProviderConnectionDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);+ await waitForInitialDialogFocus();+ await screen.findByText('settings.providers.custom.fields.apiKeySaved');+ const baseUrl = screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder');+ await user.clear(baseUrl);+ await user.type(baseUrl, 'http://127.0.0.1:8000/v2');+ await user.type(screen.getByLabelText('settings.providers.custom.fields.apiKey'), 'new-key');+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await waitFor(() => expect(window.electronAPI.maker.testProviderConnection).toHaveBeenCalledWith({+ kind: 'adhoc', spec: expect.objectContaining({ agent, baseUrl: 'http://127.0.0.1:8000/v2',+ wireProtocol: 'openai-chat', apiKey: 'new-key' }),+ }));+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());+ const saved = customProviderMocks.updateCustomProvider.mock.calls[0][0].runtimes[agent];+ expect(saved.baseUrl).toBe('http://127.0.0.1:8000/v2');+ expect(saved.models[0].route).toEqual({ baseUrl: saved.baseUrl, wireProtocol: 'openai-chat' });+ expect(saved.models[1].route).toEqual({ baseUrl: 'http://127.0.0.1:8000/special',+ wireProtocol: 'anthropic-messages', requestPath: '/messages' });+ expect(initial.runtimes[agent]!.models[0].route!.baseUrl).toBe('https://old.example.test/v1');+ },+ );++ it('preserves original model routes after clearing, editing and reverting the endpoint', async () => {+ const initial = modelRoutedCodexProvider();+ customProviderMocks.readCustomProviderKey.mockResolvedValue('saved-key');+ const user = userEvent.setup();+ render(<ProviderConnectionDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);+ await waitForInitialDialogFocus();+ await screen.findByText('settings.providers.custom.fields.apiKeySaved');+ const baseUrl = screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder');+ await user.clear(baseUrl);+ await user.type(baseUrl, 'http://127.0.0.1:8000/v2');+ await user.clear(baseUrl);+ await user.type(baseUrl, initial.runtimes.codex!.baseUrl);+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());+ expect(customProviderMocks.updateCustomProvider.mock.calls[0][0].runtimes.codex.models[0].route)+ .toEqual(initial.runtimes.codex!.models[0].route);+ });++ it.each([+ { targetBase: undefined, nextSource: 'http://127.0.0.1:8000/v2' },+ { targetBase: 'https://other.example.test/v1', nextSource: 'http://127.0.0.1:8000/v2' },+ { targetBase: 'https://old.example.test/special', nextSource: 'https://old.example.test/v2' },+ ])('keeps route provenance when filling Codex ($targetBase) after editing Pi', async ({ targetBase, nextSource }) => {+ customProviderMocks.updateCustomProvider.mockRejectedValueOnce(new Error('Save failed'));+ const initial: CustomProviderConfig = {+ id: 'runtime-fill-route', name: 'Runtime fill route', auth: { method: 'apiKey' },+ runtimes: {+ pi: { baseUrl: 'https://old.example.test/v1', wireProtocol: 'openai-chat', models: [+ { id: 'chat', name: 'Chat', route: { baseUrl: 'https://old.example.test/v1', wireProtocol: 'openai-chat' } },+ { id: 'special', name: 'Special', route: { baseUrl: 'https://old.example.test/special', wireProtocol: 'anthropic-messages' } },+ ] },+ ...(targetBase ? { codex: { baseUrl: targetBase,+ models: [{ id: 'previous', name: 'Previous' }] } } : {}),+ },+ };+ customProviderMocks.readCustomProviderKey.mockResolvedValue('saved-key');+ const user = userEvent.setup();+ render(<ProviderConnectionDialog initial={initial} focusAgent="pi" onSaved={vi.fn()} onClose={vi.fn()} />);+ await waitForInitialDialogFocus();+ await screen.findByText('settings.providers.custom.fields.apiKeySaved');+ await user.clear(screen.getByLabelText('settings.providers.custom.fields.baseUrl'));+ await user.type(screen.getByLabelText('settings.providers.custom.fields.baseUrl'), nextSource);+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.runtimeFill.action' }));+ const overwrite = screen.queryByRole('button', { name: 'settings.providers.custom.runtimeFill.continue' });+ if (overwrite) {+ await user.click(overwrite);+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.runtimeFill.applyOverwrite' }));+ } else {+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.runtimeFill.apply' }));+ }+ await user.click(screen.getByRole('tab', { name: 'settings.providers.custom.protocol.codex' }));+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());+ const filled = customProviderMocks.updateCustomProvider.mock.calls[0][0];+ for (const agent of ['claude-code', 'codex', 'pi']) {+ expect(filled.runtimes[agent].models[0].route.baseUrl).toBe(nextSource);+ expect(filled.runtimes[agent].models[1].route).toEqual({+ baseUrl: new URL(nextSource).origin + '/special', wireProtocol: 'anthropic-messages',+ });+ }+ // A failed save keeps the draft open; another edit must still use the copied routes' origin.+ const finalBase = 'http://127.0.0.1:9000/v3';+ await user.clear(screen.getByLabelText('settings.providers.custom.fields.baseUrl'));+ await user.type(screen.getByLabelText('settings.providers.custom.fields.baseUrl'), finalBase);+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await waitFor(() => expect(window.electronAPI.maker.testProviderConnection).toHaveBeenCalledWith({+ kind: 'adhoc', spec: expect.objectContaining({ agent: 'codex', baseUrl: finalBase }),+ }));+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledTimes(2));+ const edited = customProviderMocks.updateCustomProvider.mock.calls[1][0].runtimes.codex;+ expect(edited.models[0].route.baseUrl).toBe(finalBase);+ expect(edited.models[1].route.baseUrl).toBe('http://127.0.0.1:9000/special');+ });++ it('probes the rebased route instead of the saved route after filling only models', async () => {+ const chat = { id: 'chat', name: 'Chat', route: {+ baseUrl: 'https://host.example/v1', wireProtocol: 'openai-chat' as const,+ } };+ const source = { baseUrl: 'https://host.example/v1', wireProtocol: 'openai-chat' as const,+ models: [chat, { id: 'extra', name: 'Extra' }] };+ const initial: CustomProviderConfig = {+ id: 'models-only-fill', name: 'Models only fill', auth: { method: 'apiKey' },+ runtimes: { pi: source, 'claude-code': source,+ codex: { ...source, baseUrl: 'https://host.example/v2', models: [chat] } },+ };+ customProviderMocks.readCustomProviderKey.mockResolvedValue('saved-key');+ const user = userEvent.setup();+ render(<ProviderConnectionDialog initial={initial} focusAgent="pi" onSaved={vi.fn()} onClose={vi.fn()} />);+ await waitForInitialDialogFocus();+ await screen.findByText('settings.providers.custom.fields.apiKeySaved');+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.runtimeFill.action' }));+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.runtimeFill.continue' }));+ await user.click(screen.getByRole('checkbox', { name: /settings.providers.custom.runtimeFill.fields.endpointBundle/ }));+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.runtimeFill.applyOverwrite' }));+ await user.click(screen.getByRole('tab', { name: 'settings.providers.custom.protocol.codex' }));+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await waitFor(() => expect(window.electronAPI.maker.testProviderConnection).toHaveBeenCalledWith({+ kind: 'adhoc', spec: expect.objectContaining({ agent: 'codex', baseUrl: 'https://host.example/v2' }),+ }));+ await screen.findByText('settings.providers.custom.test.ok');+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());+ const saved = customProviderMocks.updateCustomProvider.mock.calls[0][0].runtimes.codex;+ expect(saved.baseUrl).toBe('https://host.example/v2');+ expect(saved.models[0].route.baseUrl).toBe(saved.baseUrl);+ expect(saved.models.map((model: { id: string }) => model.id)).toEqual(['chat', 'extra']);+ });+it.each(['target-model', 'flux-image-x'])('keeps %s in standard model settings instead of a second editor', async (modelId) => {const initial: CustomProviderConfig = {id: 'deep-link-provider',diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviderEndpointEdit.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviderEndpointEdit.test.tsnew file mode 100644index 0000000000..5d27463d50--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/customProviderEndpointEdit.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';+import type { ProviderRuntimeModelConfig } from '@cindy/model-providers';+import { modelsAfterProviderEndpointEdit } from '../customProviderEndpointEdit';++describe('editing a custom provider endpoint', () => {+ const oldBase = 'https://old.example.test/v1';+ const models: ProviderRuntimeModelConfig[] = [+ { id: 'inherited', name: 'Inherited' },+ { id: 'responses', name: 'Responses', contextWindow: 64000, defaultEnabled: false,+ route: { baseUrl: oldBase, wireProtocol: 'openai-responses', requestPath: '/responses' } },+ { id: 'independent', name: 'Independent', piApi: 'anthropic-messages',+ route: { baseUrl: 'https://old.example.test/anthropic?version=1',+ wireProtocol: 'anthropic-messages', requestPath: '/messages' } },+ ];++ it.each([+ 'http://127.0.0.1:1234/v2', 'http://192.168.1.12:8000/v1',+ 'https://new.example.test/v1', 'http://old.example.test/v1',+ 'https://old.example.test:8443/v1', 'http://[::1]:8000/v1',+ 'https://old.example.test/v2',+ ])('moves routes to %s while preserving model protocol and independent paths', nextBase => {+ const original = structuredClone(models);+ const result = modelsAfterProviderEndpointEdit(models, oldBase, nextBase);+ expect(result[0]).toBe(models[0]);+ expect(result[1]).toEqual({ ...models[1], route: { ...models[1].route, baseUrl: nextBase } });+ expect(result[2]).toEqual({ ...models[2], route: {+ ...models[2].route, baseUrl: new URL(nextBase).origin + '/anthropic?version=1',+ } });+ expect(models).toEqual(original);+ });++ it('treats a trailing slash as the same base when the connection path changes', () => {+ const model = { ...models[1], route: { ...models[1].route!, baseUrl: oldBase + '/' } };+ expect(modelsAfterProviderEndpointEdit([model], oldBase, 'https://old.example.test/proxy')[0].route)+ .toEqual({ ...model.route, baseUrl: 'https://old.example.test/proxy' });+ });++ it('preserves unchanged/reverted configurations and newly discovered routes', () => {+ expect(modelsAfterProviderEndpointEdit(models, oldBase, oldBase)).toBe(models);+ expect(modelsAfterProviderEndpointEdit(models, undefined, 'http://localhost:1234')).toBe(models);+ const newModel = { ...models[1], route: { ...models[1].route!, baseUrl: 'http://localhost:1234/new' } };+ expect(modelsAfterProviderEndpointEdit([newModel], oldBase, 'http://localhost:1234')[0]).toBe(newModel);+ });++ it.each(['', 'http://', 'ftp://old.example.test/v1', 'https://user:[email protected]/v1'])(+ 'leaves invalid endpoints for the existing validation: %s', endpoint => {+ expect(modelsAfterProviderEndpointEdit(models, oldBase, endpoint)).toBe(models);+ expect(modelsAfterProviderEndpointEdit(models, endpoint, oldBase)).toBe(models);+ },+ );++ it.each(['https://unrelated.example/v1', 'https://user:[email protected]/v1', 'invalid', 'ftp://old.example.test/v1'])(+ 'does not launder an unrelated or invalid route: %s', baseUrl => {+ const model = { ...models[1], route: { ...models[1].route!, baseUrl } };+ expect(modelsAfterProviderEndpointEdit([model], oldBase, 'http://localhost:1234')[0]).toBe(model);+ },+ );+});diff --git a/apps/desktop/src/renderer/lib/customProviderEndpointEdit.ts b/apps/desktop/src/renderer/lib/customProviderEndpointEdit.tsnew file mode 100644index 0000000000..e6aae5d6db--- /dev/null+++ b/apps/desktop/src/renderer/lib/customProviderEndpointEdit.ts@@ -0,0 +1,39 @@+import type { ProviderRuntimeModelConfig } from '@cindy/model-providers';++/**+ * Rebase saved model routes when editing their connection endpoint. Routes that+ * used the connection base follow its full URL; independent paths keep their+ * protocol/path overrides on the new origin. Always compare with the saved base,+ * not intermediate keystrokes, so clearing/retyping or reverting is lossless.+ * Unrelated or invalid routes remain subject to Main's existing validation.+ */+export function modelsAfterProviderEndpointEdit(+ models: ProviderRuntimeModelConfig[],+ previousBaseUrl: string | undefined,+ nextBaseUrl: string,+): ProviderRuntimeModelConfig[] {+ if (!previousBaseUrl) return models;+ const parse = (value: string): URL | undefined => {+ try {+ const url = new URL(value);+ return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password+ ? url : undefined;+ } catch { return undefined; }+ };+ const previous = parse(previousBaseUrl);+ const next = parse(nextBaseUrl);+ if (!previous || !next || previous.href === next.href) return models;+ const sameBase = (left: URL, right: URL) => left.origin === right.origin+ && left.pathname.replace(/\/+$/, '') === right.pathname.replace(/\/+$/, '')+ && left.search === right.search && left.hash === right.hash;+ return models.map(model => {+ if (!model.route) return model;+ const route = parse(model.route.baseUrl);+ if (!route || route.origin !== previous.origin) return model;+ const baseUrl = sameBase(route, previous)+ ? nextBaseUrl.trim()+ : next.origin + route.pathname + route.search + route.hash;+ if (baseUrl === model.route.baseUrl) return model;+ return { ...model, route: { ...model.route, baseUrl } };+ });+}