-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
437 lines (373 loc) · 17 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
437 lines (373 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Windows;
using CodexSessionManager.Core.Maintenance;
using CodexSessionManager.Core.Sessions;
using CodexSessionManager.Core.Transcripts;
using CodexSessionManager.Storage.Discovery;
using CodexSessionManager.Storage.Indexing;
using CodexSessionManager.Storage.Maintenance;
using CodexSessionManager.Storage.Parsing;
using Microsoft.Win32;
namespace CodexSessionManager.App;
[SuppressMessage("Code Smell", "S2333", Justification = "The class is split across XAML-generated and hand-authored partial files.")]
public partial class MainWindow : Window
{
private readonly ObservableCollection<IndexedLogicalSession> _sessions = [];
private SessionCatalogRepository? _repository;
private SessionWorkspaceIndexer? _workspaceIndexer;
private MaintenanceExecutor? _maintenanceExecutor;
private MaintenancePreview? _currentMaintenancePreview;
// skipcq: CS-R1137 - field is mutated via Interlocked.Exchange in partial class SessionOperations; readonly would prevent the swap
private CancellationTokenSource? _searchCts;
internal Func<string> LocalDataRootProvider { get; set; }
internal Func<string, SessionCatalogRepository> RepositoryFactory { get; set; }
internal Func<SessionCatalogRepository, SessionWorkspaceIndexer> WorkspaceIndexerFactory { get; set; }
internal Func<string, MaintenanceExecutor> MaintenanceExecutorFactory { get; set; }
internal Action ScheduleRefreshAction { get; set; }
internal Func<bool, List<KnownSessionStore>> KnownStoresProvider { get; set; }
internal Func<string> LiveSqliteStatusProvider { get; set; }
internal Func<string, CancellationToken, Task<ParsedSessionFile>> SessionParser { get; set; }
internal Func<string, string> FileTextReader { get; set; }
internal Action<string, string> ProcessStarter { get; set; }
internal Action<string> ClipboardSetter { get; set; }
internal Func<SaveFileDialog> SaveFileDialogFactory { get; set; }
internal Func<SaveFileDialog, Window, bool?> SaveFileDialogPresenter { get; set; }
internal Func<string, string?> ExportPathSelector { get; set; }
internal Action<string, string> TextFileWriter { get; set; }
internal Func<MaintenancePreview, string, string, CancellationToken, Task<MaintenanceExecutionResult>> MaintenanceRunner { get; set; }
public MainWindow()
{
InitializeComponent();
SessionsListBox.ItemsSource = _sessions;
MaintenanceActionComboBox.ItemsSource = Enum.GetValues<MaintenanceAction>();
MaintenanceActionComboBox.SelectedItem = MaintenanceAction.Archive;
LocalDataRootProvider = () =>
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CodexSessionManager");
RepositoryFactory = databasePath => new SessionCatalogRepository(databasePath);
WorkspaceIndexerFactory = repository => new SessionWorkspaceIndexer(repository);
MaintenanceExecutorFactory = checkpointRoot => new MaintenanceExecutor(checkpointRoot);
ScheduleRefreshAction = () => _ = RunBackgroundRefreshAsync();
KnownStoresProvider = deepScan => BuildKnownStores(deepScan);
LiveSqliteStatusProvider = GetLiveSqliteStatus;
SessionParser = (filePath, cancellationToken) => SessionJsonlParser.ParseAsync(filePath, cancellationToken);
FileTextReader = File.ReadAllText;
ProcessStarter = (fileName, arguments) =>
Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = true });
ClipboardSetter = Clipboard.SetText;
SaveFileDialogFactory = () => new SaveFileDialog();
SaveFileDialogPresenter = (dialog, owner) => dialog.ShowDialog(owner);
ExportPathSelector = SelectExportPath;
TextFileWriter = (fileName, content) => File.WriteAllText(fileName, content, Encoding.UTF8);
MaintenanceRunner = (preview, destinationRoot, typedConfirmation, cancellationToken) =>
_maintenanceExecutor!.ExecuteAsync(preview, destinationRoot, typedConfirmation, cancellationToken);
Loaded += async (_, _) => await InitializeAsync();
Closed += (_, _) => DisposeSearchCancellation();
}
private async Task InitializeAsync()
{
try
{
var localDataRoot = LocalDataRootProvider();
Directory.CreateDirectory(localDataRoot);
await RunOnUiThreadAsync(() => DestinationRootTextBox.Text = Path.Combine(localDataRoot, "maintenance", "archive"));
_repository = RepositoryFactory(Path.Combine(localDataRoot, "catalog.db"));
_workspaceIndexer = WorkspaceIndexerFactory(_repository);
_maintenanceExecutor = MaintenanceExecutorFactory(Path.Combine(localDataRoot, "checkpoints"));
await _repository.InitializeAsync(CancellationToken.None);
await LoadSessionsFromCatalogAsync();
ScheduleRefreshAction();
}
catch (Exception ex)
{
await RunOnUiThreadAsync(() => StatusTextBlock.Text = $"Startup failed: {ex.Message}");
}
}
private async Task RunBackgroundRefreshAsync()
{
try
{
await RefreshAsync(deepScan: false);
}
catch (Exception ex)
{
await RunOnUiThreadAsync(() => StatusTextBlock.Text = $"Background refresh failed: {ex.Message}");
}
}
private async Task LoadSessionsFromCatalogAsync()
{
if (_repository is null)
{
return;
}
var sessions = await _repository.ListSessionsAsync(CancellationToken.None);
await RunOnUiThreadAsync(() =>
{
_sessions.Clear();
foreach (var session in sessions)
{
_sessions.Add(session);
}
StatusTextBlock.Text = $"Loaded {_sessions.Count} sessions from cached index.";
});
}
private async Task RefreshAsync(bool deepScan)
{
if (_repository is null || _workspaceIndexer is null)
{
return;
}
await RunOnUiThreadAsync(() => StatusTextBlock.Text = deepScan ? "Running deep scan…" : "Refreshing known stores…");
var knownStores = KnownStoresProvider(deepScan);
await _workspaceIndexer.RebuildAsync(knownStores, CancellationToken.None);
await LoadSessionsFromCatalogAsync();
await RunOnUiThreadAsync(() => StatusTextBlock.Text = $"Indexed {_sessions.Count} deduped sessions at {DateTime.UtcNow:t}.");
}
private Task RunOnUiThreadAsync(Action action)
{
if (Dispatcher.CheckAccess())
{
action();
return Task.CompletedTask;
}
return Dispatcher.InvokeAsync(action).Task;
}
private Task<T> RunOnUiThreadValueAsync<T>(Func<T> func)
{
if (Dispatcher.CheckAccess())
{
return Task.FromResult(func());
}
return Dispatcher.InvokeAsync(func).Task;
}
private string? SelectExportPath(string defaultFileName)
{
var dialog = SaveFileDialogFactory();
dialog.FileName = defaultFileName;
dialog.Filter = "Markdown (*.md)|*.md|Text (*.txt)|*.txt|JSON (*.json)|*.json";
return SaveFileDialogPresenter(dialog, this) == true ? dialog.FileName : null;
}
private static List<KnownSessionStore> BuildKnownStores(bool deepScan)
{
var codexHome = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".codex");
var stores = new List<KnownSessionStore>(KnownStoreLocator.GetKnownStores(codexHome));
if (!deepScan)
{
return stores;
}
var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
foreach (var directory in Directory.EnumerateDirectories(userProfile, ".codex*", SearchOption.TopDirectoryOnly))
{
foreach (var store in KnownStoreLocator.GetKnownStores(directory)
.Where(store => stores.All(existing =>
!string.Equals(existing.SessionsPath, store.SessionsPath, StringComparison.OrdinalIgnoreCase))))
{
stores.Add(store);
}
}
return stores;
}
private IndexedLogicalSession? GetSelectedSession() => SessionsListBox.SelectedItem as IndexedLogicalSession;
private IndexedLogicalSession[] GetSelectedSessions() =>
SessionsListBox.SelectedItems.Cast<IndexedLogicalSession>().ToArray();
// skipcq: CS-R1005 - WPF event handler signature is fixed by the framework and must return void
private async void SessionsListBox_OnSelectionChanged(object _, System.Windows.Controls.SelectionChangedEventArgs __) =>
await LoadSelectedSessionAsync();
// skipcq: CS-R1005 - WPF event handler signature is fixed by the framework and must return void
private async void SearchTextBox_OnTextChanged(object _, System.Windows.Controls.TextChangedEventArgs __) =>
await SearchSessionsAsync();
[ExcludeFromCodeCoverage]
// skipcq: CS-R1005 - WPF event handler signature is fixed by the framework and must return void
private async void RefreshButton_OnClick(object _, RoutedEventArgs __) => await RefreshAsync(deepScan: false);
[ExcludeFromCodeCoverage]
// skipcq: CS-R1005 - WPF event handler signature is fixed by the framework and must return void
private async void DeepScanButton_OnClick(object _, RoutedEventArgs __) => await RefreshAsync(deepScan: true);
private async Task SaveSelectedMetadataAsync()
{
if (_repository is null)
{
return;
}
var metadata = await RunOnUiThreadValueAsync(() => (
Selected: GetSelectedSession(),
Alias: AliasTextBox.Text,
TagsText: TagsTextBox.Text,
Notes: NotesTextBox.Text));
var selected = metadata.Selected;
if (selected is null)
{
return;
}
var tags = metadata.TagsText
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.ToArray();
await _repository.UpdateMetadataAsync(selected.SessionId, metadata.Alias, tags, metadata.Notes, CancellationToken.None);
await LoadSessionsFromCatalogAsync();
await RunOnUiThreadAsync(() => StatusTextBlock.Text = $"Saved metadata for {selected.SessionId}.");
}
[ExcludeFromCodeCoverage]
// skipcq: CS-R1005 - WPF event handler signature is fixed by the framework and must return void
private async void SaveMetadataButton_OnClick(object _, RoutedEventArgs __) =>
await SaveSelectedMetadataAsync();
private void OpenFolderButton_OnClick(object _, RoutedEventArgs __)
{
var selected = GetSelectedSession();
if (selected is null)
{
return;
}
var folder = Path.GetDirectoryName(selected.PreferredCopy.FilePath);
if (!string.IsNullOrWhiteSpace(folder))
{
ProcessStarter("explorer.exe", $"\"{folder}\"");
}
}
private void OpenRawButton_OnClick(object _, RoutedEventArgs __)
{
var selected = GetSelectedSession();
if (selected is null)
{
return;
}
ProcessStarter("notepad.exe", $"\"{selected.PreferredCopy.FilePath}\"");
}
private void CopyPathButton_OnClick(object _, RoutedEventArgs __)
{
var selected = GetSelectedSession();
if (selected is null)
{
return;
}
ClipboardSetter(selected.PreferredCopy.FilePath);
StatusTextBlock.Text = "Copied preferred path to clipboard.";
}
private void ResumeButton_OnClick(object _, RoutedEventArgs __)
{
var selected = GetSelectedSession();
if (selected is null)
{
return;
}
var cwd = !string.IsNullOrWhiteSpace(CwdTextBlock.Text) && CwdTextBlock.Text != "-" ? CwdTextBlock.Text : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var command = $"codex resume {selected.SessionId} -C \"{cwd}\"";
ProcessStarter("pwsh.exe", $"-NoExit -Command \"{command}\"");
StatusTextBlock.Text = $"Opened Codex resume command for {selected.SessionId}.";
}
private void ExportButton_OnClick(object _, RoutedEventArgs __)
{
var selected = GetSelectedSession();
if (selected is null)
{
return;
}
var exportPath = ExportPathSelector($"{selected.SessionId}.md");
if (string.IsNullOrWhiteSpace(exportPath))
{
return;
}
TextFileWriter(exportPath, ReadableTranscriptTextBox.Text);
StatusTextBlock.Text = $"Exported session to {exportPath}.";
}
private void BuildPreviewButton_OnClick(object _, RoutedEventArgs __)
{
var selectedSessions = GetSelectedSessions();
if (selectedSessions.Length == 0)
{
return;
}
var targets = selectedSessions.SelectMany(session => session.PhysicalCopies).ToArray();
var action = MaintenanceActionComboBox.SelectedItem is MaintenanceAction selectedAction
? selectedAction
: MaintenanceAction.Archive;
var confirmation = $"{action.ToString().ToUpperInvariant()} {targets.Length} FILE{(targets.Length == 1 ? string.Empty : "S")}";
_currentMaintenancePreview = MaintenancePlanner.CreatePreview(new MaintenanceRequest(action, targets, confirmation));
MaintenanceSummaryTextBlock.Text = $"Allowed: {_currentMaintenancePreview.AllowedTargets.Count} | Blocked: {_currentMaintenancePreview.BlockedTargets.Count} | Confirm with: {confirmation}";
MaintenanceWarningsTextBox.Text = string.Join(Environment.NewLine, _currentMaintenancePreview.Warnings.Select(w => $"[{w.Severity}] {w.Message}"));
TypedConfirmationTextBox.Text = confirmation;
}
private async Task ExecuteMaintenanceAsync()
{
if (_currentMaintenancePreview is null || _maintenanceExecutor is null)
{
return;
}
string destinationRoot = string.Empty;
string typedConfirmation = string.Empty;
await RunOnUiThreadAsync(() =>
{
destinationRoot = DestinationRootTextBox.Text;
typedConfirmation = TypedConfirmationTextBox.Text;
});
if (string.IsNullOrWhiteSpace(destinationRoot))
{
destinationRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CodexSessionManager",
"maintenance",
_currentMaintenancePreview.Action.ToString().ToLowerInvariant());
}
try
{
var result = await MaintenanceRunner(_currentMaintenancePreview, destinationRoot, typedConfirmation, CancellationToken.None);
await RunOnUiThreadAsync(() => StatusTextBlock.Text = result.Executed
? $"Executed maintenance. Checkpoint: {result.ManifestPath}"
: "Maintenance did not execute.");
await RefreshAsync(deepScan: false);
}
catch (Exception ex)
{
await RunOnUiThreadAsync(() => StatusTextBlock.Text = $"Maintenance failed: {ex.Message}");
}
}
[ExcludeFromCodeCoverage]
// skipcq: CS-R1005 - WPF event handler signature is fixed by the framework and must return void
private async void ExecuteMaintenanceButton_OnClick(object _, RoutedEventArgs __) =>
await ExecuteMaintenanceAsync();
internal static string? DescribeSqlitePath(string path, Func<string, FileInfo>? fileInfoFactory = null)
{
try
{
var info = (fileInfoFactory ?? (static filePath => new FileInfo(filePath)))(path);
if (!info.Exists)
{
return null;
}
return $"{path} | {Math.Round(info.Length / 1024.0 / 1024.0, 1)} MB | {info.LastWriteTime}";
}
catch (IOException)
{
return null;
}
catch (UnauthorizedAccessException)
{
return null;
}
}
private static string GetLiveSqliteStatus()
{
var codexHome = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".codex");
return GetLiveSqliteStatus(
new[]
{
Path.Combine(codexHome, "state_5.sqlite"),
Path.Combine(codexHome, "codex-sqlite", "canonical", "state_5.sqlite")
},
path => DescribeSqlitePath(path, fileInfoFactory: null));
}
private static string GetLiveSqliteStatus(IEnumerable<string> sqlitePaths, Func<string, string?> describeSqlitePath)
{
var details = sqlitePaths
.Select(describeSqlitePath)
.Where(detail => detail is not null)
.Cast<string>()
.ToArray();
return details.Length == 0
? "No live SQLite store detected."
: string.Join(Environment.NewLine, details);
}
}