Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 36 additions & 7 deletions App.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ namespace CxShell;
public partial class App : Application
{
private TrayIcon? _windowsTrayIcon;
private NativeMenuItem? _trayShowWindowItem;
private NativeMenuItem? _trayExitItem;

public bool HasActiveTrayIcon => _windowsTrayIcon is { IsVisible: true };

public override void Initialize()
{
Expand Down Expand Up @@ -71,6 +75,7 @@ public override void OnFrameworkInitializationCompleted()
RegisterAtomUiWindowDecorationsTheme();
desktop.MainWindow = new MainWindow(desktop.Args ?? Array.Empty<string>());
InitializeWindowsTrayIcon(desktop);
desktop.ShutdownRequested += (_, _) => PrepareMainWindowForExit(desktop);
desktop.Exit += (_, _) => DisposeWindowsTrayIcon();
}

Expand Down Expand Up @@ -104,16 +109,20 @@ private void InitializeWindowsTrayIcon(IClassicDesktopStyleApplicationLifetime d
if (!OperatingSystem.IsWindows() || desktop.MainWindow is not { } mainWindow)
return;

var showWindowItem = new NativeMenuItem("显示 CxShell");
showWindowItem.Click += (_, _) => ShowMainWindow(desktop);
_trayShowWindowItem = new NativeMenuItem(LocalizationService.Shared.Text("Tray.ShowWindow"));
_trayShowWindowItem.Click += (_, _) => ShowMainWindow(desktop);

var exitItem = new NativeMenuItem("退出");
exitItem.Click += (_, _) => desktop.Shutdown();
_trayExitItem = new NativeMenuItem(LocalizationService.Shared.Text("Tray.Exit"));
_trayExitItem.Click += (_, _) =>
{
PrepareMainWindowForExit(desktop);
desktop.Shutdown();
};

var menu = new NativeMenu();
menu.Items.Add(showWindowItem);
menu.Items.Add(_trayShowWindowItem);
menu.Items.Add(new NativeMenuItemSeparator());
menu.Items.Add(exitItem);
menu.Items.Add(_trayExitItem);

_windowsTrayIcon = new TrayIcon
{
Expand All @@ -127,22 +136,42 @@ private void InitializeWindowsTrayIcon(IClassicDesktopStyleApplicationLifetime d
var trayIcons = new TrayIcons();
trayIcons.Add(_windowsTrayIcon);
TrayIcon.SetIcons(this, trayIcons);
LocalizationService.Shared.LanguageChanged += OnTrayLanguageChanged;
}

private void OnTrayLanguageChanged(object? sender, EventArgs e)
{
if (_trayShowWindowItem != null)
_trayShowWindowItem.Header = LocalizationService.Shared.Text("Tray.ShowWindow");
if (_trayExitItem != null)
_trayExitItem.Header = LocalizationService.Shared.Text("Tray.Exit");
}

private static void PrepareMainWindowForExit(IClassicDesktopStyleApplicationLifetime desktop)
{
if (desktop.MainWindow is MainWindow mainWindow)
mainWindow.PrepareForExit();
}

private static void ShowMainWindow(IClassicDesktopStyleApplicationLifetime desktop)
{
if (desktop.MainWindow is not { } mainWindow)
return;

if (!mainWindow.IsVisible)
mainWindow.Show();

if (mainWindow.WindowState == WindowState.Minimized)
mainWindow.WindowState = WindowState.Normal;

mainWindow.Show();
mainWindow.Activate();
}

private void DisposeWindowsTrayIcon()
{
LocalizationService.Shared.LanguageChanged -= OnTrayLanguageChanged;
_trayShowWindowItem = null;
_trayExitItem = null;
_windowsTrayIcon?.Dispose();
_windowsTrayIcon = null;
TrayIcon.SetIcons(this, new TrayIcons());
Expand Down
76 changes: 76 additions & 0 deletions CxShell.Tests/AppDataPathsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System;
using System.IO;
using CxShell.Services;

namespace CxShell.Tests;

public sealed class AppDataPathsTests
{
[Fact]
public void Resolve_EntersPortableModeWhenDataFolderExistsNextToExecutable()
{
using var root = new TemporaryDirectory();
var exeDir = Path.Combine(root.Path, "portable-app");
var dataDir = Path.Combine(exeDir, "data");
Directory.CreateDirectory(dataDir);

var resolved = AppDataPaths.Resolve(
exeDir,
Directory.Exists,
() => Path.Combine(root.Path, "roaming"),
() => Path.Combine(root.Path, "local"),
exeDir);

Assert.True(resolved.IsPortableMode);
Assert.Equal(Path.GetFullPath(dataDir), resolved.StorageDirectory);
Assert.Equal(Path.GetFullPath(dataDir), resolved.LocalCacheDirectory);
Assert.Equal(Path.Combine(Path.GetFullPath(dataDir), "Logs"), resolved.LogsDirectory);
}

[Fact]
public void Resolve_UsesInstalledDirectoriesWhenDataFolderIsMissing()
{
using var root = new TemporaryDirectory();
var exeDir = Path.Combine(root.Path, "installed-app");
var roamingRoot = Path.Combine(root.Path, "roaming");
var localRoot = Path.Combine(root.Path, "local");
Directory.CreateDirectory(exeDir);

var resolved = AppDataPaths.Resolve(
exeDir,
Directory.Exists,
() => roamingRoot,
() => localRoot,
exeDir);

Assert.False(resolved.IsPortableMode);
Assert.Equal(Path.Combine(Path.GetFullPath(roamingRoot), "CxShell"), resolved.StorageDirectory);
Assert.Equal(Path.Combine(Path.GetFullPath(localRoot), "CxShell"), resolved.LocalCacheDirectory);
Assert.Equal(Path.Combine(Path.GetFullPath(localRoot), "CxShell", "Logs"), resolved.LogsDirectory);
}

private sealed class TemporaryDirectory : IDisposable
{
public TemporaryDirectory()
{
Path = System.IO.Path.Combine(
System.IO.Path.GetTempPath(),
$"cxshell-portable-tests-{Guid.NewGuid():N}");
Directory.CreateDirectory(Path);
}

public string Path { get; }

public void Dispose()
{
try
{
Directory.Delete(Path, recursive: true);
}
catch
{
// Best-effort cleanup for test artifacts.
}
}
}
}
43 changes: 43 additions & 0 deletions CxShell.Tests/ApplicationSettingsStoreTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.Text.Json;
using Avalonia.Controls;
using CxShell.Models;
using CxShell.Services;
using CxShell.Views;

namespace CxShell.Tests;

Expand Down Expand Up @@ -71,6 +73,47 @@ public void SaveAndLoad_PreservesGlobalPanelVisibility()
Assert.True(loaded.ShowAgentPanel);
}

[Fact]
public void MinimizeToTrayOnClose_DefaultsToTrueAndPersistsChanges()
{
using var directory = new TemporaryDirectory();
var store = new ApplicationSettingsStore(directory.Path);

var defaults = new ApplicationSettings();
Assert.True(defaults.MinimizeToTrayOnClose);

store.Save(new ApplicationSettings { MinimizeToTrayOnClose = false });
var loadedDisabled = store.Load();
Assert.False(loadedDisabled.MinimizeToTrayOnClose);

store.Save(new ApplicationSettings { MinimizeToTrayOnClose = true });
var loadedEnabled = store.Load();
Assert.True(loadedEnabled.MinimizeToTrayOnClose);
}

[Theory]
[InlineData(false, true, true, WindowCloseReason.WindowClosing, true)]
[InlineData(false, true, false, WindowCloseReason.WindowClosing, false)]
[InlineData(false, false, true, WindowCloseReason.WindowClosing, false)]
[InlineData(true, true, true, WindowCloseReason.WindowClosing, false)]
[InlineData(false, true, true, WindowCloseReason.ApplicationShutdown, false)]
[InlineData(false, true, true, WindowCloseReason.OSShutdown, false)]
public void ShouldMinimizeToTrayOnClose_HandlesCloseReasonsAndGuards(
bool allowClose,
bool hasActiveTrayIcon,
bool minimizeToTrayOnClose,
WindowCloseReason closeReason,
bool expected)
{
var result = MainWindow.ShouldMinimizeToTrayOnClose(
allowClose,
hasActiveTrayIcon,
minimizeToTrayOnClose,
closeReason);

Assert.Equal(expected, result);
}

[Fact]
public void SaveAndLoad_PreservesExternalLaunchSecuritySettings()
{
Expand Down
121 changes: 121 additions & 0 deletions CxShell.Tests/SingleInstanceChannelTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
using System;
using System.IO;
using System.Threading.Tasks;
using CxShell.Services;

namespace CxShell.Tests;

public sealed class SingleInstanceChannelTests
{
[Fact]
public async Task SingleInstanceChannel_BlocksSecondInstanceInSameDataDirAndForwardsArguments()
{
using var dataDir = new TemporaryDirectory();
var received = new TaskCompletionSource<string[]>(TaskCreationOptions.RunContinuationsAsynchronously);

using var first = new SingleInstanceChannel(dataDir.Path, isPortableMode: true);
Assert.True(first.IsFirstInstance);

using var second = new SingleInstanceChannel(dataDir.Path, isPortableMode: true);
Assert.False(second.IsFirstInstance);
Assert.Equal(first.PipeName, second.PipeName);

// Send before handler is attached to verify pending messages are buffered and flushed on AttachHandler.
var sent = second.SendToFirstInstance(["-url", "ssh://ops@example.test:22"]);
Assert.True(sent);

first.AttachHandler(args =>
{
received.TrySetResult(args);
return Task.CompletedTask;
});

var delivered = await received.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(["-url", "ssh://ops@example.test:22"], delivered);
}

[Fact]
public async Task SingleInstanceChannel_ForwardsEmptyActivationPing()
{
using var dataDir = new TemporaryDirectory();
var received = new TaskCompletionSource<string[]>(TaskCreationOptions.RunContinuationsAsynchronously);

using var first = new SingleInstanceChannel(dataDir.Path, isPortableMode: true);
first.AttachHandler(args =>
{
received.TrySetResult(args);
return Task.CompletedTask;
});

using var second = new SingleInstanceChannel(dataDir.Path, isPortableMode: true);
Assert.False(second.IsFirstInstance);
Assert.True(second.SendToFirstInstance([]));

var delivered = await received.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Empty(delivered);
}

[Fact]
public void SingleInstanceChannel_AllowsInstalledAndPortableInstancesSimultaneously()
{
using var installedDir = new TemporaryDirectory();
using var portableDir = new TemporaryDirectory();

using var installedInstance = new SingleInstanceChannel(installedDir.Path, isPortableMode: false);
using var portableInstance = new SingleInstanceChannel(portableDir.Path, isPortableMode: true);

Assert.True(installedInstance.IsFirstInstance);
Assert.True(portableInstance.IsFirstInstance);
Assert.NotEqual(installedInstance.PipeName, portableInstance.PipeName);
Assert.NotEqual(installedInstance.LockFilePath, portableInstance.LockFilePath);
}

[Fact]
public void SingleInstanceChannel_ReleasesLockOnDispose()
{
using var dataDir = new TemporaryDirectory();

var first = new SingleInstanceChannel(dataDir.Path, isPortableMode: true);
Assert.True(first.IsFirstInstance);
first.Dispose();

using var restarted = new SingleInstanceChannel(dataDir.Path, isPortableMode: true);
Assert.True(restarted.IsFirstInstance);
}

[Theory]
[InlineData(new string[0], false)]
[InlineData(new[] { "-url", "ssh://ops@example.test:22" }, false)]
[InlineData(new[] { "-newwin" }, true)]
[InlineData(new[] { "--newwin", "-url", "ssh://ops@example.test:22" }, true)]
[InlineData(new[] { "--rdp-smoke" }, true)]
public void ShouldBypassSingleInstance_RespectsExplicitNewWindowAndSmokeArgs(string[] args, bool expected)
{
Assert.Equal(expected, CommandLineHandoffService.ShouldBypassSingleInstance(args));
}

private sealed class TemporaryDirectory : IDisposable
{
public TemporaryDirectory()
{
Path = System.IO.Path.Combine(
System.IO.Path.GetTempPath(),
$"cxshell-single-instance-tests-{Guid.NewGuid():N}");
Directory.CreateDirectory(Path);
}

public string Path { get; }

public void Dispose()
{
try
{
Directory.Delete(Path, recursive: true);
}
catch
{
// Best-effort cleanup for test artifacts.
}
}
}
}
1 change: 1 addition & 0 deletions Models/SessionInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ public class ApplicationSettings
public string UiLanguage { get; set; } = "zh-CN";
public string ThemeMode { get; set; } = DarkThemeMode;
public bool ShowSessionManagerOnStartup { get; set; } = true;
public bool MinimizeToTrayOnClose { get; set; } = true;
public bool AutoCheckForUpdates { get; set; } = true;
public bool IncludePrereleaseUpdates { get; set; }
public AgentProviderSettings AgentProvider { get; set; } = new();
Expand Down
9 changes: 6 additions & 3 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@ public static void Main(string[] args)
.SetArgs(args)
.Run();

if (CommandLineHandoffService.TrySendToExistingInstance(args))
if (!CommandLineHandoffService.TryAcquireSingleInstanceOrForward(args, out var singleInstance))
return;

BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
using (singleInstance)
{
BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
}
}

public static AppBuilder BuildAvaloniaApp()
Expand Down
3 changes: 1 addition & 2 deletions Services/Agent/AgentRunHistoryStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ public SqliteAgentRunHistoryStore(string? legacyHistoryPath = null)
var isDefaultPath = string.IsNullOrWhiteSpace(legacyHistoryPath);
_legacyHistoryPath = isDefaultPath
? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CxShell",
AppDataPaths.GetLocalCacheDirectory(),
"agent-runs.json")
: Path.GetFullPath(legacyHistoryPath!);
_legacyRecoveryPath = _legacyHistoryPath + ".recovery";
Expand Down
6 changes: 2 additions & 4 deletions Services/Agent/SqliteAgentConversationHistoryStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,12 @@ public SqliteAgentConversationHistoryStore(string? filePath = null, string? lega
: Path.GetFullPath(filePath!);
_legacyFilePath = string.IsNullOrWhiteSpace(legacyFilePath)
? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CxShell",
AppDataPaths.GetLocalCacheDirectory(),
"agent-history.json")
: Path.GetFullPath(legacyFilePath);
_legacyDatabasePath = isDefaultPath
? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CxShell",
AppDataPaths.GetLocalCacheDirectory(),
"agent-history.db")
: string.Empty;

Expand Down
Loading
Loading