-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
1492 lines (1361 loc) · 55.5 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
1492 lines (1361 loc) · 55.5 KB
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Media;
using KimiMultilingual.Services;
using Microsoft.Web.WebView2.Core;
using Button = System.Windows.Controls.Button;
using Brush = System.Windows.Media.Brush;
using Color = System.Windows.Media.Color;
using FontFamily = System.Windows.Media.FontFamily;
using HorizontalAlignment = System.Windows.HorizontalAlignment;
using Key = System.Windows.Input.Key;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using Point = System.Windows.Point;
using SystemColors = System.Windows.SystemColors;
using VerticalAlignment = System.Windows.VerticalAlignment;
namespace KimiMultilingual;
public partial class MainWindow : Window
{
public const string ProjectContact = "Discord: NN6";
private const string OnboardingCompleteMessage = "kimi-multilingual:onboarding-complete";
private const string OnboardingBridgeScript = """
(() => {
if (window.__kimiMultilingualOnboardingBridge) return;
window.__kimiMultilingualOnboardingBridge = true;
const key = 'kimi-web.onboarded';
const message = 'kimi-multilingual:onboarding-complete';
let sent = false;
let timer = 0;
const report = () => {
if (sent) return;
try {
if (localStorage.getItem(key) !== '1') return;
sent = true;
window.chrome?.webview?.postMessage(message);
if (timer) window.clearInterval(timer);
} catch {
// Kimi Web remains usable if browser storage is unavailable.
}
};
timer = window.setInterval(report, 250);
report();
window.addEventListener('pagehide', () => window.clearInterval(timer), { once: true });
})();
""";
private readonly CancellationTokenSource _lifetime = new();
private readonly string? _updateDemoVersion =
Environment.GetEnvironmentVariable("KIMI_MULTILINGUAL_UPDATE_DEMO_VERSION");
private AppPaths? _paths;
private KimiServerHost? _server;
private LlamaCppModelHost? _localModel;
private AirLlmServerHost? _airLlm;
private KimiUpdateService? _updateService;
private DesktopNotification? _desktopNotification;
private KimiUpdateStatus? _updateStatus;
private RuntimePreference? _runtimePreference;
private IReadOnlyList<LocalModelDefinition> _localModels = Array.Empty<LocalModelDefinition>();
private LocalModelDefinition? _activeLocalModel;
private LocalModelState? _lastLocalModelState;
private bool _webViewInitialized;
private bool _onboardingStateLoaded;
private bool _onboardingComplete;
private bool _shuttingDown;
private bool _allowClose;
private bool _syncingUpdatePreference;
private bool _switchingRuntime;
private bool _recoveringRuntime;
private int _runtimeRecoveryAttempts;
private DateTimeOffset _runtimeRecoveryWindowStarted;
private DateTimeOffset _runtimeCenterClosedAt;
public MainWindow()
{
InitializeComponent();
ProjectContactText.Text = ProjectContact;
ApplyHighContrastChrome();
}
private void ApplyHighContrastChrome()
{
if (!SystemParameters.HighContrast)
{
return;
}
OuterFrame.Background = SystemColors.WindowBrush;
OuterFrame.BorderBrush = SystemColors.WindowTextBrush;
CommandBar.Background = SystemColors.ControlBrush;
LoadingOverlay.Background = SystemColors.WindowBrush;
LoadingLocalGlow.Visibility = Visibility.Collapsed;
LoadingCloudGlow.Visibility = Visibility.Collapsed;
LoadingCard.Background = SystemColors.WindowBrush;
LoadingCard.BorderBrush = SystemColors.WindowTextBrush;
LoadingCard.Effect = null;
LoadingModeBadge.Background = SystemColors.ControlBrush;
LoadingModeBadge.BorderBrush = SystemColors.WindowTextBrush;
LoadingModeBadgeText.Foreground = SystemColors.WindowTextBrush;
RuntimeCenterSurface.Background = SystemColors.WindowBrush;
RuntimeCenterSurface.BorderBrush = SystemColors.WindowTextBrush;
RuntimeCenterSurface.Effect = null;
RuntimeActiveCard.Background = SystemColors.ControlBrush;
RuntimeActiveCard.BorderBrush = SystemColors.WindowTextBrush;
}
private async void OnLoaded(object sender, RoutedEventArgs e)
{
_desktopNotification = new DesktopNotification();
ApplyResponsiveChrome(ActualWidth);
if (!SystemParameters.ClientAreaAnimation || SystemParameters.HighContrast)
{
RuntimeCenterPopup.PopupAnimation = System.Windows.Controls.Primitives.PopupAnimation.None;
}
StartAmbientMotion();
await StartWorkspaceAsync();
}
private void OnSourceInitialized(object? sender, EventArgs e)
{
WindowBackdrop.TryApply(this);
}
private void OnWindowStateChanged(object? sender, EventArgs e)
{
var maximized = WindowState == WindowState.Maximized;
OuterFrame.CornerRadius = maximized ? new CornerRadius(0) : new CornerRadius(14);
OuterFrame.BorderThickness = maximized ? new Thickness(0) : new Thickness(1);
MaximizeGlyph.Text = maximized ? "\uE923" : "\uE922";
MaximizeButton.ToolTip = maximized ? "Restore" : "Maximize";
AutomationProperties.SetName(MaximizeButton, maximized ? "Restore" : "Maximize");
}
private void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
ApplyResponsiveChrome(e.NewSize.Width);
}
private void ApplyResponsiveChrome(double width)
{
var compact = width < 1260;
BrandBadge.Visibility = width < 1360 ? Visibility.Collapsed : Visibility.Visible;
BrandSubtitle.Visibility = width < 1420 ? Visibility.Collapsed : Visibility.Visible;
BrandDetails.Visibility = width < 1080 ? Visibility.Collapsed : Visibility.Visible;
HeaderStatusPill.Visibility = width < 1120 ? Visibility.Collapsed : Visibility.Visible;
EngineVersionText.Visibility = width < 1320 ? Visibility.Collapsed : Visibility.Visible;
OpenBrowserButton.Visibility = width < 1180 ? Visibility.Collapsed : Visibility.Visible;
HeaderStatusPill.MaxWidth = compact ? 270 : 360;
RuntimeModeButton.MaxWidth = compact ? 176 : 206;
}
private async Task StartWorkspaceAsync()
{
LoadingTitle.Text = "Opening your multilingual Kimi space";
SetLoading("Starting Kimi workspace… | جارٍ تشغيل مساحة عمل كيمي…");
RetryButton.Visibility = Visibility.Collapsed;
LoadingProgress.Visibility = Visibility.Visible;
ReloadButton.IsEnabled = false;
OpenBrowserButton.IsEnabled = false;
RuntimeModeButton.IsEnabled = false;
LocalModelButton.IsEnabled = false;
LocalModelButtonText.Text = "Checking…";
LocalModelDot.Fill = new SolidColorBrush(Color.FromRgb(242, 197, 103));
ConnectionDot.Fill = new SolidColorBrush(Color.FromRgb(240, 185, 77));
try
{
if (_server is not null)
{
_server.UnexpectedExit -= OnRuntimeUnexpectedExit;
await _server.DisposeAsync();
_server = null;
}
if (_localModel is not null)
{
_localModel.UnexpectedExit -= OnRuntimeUnexpectedExit;
await _localModel.DisposeAsync();
_localModel = null;
}
if (_airLlm is not null)
{
_airLlm.UnexpectedExit -= OnRuntimeUnexpectedExit;
await _airLlm.DisposeAsync();
_airLlm = null;
}
_paths ??= AppPaths.Discover();
if (!_onboardingStateLoaded)
{
_onboardingComplete = await KimiOnboardingStore.LoadAsync(_paths, _lifetime.Token);
_onboardingStateLoaded = true;
}
_runtimePreference ??= await RuntimePreferenceStore.LoadAsync(_paths, _lifetime.Token);
await KimiLocalConfigMigration.ApplyAsync(
_paths,
_runtimePreference.Kind,
_lifetime.Token);
_localModels = LocalModelCatalog.Discover(_paths);
KimiModelEnvironment? modelEnvironment = null;
string runtimeLabel;
if (_runtimePreference.Kind == KimiRuntimeKind.AirLlmK3)
{
_activeLocalModel = null;
_lastLocalModelState = null;
LocalModelButton.Visibility = Visibility.Visible;
_airLlm = new AirLlmServerHost(_paths, SetLocalModelStateThreadSafe);
_airLlm.UnexpectedExit += OnRuntimeUnexpectedExit;
UpdateRuntimeModeUi();
await _airLlm.StartAsync(_lifetime.Token);
modelEnvironment = _airLlm.CreateKimiModelEnvironment();
runtimeLabel = AirLlmServerHost.DisplayName;
}
else if (_runtimePreference.Kind == KimiRuntimeKind.LocalGguf)
{
_activeLocalModel = LocalModelCatalog.Resolve(_localModels, _runtimePreference.LocalModelPath)
?? throw new FileNotFoundException(
$"No runnable GGUF checkpoint was found under {Path.Combine(_paths.KimiRoot, "models")}.");
_lastLocalModelState = null;
LocalModelButton.Visibility = Visibility.Visible;
_localModel = new LlamaCppModelHost(_paths, SetLocalModelStateThreadSafe, _activeLocalModel);
_localModel.UnexpectedExit += OnRuntimeUnexpectedExit;
UpdateRuntimeModeUi();
await _localModel.StartAsync(_lifetime.Token);
modelEnvironment = _localModel.CreateKimiModelEnvironment();
runtimeLabel = _activeLocalModel.CompactDisplayName;
}
else
{
_activeLocalModel = null;
_lastLocalModelState = null;
LocalModelButton.Visibility = Visibility.Collapsed;
runtimeLabel = "Original Kimi cloud";
SetLocalModelStateThreadSafe(new LocalModelState(runtimeLabel, false, false));
UpdateRuntimeModeUi();
}
// Runtime initialization can take many minutes for Kimi K3. Reflect the
// persisted selection before awaiting it so the loading screen never
// mislabels AirLLM as the default GGUF runtime.
UpdateRuntimeModeUi();
// The Kimi child must inherit this launch's private endpoint and API
// token, so attaching to a pre-existing server is deliberately disabled.
_server = new KimiServerHost(_paths, SetStatusThreadSafe, modelEnvironment, allowAttach: false);
_server.UnexpectedExit += OnRuntimeUnexpectedExit;
await _server.StartAsync(_lifetime.Token);
EngineVersionText.Text = $"Kimi Code {_server.ServerVersion ?? "local"} - {runtimeLabel}";
UpdateRuntimeModeUi();
// This build carries local compatibility fixes in its Kimi engine.
// An upstream auto-update would replace those fixes, so updates are
// intentionally pinned to app releases that are tested as a unit.
UpdateButton.Visibility = Visibility.Collapsed;
UpdateBanner.Visibility = Visibility.Collapsed;
AutoUpdateCheckBox.IsChecked = false;
AutoUpdateCheckBox.IsEnabled = false;
InstallUpdateButton.IsEnabled = false;
await InitializeWebViewAsync(_paths);
if (Environment.GetEnvironmentVariable("KIMI_MULTILINGUAL_RTL_DEMO") == "1")
{
KimiWebView.Source = new Uri("https://kimi-multilingual.test/rtl-showcase.html");
}
else
{
KimiWebView.Source = GetKimiWebUri();
}
ReloadButton.IsEnabled = true;
OpenBrowserButton.IsEnabled = true;
RuntimeModeButton.IsEnabled = true;
if (!_recoveringRuntime)
{
_runtimeRecoveryAttempts = 0;
}
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
{
}
catch (Exception error)
{
if (_server is not null)
{
try
{
_server.UnexpectedExit -= OnRuntimeUnexpectedExit;
await _server.DisposeAsync();
}
catch
{
// Preserve the startup error shown below.
}
_server = null;
}
if (_localModel is not null)
{
try
{
_localModel.UnexpectedExit -= OnRuntimeUnexpectedExit;
await _localModel.DisposeAsync();
}
catch
{
// Preserve the startup error shown below.
}
_localModel = null;
}
if (_airLlm is not null)
{
try
{
_airLlm.UnexpectedExit -= OnRuntimeUnexpectedExit;
await _airLlm.DisposeAsync();
}
catch
{
// Preserve the startup error shown below.
}
_airLlm = null;
}
ShowError(error);
}
finally
{
RuntimeModeButton.IsEnabled = !_shuttingDown && !_switchingRuntime && !_recoveringRuntime;
}
}
private async Task InitializeWebViewAsync(AppPaths paths)
{
if (_webViewInitialized)
{
return;
}
SetLoading("Starting browser-grade multilingual renderer… | جارٍ تشغيل عارض اللغات…");
var environment = await CoreWebView2Environment.CreateAsync(
browserExecutableFolder: null,
userDataFolder: paths.WebViewProfile);
await KimiWebView.EnsureCoreWebView2Async(environment);
var core = KimiWebView.CoreWebView2;
core.Settings.AreDevToolsEnabled = false;
core.Settings.IsStatusBarEnabled = false;
core.Settings.AreBrowserAcceleratorKeysEnabled = true;
core.Settings.IsZoomControlEnabled = true;
if (Environment.GetEnvironmentVariable("KIMI_MULTILINGUAL_RTL_DEMO") == "1")
{
core.SetVirtualHostNameToFolderMapping(
"kimi-multilingual.test",
Path.GetDirectoryName(paths.ShowcasePath)!,
CoreWebView2HostResourceAccessKind.DenyCors);
}
var bidiScript = await File.ReadAllTextAsync(paths.BidiScriptPath, _lifetime.Token);
await core.AddScriptToExecuteOnDocumentCreatedAsync(bidiScript);
await core.AddScriptToExecuteOnDocumentCreatedAsync(OnboardingBridgeScript);
core.NavigationStarting += OnNavigationStarting;
core.NavigationCompleted += OnNavigationCompleted;
core.NewWindowRequested += OnNewWindowRequested;
core.ProcessFailed += OnWebProcessFailed;
core.WebMessageReceived += OnWebMessageReceived;
_webViewInitialized = true;
}
private void OnNavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e)
{
if (IsLocalKimiUri(e.Uri))
{
return;
}
e.Cancel = true;
OpenExternalUri(e.Uri);
}
private void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e)
{
e.Handled = true;
if (IsLocalKimiUri(e.Uri) && Uri.TryCreate(e.Uri, UriKind.Absolute, out var localUri))
{
KimiWebView.Source = localUri;
return;
}
OpenExternalUri(e.Uri);
}
private async void OnNavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
{
if (!e.IsSuccess)
{
if (e.WebErrorStatus == CoreWebView2WebErrorStatus.OperationCanceled)
{
return;
}
ShowError(new InvalidOperationException($"Kimi Web failed to load: {e.WebErrorStatus}"));
return;
}
// A successful document is usable immediately. Direction QA runs after
// reveal so valid non-chat routes (including the one-time welcome page)
// can never be hidden behind a composer-specific startup check.
KimiWebView.Visibility = Visibility.Visible;
LoadingOverlay.Visibility = Visibility.Collapsed;
ConnectionDot.Fill = new SolidColorBrush(Color.FromRgb(82, 227, 164));
HeaderStatusText.Text = "Connected · Automatic direction";
HeaderStatusText.ToolTip = null;
try
{
if (!await VerifyBidiPolicyAsync())
{
ConnectionDot.Fill = new SolidColorBrush(Color.FromRgb(242, 197, 103));
HeaderStatusText.Text = "Connected · Direction helper needs attention";
HeaderStatusText.ToolTip = "The page is usable, but automatic RTL/LTR initialization did not pass its check.";
}
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
{
}
catch (Exception error)
{
// Renderer diagnostics must not replace a working Kimi page. Keep
// the application usable and expose the diagnostic in the status UI.
ConnectionDot.Fill = new SolidColorBrush(Color.FromRgb(242, 197, 103));
HeaderStatusText.Text = "Connected · Direction check unavailable";
HeaderStatusText.ToolTip = error.Message;
}
}
private void OnWebProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e)
{
ShowError(new InvalidOperationException($"The multilingual renderer stopped: {e.ProcessFailedKind}"));
}
private async void OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
{
if (_onboardingComplete || _paths is null || !IsLocalKimiUri(e.Source))
{
return;
}
string message;
try
{
message = e.TryGetWebMessageAsString();
}
catch (ArgumentException)
{
return;
}
if (!message.Equals(OnboardingCompleteMessage, StringComparison.Ordinal))
{
return;
}
_onboardingComplete = true;
try
{
await KimiOnboardingStore.MarkCompletedAsync(
_paths,
"web-onboarding-completed",
_lifetime.Token);
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
{
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{
_onboardingComplete = false;
HeaderStatusText.Text = "Connected · first-run choice could not be saved";
}
}
private async Task<bool> VerifyBidiPolicyAsync()
{
const string probe = """
(() => {
const composer = document.querySelector('textarea, [contenteditable="true"], [role="textbox"]');
const sentMessages = Array.from(document.querySelectorAll('.u-text'));
const style = composer ? getComputedStyle(composer) : null;
return {
composerFound: composer !== null,
composerDirection: composer?.getAttribute('dir') ?? null,
composerUnicodeBidi: style?.unicodeBidi ?? null,
sentMessagesFound: sentMessages.length,
sentMessagesReady: sentMessages.every((node) => node.getAttribute('dir') === 'auto'),
};
})()
""";
var sawDirectionSensitiveContent = false;
for (var attempt = 0; attempt < 30; attempt++)
{
var result = await KimiWebView.CoreWebView2.ExecuteScriptAsync(probe);
using var document = JsonDocument.Parse(result);
var root = document.RootElement;
var composerFound = root.GetProperty("composerFound").GetBoolean();
var composerDirection = root.GetProperty("composerDirection").GetString();
var composerUnicodeBidi = root.GetProperty("composerUnicodeBidi").GetString();
var sentMessagesFound = root.GetProperty("sentMessagesFound").GetInt32();
var sentMessagesReady = root.GetProperty("sentMessagesReady").GetBoolean();
sawDirectionSensitiveContent |= composerFound || sentMessagesFound > 0;
if (ShouldAcceptBidiProbe(
composerFound,
composerDirection,
composerUnicodeBidi,
sentMessagesFound,
sentMessagesReady,
sawDirectionSensitiveContent,
attempt))
{
return true;
}
await Task.Delay(200, _lifetime.Token);
}
return !sawDirectionSensitiveContent;
}
internal static bool ShouldAcceptBidiProbe(
bool composerFound,
string? composerDirection,
string? composerUnicodeBidi,
int sentMessagesFound,
bool sentMessagesReady,
bool sawDirectionSensitiveContent,
int attempt)
{
var relevant = sawDirectionSensitiveContent || composerFound || sentMessagesFound > 0;
var ready = (!composerFound ||
(composerDirection == "auto" && composerUnicodeBidi == "plaintext")) &&
(composerFound || sentMessagesFound > 0) &&
sentMessagesReady;
if (ready)
{
return true;
}
// Welcome, settings, and other valid Kimi routes have no composer.
// Give the SPA a short render window, then accept an irrelevant route.
return !relevant && attempt >= 2;
}
private void OnReload(object sender, RoutedEventArgs e)
{
KimiWebView.Reload();
}
private void OnMinimize(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void OnMaximizeRestore(object sender, RoutedEventArgs e)
{
WindowState = WindowState == WindowState.Maximized
? WindowState.Normal
: WindowState.Maximized;
}
private void OnCloseWindow(object sender, RoutedEventArgs e)
{
Close();
}
private void OnUpdateButton(object sender, RoutedEventArgs e)
{
if (UpdateBanner.Visibility == Visibility.Visible)
{
HideUpdateBanner();
}
else
{
ShowUpdateBanner();
}
}
private void OnDismissUpdate(object sender, RoutedEventArgs e)
{
HideUpdateBanner();
}
private async void OnAutoUpdateChanged(object sender, RoutedEventArgs e)
{
if (_syncingUpdatePreference || _updateService is null)
{
return;
}
await _updateService.SetAutomaticInstallAsync(AutoUpdateCheckBox.IsChecked == true, _lifetime.Token);
}
private async void OnInstallUpdate(object sender, RoutedEventArgs e)
{
if (_updateService is null)
{
return;
}
if (_updateStatus?.Phase == KimiUpdatePhase.RestartPending)
{
if (_server is null)
{
return;
}
var confirmation = System.Windows.MessageBox.Show(
"The verified Kimi update is installed.\n\n" +
"Send any unsent draft first. Restarting reloads the local Kimi page, while saved session history and files remain in place.\n\n" +
"تم تثبيت التحديث. أرسل أي مسودة غير مرسلة أولاً، ثم أعد تشغيل المحرك.\n\n" +
"Restart the local Kimi engine now?",
"Restart Kimi engine",
MessageBoxButton.YesNo,
MessageBoxImage.Information,
MessageBoxResult.No);
if (confirmation != MessageBoxResult.Yes)
{
return;
}
InstallUpdateButton.IsEnabled = false;
SetLoading("Restarting the verified Kimi engine… | جارٍ إعادة تشغيل محرك كيمي المحدّث…");
try
{
await _server.RestartAsync(_lifetime.Token);
_updateService.SetRunningVersion(_server.ServerVersion);
KimiWebView.Source = GetKimiWebUri();
await _updateService.CheckNowAsync(_lifetime.Token);
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
{
}
catch (Exception error)
{
ShowError(error);
}
return;
}
await _updateService.InstallAvailableAsync(_lifetime.Token);
}
private void OnOpenInBrowser(object sender, RoutedEventArgs e)
{
if (_server?.WebUri is null)
{
return;
}
Process.Start(new ProcessStartInfo(GetKimiWebUri()!.AbsoluteUri) { UseShellExecute = true });
}
private bool IsLocalKimiUri(string value)
{
if (value.Equals("about:blank", StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (Environment.GetEnvironmentVariable("KIMI_MULTILINGUAL_RTL_DEMO") == "1" &&
Uri.TryCreate(value, UriKind.Absolute, out var demoUri) &&
demoUri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) &&
demoUri.Host.Equals("kimi-multilingual.test", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return _server is not null &&
Uri.TryCreate(value, UriKind.Absolute, out var uri) &&
uri.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) &&
uri.Host.Equals("127.0.0.1", StringComparison.OrdinalIgnoreCase) &&
uri.Port == _server.Port;
}
private Uri? GetKimiWebUri() => _server?.WebUri is { } webUri
? KimiOnboardingStore.ApplyCompletionFlag(webUri, _onboardingComplete)
: null;
private static void OpenExternalUri(string value)
{
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri) ||
(uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
{
return;
}
Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true });
}
private async void OnRetry(object sender, RoutedEventArgs e)
{
_runtimeRecoveryAttempts = 0;
await StartWorkspaceAsync();
}
private void OnRuntimeUnexpectedExit(object? sender, EventArgs e)
{
_ = Dispatcher.BeginInvoke(new Action(() => _ = RecoverWorkspaceAsync()));
}
private async Task RecoverWorkspaceAsync()
{
if (_shuttingDown || _switchingRuntime || _recoveringRuntime)
{
return;
}
var now = DateTimeOffset.UtcNow;
if (_runtimeRecoveryWindowStarted == default ||
now - _runtimeRecoveryWindowStarted > TimeSpan.FromMinutes(5))
{
_runtimeRecoveryWindowStarted = now;
_runtimeRecoveryAttempts = 0;
}
if (_runtimeRecoveryAttempts >= 2)
{
ShowError(new InvalidOperationException(
"The selected runtime stopped repeatedly. Choose Original Kimi, AirLLM K3, or another GGUF model, then Retry."));
return;
}
_runtimeRecoveryAttempts++;
_recoveringRuntime = true;
RuntimeModeButton.IsEnabled = false;
try
{
SetLoading("Recovering the selected Kimi runtime...");
await Task.Delay(750, _lifetime.Token);
await StartWorkspaceAsync();
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
{
}
finally
{
_recoveringRuntime = false;
RuntimeModeButton.IsEnabled = !_shuttingDown && !_switchingRuntime;
}
}
private void OnRuntimeMode(object sender, RoutedEventArgs e)
{
if (_paths is null || _switchingRuntime)
{
return;
}
if (RuntimeCenterPopup.IsOpen)
{
RuntimeCenterPopup.IsOpen = false;
return;
}
// A StaysOpen=false popup closes during preview input when its anchor is
// clicked. Suppress the same click's later Button.Click so it toggles
// closed instead of immediately reopening.
if (RuntimeModeButton.IsMouseOver &&
DateTimeOffset.UtcNow - _runtimeCenterClosedAt < TimeSpan.FromMilliseconds(300))
{
return;
}
RefreshRuntimeCenter();
RuntimeCenterPopup.IsOpen = true;
_ = Dispatcher.BeginInvoke(
() => RuntimeOptionsPanel.Children.OfType<Button>().FirstOrDefault()?.Focus(),
System.Windows.Threading.DispatcherPriority.Input);
}
private void OnCloseRuntimeCenter(object sender, RoutedEventArgs e)
{
RuntimeCenterPopup.IsOpen = false;
RuntimeModeButton.Focus();
}
private void OnRuntimeCenterClosed(object? sender, EventArgs e)
{
_runtimeCenterClosedAt = DateTimeOffset.UtcNow;
}
private void OnRuntimeCenterKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Escape)
{
return;
}
RuntimeCenterPopup.IsOpen = false;
RuntimeModeButton.Focus();
e.Handled = true;
}
private void OnOpenModelsFolder(object sender, RoutedEventArgs e)
{
RuntimeCenterPopup.IsOpen = false;
OpenModelsFolder();
}
private void OnOpenBrowserFromRuntimeCenter(object sender, RoutedEventArgs e)
{
RuntimeCenterPopup.IsOpen = false;
OnOpenInBrowser(sender, e);
}
private void RefreshRuntimeCenter()
{
if (_paths is null)
{
return;
}
_localModels = LocalModelCatalog.Discover(_paths);
RuntimeOptionsPanel.Children.Clear();
RuntimeOptionsPanel.Children.Add(CreateRuntimeChoiceButton(
"Original Kimi",
"Cloud account · Official models, vision, tools, and internet",
_runtimePreference?.Kind == KimiRuntimeKind.OriginalKimi,
isCloud: true,
new RuntimePreference(KimiRuntimeKind.OriginalKimi, _runtimePreference?.LocalModelPath),
"Uses the isolated Kimi profile and never inherits a stale local endpoint."));
RuntimeOptionsPanel.Children.Add(CreateRuntimeChoiceButton(
"Kimi K3 (2.8T)",
"AirLLM 3.1 · Offline · 2K proof · 1 token · RTX single-card",
_runtimePreference?.Kind == KimiRuntimeKind.AirLlmK3,
isCloud: false,
new RuntimePreference(KimiRuntimeKind.AirLlmK3, _runtimePreference?.LocalModelPath),
Path.Combine(_paths.KimiRoot, "airllm-v3.1.0", "models", "moonshotai--Kimi-K3")));
foreach (var model in _localModels)
{
var selected = _runtimePreference?.Kind == KimiRuntimeKind.LocalGguf &&
_activeLocalModel is not null &&
string.Equals(
Path.GetFullPath(_activeLocalModel.ModelPath),
Path.GetFullPath(model.ModelPath),
StringComparison.OrdinalIgnoreCase);
var capability = model.ProjectorPath is null ? "Text + tools" : "Text + tools + vision";
RuntimeOptionsPanel.Children.Add(CreateRuntimeChoiceButton(
model.CompactDisplayName,
$"{(model.IsBundled ? "Standalone" : "Local GGUF")} · {model.ContextSize:N0} context · {capability}",
selected,
isCloud: false,
new RuntimePreference(KimiRuntimeKind.LocalGguf, model.ModelPath),
$"{model.DisplayName}\n{model.ModelPath}"));
}
if (_localModels.Count == 0)
{
RuntimeOptionsPanel.Children.Add(new Border
{
Background = new SolidColorBrush(Color.FromArgb(15, 255, 255, 255)),
BorderBrush = new SolidColorBrush(Color.FromArgb(36, 255, 255, 255)),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(14),
Padding = new Thickness(14, 12, 14, 12),
Margin = new Thickness(0, 4, 0, 0),
Child = new TextBlock
{
Text = "No GGUF checkpoints found. Open the models folder to add one.",
Foreground = (Brush)FindResource("SecondaryText"),
FontSize = 11,
TextWrapping = TextWrapping.Wrap,
},
});
}
UpdateRuntimeModeUi();
}
private Button CreateRuntimeChoiceButton(
string title,
string subtitle,
bool selected,
bool isCloud,
RuntimePreference preference,
string toolTip)
{
var button = new Button
{
Style = (Style)FindResource("RuntimeChoiceButtonStyle"),
ToolTip = toolTip,
};
if (SystemParameters.HighContrast)
{
button.Background = selected ? SystemColors.HighlightBrush : SystemColors.ControlBrush;
button.BorderBrush = SystemColors.WindowTextBrush;
}
else if (selected)
{
button.Background = new SolidColorBrush(isCloud
? Color.FromArgb(28, 165, 150, 255)
: Color.FromArgb(28, 82, 227, 164));
button.BorderBrush = new SolidColorBrush(isCloud
? Color.FromArgb(74, 165, 150, 255)
: Color.FromArgb(74, 82, 227, 164));
}
AutomationProperties.SetName(button, $"{title}. {subtitle}");
var primaryChoiceText = SystemParameters.HighContrast
? selected ? SystemColors.HighlightTextBrush : SystemColors.WindowTextBrush
: (Brush)FindResource("PrimaryText");
var secondaryChoiceText = SystemParameters.HighContrast
? selected ? SystemColors.HighlightTextBrush : SystemColors.WindowTextBrush
: (Brush)FindResource("SecondaryText");
var layout = new Grid();
layout.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
layout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
layout.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
var icon = new Border
{
Width = 28,
Height = 28,
CornerRadius = new CornerRadius(10),
Background = SystemParameters.HighContrast
? selected ? SystemColors.HighlightBrush : SystemColors.ControlBrush
: new SolidColorBrush(isCloud
? Color.FromArgb(30, 165, 150, 255)
: Color.FromArgb(30, 82, 227, 164)),
BorderBrush = SystemParameters.HighContrast
? SystemColors.WindowTextBrush
: new SolidColorBrush(isCloud
? Color.FromArgb(60, 165, 150, 255)
: Color.FromArgb(60, 82, 227, 164)),
BorderThickness = new Thickness(1),
Margin = new Thickness(0, 0, 11, 0),
Child = new TextBlock
{
Text = isCloud ? "\uE753" : "\uE950",
FontFamily = new FontFamily("Segoe Fluent Icons"),
FontSize = 12,
Foreground = SystemParameters.HighContrast
? primaryChoiceText
: isCloud
? new SolidColorBrush(Color.FromRgb(191, 180, 255))
: new SolidColorBrush(Color.FromRgb(142, 240, 196)),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
},
};
layout.Children.Add(icon);
var labels = new StackPanel { VerticalAlignment = VerticalAlignment.Center };
labels.Children.Add(new TextBlock
{
Text = title,
Foreground = primaryChoiceText,
FontSize = 12,
FontWeight = FontWeights.SemiBold,
TextTrimming = TextTrimming.CharacterEllipsis,
});
labels.Children.Add(new TextBlock
{
Text = subtitle,
Foreground = secondaryChoiceText,
FontSize = 10,
Margin = new Thickness(0, 3, 0, 0),
TextTrimming = TextTrimming.CharacterEllipsis,
});
Grid.SetColumn(labels, 1);
layout.Children.Add(labels);
if (selected)
{
var check = new TextBlock
{
Text = "\uE73E",
FontFamily = new FontFamily("Segoe Fluent Icons"),
Foreground = SystemParameters.HighContrast
? SystemColors.HighlightTextBrush
: isCloud
? new SolidColorBrush(Color.FromRgb(191, 180, 255))
: new SolidColorBrush(Color.FromRgb(82, 227, 164)),
FontSize = 13,
Margin = new Thickness(10, 0, 0, 0),
VerticalAlignment = VerticalAlignment.Center,
};
Grid.SetColumn(check, 2);
layout.Children.Add(check);
}
button.Content = layout;
button.Click += async (_, _) =>
{
RuntimeCenterPopup.IsOpen = false;
await SwitchRuntimeAsync(preference);