基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-17 9b5711d3124622b1f1b18500d442c76492da877a
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
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
 
namespace Moli.Desktop.Llm;
 
public sealed class LlmModelRegistry : ILlmModelRegistry
{
    public const string FileName = "llm-models.json";
 
    private readonly DesktopPaths _paths;
    private readonly IDiagnosticsService _diagnostics;
    private readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        PropertyNameCaseInsensitive = true,
        WriteIndented = true,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
    };
 
    public LlmModelRegistry(DesktopPaths paths, IDiagnosticsService diagnostics)
    {
        _paths = paths;
        _diagnostics = diagnostics;
    }
 
    public async Task<LlmSettingsDocument> LoadAsync(CancellationToken cancellationToken = default)
    {
        Directory.CreateDirectory(_paths.ConfigDirectory);
        var path = Path.Combine(_paths.ConfigDirectory, FileName);
 
        if (!File.Exists(path))
        {
            var created = CreateDefault();
            await SaveAsync(created, cancellationToken).ConfigureAwait(false);
            return created;
        }
 
        try
        {
            await using var stream = File.OpenRead(path);
            var document = await JsonSerializer.DeserializeAsync<LlmSettingsDocument>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
            if (document is null || document.SchemaVersion <= 0)
            {
                throw new JsonException("LLM settings document is empty or missing schemaVersion.");
            }
 
            return Normalize(document);
        }
        catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
        {
            BackupInvalidFile(path);
            var recovered = CreateDefault();
            await SaveAsync(recovered, cancellationToken).ConfigureAwait(false);
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.ConfigurationRecovered,
                "Recovered llm-models.json from invalid configuration.",
                new Dictionary<string, string> { ["exception"] = ex.GetType().Name });
            return recovered;
        }
    }
 
    public async Task<LlmModelConfig?> GetEnabledModelAsync(string modelId, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(modelId))
        {
            return null;
        }
 
        var document = await LoadAsync(cancellationToken).ConfigureAwait(false);
        return document.Models.FirstOrDefault(model =>
            model.Enabled &&
            string.Equals(model.Id, modelId, StringComparison.OrdinalIgnoreCase));
    }
 
    private async Task SaveAsync(LlmSettingsDocument document, CancellationToken cancellationToken)
    {
        Directory.CreateDirectory(_paths.ConfigDirectory);
        var path = Path.Combine(_paths.ConfigDirectory, FileName);
        var tempPath = path + ".tmp";
        var backupPath = path + ".bak";
 
        await using (var stream = File.Create(tempPath))
        {
            await JsonSerializer.SerializeAsync(stream, document, _jsonOptions, cancellationToken).ConfigureAwait(false);
        }
 
        if (File.Exists(path))
        {
            File.Copy(path, backupPath, overwrite: true);
        }
 
        File.Move(tempPath, path, overwrite: true);
    }
 
    private LlmSettingsDocument Normalize(LlmSettingsDocument document)
    {
        var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        var normalized = new List<LlmModelConfig>();
 
        foreach (var model in document.Models)
        {
            if (!IsValidModel(model, seen))
            {
                continue;
            }
 
            seen.Add(model.Id);
            normalized.Add(model with
            {
                BaseUrl = model.GetBaseUrl(),
                Endpoint = null
            });
        }
 
        var defaultModel = normalized.Any(model =>
            model.Enabled &&
            string.Equals(model.Id, document.DefaultModel, StringComparison.OrdinalIgnoreCase))
                ? document.DefaultModel
                : normalized.FirstOrDefault(model => model.Enabled)?.Id;
 
        return document with
        {
            DefaultModel = defaultModel,
            Models = normalized
        };
    }
 
    private bool IsValidModel(LlmModelConfig model, HashSet<string> seen)
    {
        if (string.IsNullOrWhiteSpace(model.Id) || seen.Contains(model.Id))
        {
            RecordInvalid(model.Id, "Model id is empty or duplicated.");
            return false;
        }
 
        if (string.IsNullOrWhiteSpace(model.Label) || model.Label.Length > 40)
        {
            RecordInvalid(model.Id, "Model label is empty or too long.");
            return false;
        }
 
        if (string.IsNullOrWhiteSpace(model.Provider))
        {
            RecordInvalid(model.Id, "Model provider is required.");
            return false;
        }
 
        if (!LlmOpenAiUrls.IsAbsoluteHttpUrl(model.GetBaseUrl()))
        {
            RecordInvalid(model.Id, "Model baseUrl must be an absolute HTTP or HTTPS URL.");
            return false;
        }
 
        if (string.IsNullOrWhiteSpace(model.ApiModel))
        {
            RecordInvalid(model.Id, "apiModel is required.");
            return false;
        }
 
        return true;
    }
 
    private void RecordInvalid(string? modelId, string message)
    {
        _diagnostics.Record(
            DiagnosticSeverity.Warning,
            "LlmModelInvalid",
            message,
            new Dictionary<string, string> { ["modelId"] = modelId ?? "" });
    }
 
    private static LlmSettingsDocument CreateDefault() => new()
    {
        DefaultModel = null,
        Models =
        [
            new LlmModelConfig
            {
                Id = "local-openai-compatible",
                Label = "Local",
                Provider = "openai-compatible",
                BaseUrl = "http://127.0.0.1:11434/v1",
                AuthRef = null,
                ApiModel = "qwen2.5:14b",
                SupportsStreaming = true,
                Enabled = false
            }
        ]
    };
 
    private static void BackupInvalidFile(string path)
    {
        if (!File.Exists(path))
        {
            return;
        }
 
        var timestamp = DateTimeOffset.Now.ToString("yyyyMMddHHmmss");
        var invalidPath = Path.Combine(
            Path.GetDirectoryName(path)!,
            $"{Path.GetFileNameWithoutExtension(path)}.invalid.{timestamp}{Path.GetExtension(path)}");
        File.Move(path, invalidPath, overwrite: true);
    }
}