From b84db8983d63a9a981083ebce1a139860c6bdf25 Mon Sep 17 00:00:00 2001
From: chunhualin1 <chunhualin1@lenovo.com>
Date: 星期五, 14 八月 2026 15:35:21 +0800
Subject: [PATCH] commit
---
src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs | 369 ++++++++++++++++++++++++++++++++++++++++++++++++++++
1 files changed, 366 insertions(+), 3 deletions(-)
diff --git a/src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs b/src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs
index 50b76ed..daaec2c 100644
--- a/src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs
+++ b/src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs
@@ -1,3 +1,4 @@
+using System.Net.Http;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Llm;
@@ -30,7 +31,7 @@
Messages = [new LlmMessage { Role = "user", Content = "hello" }]
}).ToListAsync();
- Assert.Equal("http://127.0.0.1:11434/v1/chat/completions", adapter.LastRequest?.Model.Endpoint);
+ Assert.Equal("http://127.0.0.1:11434/v1/chat/completions", adapter.LastRequest?.Model.GetChatCompletionsUrl());
Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "ok" });
Assert.Contains(events, item => item is LlmCompletedEvent);
}
@@ -88,16 +89,283 @@
Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "ok" });
}
+ [Fact]
+ public async Task StreamChatAsync_UsesBaseUrlOnlyModel()
+ {
+ var adapter = new CapturingAdapter("openai-compatible");
+ var gateway = CreateGateway(adapter, new LlmModelConfig
+ {
+ Id = "model-a",
+ Label = "Model A",
+ Provider = "openai-compatible",
+ BaseUrl = "http://127.0.0.1:11434/v1",
+ ApiModel = "actual-model",
+ Enabled = true
+ });
+
+ await gateway.StreamChatAsync(new LlmChatRequest
+ {
+ RequestId = "req-base",
+ PluginId = "sample.llm-command-palette",
+ InstanceId = "host-1",
+ ModelId = "model-a",
+ Messages = [new LlmMessage { Role = "user", Content = "hello" }]
+ }).ToListAsync();
+
+ Assert.Equal("http://127.0.0.1:11434/v1/chat/completions", adapter.LastRequest?.Model.GetChatCompletionsUrl());
+ }
+
+ [Fact]
+ public async Task StreamChatAsync_ResolvesProviderModelId()
+ {
+ var adapter = new CapturingAdapter("openai-compatible");
+ var gateway = CreateGateway(adapter);
+
+ await gateway.StreamChatAsync(new LlmChatRequest
+ {
+ RequestId = "req-provider",
+ PluginId = "sample.llm-command-palette",
+ InstanceId = "host-1",
+ ModelId = "provider:deepseek:deepseek-v4-flash",
+ Messages = [new LlmMessage { Role = "user", Content = "hello" }],
+ RuntimeConfig = new LlmPluginRuntimeConfig
+ {
+ Providers =
+ [
+ new LlmProviderConfig
+ {
+ Id = "deepseek",
+ Label = "DeepSeek",
+ BaseUrl = "https://api.deepseek.com"
+ }
+ ]
+ }
+ }).ToListAsync();
+
+ Assert.Equal("deepseek-v4-flash", adapter.LastRequest?.Model.ApiModel);
+ Assert.Equal("https://api.deepseek.com/chat/completions", adapter.LastRequest?.Model.GetChatCompletionsUrl());
+ }
+
+ [Fact]
+ public async Task GetModelsAsync_MergesCustomThenProviderAndIsolatesFailures()
+ {
+ var adapter = new CapturingAdapter("openai-compatible")
+ {
+ ListModels = baseUrl => baseUrl.Contains("bad", StringComparison.Ordinal)
+ ? throw new HttpRequestException("down")
+ : ["deepseek-v4-flash"]
+ };
+ var (gateway, diagnostics) = CreateGatewayWithDiagnostics(adapter);
+ var models = await gateway.GetModelsAsync(new LlmPluginRuntimeConfig
+ {
+ DefaultModel = "local-qwen",
+ Models =
+ [
+ new LlmModelConfig
+ {
+ Id = "local-qwen",
+ Label = "qwen2.5:14b",
+ Provider = "openai-compatible",
+ BaseUrl = "http://127.0.0.1:11434/v1",
+ ApiModel = "qwen2.5:14b",
+ Enabled = true
+ }
+ ],
+ Providers =
+ [
+ new LlmProviderConfig { Id = "bad", Label = "Bad", BaseUrl = "https://bad.example" },
+ new LlmProviderConfig { Id = "deepseek", Label = "DeepSeek", BaseUrl = "https://api.deepseek.com" }
+ ]
+ });
+
+ Assert.Equal("local-qwen", models[0].Id);
+ Assert.Equal("qwen2.5:14b(Custom) *", models[0].Label);
+ Assert.Equal("provider:deepseek:deepseek-v4-flash", models[1].Id);
+ Assert.Equal("deepseek-v4-flash(DeepSeek)", models[1].Label);
+ Assert.Equal(2, models.Count);
+ Assert.Contains(diagnostics.Snapshot(), entry => entry.Code == LlmErrorCodes.EndpointUnavailable);
+ Assert.All(diagnostics.Snapshot(), entry =>
+ {
+ Assert.DoesNotContain("sk-", string.Join(" ", entry.Properties.Values), StringComparison.OrdinalIgnoreCase);
+ });
+ }
+
+ [Fact]
+ public async Task GetModelsAsync_FormatsAiChatLabels()
+ {
+ var aiChat = new FakeAiChatClient();
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+
+ var models = await gateway.GetModelsAsync(new LlmPluginRuntimeConfig
+ {
+ Mode = LlmConnectionModes.AiChatApi,
+ AiChat = new AiChatRuntimeConfig
+ {
+ Account = new AiChatAccountConfig { Email = "user@example.com" }
+ }
+ });
+
+ var model = Assert.Single(models);
+ Assert.Equal("deepseek-v4-flash(AiChat)", model.Label);
+ Assert.Equal(1, aiChat.Calls);
+ }
+
+ [Fact]
+ public async Task GetProjectsAsync_ReturnsNotConfiguredWithoutCallingAiChat()
+ {
+ var aiChat = new FakeAiChatClient();
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+
+ var result = await gateway.GetProjectsAsync(new LlmPluginRuntimeConfig
+ {
+ AiChat = new AiChatRuntimeConfig { BaseUrl = "http://192.168.1.111:13000" }
+ });
+
+ Assert.Equal(AiChatProjectStatuses.NotConfigured, result.Status);
+ Assert.Empty(result.Projects);
+ Assert.Equal(0, aiChat.Calls);
+ }
+
+ [Fact]
+ public async Task GetProjectsAsync_ReturnsNotConnectedWhenLoginFails()
+ {
+ var aiChat = new FakeAiChatClient { ThrowOnProjects = new AiChatClientException(LlmErrorCodes.AiChatLoginFailed, "password rejected") };
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+
+ var result = await gateway.GetProjectsAsync(new LlmPluginRuntimeConfig
+ {
+ AiChat = new AiChatRuntimeConfig
+ {
+ Account = new AiChatAccountConfig { Email = "user@example.com" }
+ }
+ });
+
+ Assert.Equal(AiChatProjectStatuses.NotConnected, result.Status);
+ Assert.Equal("password rejected", result.Message);
+ Assert.Empty(result.Projects);
+ }
+
+ [Fact]
+ public async Task MemoryApis_DoNotCallAiChatWhenAccountMissing()
+ {
+ var aiChat = new FakeAiChatClient();
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+ var config = new LlmPluginRuntimeConfig();
+
+ var capabilities = await gateway.GetMemoryCapabilitiesAsync(config);
+ await gateway.GetMemoriesAsync(config, new AiChatGetMemoriesRequest());
+ await gateway.CreateMemoryAsync(config, new AiChatCreateMemoryRequest { Scope = "GLOBAL", Content = "x" });
+ await gateway.DeleteMemoryAsync(config, "mem-1");
+ await gateway.RecallMemoriesAsync(config, new AiChatRecallMemoriesRequest { Query = "hello" });
+
+ Assert.False(capabilities.CanUseMemory);
+ Assert.False(capabilities.CanViewMemory);
+ Assert.False(capabilities.CanManageMemory);
+ Assert.Equal(0, aiChat.Calls);
+ }
+
+ [Fact]
+ public async Task StreamChatAsync_RecordsHostWithoutApiKey()
+ {
+ var adapter = new CapturingAdapter("openai-compatible") { ThrowOnStream = new HttpRequestException("boom") };
+ var (gateway, diagnostics) = CreateGatewayWithDiagnostics(adapter, new LlmModelConfig
+ {
+ Id = "model-a",
+ Label = "Model A",
+ Provider = "openai-compatible",
+ BaseUrl = "https://api.deepseek.com",
+ ApiModel = "deepseek-v4-flash",
+ Enabled = true
+ });
+
+ await gateway.StreamChatAsync(new LlmChatRequest
+ {
+ RequestId = "req-fail",
+ PluginId = "sample.llm-command-palette",
+ InstanceId = "host-1",
+ ModelId = "model-a",
+ Messages = [new LlmMessage { Role = "user", Content = "hello" }]
+ }).ToListAsync();
+
+ var entry = Assert.Single(diagnostics.Snapshot(), item => item.Code == LlmErrorCodes.EndpointUnavailable);
+ Assert.Equal("api.deepseek.com", entry.Properties["endpointHost"]);
+ Assert.DoesNotContain("test-key", string.Join(" ", entry.Properties.Select(pair => pair.Key + pair.Value)));
+ }
+
+ [Fact]
+ public async Task StreamChatAsync_UsesAiChatClientWhenModeIsAiChatApi()
+ {
+ var aiChat = new FakeAiChatClient();
+ var gateway = CreateGateway(
+ new CapturingAdapter("openai-compatible"),
+ aiChat,
+ new LlmModelConfig
+ {
+ Id = "provider-model",
+ Label = "Provider",
+ Provider = "openai-compatible",
+ Endpoint = "http://127.0.0.1:11434/v1/chat/completions",
+ ApiModel = "provider-model",
+ Enabled = true
+ });
+
+ var events = await gateway.StreamChatAsync(new LlmChatRequest
+ {
+ RequestId = "req-aichat",
+ PluginId = "sample.llm-command-palette",
+ InstanceId = "host-1",
+ Mode = LlmConnectionModes.AiChatApi,
+ ProjectId = "project-1",
+ ModelId = "deepseek-v4-flash",
+ Messages = [new LlmMessage { Role = "user", Content = "hello" }],
+ RuntimeConfig = new LlmPluginRuntimeConfig { Mode = LlmConnectionModes.AiChatApi }
+ }).ToListAsync();
+
+ Assert.Equal("project-1", aiChat.LastRequest?.ProjectId);
+ Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "from-aichat" });
+ }
+
+ [Fact]
+ public async Task GetModelsAsync_AiChatModeWithoutAccountDoesNotCallClient()
+ {
+ var aiChat = new FakeAiChatClient();
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+
+ var models = await gateway.GetModelsAsync(new LlmPluginRuntimeConfig
+ {
+ Mode = LlmConnectionModes.AiChatApi,
+ AiChat = new AiChatRuntimeConfig { BaseUrl = "http://192.168.1.111:13000" }
+ });
+
+ Assert.Empty(models);
+ Assert.Equal(0, aiChat.Calls);
+ }
+
private static LlmGatewayService CreateGateway(CapturingAdapter adapter, params LlmModelConfig[] models)
+ => CreateGatewayWithDiagnostics(adapter, null, models).Gateway;
+
+ private static LlmGatewayService CreateGateway(CapturingAdapter adapter, IAiChatClient? aiChatClient, params LlmModelConfig[] models)
+ => CreateGatewayWithDiagnostics(adapter, aiChatClient, models).Gateway;
+
+ private static (LlmGatewayService Gateway, DiagnosticsService Diagnostics) CreateGatewayWithDiagnostics(
+ CapturingAdapter adapter,
+ params LlmModelConfig[] models)
+ => CreateGatewayWithDiagnostics(adapter, null, models);
+
+ private static (LlmGatewayService Gateway, DiagnosticsService Diagnostics) CreateGatewayWithDiagnostics(
+ CapturingAdapter adapter,
+ IAiChatClient? aiChatClient,
+ params LlmModelConfig[] models)
{
var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N"));
var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local"));
var diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance);
- return new LlmGatewayService(
+ return (new LlmGatewayService(
new InMemoryRegistry(models),
new EnvironmentCredentialStore(),
new LlmProviderAdapterFactory([adapter]),
- diagnostics);
+ diagnostics,
+ aiChatClient), diagnostics);
}
private sealed class InMemoryRegistry(IEnumerable<LlmModelConfig> models) : ILlmModelRegistry
@@ -115,6 +383,8 @@
{
public string Provider { get; } = provider;
public LlmProviderRequest? LastRequest { get; private set; }
+ public Func<string, IReadOnlyList<string>>? ListModels { get; set; }
+ public Exception? ThrowOnStream { get; set; }
public async IAsyncEnumerable<LlmProviderChunk> StreamAsync(
LlmProviderRequest request,
@@ -122,9 +392,102 @@
{
await Task.Yield();
LastRequest = request;
+ if (ThrowOnStream is not null)
+ {
+ throw ThrowOnStream;
+ }
+
yield return new LlmProviderChunk { Delta = "ok" };
yield return new LlmProviderChunk { IsCompleted = true };
}
+
+ public Task<IReadOnlyList<string>> ListModelIdsAsync(
+ string baseUrl,
+ string? apiKey,
+ CancellationToken cancellationToken = default)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ return Task.FromResult(ListModels?.Invoke(baseUrl) ?? (IReadOnlyList<string>)[]);
+ }
+ }
+
+ private sealed class FakeAiChatClient : IAiChatClient
+ {
+ public LlmChatRequest? LastRequest { get; private set; }
+ public int Calls { get; private set; }
+ public Exception? ThrowOnProjects { get; set; }
+
+ public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
+ {
+ Calls++;
+ return Task.FromResult<IReadOnlyList<LlmModelSummary>>(
+ [
+ new LlmModelSummary
+ {
+ Id = "deepseek-v4-flash",
+ Label = "deepseek-v4-flash",
+ Provider = "aichat",
+ SupportsStreaming = true,
+ Enabled = true
+ }
+ ]);
+ }
+
+ public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
+ {
+ Calls++;
+ if (ThrowOnProjects is not null)
+ {
+ throw ThrowOnProjects;
+ }
+
+ return Task.FromResult<IReadOnlyList<AiChatProjectSummary>>(
+ [
+ new AiChatProjectSummary { Id = "project-1", Name = "Project 1" }
+ ]);
+ }
+
+ public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
+ LlmChatRequest request,
+ LlmPluginRuntimeConfig runtimeConfig,
+ [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
+ {
+ Calls++;
+ await Task.Yield();
+ LastRequest = request;
+ yield return new LlmDeltaEvent { RequestId = request.RequestId, Delta = "from-aichat" };
+ yield return new LlmCompletedEvent { RequestId = request.RequestId };
+ }
+
+ public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
+ {
+ Calls++;
+ return Task.FromResult(new AiChatMemoryCapabilities());
+ }
+
+ public Task<AiChatJsonResult> GetMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default)
+ {
+ Calls++;
+ return Task.FromResult(new AiChatJsonResult());
+ }
+
+ public Task<AiChatJsonResult> CreateMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default)
+ {
+ Calls++;
+ return Task.FromResult(new AiChatJsonResult());
+ }
+
+ public Task DeleteMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default)
+ {
+ Calls++;
+ return Task.CompletedTask;
+ }
+
+ public Task<AiChatJsonResult> RecallMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default)
+ {
+ Calls++;
+ return Task.FromResult(new AiChatJsonResult());
+ }
}
}
--
Gitblit v1.9.1