GsDChat.Client fixes:

- Command output not being displayed.
- Screen not cleaning up.
+ Better initial UI.
This commit is contained in:
tyuXX 2026-10-17 14:59:07 +03:00
parent b60b5a0774
commit 302d440dbd
12 changed files with 348 additions and 47 deletions

8
GsDChat.code-workspace Normal file
View file

@ -0,0 +1,8 @@
{
"folders": [
{
"path": "."
}
],
"settings": {}
}

View file

@ -272,6 +272,11 @@ public class ChatClientConnection : IDisposable
{
_state.AddNotice(cmdRes.Output);
_state.SetStatus(cmdRes.Success ? "Command executed." : "Command error.", 4);
// Also add to chat as a system message for visibility
if (!string.IsNullOrEmpty(cmdRes.Output) && !string.IsNullOrEmpty(cmdRes.ChannelId))
{
_state.AddSystemMessageToChat(cmdRes.Output, cmdRes.ChannelId);
}
}
break;

View file

@ -41,7 +41,7 @@ public class Program
Console.WriteLine($"========================================{Ansi.Reset}");
var historyManager = new ServerHistoryManager();
string? rememberedUsername = null;
UserProfile? selectedProfile = null;
// If no server was specified via CLI, show interactive server selection menu
while (string.IsNullOrEmpty(serverUrl))
@ -54,8 +54,8 @@ public class Program
for (int i = 0; i < servers.Count; i++)
{
var s = servers[i];
string userTag = !string.IsNullOrEmpty(s.LastUsername) ? $" (@{s.LastUsername})" : "";
Console.WriteLine($" {Ansi.BrightYellow}[{i + 1}]{Ansi.Reset} {Ansi.BrightWhite}{s.Name}{Ansi.Reset} {Ansi.Gray}({s.Url}){userTag}{Ansi.Reset}");
string profileCount = s.UserProfiles.Count > 0 ? $" ({s.UserProfiles.Count} profile{(s.UserProfiles.Count > 1 ? "s" : "")})" : "";
Console.WriteLine($" {Ansi.BrightYellow}[{i + 1}]{Ansi.Reset} {Ansi.BrightWhite}{s.Name}{Ansi.Reset} {Ansi.Gray}({s.Url}){profileCount}{Ansi.Reset}");
}
}
else
@ -71,27 +71,42 @@ public class Program
Console.WriteLine($" {Ansi.Gray}[Q]{Ansi.Reset} Quit");
Console.Write($"\nSelect option: ");
string? input = Console.ReadLine()?.Trim();
char input = ReadKeyChar();
if (string.Equals(input, "Q", StringComparison.OrdinalIgnoreCase))
if (char.ToUpper(input) == 'Q')
{
Console.WriteLine("Goodbye.");
return;
}
if (string.Equals(input, "D", StringComparison.OrdinalIgnoreCase) && servers.Count > 0)
if (char.ToUpper(input) == 'D' && servers.Count > 0)
{
selectedProfile = null;
Console.Write("Enter number to delete: ");
if (int.TryParse(Console.ReadLine(), out int delIdx) && delIdx >= 1 && delIdx <= servers.Count)
char delChar = ReadKeyChar();
if (delChar >= '1' && delChar <= '9')
{
int delIdx = delChar - '0';
if (delIdx >= 1 && delIdx <= servers.Count)
{
historyManager.RemoveServer(servers[delIdx - 1].Id);
Console.WriteLine($"{Ansi.Green}Removed server from history.{Ansi.Reset}");
}
else
{
Console.WriteLine($"{Ansi.BrightRed}Invalid number.{Ansi.Reset}");
}
}
else
{
Console.WriteLine($"{Ansi.BrightRed}Invalid input.{Ansi.Reset}");
}
continue;
}
if (string.Equals(input, "N", StringComparison.OrdinalIgnoreCase) || servers.Count == 0 && string.IsNullOrEmpty(input))
if (char.ToUpper(input) == 'N' || (servers.Count == 0 && input == '\r'))
{
selectedProfile = null;
Console.Write("\nEnter Server URL or IP (e.g. chat.example.com, http://localhost:5000): ");
string? customUrl = Console.ReadLine()?.Trim();
if (!string.IsNullOrEmpty(customUrl))
@ -101,13 +116,35 @@ public class Program
continue;
}
if (int.TryParse(input, out int sel) && sel >= 1 && sel <= servers.Count)
if (input >= '1' && input <= '9')
{
int sel = input - '0';
if (sel >= 1 && sel <= servers.Count)
{
var chosen = servers[sel - 1];
serverUrl = chosen.Url;
rememberedUsername = chosen.LastUsername;
selectedProfile = null;
// Show profile selection if profiles exist
if (chosen.UserProfiles.Count > 0)
{
selectedProfile = SelectProfile(chosen);
if (selectedProfile == null)
{
// User cancelled profile selection, reset serverUrl and let them choose again
serverUrl = null;
continue;
}
// If user chose "use different username", clear selectedProfile
if (string.IsNullOrEmpty(selectedProfile.Username))
{
selectedProfile = null;
}
}
break;
}
}
Console.WriteLine($"{Ansi.BrightRed}Invalid choice. Please select again.{Ansi.Reset}");
}
@ -129,17 +166,19 @@ public class Program
{
Console.WriteLine($"{Ansi.BrightRed}Failed to reach server!{Ansi.Reset}");
Console.Write("Would you like to [R]etry, choose [A]nother server, or [Q]uit? ");
var failChoice = Console.ReadLine()?.Trim().ToUpperInvariant();
if (failChoice == "A")
char failChoice = ReadKeyChar();
if (char.ToUpper(failChoice) == 'A')
{
serverUrl = null;
selectedProfile = null;
await Main(args); // Restart server selection
return;
}
if (failChoice == "Q")
if (char.ToUpper(failChoice) == 'Q')
{
return;
}
selectedProfile = null;
continue; // Retry
}
@ -158,30 +197,42 @@ public class Program
if (string.IsNullOrEmpty(username))
{
Console.Write("\nChoose action: [L]ogin or [R]egister: ");
var choice = Console.ReadLine()?.Trim().ToUpperInvariant();
if (choice == "R" || choice == "REGISTER")
// If a profile is selected with a username, skip login/register choice and use the profile
if (selectedProfile != null && !string.IsNullOrEmpty(selectedProfile.Username))
{
doRegister = true;
username = selectedProfile.Username;
// If profile has saved password, use it without prompting
if (!string.IsNullOrEmpty(selectedProfile.SavedPassword))
{
password = selectedProfile.SavedPassword;
Console.WriteLine($"\nUsing saved profile: {Ansi.BrightCyan}{username}{Ansi.Reset}");
Console.WriteLine("Password: (saved)");
}
string userPrompt = !string.IsNullOrEmpty(rememberedUsername)
? $"Username [{rememberedUsername}]: "
: "Username: ";
Console.Write(userPrompt);
string? enteredUser = Console.ReadLine()?.Trim();
username = string.IsNullOrEmpty(enteredUser) ? rememberedUsername : enteredUser;
else
{
Console.WriteLine($"\nUsing saved profile: {Ansi.BrightCyan}{username}{Ansi.Reset}");
Console.Write("Password: ");
password = ReadMaskedPassword();
}
}
else
{
// No profile selected or user chose different username - skip login/register since we have a server
Console.Write("\nUsername: ");
username = Console.ReadLine()?.Trim();
Console.Write("Password: ");
password = ReadMaskedPassword();
}
}
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
Console.WriteLine($"{Ansi.BrightRed}Username and password are required.{Ansi.Reset}");
username = null;
password = null;
selectedProfile = null;
continue;
}
@ -196,13 +247,38 @@ public class Program
Console.WriteLine($"{Ansi.BrightRed}Authentication failed: {authResult.ErrorMessage}{Ansi.Reset}");
username = null;
password = null;
selectedProfile = null;
continue;
}
Console.WriteLine($"{Ansi.BrightGreen}Success! Welcome @{authResult.Username} [{authResult.Role}]{Ansi.Reset}");
// Save server to history (with upgraded protocol if applicable)
historyManager.SaveServer(state.ServerUrl, info.ServerName, authResult.Username);
// Handle profile saving
if (!string.IsNullOrEmpty(authResult.Username))
{
if (selectedProfile == null || selectedProfile.Username != authResult.Username)
{
// Ask if user wants to save this profile
Console.Write($"\nSave this profile for {Ansi.BrightCyan}{info.ServerName}{Ansi.Reset}? [Y/n]: ");
char saveChoice = ReadKeyChar();
if (char.ToUpper(saveChoice) != 'N')
{
// Ask if user wants to save password
Console.Write($"Save password for {Ansi.BrightCyan}{authResult.Username}{Ansi.Reset}? [y/N]: ");
char savePasswordChoice = ReadKeyChar();
bool savePassword = char.ToUpper(savePasswordChoice) == 'Y';
historyManager.SaveProfile(state.ServerUrl, authResult.Username, password, savePassword);
Console.WriteLine(savePassword ? $"{Ansi.Green}Profile and password saved.{Ansi.Reset}" : $"{Ansi.Green}Profile saved (password not saved).{Ansi.Reset}");
}
}
else
{
// Update last used time for existing profile
historyManager.SaveProfile(state.ServerUrl, authResult.Username, null, false);
}
}
state.Token = authResult.Token;
state.CurrentUserId = authResult.UserId ?? "";
@ -252,4 +328,68 @@ public class Program
}
return pwd;
}
private static char ReadKeyChar()
{
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
return '\r';
}
if (!char.IsControl(key.KeyChar))
{
Console.Write(key.KeyChar);
Console.WriteLine();
return key.KeyChar;
}
}
}
private static UserProfile? SelectProfile(ServerProfile server)
{
Console.WriteLine($"\n{Ansi.Bold}Select Profile for {server.Name}:{Ansi.Reset}");
for (int i = 0; i < server.UserProfiles.Count; i++)
{
var p = server.UserProfiles[i];
string hasPassword = !string.IsNullOrEmpty(p.SavedPassword) ? $"{Ansi.Green}[+password]{Ansi.Reset}" : $"{Ansi.Gray}[no password]{Ansi.Reset}";
Console.WriteLine($" {Ansi.BrightYellow}[{i + 1}]{Ansi.Reset} {Ansi.BrightWhite}{p.Username}{Ansi.Reset} {hasPassword}");
}
Console.WriteLine($" {Ansi.BrightCyan}[N]{Ansi.Reset} Use a different username");
Console.WriteLine($" {Ansi.Gray}[Esc]{Ansi.Reset} Go back");
Console.Write($"\nSelect option: ");
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Escape)
{
Console.WriteLine();
return null;
}
if (char.ToUpper(key.KeyChar) == 'N')
{
Console.WriteLine();
// Return a special marker to indicate "use different username"
return new UserProfile { Username = "" };
}
if (key.KeyChar >= '1' && key.KeyChar <= '9')
{
int sel = key.KeyChar - '0';
if (sel >= 1 && sel <= server.UserProfiles.Count)
{
Console.WriteLine();
return server.UserProfiles[sel - 1];
}
}
}
}
}

View file

@ -168,9 +168,11 @@ public class ConsoleUi
private void Draw()
{
Console.SetCursorPosition(0, 0);
var (width, height) = GetWindowDimensions();
var sb = new StringBuilder();
sb.Append(Ansi.ClearScreen);
sb.Append(Ansi.CursorHome);
// 1. Top Bar: Server Title & Screen Tabs

View file

@ -70,11 +70,17 @@ public class ChatScreen : IScreen
{
"Owner" => Ansi.BrightYellow,
"Admin" => Ansi.BrightMagenta,
"System" => Ansi.BrightGreen,
_ => Ansi.BrightCyan
};
string line;
if (!string.IsNullOrEmpty(msg.AttachmentId))
if (msg.SenderRole == "System")
{
// System messages (command output) rendered differently
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} {Ansi.BrightGreen}*** {msg.Content}{Ansi.Reset}";
}
else if (!string.IsNullOrEmpty(msg.AttachmentId))
{
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} <{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {Ansi.BrightYellow}📎 [{msg.AttachmentName} - {FileStorageServiceFormat(msg.AttachmentSizeBytes ?? 0)}]{Ansi.Reset}";
}

View file

@ -67,6 +67,28 @@ public class ClientState
}
}
public void AddSystemMessageToChat(string text, string channelId)
{
lock (_lock)
{
if (!ChannelMessages.TryGetValue(channelId, out var list))
{
list = new List<ChatMessage>();
ChannelMessages[channelId] = list;
}
list.Add(new ChatMessage
{
Id = Guid.NewGuid().ToString(),
ChannelId = channelId,
SenderUsername = "System",
SenderRole = "System",
Content = text,
CreatedAt = DateTime.UtcNow
});
NeedsRedraw = true;
}
}
public void AddChatMessage(ChatMessage message)
{
lock (_lock)

View file

@ -68,18 +68,26 @@ public class ServerHistoryManager
{
existing.Name = string.IsNullOrWhiteSpace(name) ? existing.Name : name;
existing.Url = normalizedUrl;
if (!string.IsNullOrWhiteSpace(username)) existing.LastUsername = username;
existing.LastConnected = DateTime.UtcNow;
// Add or update the user profile without saving password
AddOrUpdateProfile(existing, username, null);
}
else
{
servers.Insert(0, new ServerProfile
var newServer = new ServerProfile
{
Name = string.IsNullOrWhiteSpace(name) ? normalizedUrl : name,
Url = normalizedUrl,
LastUsername = username,
LastConnected = DateTime.UtcNow
});
};
if (!string.IsNullOrWhiteSpace(username))
{
AddOrUpdateProfile(newServer, username, null);
}
servers.Insert(0, newServer);
}
var trimmed = servers.OrderByDescending(s => s.LastConnected).Take(MaxServers).ToList();
@ -95,6 +103,106 @@ public class ServerHistoryManager
}
}
public void SaveProfile(string url, string username, string? password, bool savePassword)
{
try
{
var servers = LoadServers();
string normalizedUrl = NormalizeUrl(url);
var existing = servers.FirstOrDefault(s => NormalizeUrl(s.Url).Equals(normalizedUrl, StringComparison.OrdinalIgnoreCase));
if (existing == null)
{
existing = new ServerProfile
{
Name = normalizedUrl,
Url = normalizedUrl,
LastConnected = DateTime.UtcNow
};
servers.Insert(0, existing);
}
existing.LastConnected = DateTime.UtcNow;
AddOrUpdateProfile(existing, username, savePassword ? password : null);
var trimmed = servers.OrderByDescending(s => s.LastConnected).Take(MaxServers).ToList();
string json = JsonSerializer.Serialize(trimmed, new JsonSerializerOptions { WriteIndented = true });
string? dir = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(_filePath, json);
}
catch (Exception ex)
{
Console.WriteLine($"[Warning] Could not save profile: {ex.Message}");
}
}
private void AddOrUpdateProfile(ServerProfile server, string? username, string? password)
{
if (string.IsNullOrWhiteSpace(username)) return;
var existingProfile = server.UserProfiles.FirstOrDefault(p =>
p.Username.Equals(username, StringComparison.OrdinalIgnoreCase));
if (existingProfile != null)
{
existingProfile.LastUsed = DateTime.UtcNow;
// Only update password if a new one is provided
if (password != null)
{
existingProfile.SavedPassword = password;
}
}
else
{
server.UserProfiles.Add(new UserProfile
{
Username = username,
SavedPassword = password,
LastUsed = DateTime.UtcNow
});
}
}
public UserProfile? GetProfile(string url, string username)
{
var servers = LoadServers();
string normalizedUrl = NormalizeUrl(url);
var server = servers.FirstOrDefault(s => NormalizeUrl(s.Url).Equals(normalizedUrl, StringComparison.OrdinalIgnoreCase));
if (server == null) return null;
return server.UserProfiles.FirstOrDefault(p =>
p.Username.Equals(username, StringComparison.OrdinalIgnoreCase));
}
public void RemoveProfile(string url, string username)
{
try
{
var servers = LoadServers();
string normalizedUrl = NormalizeUrl(url);
var server = servers.FirstOrDefault(s => NormalizeUrl(s.Url).Equals(normalizedUrl, StringComparison.OrdinalIgnoreCase));
if (server != null)
{
server.UserProfiles.RemoveAll(p =>
p.Username.Equals(username, StringComparison.OrdinalIgnoreCase));
// If no profiles left, remove the server entirely
if (server.UserProfiles.Count == 0)
{
servers.Remove(server);
}
string json = JsonSerializer.Serialize(servers, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(_filePath, json);
}
}
catch { }
}
public void RemoveServer(string idOrUrl)
{
try

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
namespace GsDChat.Client.State;
@ -7,6 +8,13 @@ public class ServerProfile
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public string Name { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
public string? LastUsername { get; set; }
public List<UserProfile> UserProfiles { get; set; } = new();
public DateTime LastConnected { get; set; } = DateTime.UtcNow;
}
public class UserProfile
{
public string Username { get; set; } = string.Empty;
public string? SavedPassword { get; set; }
public DateTime LastUsed { get; set; } = DateTime.UtcNow;
}

View file

@ -164,4 +164,5 @@ public class CommandResultPacket
{
public bool Success { get; set; }
public string Output { get; set; } = string.Empty;
public string ChannelId { get; set; } = string.Empty;
}

View file

@ -82,7 +82,8 @@ public class ModLoaderService
return new Core.Protocol.CommandResultPacket
{
Success = res.Success,
Output = res.Output
Output = res.Output,
ChannelId = client.ActiveChannelId
};
}
return null;

View file

@ -379,30 +379,30 @@ public class ChatWebSocketManager
" /delete <name> - Delete a channel (Admin)\n" +
" /users - List all registered users\n" +
" /motd - Display message of the day";
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText }, ct);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText, ChannelId = packet.ChannelId }, ct);
break;
case "motd":
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}" }, ct);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}", ChannelId = packet.ChannelId }, ct);
break;
case "users":
var users = await _db.GetAllUsersAsync();
var userListStr = string.Join("\n", users.Select(u => $" • {u.Username} [{u.Role}]"));
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"Users:\n{userListStr}" }, ct);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"Users:\n{userListStr}", ChannelId = packet.ChannelId }, ct);
break;
case "delete":
string channelToDelete = (packet.Args ?? string.Empty).Trim().TrimStart('#');
if (string.IsNullOrEmpty(channelToDelete))
{
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = "Usage: /delete <channel_name>" }, ct);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = "Usage: /delete <channel_name>", ChannelId = packet.ChannelId }, ct);
break;
}
var chToDelete = await _db.GetChannelByNameAsync(channelToDelete);
if (chToDelete == null)
{
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Channel #{channelToDelete} not found." }, ct);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Channel #{channelToDelete} not found.", ChannelId = packet.ChannelId }, ct);
break;
}
await HandleDeleteChannelAsync(client, chToDelete.Id, ct);

View file

@ -58,7 +58,7 @@ public class ServerHistoryTests : IDisposable
Assert.Equal(2, updatedList.Count);
Assert.Equal("http://server1.local:5000", updatedList[0].Url);
Assert.Equal("Server 1 Updated", updatedList[0].Name);
Assert.Equal("User1New", updatedList[0].LastUsername);
Assert.Contains(updatedList[0].UserProfiles, p => p.Username == "User1New");
}
[Fact]