feat(ui): complete Avalonia UI port with 7 main pages, tool settings & top MenuBar
This commit is contained in:
@@ -1,147 +0,0 @@
|
||||
using ClawdDotNet.Core.Backup;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ClawdDotNet.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Erstellt einmal täglich zur eingestellten Uhrzeit eine Sicherung.
|
||||
///
|
||||
/// Bewusst ohne Zugangsdaten: Die Passphrase müsste dafür gespeichert werden, und
|
||||
/// neben den Sicherungen abgelegt wäre sie wirkungslos. Wer die Zugangsdaten
|
||||
/// mitsichern will, macht das von Hand.
|
||||
///
|
||||
/// Der Zeitpunkt wird bei jedem Durchlauf neu gegen die Einstellungen geprüft, damit
|
||||
/// eine Änderung ohne Neustart greift.
|
||||
/// </summary>
|
||||
public sealed class BackupScheduler : IDisposable
|
||||
{
|
||||
private readonly string _instanceDir;
|
||||
private readonly string _instanceName;
|
||||
private readonly SettingsManager _settings;
|
||||
private readonly ILogger _logger;
|
||||
private readonly BackupService _service = new();
|
||||
private readonly System.Windows.Forms.Timer _timer;
|
||||
|
||||
/// <summary>Verhindert mehrere Sicherungen innerhalb derselben Minute.</summary>
|
||||
private DateTime? _lastRun;
|
||||
|
||||
private bool _running;
|
||||
|
||||
public event Action<string>? OnBackupCreated;
|
||||
|
||||
public BackupScheduler(string instanceDir, string instanceName,
|
||||
SettingsManager settings, ILogger logger)
|
||||
{
|
||||
_instanceDir = instanceDir;
|
||||
_instanceName = instanceName;
|
||||
_settings = settings;
|
||||
_logger = logger;
|
||||
|
||||
// Minütlich prüfen reicht — die Uhrzeit ist auf Minuten genau eingestellt.
|
||||
_timer = new System.Windows.Forms.Timer { Interval = 60_000 };
|
||||
_timer.Tick += async (_, _) => await TickAsync();
|
||||
}
|
||||
|
||||
public void Start() => _timer.Start();
|
||||
|
||||
public void Stop() => _timer.Stop();
|
||||
|
||||
private async Task TickAsync()
|
||||
{
|
||||
if (_running)
|
||||
return;
|
||||
|
||||
var settings = _settings.AppSettings;
|
||||
if (!settings.AutoBackupEnabled)
|
||||
return;
|
||||
|
||||
if (!TimeSpan.TryParse(settings.AutoBackupTime, out var scheduled))
|
||||
return;
|
||||
|
||||
var now = DateTime.Now;
|
||||
|
||||
// Fällig, sobald die Uhrzeit erreicht ist und heute noch nichts lief.
|
||||
if (now.TimeOfDay < scheduled)
|
||||
return;
|
||||
|
||||
if (_lastRun?.Date == now.Date)
|
||||
return;
|
||||
|
||||
_running = true;
|
||||
try
|
||||
{
|
||||
await RunAsync(settings.BackupDirectory, settings.BackupKeepCount);
|
||||
_lastRun = now;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Ein Fehlschlag darf die Anwendung nicht stören; er wird protokolliert
|
||||
// und morgen erneut versucht.
|
||||
_logger.LogError(ex, "Automatische Sicherung fehlgeschlagen");
|
||||
_lastRun = now;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_running = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAsync(string folder, int keepCount)
|
||||
{
|
||||
var safeName = string.Concat(
|
||||
_instanceName.Select(c => Path.GetInvalidFileNameChars().Contains(c) ? '_' : c));
|
||||
|
||||
var file = Path.Combine(
|
||||
Path.GetFullPath(folder),
|
||||
$"backup_{safeName}_{DateTime.Now:yyyy-MM-dd_HHmm}.zip");
|
||||
|
||||
var result = await _service.CreateAsync(_instanceDir, file, new BackupOptions
|
||||
{
|
||||
Secrets = SecretMode.Exclude,
|
||||
IncludeChatHistory = true,
|
||||
IncludeLogs = false
|
||||
});
|
||||
|
||||
_logger.LogInformation("Automatische Sicherung erstellt: {Path} ({Size} Bytes)",
|
||||
result.ZipPath, result.SizeBytes);
|
||||
|
||||
ApplyRotation(Path.GetFullPath(folder), safeName, keepCount);
|
||||
|
||||
OnBackupCreated?.Invoke(result.ZipPath);
|
||||
}
|
||||
|
||||
/// <summary>Behält die neuesten Sicherungen dieser Instanz und entfernt den Rest.</summary>
|
||||
private void ApplyRotation(string folder, string safeName, int keepCount)
|
||||
{
|
||||
if (keepCount <= 0 || !Directory.Exists(folder))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
var prefix = $"backup_{safeName}_";
|
||||
|
||||
var obsolete = new DirectoryInfo(folder)
|
||||
.GetFiles("*.zip")
|
||||
.Where(f => f.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderByDescending(f => f.LastWriteTime)
|
||||
.Skip(keepCount)
|
||||
.ToList();
|
||||
|
||||
foreach (var file in obsolete)
|
||||
{
|
||||
file.Delete();
|
||||
_logger.LogInformation("Alte Sicherung entfernt: {Name}", file.Name);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Rotation der Sicherungen fehlgeschlagen");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timer.Stop();
|
||||
_timer.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,454 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using ClawdDotNet.Core.Config;
|
||||
using ClawdDotNet.Core.Security;
|
||||
using ClawdDotNet.Core.Storage;
|
||||
using ClawdDotNet.Models;
|
||||
|
||||
namespace ClawdDotNet.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Verwaltet die gesamte Verzeichnisstruktur für Instanzen und Agenten.
|
||||
///
|
||||
/// Layout:
|
||||
/// {InstancesDir}/
|
||||
/// ├── Instance-{Name}/
|
||||
/// │ ├── InstanceSettings.json
|
||||
/// │ ├── TokenUsage.json
|
||||
/// │ └── Agents/
|
||||
/// │ ├── AgentList.json
|
||||
/// │ └── Agent-{Name}/
|
||||
/// │ ├── AgentSettings.json
|
||||
/// │ ├── Soul.md
|
||||
/// │ ├── Identity.md
|
||||
/// │ ├── Logs/
|
||||
/// │ └── Workspace/
|
||||
/// </summary>
|
||||
public sealed class InstanceDirectoryManager
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOpts = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
private readonly string _instancesDir;
|
||||
private readonly Lock _tokenUsageLock = new();
|
||||
|
||||
public InstanceDirectoryManager(string instancesDirectory)
|
||||
{
|
||||
_instancesDir = Path.GetFullPath(instancesDirectory);
|
||||
Directory.CreateDirectory(_instancesDir);
|
||||
}
|
||||
|
||||
public string InstancesDirectory => _instancesDir;
|
||||
|
||||
// ═══════════════════════════════════════════════════
|
||||
// INSTANZ-OPERATIONEN
|
||||
// ═══════════════════════════════════════════════════
|
||||
|
||||
public static string BuildInstanceFolderName(string instanceName)
|
||||
=> $"Instance-{SanitizeName(instanceName)}";
|
||||
|
||||
public string GetInstancePath(string instanceName)
|
||||
=> Path.Combine(_instancesDir, BuildInstanceFolderName(instanceName));
|
||||
|
||||
public List<InstanceInfo> ListInstances()
|
||||
{
|
||||
var result = new List<InstanceInfo>();
|
||||
|
||||
if (!Directory.Exists(_instancesDir))
|
||||
return result;
|
||||
|
||||
foreach (var dir in Directory.GetDirectories(_instancesDir, "Instance-*"))
|
||||
{
|
||||
var folderName = Path.GetFileName(dir);
|
||||
var settingsPath = Path.Combine(dir, "InstanceSettings.json");
|
||||
|
||||
var info = new InstanceInfo
|
||||
{
|
||||
FolderName = folderName,
|
||||
FolderPath = dir,
|
||||
InstanceName = folderName.Replace("Instance-", "")
|
||||
};
|
||||
|
||||
if (File.Exists(settingsPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(settingsPath);
|
||||
var config = JsonSerializer.Deserialize<InstanceConfig>(json, JsonOpts);
|
||||
if (config is not null)
|
||||
{
|
||||
info.InstanceName = config.InstanceName;
|
||||
info.ApiKeyStatus = string.IsNullOrWhiteSpace(config.OpenRouterApiKey)
|
||||
? "Fehlt" : "Konfiguriert";
|
||||
}
|
||||
}
|
||||
catch { /* defekte Config → Standardwerte */ }
|
||||
}
|
||||
|
||||
// Agenten zählen
|
||||
var agentsDir = Path.Combine(dir, "Agents");
|
||||
if (Directory.Exists(agentsDir))
|
||||
info.AgentCount = Directory.GetDirectories(agentsDir, "Agent-*").Length;
|
||||
|
||||
result.Add(info);
|
||||
}
|
||||
|
||||
return result.OrderBy(i => i.InstanceName).ToList();
|
||||
}
|
||||
|
||||
public string CreateInstance(string instanceName)
|
||||
{
|
||||
var instanceDir = GetInstancePath(instanceName);
|
||||
|
||||
if (Directory.Exists(instanceDir))
|
||||
throw new InvalidOperationException($"Instanz '{instanceName}' existiert bereits.");
|
||||
|
||||
// Hauptverzeichnis
|
||||
Directory.CreateDirectory(instanceDir);
|
||||
|
||||
// Agents-Unterverzeichnis
|
||||
var agentsDir = Path.Combine(instanceDir, "Agents");
|
||||
Directory.CreateDirectory(agentsDir);
|
||||
|
||||
// SharedWorkspace-Verzeichnis
|
||||
Directory.CreateDirectory(Path.Combine(agentsDir, "SharedWorkspace"));
|
||||
|
||||
// InstanceSettings.json
|
||||
var config = new InstanceConfig
|
||||
{
|
||||
InstanceId = Guid.NewGuid().ToString("N")[..8],
|
||||
InstanceName = instanceName,
|
||||
LogDirectory = "./Logs",
|
||||
WorkingDirectory = instanceDir
|
||||
};
|
||||
SaveJson(Path.Combine(instanceDir, "InstanceSettings.json"), config);
|
||||
|
||||
// TokenUsage.json (leer)
|
||||
var tokenUsage = new TokenUsageFile
|
||||
{
|
||||
InstanceId = config.InstanceId,
|
||||
InstanceName = instanceName
|
||||
};
|
||||
SaveJson(Path.Combine(instanceDir, "TokenUsage.json"), tokenUsage);
|
||||
|
||||
// AgentList.json (leer)
|
||||
SaveJson(Path.Combine(agentsDir, "AgentList.json"), new AgentListFile());
|
||||
|
||||
return instanceDir;
|
||||
}
|
||||
|
||||
public InstanceConfig LoadInstanceConfig(string instanceDir)
|
||||
{
|
||||
var settingsPath = Path.Combine(instanceDir, "InstanceSettings.json");
|
||||
|
||||
if (!File.Exists(settingsPath))
|
||||
throw new FileNotFoundException($"InstanceSettings.json nicht gefunden in: {instanceDir}");
|
||||
|
||||
var json = File.ReadAllText(settingsPath);
|
||||
var config = JsonSerializer.Deserialize<InstanceConfig>(json, JsonOpts)
|
||||
?? throw new InvalidOperationException("InstanceSettings.json ist leer oder ungültig.");
|
||||
|
||||
// Agenten aus Verzeichnisstruktur laden
|
||||
config.Agents.Clear();
|
||||
var agentsDir = Path.Combine(instanceDir, "Agents");
|
||||
|
||||
// Sicherstellen, dass SharedWorkspace existiert (Migration)
|
||||
Directory.CreateDirectory(Path.Combine(agentsDir, "SharedWorkspace"));
|
||||
|
||||
// AgentList.json für Descriptions laden
|
||||
var agentListPath = Path.Combine(agentsDir, "AgentList.json");
|
||||
var agentList = File.Exists(agentListPath)
|
||||
? LoadJson<AgentListFile>(agentListPath) ?? new AgentListFile()
|
||||
: new AgentListFile();
|
||||
|
||||
if (Directory.Exists(agentsDir))
|
||||
{
|
||||
foreach (var agentDir in Directory.GetDirectories(agentsDir, "Agent-*").OrderBy(d => d))
|
||||
{
|
||||
var agent = LoadAgentConfig(agentDir);
|
||||
|
||||
var folderName = Path.GetFileName(agentDir);
|
||||
var listEntry = agentList.Agents.FirstOrDefault(a => a.FolderName == folderName);
|
||||
if (listEntry is not null && !string.IsNullOrWhiteSpace(listEntry.Description))
|
||||
agent.Description = listEntry.Description;
|
||||
|
||||
config.Agents.Add(agent);
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
public void SaveInstanceConfig(string instanceDir, InstanceConfig config)
|
||||
{
|
||||
var settingsPath = Path.Combine(instanceDir, "InstanceSettings.json");
|
||||
|
||||
// Zugangsdaten nur für das Schreiben verschlüsseln — die laufende Instanz
|
||||
// braucht sie danach wieder im Klartext.
|
||||
ConfigSecrets.Protect(config);
|
||||
try
|
||||
{
|
||||
SaveJson(settingsPath, config);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ConfigSecrets.Unprotect(config);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════
|
||||
// AGENTEN-OPERATIONEN
|
||||
// ═══════════════════════════════════════════════════
|
||||
|
||||
public static string BuildAgentFolderName(string agentName)
|
||||
=> $"Agent-{SanitizeName(agentName)}";
|
||||
|
||||
public string GetAgentPath(string instanceDir, string agentName)
|
||||
=> Path.Combine(instanceDir, "Agents", BuildAgentFolderName(agentName));
|
||||
|
||||
public string CreateAgent(string instanceDir, string agentName, string description = "")
|
||||
{
|
||||
var agentDir = GetAgentPath(instanceDir, agentName);
|
||||
|
||||
if (Directory.Exists(agentDir))
|
||||
throw new InvalidOperationException($"Agent '{agentName}' existiert bereits in dieser Instanz.");
|
||||
|
||||
// Verzeichnisse anlegen
|
||||
Directory.CreateDirectory(agentDir);
|
||||
Directory.CreateDirectory(Path.Combine(agentDir, "Logs"));
|
||||
Directory.CreateDirectory(Path.Combine(agentDir, "Workspace"));
|
||||
|
||||
// AgentSettings.json
|
||||
var agentConfig = new AgentConfig
|
||||
{
|
||||
AgentId = SanitizeName(agentName).ToLowerInvariant(),
|
||||
DisplayName = agentName,
|
||||
Model = "anthropic/claude-sonnet-4-5"
|
||||
};
|
||||
SaveAgentSettings(agentDir, agentConfig);
|
||||
|
||||
// Identity.md
|
||||
AtomicFile.WriteAllText(Path.Combine(agentDir, "Identity.md"),
|
||||
$"""
|
||||
# Identity: {agentName}
|
||||
|
||||
Du bist **{agentName}**, ein spezialisierter KI-Agent im ClawdDotNet-System.
|
||||
|
||||
## Rolle
|
||||
[Beschreibe hier die Rolle und Verantwortlichkeiten des Agenten]
|
||||
|
||||
## Expertise
|
||||
[Beschreibe hier die Fachgebiete und Fähigkeiten]
|
||||
|
||||
## Kontext
|
||||
[Beschreibe hier den Arbeitskontext und die Teamzugehörigkeit]
|
||||
""");
|
||||
|
||||
// Soul.md
|
||||
AtomicFile.WriteAllText(Path.Combine(agentDir, "Soul.md"),
|
||||
$"""
|
||||
# Soul: {agentName}
|
||||
|
||||
## Persönlichkeit
|
||||
- Gründlich und zuverlässig
|
||||
- Klar und präzise in der Kommunikation
|
||||
- Proaktiv bei der Problemerkennung
|
||||
|
||||
## Arbeitsweise
|
||||
- Analysiere Aufgaben sorgfältig bevor du handelst
|
||||
- Dokumentiere deine Entscheidungen und Ergebnisse
|
||||
- Nutze die dir zugewiesenen Tools effizient
|
||||
|
||||
## Werte
|
||||
- Genauigkeit vor Geschwindigkeit
|
||||
- Transparenz in der Entscheidungsfindung
|
||||
- Sicherheit und Datenschutz haben Priorität
|
||||
""");
|
||||
|
||||
// AgentList.json aktualisieren
|
||||
UpdateAgentList(instanceDir, agentName, description, BuildAgentFolderName(agentName));
|
||||
|
||||
return agentDir;
|
||||
}
|
||||
|
||||
public AgentConfig LoadAgentConfig(string agentDir)
|
||||
{
|
||||
// AgentSettings.json laden
|
||||
var settingsPath = Path.Combine(agentDir, "AgentSettings.json");
|
||||
AgentConfig config;
|
||||
|
||||
if (File.Exists(settingsPath))
|
||||
{
|
||||
var json = File.ReadAllText(settingsPath);
|
||||
config = JsonSerializer.Deserialize<AgentConfig>(json, JsonOpts) ?? new AgentConfig();
|
||||
ConfigLoader.Migrate(config);
|
||||
ConfigSecrets.Unprotect(config);
|
||||
}
|
||||
else
|
||||
{
|
||||
config = new AgentConfig
|
||||
{
|
||||
AgentId = Path.GetFileName(agentDir).Replace("Agent-", "").ToLowerInvariant(),
|
||||
DisplayName = Path.GetFileName(agentDir).Replace("Agent-", "")
|
||||
};
|
||||
}
|
||||
|
||||
// Identity.md laden
|
||||
var identityPath = Path.Combine(agentDir, "Identity.md");
|
||||
if (File.Exists(identityPath))
|
||||
config.Identity = File.ReadAllText(identityPath);
|
||||
|
||||
// Soul.md laden
|
||||
var soulPath = Path.Combine(agentDir, "Soul.md");
|
||||
if (File.Exists(soulPath))
|
||||
config.Soul = File.ReadAllText(soulPath);
|
||||
|
||||
// Agent-Verzeichnis merken (stabil auch bei DisplayName-Änderungen)
|
||||
config.AgentDir = Path.GetFullPath(agentDir);
|
||||
|
||||
// Workspace-Pfad setzen
|
||||
config.WorkspacePath = Path.GetFullPath(Path.Combine(agentDir, "Workspace"));
|
||||
|
||||
// SharedWorkspace-Pfad setzen
|
||||
var agentsDir = Path.GetDirectoryName(agentDir); // Dies ist der /Agents Ordner
|
||||
if (agentsDir != null)
|
||||
{
|
||||
config.SharedWorkspacePath = Path.GetFullPath(Path.Combine(agentsDir, "SharedWorkspace"));
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
public void SaveAgentSettings(string agentDir, AgentConfig config)
|
||||
{
|
||||
var settingsPath = Path.Combine(agentDir, "AgentSettings.json");
|
||||
|
||||
ConfigSecrets.Protect(config);
|
||||
try
|
||||
{
|
||||
SaveJson(settingsPath, config);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ConfigSecrets.Unprotect(config);
|
||||
}
|
||||
}
|
||||
|
||||
public void SaveAgentIdentity(string agentDir, string identity)
|
||||
{
|
||||
AtomicFile.WriteAllText(Path.Combine(agentDir, "Identity.md"), identity);
|
||||
}
|
||||
|
||||
public void SaveAgentSoul(string agentDir, string soul)
|
||||
{
|
||||
AtomicFile.WriteAllText(Path.Combine(agentDir, "Soul.md"), soul);
|
||||
}
|
||||
|
||||
public void RemoveAgent(string instanceDir, string agentFolderName)
|
||||
{
|
||||
var agentDir = Path.Combine(instanceDir, "Agents", agentFolderName);
|
||||
if (Directory.Exists(agentDir))
|
||||
Directory.Delete(agentDir, recursive: true);
|
||||
|
||||
// AgentList.json aktualisieren
|
||||
var agentListPath = Path.Combine(instanceDir, "Agents", "AgentList.json");
|
||||
if (File.Exists(agentListPath))
|
||||
{
|
||||
var list = LoadJson<AgentListFile>(agentListPath) ?? new AgentListFile();
|
||||
list.Agents.RemoveAll(a => a.FolderName == agentFolderName);
|
||||
SaveJson(agentListPath, list);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════
|
||||
// TOKEN USAGE
|
||||
// ═══════════════════════════════════════════════════
|
||||
|
||||
public void AppendTokenUsage(string instanceDir, TokenUsageRecord record)
|
||||
{
|
||||
lock (_tokenUsageLock)
|
||||
{
|
||||
var path = Path.Combine(instanceDir, "TokenUsage.json");
|
||||
TokenUsageFile file;
|
||||
|
||||
if (File.Exists(path))
|
||||
{
|
||||
try
|
||||
{
|
||||
file = LoadJson<TokenUsageFile>(path) ?? new TokenUsageFile();
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Korrupte Datei: Backup erstellen, neu anfangen
|
||||
var backupPath = path + $".corrupt_{DateTime.Now:yyyyMMdd_HHmmss}";
|
||||
try { File.Copy(path, backupPath, overwrite: true); } catch { /* best effort */ }
|
||||
file = new TokenUsageFile();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
file = new TokenUsageFile();
|
||||
}
|
||||
|
||||
file.Records.Add(record);
|
||||
SaveJson(path, file);
|
||||
}
|
||||
}
|
||||
|
||||
public TokenUsageFile LoadTokenUsage(string instanceDir)
|
||||
{
|
||||
var path = Path.Combine(instanceDir, "TokenUsage.json");
|
||||
return File.Exists(path)
|
||||
? LoadJson<TokenUsageFile>(path) ?? new TokenUsageFile()
|
||||
: new TokenUsageFile();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════
|
||||
// HILFSMETHODEN
|
||||
// ═══════════════════════════════════════════════════
|
||||
|
||||
private void UpdateAgentList(string instanceDir, string agentName, string description, string folderName)
|
||||
{
|
||||
var agentListPath = Path.Combine(instanceDir, "Agents", "AgentList.json");
|
||||
var list = File.Exists(agentListPath)
|
||||
? LoadJson<AgentListFile>(agentListPath) ?? new AgentListFile()
|
||||
: new AgentListFile();
|
||||
|
||||
// Duplikat-Check
|
||||
if (list.Agents.All(a => a.FolderName != folderName))
|
||||
{
|
||||
list.Agents.Add(new AgentListItem
|
||||
{
|
||||
Name = agentName,
|
||||
Description = description,
|
||||
FolderName = folderName
|
||||
});
|
||||
}
|
||||
|
||||
SaveJson(agentListPath, list);
|
||||
}
|
||||
|
||||
private static void SaveJson<T>(string path, T obj)
|
||||
{
|
||||
// Atomar: Ein Absturz mitten im Schreiben soll keine halbe Datei hinterlassen.
|
||||
// Genau das ist bereits passiert (TokenUsage.json.corrupt_…).
|
||||
AtomicFile.WriteAllText(path, JsonSerializer.Serialize(obj, JsonOpts));
|
||||
}
|
||||
|
||||
private static T? LoadJson<T>(string path)
|
||||
{
|
||||
// Lesen ohne den Schreiber zu blockieren — siehe AtomicFile.ReadAllText.
|
||||
var json = AtomicFile.ReadAllText(path);
|
||||
return JsonSerializer.Deserialize<T>(json, JsonOpts);
|
||||
}
|
||||
|
||||
private static string SanitizeName(string name)
|
||||
{
|
||||
var sanitized = name.Trim();
|
||||
foreach (var c in Path.GetInvalidFileNameChars())
|
||||
sanitized = sanitized.Replace(c, '_');
|
||||
return sanitized.Replace(' ', '_');
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using ClawdDotNet.Models;
|
||||
|
||||
namespace ClawdDotNet.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Thread-safe JSON persistence for job execution history.
|
||||
/// Uses file locking to handle concurrent access from multiple schedulers.
|
||||
/// </summary>
|
||||
public sealed class JobHistoryService
|
||||
{
|
||||
private readonly string _filePath;
|
||||
private readonly Lock _lock = new();
|
||||
private readonly int _maxEntries;
|
||||
private List<JobHistoryEntry> _entries = new();
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
public JobHistoryService(string instancePath, int maxEntries = 500)
|
||||
{
|
||||
_filePath = Path.Combine(instancePath, "job_history.json");
|
||||
_maxEntries = maxEntries;
|
||||
Load();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new entry to the history (thread-safe, persists immediately).
|
||||
/// </summary>
|
||||
public void Add(JobHistoryEntry entry)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_entries.Insert(0, entry); // newest first
|
||||
|
||||
// Trim old entries
|
||||
if (_entries.Count > _maxEntries)
|
||||
_entries = _entries.Take(_maxEntries).ToList();
|
||||
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a snapshot of all entries (newest first).
|
||||
/// </summary>
|
||||
public List<JobHistoryEntry> GetAll()
|
||||
{
|
||||
lock (_lock)
|
||||
return new List<JobHistoryEntry>(_entries);
|
||||
}
|
||||
|
||||
private void Load()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(_filePath))
|
||||
{
|
||||
_entries = new List<JobHistoryEntry>();
|
||||
return;
|
||||
}
|
||||
|
||||
using var stream = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
_entries = JsonSerializer.Deserialize<List<JobHistoryEntry>>(stream, JsonOptions)
|
||||
?? new List<JobHistoryEntry>();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_entries = new List<JobHistoryEntry>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
var tmpPath = _filePath + ".tmp";
|
||||
using (var stream = new FileStream(tmpPath, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
JsonSerializer.Serialize(stream, _entries, JsonOptions);
|
||||
}
|
||||
|
||||
File.Move(tmpPath, _filePath, overwrite: true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Silently ignore write failures — next save will retry
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using ClawdDotNet.Core.Api;
|
||||
using ClawdDotNet.Core.Api.Models;
|
||||
|
||||
namespace ClawdDotNet.Services;
|
||||
|
||||
public sealed class OpenRouterStatusService : IDisposable
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private readonly System.Windows.Forms.Timer _timer;
|
||||
|
||||
private readonly ConcurrentBag<UsageRecord> _usageRecords = new();
|
||||
|
||||
/// <summary>
|
||||
/// Preise kommen vom /models-Endpunkt statt aus einer fest verdrahteten Tabelle.
|
||||
/// Die alte Tabelle war veraltet und enthielt ausgerechnet das Standardmodell der
|
||||
/// Agenten nicht — die Anzeige meldete dafür stillschweigend 0 €.
|
||||
/// </summary>
|
||||
private readonly ModelPricingCatalog _pricing = new();
|
||||
|
||||
/// <summary>Modelle, für die keine Preise vorliegen — werden in der Anzeige benannt.</summary>
|
||||
private readonly ConcurrentDictionary<string, byte> _modelsWithoutPricing = new();
|
||||
|
||||
private const double UsdToEur = 0.92;
|
||||
|
||||
public bool IsApiReachable { get; private set; }
|
||||
public string StatusText { get; private set; } = "Prüfe...";
|
||||
public string CreditsText { get; private set; } = "—";
|
||||
public string CreditsTooltip { get; private set; } = "";
|
||||
public double? CreditBalance { get; private set; }
|
||||
public double? CreditRemaining { get; private set; }
|
||||
|
||||
public event Action? OnStatusUpdated;
|
||||
|
||||
public OpenRouterStatusService(string apiKey, string baseUrl = "https://openrouter.ai/api/v1/", int checkIntervalSeconds = 60)
|
||||
{
|
||||
_http = new HttpClient { BaseAddress = new Uri(baseUrl) };
|
||||
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
|
||||
_http.DefaultRequestHeaders.Add("HTTP-Referer", "ClawdDotNet");
|
||||
|
||||
_timer = new System.Windows.Forms.Timer { Interval = checkIntervalSeconds * 1000 };
|
||||
_timer.Tick += async (_, _) => await CheckStatusAsync();
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_timer.Start();
|
||||
_ = CheckStatusAsync();
|
||||
}
|
||||
|
||||
public void Stop() => _timer.Stop();
|
||||
|
||||
public void RecordUsage(string model, int promptTokens, int completionTokens)
|
||||
{
|
||||
var estimate = _pricing.Estimate(model, promptTokens, completionTokens);
|
||||
|
||||
if (!estimate.IsKnown)
|
||||
_modelsWithoutPricing.TryAdd(model, 0);
|
||||
|
||||
_usageRecords.Add(new UsageRecord(
|
||||
DateTime.Now, model, promptTokens, completionTokens, (double)estimate.Usd, estimate.IsKnown));
|
||||
|
||||
UpdateCreditsText();
|
||||
OnStatusUpdated?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lädt die aktuellen Modellpreise. Ohne diesen Aufruf bleibt der Katalog leer und
|
||||
/// alle Kosten werden als unbekannt ausgewiesen.
|
||||
/// </summary>
|
||||
public async Task LoadPricingAsync(OpenRouterClient client, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var models = await client.GetAvailableModelsAsync(ct);
|
||||
_pricing.Load(models);
|
||||
|
||||
// Modelle, die bisher als unbekannt galten, sind jetzt vielleicht bekannt.
|
||||
foreach (var model in _modelsWithoutPricing.Keys)
|
||||
{
|
||||
if (_pricing.IsKnown(model))
|
||||
_modelsWithoutPricing.TryRemove(model, out _);
|
||||
}
|
||||
|
||||
UpdateCreditsText();
|
||||
OnStatusUpdated?.Invoke();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Ohne Preise bleibt die Anzeige ehrlich unbekannt statt falsch null.
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CheckStatusAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var response = await _http.GetAsync("auth/key");
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
var doc = JsonDocument.Parse(body);
|
||||
|
||||
IsApiReachable = true;
|
||||
|
||||
if (doc.RootElement.TryGetProperty("data", out var data))
|
||||
{
|
||||
if (data.TryGetProperty("limit", out var limit))
|
||||
CreditBalance = limit.GetDouble();
|
||||
|
||||
if (data.TryGetProperty("usage", out var usage))
|
||||
{
|
||||
var used = usage.GetDouble();
|
||||
var remaining = (CreditBalance ?? 0) - used;
|
||||
CreditRemaining = remaining;
|
||||
StatusText = $"✓ API OK | Credits: ${remaining:F4} von ${CreditBalance:F2}";
|
||||
}
|
||||
else
|
||||
{
|
||||
StatusText = "✓ API erreichbar";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
StatusText = "✓ API erreichbar";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
IsApiReachable = false;
|
||||
StatusText = $"✗ API Fehler: {(int)response.StatusCode}";
|
||||
}
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
IsApiReachable = false;
|
||||
StatusText = $"✗ Nicht erreichbar: {ex.Message}";
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
IsApiReachable = false;
|
||||
StatusText = "✗ Timeout";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
IsApiReachable = false;
|
||||
StatusText = $"✗ Fehler: {ex.Message}";
|
||||
}
|
||||
|
||||
UpdateCreditsText();
|
||||
OnStatusUpdated?.Invoke();
|
||||
}
|
||||
|
||||
private void UpdateCreditsText()
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
var oneHourAgo = now.AddHours(-1);
|
||||
var oneDayAgo = now.AddHours(-24);
|
||||
|
||||
var records = _usageRecords.ToArray();
|
||||
|
||||
var lastHour = records.Where(r => r.Timestamp >= oneHourAgo).ToArray();
|
||||
var last24h = records.Where(r => r.Timestamp >= oneDayAgo).ToArray();
|
||||
|
||||
var tokensLastHour = lastHour.Sum(r => r.PromptTokens + r.CompletionTokens);
|
||||
var tokensLast24h = last24h.Sum(r => r.PromptTokens + r.CompletionTokens);
|
||||
var costLastHour = lastHour.Sum(r => r.CostUsd);
|
||||
var costLast24h = last24h.Sum(r => r.CostUsd);
|
||||
|
||||
// Ein Hinweis, sobald Läufe dabei sind, deren Kosten nicht bezifferbar sind —
|
||||
// sonst liest sich eine zu niedrige Summe wie eine vollständige.
|
||||
var unpriced = last24h.Count(r => !r.CostIsKnown);
|
||||
var warning = unpriced > 0 ? " ⚠" : "";
|
||||
|
||||
CreditsText = $"1h: {tokensLastHour:N0} Tok (~{costLastHour * UsdToEur:F4}€) | " +
|
||||
$"24h: {tokensLast24h:N0} Tok (~{costLast24h * UsdToEur:F4}€){warning}";
|
||||
|
||||
// Detaillierter Tooltip: Pro-Model-Aufschlüsselung (letzte 24h)
|
||||
var modelGroups = last24h
|
||||
.GroupBy(r => r.Model)
|
||||
.OrderByDescending(g => g.Sum(r => r.CostUsd))
|
||||
.ToList();
|
||||
|
||||
if (modelGroups.Count == 0)
|
||||
{
|
||||
CreditsTooltip = "Keine Token-Nutzung in den letzten 24h";
|
||||
return;
|
||||
}
|
||||
|
||||
var sb = new System.Text.StringBuilder();
|
||||
sb.AppendLine("═══ Token-Verbrauch (24h) ═══");
|
||||
sb.AppendLine();
|
||||
|
||||
foreach (var group in modelGroups)
|
||||
{
|
||||
var modelName = group.Key;
|
||||
var shortName = modelName.Contains('/') ? modelName[(modelName.IndexOf('/') + 1)..] : modelName;
|
||||
var prompt = group.Sum(r => r.PromptTokens);
|
||||
var completion = group.Sum(r => r.CompletionTokens);
|
||||
var total = prompt + completion;
|
||||
var cost = group.Sum(r => r.CostUsd);
|
||||
var runs = group.Count();
|
||||
|
||||
sb.AppendLine($"▸ {shortName}");
|
||||
sb.AppendLine($" {runs}x Runs | {total:N0} Tokens ({prompt:N0} in / {completion:N0} out)");
|
||||
|
||||
if (_pricing.Get(modelName) is { } pricing)
|
||||
{
|
||||
sb.AppendLine($" Preis: ${pricing.InputPer1M:0.####}/1M in, ${pricing.OutputPer1M:0.####}/1M out");
|
||||
sb.AppendLine($" Kosten: ${cost:F4} (~{cost * UsdToEur:F4}€)");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.AppendLine(" Kosten: unbekannt — für dieses Modell liegen keine Preise vor");
|
||||
}
|
||||
|
||||
sb.AppendLine();
|
||||
}
|
||||
|
||||
var totalCost = last24h.Sum(r => r.CostUsd);
|
||||
sb.AppendLine($"═══ Gesamt: ${totalCost:F4} (~{totalCost * UsdToEur:F4}€) ═══");
|
||||
|
||||
if (unpriced > 0)
|
||||
{
|
||||
sb.AppendLine();
|
||||
sb.AppendLine($"⚠ {unpriced} Lauf/Läufe ohne Preisangabe — die Summe ist unvollständig.");
|
||||
sb.AppendLine($" Betroffene Modelle: {string.Join(", ", _modelsWithoutPricing.Keys.Order())}");
|
||||
}
|
||||
|
||||
if (_pricing.LastUpdated is { } updated)
|
||||
sb.AppendLine($"\nPreise abgerufen: {updated:g} ({_pricing.Count} Modelle)");
|
||||
else
|
||||
sb.AppendLine("\n⚠ Preise noch nicht geladen.");
|
||||
|
||||
CreditsTooltip = sb.ToString().TrimEnd();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timer.Stop();
|
||||
_timer.Dispose();
|
||||
_http.Dispose();
|
||||
}
|
||||
|
||||
private sealed record UsageRecord(
|
||||
DateTime Timestamp,
|
||||
string Model,
|
||||
int PromptTokens,
|
||||
int CompletionTokens,
|
||||
double CostUsd,
|
||||
bool CostIsKnown);
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using ClawdDotNet.Models;
|
||||
|
||||
namespace ClawdDotNet.Services;
|
||||
|
||||
public sealed class SettingsManager
|
||||
{
|
||||
private const string SettingsFileName = "Settings.json";
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true,
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
private readonly string _settingsPath;
|
||||
|
||||
public AppSettings AppSettings { get; private set; } = new();
|
||||
|
||||
public SettingsManager(string? basePath = null)
|
||||
{
|
||||
var dir = basePath ?? AppDomain.CurrentDomain.BaseDirectory;
|
||||
_settingsPath = Path.Combine(dir, SettingsFileName);
|
||||
}
|
||||
|
||||
public void Load()
|
||||
{
|
||||
if (!File.Exists(_settingsPath))
|
||||
{
|
||||
AppSettings = new AppSettings();
|
||||
Save(); // Defaults schreiben
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(_settingsPath);
|
||||
AppSettings = JsonSerializer.Deserialize<AppSettings>(json, JsonOptions)
|
||||
?? new AppSettings();
|
||||
}
|
||||
catch
|
||||
{
|
||||
AppSettings = new AppSettings();
|
||||
}
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = JsonSerializer.Serialize(AppSettings, JsonOptions);
|
||||
ClawdDotNet.Core.Storage.AtomicFile.WriteAllText(_settingsPath, json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Logging ist hier ggf. noch nicht verfügbar – Fallback auf MessageBox
|
||||
MessageBox.Show(
|
||||
$"Settings konnten nicht gespeichert werden:\n{ex.Message}",
|
||||
"Fehler", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user