RynthChat server tabs: review fixes (pure apply core, pairing, clashes)

The decision core of ChatModel.ApplyServerTab moves into
ChatServerTabs.Apply, a pure function returning edits (rule updates,
inserts, removals, tab create, pin, seed mark, tab server); ChatModel
only carries them out. ChatFilterTests drives it through a small
settings model.

- A seeded entry whose tab was deleted never gets a rule turned on: a
  rule the manifest gains, or one re-added after the player deleted
  the rules, is added off. Tab listing skips a tab only an inactive
  server's rule fills.
- Owned rules pair with declared ones by content (Global-room flag,
  then when/action/mode/pattern, then leftovers), never by position,
  so a reorder or delete no longer moves on/off or colour to another
  rule. Reclaim uses the same pairing.
- Settings count as ready only after a successful read (or no file);
  a failed read is retried every 2 s, the unreadable copy kept once.
- Export leaves out server rules and server tabs; Import makes every
  imported rule the player's (no owner, server or globalRoom).
- Both rule editors lock pattern, mode, when, action, tab, move and
  delete on a server rule; on/off and colour stay live, with a note.
- No adopt-by-name: a taken name seeds "<Name> (<server name>)"
  instead, and tabServers is written only for a tab the plugin made.
  Reclaim requires the entry's name, its clash name, or a tab holding
  only the matched rules. AddCustomTab checks hidden tabs.
- Global-room discovery re-reads the entries and active servers under
  the lock. The manifest parser rejects a bad when or mode, and keeps
  a pattern's spaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-11-15 08:59:53 -08:00
commit 05a6d7d088
8 changed files with 717 additions and 281 deletions

View file

@ -1146,19 +1146,82 @@ internal static class Program
Check(old.Filters!.All(f => f.Server == null && f.Owner == null && f.GlobalRoom == null), "an old file's rules have none of the rule fields");
}
// ── Server default tabs (2026-11-15) ──
// -- Server default tabs (2026-11-15) --
private static SectionChatTabDecl NetworkDecl() => new(
"dreamweave", "dereth-network", "Network", true, "Roleplay",
new[]
private static readonly SectionChatRuleDecl TellRule = new("copy", "type:3", "", "^[^\"]+@[a-z0-9-]+( \\(discord\\))? tells you, \"", false);
private static readonly SectionChatRuleDecl SentRule = new("copy", "type:4", "", "^You tell [^\"]+@[a-z0-9-]+( \\(discord\\))?, \"", false);
private static readonly SectionChatRuleDecl GlobalRule = new("copy", "", "startswith", "", true);
private static SectionChatTabDecl NetworkDecl(params SectionChatRuleDecl[] extra) => new(
"dreamweave", "dereth-network", "Network", true, "Roleplay", new[] { TellRule, SentRule, GlobalRule }.Concat(extra).ToArray());
private static RynthChatFilterDto CloneRule(RynthChatFilterDto r) => new()
{
Enabled = r.Enabled, Pattern = r.Pattern, Tab = r.Tab, Action = r.Action, When = r.When, ColorMode = r.ColorMode,
Color = r.Color, Mode = r.Mode, Server = r.Server, Owner = r.Owner, GlobalRoom = r.GlobalRoom,
};
/// <summary>The chat settings in miniature: carries out ChatServerTabs.Apply's edits the way ChatModel.ApplyServerTab does.</summary>
private sealed class TabSim
{
public static readonly string[] BaseTabs = { "All", "Chat", "Channels" };
public List<RynthChatFilterDto> Rules = new();
public List<string> Custom = new();
public List<string> Seeded = new();
public string[] Pins = Array.Empty<string>();
public Dictionary<string, string> TabServers = ChatServerTabs.NewMap();
public string? Room;
public string ServerName = "DreamWeave";
public string[] AllTabs() => BaseTabs.Concat(Custom)
.Concat(Rules.Where(r => r.Enabled && r.Action is "copy" or "move" && !string.IsNullOrEmpty(r.Tab)).Select(r => r.Tab!))
.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
public ChatServerTabs.TabEdits Apply(SectionChatTabDecl d)
{
new SectionChatRuleDecl("copy", "type:3", "", "^[^\"]+@[a-z0-9-]+( \\(discord\\))? tells you, \"", false),
new SectionChatRuleDecl("copy", "type:4", "", "^You tell [^\"]+@[a-z0-9-]+( \\(discord\\))?, \"", false),
new SectionChatRuleDecl("copy", "", "startswith", "", true),
});
var state = new ChatServerTabs.TabState(Seeded.ToArray(), Custom.ToArray(), AllTabs(), ChatServerTabs.NewMap(TabServers),
Pins.ToArray(), Rules.Select(CloneRule).ToArray(), Room, ServerName);
ChatServerTabs.TabEdits e = ChatServerTabs.Apply(d, state);
RynthChatFilterDto[] before = Rules.ToArray();
foreach ((int index, RynthChatFilterDto want) in e.Updates)
{
RynthChatFilterDto w = CloneRule(want);
w.Color = before[index].Color; // the colour is the player's
w.ColorMode = before[index].ColorMode;
Rules[Rules.IndexOf(before[index])] = w;
}
int at = e.InsertAt;
foreach (int index in e.Removes)
{
Rules.Remove(before[index]);
if (index < e.InsertAt) at--;
}
foreach (RynthChatFilterDto want in e.Inserts) Rules.Insert(Math.Min(at++, Rules.Count), CloneRule(want));
if (e.CreateTab != null) Custom.Add(e.CreateTab);
if (e.Pin != null) Pins = Pins.Append(e.Pin).ToArray();
if (e.Seed != null) Seeded.Add(e.Seed);
if (e.TabServer != null) TabServers[e.TabServer] = d.Server;
return e;
}
private static ChatServerTabs.SeedState State(string[]? seeded = null, string[]? tabs = null, RynthChatFilterDto[]? owned = null)
=> new(seeded ?? Array.Empty<string>(), tabs ?? new[] { "All", "Chat" }, owned ?? Array.Empty<RynthChatFilterDto>());
/// <summary>RenameCustomTab: the tab, its rules, its server entry and its pin.</summary>
public void Rename(string from, string to)
{
Custom = Custom.Select(t => string.Equals(t, from, StringComparison.OrdinalIgnoreCase) ? to : t).ToList();
foreach (RynthChatFilterDto r in Rules) if (string.Equals(r.Tab, from, StringComparison.OrdinalIgnoreCase)) r.Tab = to;
(TabServers, Pins) = ChatServerTabs.RenameTab(TabServers, Pins, from, to);
}
/// <summary>DeleteCustomTab: the tab goes, its Move/Copy rules turn off, its server entry and pin go, the seed mark stays.</summary>
public void Delete(string tab)
{
Custom.RemoveAll(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase));
foreach (RynthChatFilterDto r in Rules)
if (r.Action is "copy" or "move" && string.Equals(r.Tab, tab, StringComparison.OrdinalIgnoreCase)) r.Enabled = false;
(TabServers, Pins) = ChatServerTabs.DeleteTab(TabServers, Pins, tab);
}
}
private static void ServerTabDiscovery()
{
@ -1179,75 +1242,200 @@ internal static class Program
{
SectionChatTabDecl d = NetworkDecl();
string key = ChatServerTabs.OwnerKey(d);
Case("Plan_SeedsFresh");
Case("Apply_SeedsFresh");
Check(key == "dreamweave/dereth-network", "owner key");
ChatServerTabs.SeedPlan p = ChatServerTabs.Plan(d, State(), null);
Check(p.CreateTab && p.TabName == "Network" && p.Pin && p.MarkSeeded, "creates, names, pins and marks the tab");
Check(p.Rules.Length == 3 && p.Rules.All(r => r.Owner == key && r.Server == "dreamweave" && r.Tab == "Network" && r.Enabled), "3 owned rules for the tab");
RynthChatFilterDto g = p.Rules[2];
Check(g.GlobalRoom == true && g.Mode == "startswith" && g.Pattern == "[Roleplay] ", "the Global rule uses the fallback room");
Check(p.Rules[0].GlobalRoom == null && p.Rules[0].Pattern == d.Rules[0].Pattern && p.Rules[0].When == "type:3", "other rules copy the declaration");
var sim = new TabSim();
ChatServerTabs.TabEdits e = sim.Apply(d);
Check(e.CreateTab == "Network" && e.Pin == "Network" && e.Seed == key && e.TabServer == "Network", "creates, pins, marks and claims the tab");
Check(e.Inserts.Length == 3 && e.Inserts.All(r => r.Owner == key && r.Server == "dreamweave" && r.Tab == "Network" && r.Enabled), "3 owned rules, on");
Check(e.Inserts[2].GlobalRoom == true && e.Inserts[2].Mode == "startswith" && e.Inserts[2].Pattern == "[Roleplay] ", "the Global rule uses the fallback room");
Check(e.Inserts[0].GlobalRoom == null && e.Inserts[0].Pattern == TellRule.Pattern && e.Inserts[0].When == "type:3", "other rules copy the declaration");
Case("Plan_UsesDiscoveredRoom");
Check(ChatServerTabs.Plan(d, State(), "General").Rules[2].Pattern == "[General] ", "the discovered room wins over the fallback");
Case("Apply_SecondApplyIsANoOp");
// ChatModel.ApplyServerTabs runs every second: once applied, nothing may be left to change.
Check(!sim.Apply(d).Changed, "a second apply changes nothing");
sim.Rules.Add(new RynthChatFilterDto { Tab = "Network", Action = "copy", Pattern = "^Bob", Enabled = true });
Check(!sim.Apply(d).Changed, "a rule the player added to the tab is left alone");
sim.Room = "Trade";
e = sim.Apply(d);
Check(e.Updates.Count == 1 && e.Updates[0].Rule.Pattern == "[Trade] " && e.Inserts.Length == 0 && e.Removes.Length == 0, "a new room rewrites the Global rule only");
Check(!sim.Apply(d).Changed, "and then nothing again");
Case("Plan_AdoptsExistingTabByName");
p = ChatServerTabs.Plan(d, State(tabs: new[] { "All", "Chat", "Network" }), null);
Check(!p.CreateTab && !p.Pin && p.MarkSeeded && p.TabName == "Network", "an existing Network tab is adopted, not duplicated or re-pinned");
p = ChatServerTabs.Plan(d, State(tabs: new[] { "network" }), null);
Check(!p.CreateTab, "the name match ignores case");
var strayRule = new RynthChatFilterDto { Owner = key, Tab = "DN" };
p = ChatServerTabs.Plan(d, State(owned: new[] { strayRule }), null);
Check(!p.CreateTab && !p.Pin && p.MarkSeeded && p.TabName == "DN", "owned rules without a seed mark (older engine) are adopted too");
Case("Apply_UsesDiscoveredRoom");
Check(new TabSim { Room = "General" }.Apply(d).Inserts[2].Pattern == "[General] ", "the discovered room wins over the fallback");
Case("Apply_ClashSeedsUnderServerName");
sim = new TabSim { Custom = { "Network" } };
sim.Rules.Add(new RynthChatFilterDto { Tab = "Network", Action = "move", Pattern = "^guild", Enabled = true });
e = sim.Apply(d);
Check(e.CreateTab == "Network (DreamWeave)" && e.Inserts.All(r => r.Tab == "Network (DreamWeave)"), "a player's Network tab is not taken: seeds under the server's name");
Check(e.TabServer == "Network (DreamWeave)" && !sim.TabServers.ContainsKey("Network"), "the player's tab gets no server entry");
Check(sim.Rules[0].Owner == null && sim.Rules[0].Tab == "Network", "the player's rule is untouched");
Check(!sim.Apply(d).Changed, "and the clash-named tab is stable");
sim = new TabSim { Custom = { "Network", "Network (DreamWeave)" } };
Check(sim.Apply(d).CreateTab == "Network (DreamWeave) 2", "both names taken: numbered");
var chatDecl = d with { Name = "Chat" };
Check(new TabSim { ServerName = "" }.Apply(chatDecl).CreateTab == "Chat (dreamweave)", "a base tab's name: the server id when no display name");
Case("Refresh_FollowsRenamedTab");
RynthChatFilterDto[] owned = ChatServerTabs.Plan(d, State(), null).Rules;
foreach (RynthChatFilterDto r in owned) r.Tab = "DN";
p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, tabs: new[] { "All", "Chat", "DN" }, owned: owned), "Trade");
Check(p.TabName == "DN" && !p.CreateTab && !p.Pin && !p.MarkSeeded, "seeded: no create, no pin, no new mark");
Check(p.Rules.All(r => r.Tab == "DN"), "every rule follows the rename");
Check(p.Rules[2].Pattern == "[Trade] ", "a refresh rewrites the Global pattern");
sim = new TabSim();
sim.Apply(d);
sim.Rename("Network", "DN");
Check(sim.TabServers.ContainsKey("DN") && !sim.TabServers.ContainsKey("Network") && sim.Pins.SequenceEqual(new[] { "DN" }), "rename moves the server entry and the pin");
sim.Room = "Trade";
e = sim.Apply(d);
Check(e.TabName == "DN" && e.CreateTab == null && e.Pin == null && e.Seed == null && e.TabServer == null, "seeded: no create, pin, mark or claim");
Check(sim.Rules.All(r => r.Tab == "DN") && sim.Rules[2].Pattern == "[Trade] ", "every rule follows the rename; the Global pattern refreshes");
Check(!sim.Apply(d).Changed, "stable after the rename");
Case("Refresh_KeepsDeletedTabDeleted");
owned = ChatServerTabs.Plan(d, State(), null).Rules;
foreach (RynthChatFilterDto r in owned) r.Enabled = false;
p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, owned: owned), null);
Check(!p.CreateTab && !p.Pin, "a seeded tab that is gone is not re-created");
Check(p.Rules.All(r => !r.Enabled), "its rules stay disabled");
sim = new TabSim();
sim.Apply(d);
sim.Delete("Network");
Check(sim.TabServers.Count == 0 && sim.Pins.Length == 0 && sim.Seeded.Contains(key), "delete drops the server entry and pin, keeps the seed mark");
e = sim.Apply(d);
Check(!e.Changed, "a deleted tab: nothing to do: " + e);
Check(!sim.AllTabs().Contains("Network") && sim.Rules.All(r => !r.Enabled), "the tab stays gone, its rules off");
Case("Refresh_IsANoOpWhenNothingChanged");
// ChatModel.ApplyServerTabs runs every second: a plan made from its own output must match it
// rule for rule (SameRule), and want no create, pin or seed mark, or every Rebuild would save.
owned = ChatServerTabs.Plan(d, State(), "Trade").Rules;
p = ChatServerTabs.Plan(d, State(seeded: new[] { key }, tabs: new[] { "All", "Network" }, owned: owned), "Trade");
Check(!p.CreateTab && !p.Pin && !p.MarkSeeded, "seeded: nothing to create, pin or mark");
Check(p.Rules.Length == owned.Length && p.Rules.Zip(owned).All(z => ChatServerTabs.SameRule(z.First, z.Second)), "every rule is the same as before");
Case("Refresh_NewRuleStaysOffForDeletedTab");
var bigger = NetworkDecl(new SectionChatRuleDecl("copy", "type:18", "", "^\\[Network\\]", false));
e = sim.Apply(bigger);
Check(e.Inserts.Length == 1 && !e.Inserts[0].Enabled && e.CreateTab == null && e.TabServer == null, "a rule the manifest gained is added off, the tab not re-created");
Check(!sim.AllTabs().Contains("Network"), "the tab is still gone");
Case("Refresh_AllRulesDeletedStaysOff");
sim = new TabSim();
sim.Apply(d);
sim.Delete("Network");
sim.Rules.Clear(); // the player also deleted the rules
e = sim.Apply(d);
Check(e.Inserts.Length == 3 && e.Inserts.All(r => !r.Enabled) && e.CreateTab == null && e.Pin == null && e.TabServer == null, "re-added, all off, no tab");
Check(!sim.AllTabs().Contains("Network") && !sim.Apply(d).Changed, "the tab stays gone, and it is stable");
Case("Pair_ByContentNotPosition");
sim = new TabSim();
sim.Apply(d);
sim.Rules[1].Enabled = false; // the player turned off "tells you send"
sim.Rules[0].Color = "#FF0000"; // and coloured "tells to you"
sim.Rules[0].ColorMode = "line";
// Reordered by the player (and an older editor): Global first, a player rule between.
sim.Rules = new List<RynthChatFilterDto>
{
sim.Rules[2], new() { Tab = "Junk", Action = "hide", Pattern = "spam", Enabled = true }, sim.Rules[1], sim.Rules[0],
};
string[] order = sim.Rules.Select(r => r.Pattern ?? "").ToArray();
Check(!sim.Apply(d).Changed, "a permuted list pairs by content: nothing to change");
Check(sim.Rules.Select(r => r.Pattern ?? "").SequenceEqual(order), "the player's order is kept");
Check(!sim.Rules.Single(r => r.When == "type:4").Enabled && sim.Rules.Single(r => r.When == "type:3").Enabled, "the off switch stays on the rule it was set on");
var changed = new SectionChatTabDecl(d.Server, d.Id, d.Name, d.Pinned, d.GlobalRoomFallback,
new[] { TellRule with { Pattern = "^[^\"]+@[a-z0-9-]+ tells you, \"" }, SentRule, GlobalRule });
e = sim.Apply(changed);
RynthChatFilterDto tell = sim.Rules.Single(r => r.When == "type:3");
Check(e.Updates.Count == 1 && e.Inserts.Length == 0 && e.Removes.Length == 0 && tell.Pattern == changed.Rules[0].Pattern, "a pattern the manifest changed is rewritten in place");
Check(tell.Color == "#FF0000" && !sim.Rules.Single(r => r.When == "type:4").Enabled, "the colour and the other rule's off switch stay put");
Case("Reclaim_FindsRulesAnOlderEngineStripped");
// An older engine rewrote the file: its copy of the rules has no owner, server or globalRoom.
RynthChatFilterDto Strip(RynthChatFilterDto r) => new() { Tab = r.Tab, Action = r.Action, When = r.When, Mode = r.Mode, Pattern = r.Pattern, Enabled = r.Enabled };
RynthChatFilterDto[] ours = new TabSim { Room = "Trade" }.Apply(d).Inserts;
var player = new RynthChatFilterDto { Tab = "RP", Action = "copy", Mode = "startswith", Pattern = "[Roleplay] " };
var file = new List<RynthChatFilterDto> { player, Strip(ours[1]), new() { Tab = "Junk", Action = "hide", Pattern = "spam" }, Strip(ours[0]), Strip(ours[2]) };
int[]? found = ChatServerTabs.Reclaim(d, file, "DreamWeave");
Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), $"found in declaration order, not the player's look-alike Global rule: {(found == null ? "null" : string.Join(",", found))}");
foreach (RynthChatFilterDto r in file) if (r.Tab == "Network") r.Tab = "DN";
found = ChatServerTabs.Reclaim(d, file, "DreamWeave");
Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), "a renamed tab holding only those rules is found too");
Check(ChatServerTabs.Reclaim(d, new[] { player, Strip(ours[0]) }) == null, "an incomplete set is not reclaimed");
Check(ChatServerTabs.Reclaim(d, new[] { Strip(ours[0]), Strip(ours[1]), new RynthChatFilterDto { Tab = "Other", Action = "copy", Mode = "startswith", Pattern = "[Trade] " } }) == null,
"the set must be in one tab");
file[3].Owner = key;
Check(ChatServerTabs.Reclaim(d, file, "DreamWeave") == null, "a rule that still has an owner is not reclaimed");
Case("Reclaim_RefusesAPlayersLookAlikeTab");
var mine = new List<RynthChatFilterDto> { Strip(ours[0]), Strip(ours[1]), Strip(ours[2]) };
foreach (RynthChatFilterDto r in mine) r.Tab = "Mine";
Check(ChatServerTabs.Reclaim(d, mine, "DreamWeave") != null, "a tab holding only those rules is reclaimed (renamed)");
mine.Add(new RynthChatFilterDto { Tab = "Mine", Action = "copy", Pattern = "^Bob" });
Check(ChatServerTabs.Reclaim(d, mine, "DreamWeave") == null, "a tab with another rule of the player's, not named for the entry, is not");
foreach (RynthChatFilterDto r in mine) r.Tab = "Network (DreamWeave)";
Check(ChatServerTabs.Reclaim(d, mine, "DreamWeave") != null, "the entry's clash name is reclaimed with the player's rule in it");
foreach (RynthChatFilterDto r in mine) r.Tab = "Network";
Check(ChatServerTabs.Reclaim(d, mine, "DreamWeave") != null, "so is the entry's own name");
Case("Apply_StrippedByOlderEngineAddsNoSecondSet");
sim = new TabSim();
sim.Apply(d);
sim.Rules[1].Enabled = false;
sim.Rules = sim.Rules.Select(Strip).ToList(); // an older engine saved: owner, server, globalRoom gone
sim.Seeded.Clear();
sim.TabServers.Clear();
sim.Pins = Array.Empty<string>();
e = sim.Apply(d);
Check(e.Inserts.Length == 0 && e.Removes.Length == 0 && e.Updates.Count == 3 && e.CreateTab == null, "the stripped rules are rewritten, not doubled: " + e.Inserts.Length);
Check(e.Seed == key && e.TabServer == "Network" && e.Pin == null, "seed mark and server entry restored, pin not forced back");
Check(sim.Rules.Count == 3 && sim.Rules.All(r => r.Owner == key) && !sim.Rules[1].Enabled, "owned again, the off switch kept");
Check(!sim.Apply(d).Changed, "and stable");
Case("TabBookkeeping_RenameAndDelete");
var servers = ChatServerTabs.NewMap(new Dictionary<string, string> { ["Network"] = "dreamweave", ["Other"] = "aelrynth" });
(Dictionary<string, string> s1, string[] p1) = ChatServerTabs.RenameTab(servers, new[] { "Chat", "network", "All" }, "Network", "DN");
Check(s1["DN"] == "dreamweave" && !s1.ContainsKey("Network") && s1["Other"] == "aelrynth", "rename: the server entry moves, others stay");
Check(p1.SequenceEqual(new[] { "Chat", "DN", "All" }), "rename: the pin keeps its place (any case)");
(Dictionary<string, string> s2, string[] p2) = ChatServerTabs.DeleteTab(s1, p1, "dn");
Check(!s2.ContainsKey("DN") && s2.Count == 1 && p2.SequenceEqual(new[] { "Chat", "All" }), "delete: the server entry and the pin go");
(Dictionary<string, string> s3, string[] p3) = ChatServerTabs.RenameTab(s2, p2, "Mine", "Ours");
Check(s3.Count == 1 && p3.SequenceEqual(p2), "renaming an unpinned player tab touches neither");
Case("ListTabs_HidesInactiveServerTabs");
ChatFilterRule Rule(string tab, string server = "", bool on = true)
{
var r = new ChatFilterRule { Pattern = "^x", Tab = tab, Action = ChatRuleAction.Copy, Server = server, Enabled = on };
r.Recompile();
return r;
}
string[] baseTabs = { "All", "Chat" };
var rules = new[] { Rule("Network", "dreamweave"), Rule("Extra", "dreamweave"), Rule("Mine"), Rule("Off", "", on: false) };
var tabServers = ChatServerTabs.NewMap(new Dictionary<string, string> { ["Network"] = "dreamweave" });
string[] custom = { "Network", "Kept" };
string[] onDw = ChatServerTabs.ListTabs(baseTabs, custom, rules, new[] { "Preset" }, tabServers, new[] { "DreamWeave" });
string[] onOther = ChatServerTabs.ListTabs(baseTabs, custom, rules, new[] { "Preset" }, tabServers, new[] { "aelrynth" });
string[] every = ChatServerTabs.ListTabs(baseTabs, custom, rules, new[] { "Preset" }, tabServers, null);
Check(onDw.SequenceEqual(new[] { "All", "Chat", "Network", "Kept", "Extra", "Mine", "Preset" }), "its server active: every tab: " + string.Join(",", onDw));
Check(onOther.SequenceEqual(new[] { "All", "Chat", "Kept", "Mine", "Preset" }), "another server: the server's tab and the tab only its rule fills are hidden: " + string.Join(",", onOther));
Check(every.SequenceEqual(onDw), "no filter: every tab");
Check(ChatServerTabs.ListTabs(baseTabs, custom, rules, Array.Empty<string>(), ChatServerTabs.NewMap(new Dictionary<string, string> { ["Chat"] = "dreamweave" }), Array.Empty<string>()).Contains("Chat"),
"a base tab is never hidden");
Case("Export_SkipsServerRules_ImportClearsOwnership");
sim = new TabSim();
sim.Apply(d);
sim.Custom.Add("Mine");
sim.Rules.Add(new RynthChatFilterDto { Tab = "Mine", Action = "copy", Pattern = "^Bob", Enabled = true });
var set = new RynthChatRuleSetDto
{
Format = RynthChatRuleSetDto.FormatName,
Tabs = ChatServerTabs.ExportTabs(sim.Custom, sim.TabServers),
Rules = ChatServerTabs.ExportRules(sim.Rules),
};
string json = JsonSerializer.Serialize(set, RynthChatJsonContext.Default.RynthChatRuleSetDto);
RynthChatRuleSetDto? back = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatRuleSetDto);
Check(back?.Rules?.Length == 1 && back.Rules[0].Pattern == "^Bob" && back.Tabs!.SequenceEqual(new[] { "Mine" }), "export: the player's rule and tab only");
Check(!json.Contains("\"owner\"") && !json.Contains("Network"), "export: no server rule, no server tab");
// A whole settings file pasted into Import carries the server's rules: they become the player's.
RynthChatFilterDto[] imported = sim.Rules.Select(CloneRule).Select(ChatServerTabs.AsPlayerRule).ToArray();
Check(imported.All(r => r.Owner == null && r.Server == null && r.GlobalRoom == null), "import: no owner, every server, a fixed pattern");
Check(imported[2].Pattern == "[Roleplay] " && imported[2].Mode == "startswith" && imported[0].When == "type:3", "import keeps what the rule does");
Case("Refresh_IsANoOpWhenNothingChanged (SameRule)");
var absent = new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", When = null, Mode = null, Pattern = "x", GlobalRoom = null, Enabled = true };
var empty = new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", When = "", Mode = "", Pattern = "x", GlobalRoom = false, Enabled = true };
Check(ChatServerTabs.SameRule(absent, empty), "absent and empty When / Mode / GlobalRoom are the same");
Check(ChatServerTabs.SameRule(empty, new RynthChatFilterDto { Owner = key, Server = "dreamweave", Tab = "Network", Action = "copy", Pattern = "x", Color = "#FF0000", ColorMode = "line" }),
"a colour the player gave the rule is not a difference");
Check(!ChatServerTabs.SameRule(owned[2], ChatServerTabs.Plan(d, State(), "General").Rules[2]), "a new Global room is a difference");
var off = ChatServerTabs.Plan(d, State(), "Trade").Rules;
off[0].Enabled = false;
Check(!ChatServerTabs.SameRule(owned[0], off[0]), "on / off is a difference");
Case("Reclaim_FindsRulesAnOlderEngineStripped");
// An older engine rewrote the file: its copy of the rules has no owner, server or globalRoom.
RynthChatFilterDto Strip(RynthChatFilterDto r) => new() { Tab = r.Tab, Action = r.Action, When = r.When, Mode = r.Mode, Pattern = r.Pattern, Enabled = r.Enabled };
RynthChatFilterDto[] ours = ChatServerTabs.Plan(d, State(), "Trade").Rules;
var player = new RynthChatFilterDto { Tab = "RP", Action = "copy", Mode = "startswith", Pattern = "[Roleplay] " };
var file = new List<RynthChatFilterDto> { player, Strip(ours[1]), new() { Tab = "Junk", Action = "hide", Pattern = "spam" }, Strip(ours[0]), Strip(ours[2]) };
int[]? found = ChatServerTabs.Reclaim(d, file);
Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), $"found in declaration order, not the player's look-alike Global rule: {(found == null ? "null" : string.Join(",", found))}");
foreach (RynthChatFilterDto r in file) if (r.Tab == "Network") r.Tab = "DN";
found = ChatServerTabs.Reclaim(d, file);
Check(found != null && found.SequenceEqual(new[] { 3, 1, 4 }), "a renamed tab's stripped rules are found too");
Check(ChatServerTabs.Reclaim(d, new[] { player, Strip(ours[0]) }) == null, "an incomplete set is not reclaimed");
file[3].Owner = key;
Check(ChatServerTabs.Reclaim(d, file) == null, "a rule that still has an owner is not reclaimed");
Check(ChatServerTabs.Reclaim(d, new[] { Strip(ours[0]), Strip(ours[1]), new RynthChatFilterDto { Tab = "Other", Action = "copy", Mode = "startswith", Pattern = "[Trade] " } }) == null,
"the set must be in one tab");
var off = CloneRule(empty);
off.Enabled = false;
Check(!ChatServerTabs.SameRule(empty, off), "on / off is a difference");
Case("Router_SkipsRulesOfInactiveServers");
var serverRule = new ChatFilterRule { Pattern = "^x", Tab = "Network", Action = ChatRuleAction.Copy, Server = "dreamweave" };
@ -1261,8 +1449,8 @@ internal static class Program
Check(!offRoute.ShowsIn("Network", "Chat") && offRoute.ShowsIn("Every", "Chat"), "another server: only the every-server rule runs");
Check(!none.ShowsIn("Network", "Chat") && none.ShowsIn("Every", "Chat"), "no servers known: only the every-server rule runs");
Case("Plan rules compile");
foreach (RynthChatFilterDto r in ChatServerTabs.Plan(d, State(), "LFG").Rules)
Case("Apply rules compile");
foreach (RynthChatFilterDto r in new TabSim { Room = "LFG" }.Apply(d).Inserts)
{
System.Text.RegularExpressions.Regex? rx = ChatRuleMatching.Compile(ChatRuleMatching.Parse(r.Mode), r.Pattern, 5000, out string? err);
Check(err == null && rx != null, $"rule '{r.Pattern}' compiles: {err}");

View file

@ -616,6 +616,19 @@ internal static class Program
var noFallback = SectionManifestParser.Parse("DW", """{ "chatTabs": [ { "server": "dw", "id": "a", "name": "A", "rules": [] } ] }""", out _);
Check(noFallback.ChatTabs.Length == 1 && noFallback.ChatTabs[0].GlobalRoomFallback == "Roleplay", "absent globalRoomFallback = Roleplay");
Case("manifest: chatTabs rule when, mode and pattern are kept as written");
m = SectionManifestParser.Parse("DW", """
{ "chatTabs": [ { "server": "dw", "id": "a", "name": "A", "rules": [
{ "action": "copy", "when": "chan:Combat", "mode": "StartsWith", "pattern": "[Trade] " },
{ "action": "copy", "when": "TYPE:4", "mode": "contains", "pattern": " two " },
{ "action": "copy", "when": "", "mode": "startswith", "pattern": "ignored", "globalRoom": true } ] } ] }
""", out err);
Check(err.Length == 0 && m.ChatTabs.Length == 1 && m.ChatTabs[0].Rules.Length == 3, "three valid rules parse: " + err);
SectionChatRuleDecl[] kept = m.ChatTabs.Length == 1 ? m.ChatTabs[0].Rules : System.Array.Empty<SectionChatRuleDecl>();
Check(kept.Length == 3 && kept[0].Pattern == "[Trade] " && kept[1].Pattern == " two ", "a pattern's spaces are kept");
Check(kept.Length == 3 && kept[0].When == "chan:Combat" && kept[1].When == "TYPE:4" && kept[0].Mode == "startswith", "chan:/type: when accepted, mode lower-cased");
Check(kept.Length == 3 && kept[2].Pattern == "", "a globalRoom rule's pattern is ignored (the engine supplies it)");
// Each reject drops the entry, reports it in error, and still parses the other keys.
string section = """ "sections": [ { "id": "quests", "label": "Quests", "order": 150 } ] """;
string[] bad =
@ -625,8 +638,14 @@ internal static class Program
"""{ "server": "dw", "id": "Bad Id", "name": "A", "globalRoomFallback": "General", "rules": [] }""",
"""{ "server": "dw", "id": "a", "name": "A", "globalRoomFallback": "General", "rules": [ { "action": "delete", "when": "", "mode": "", "pattern": "x" } ] }""",
"""{ "server": "dw", "id": "a", "name": "A", "globalRoomFallback": "Sports", "rules": [] }""",
"""{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "typo:3", "mode": "", "pattern": "x" } ] }""",
"""{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "type:x", "mode": "", "pattern": "x" } ] }""",
"""{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "type:-1", "mode": "", "pattern": "x" } ] }""",
"""{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "chan:", "mode": "", "pattern": "x" } ] }""",
"""{ "server": "dw", "id": "a", "name": "A", "rules": [ { "action": "copy", "when": "", "mode": "startwith", "pattern": "x" } ] }""",
};
string[] why = { "missing server", "missing id", "bad id", "bad action", "bad fallback" };
string[] why = { "missing server", "missing id", "bad id", "bad action", "bad fallback",
"when typo:3", "when type:x", "when type:-1", "when chan: with no tab", "mode startwith" };
for (int i = 0; i < bad.Length; i++)
{
m = SectionManifestParser.Parse("DW", "{ " + section + ", \"chatTabs\": [" + bad[i] + "] }", out err);