Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1934 lines (1786 loc) · 75.2 KB
/
Copy pathmain.cpp
File metadata and controls
1934 lines (1786 loc) · 75.2 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// OpenCode Session Manager -- terminal UI (ncursesw).
//
// Browse and clean old OpenCode conversations & orphan snapshot directories.
// Feature set mirrors the GUI: filter, sort, page navigation, reveal in
// Explorer, on-demand orphan diff cleanup and progressive snapshot sizing.
//
// Build (MinGW-w64, ncursesw + sqlite3 from C:\MinGW\opt), one line:
// g++ -std=c++17 -O2 -DNCURSES_WIDECHAR -I"C:\MinGW\opt\include" main.cpp opencode_data.cpp
// -L"C:\MinGW\opt\lib" -lncursesw -lsqlite3 -luser32 -lshell32 -lole32
// -o opencode-session-manager.exe
//
// Optional env override for data location (handy for testing):
// OPENCODE_DATA_DIR=<dir containing opencode.db, storage/, snapshot/>
//
// Key bindings (also shown in the on-screen help):
// up/down, j/k move cursor PgUp/PgDn, Home/End page / jump
// Space toggle selection Ctrl+A / Ctrl+D all / none
// Tab switch view F5 reload data
// / filter Esc clear filter, else quit
// s / S cycle sort field / reverse direction
// d / Enter delete selected (confirm with y/n)
// c copy resume command (opencode -s <id>)
// o resume session in a new console
// r reveal in Explorer
// O snapshots: orphan directories only
// x clean orphan session_diff files now
// Ctrl+E toggle cleanup-on-exit
// q quit
//
// Removals go to the Windows Recycle Bin by default; set OPENCODE_SM_NO_RECYCLE=1
// to delete permanently instead.
#define NCURSES_WIDECHAR 1
#include <ncursesw/ncurses.h>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h> // SetConsoleOutputCP
#endif
#include <algorithm>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <set>
#include <string>
#include <vector>
#include "opencode_data.hpp"
#include "db_maintenance.hpp"
#include "session_view.hpp"
#include "version.h"
using std::string;
using std::wstring;
// ---------------------------------------------------------------------------
// Color pair ids (keep names from original)
// ---------------------------------------------------------------------------
enum {
COLOR_NORMAL = 1,
COLOR_SELECTED,
COLOR_HEADER,
COLOR_HELP,
COLOR_WARN,
COLOR_DIM,
COLOR_TAB_ACTIVE,
COLOR_TAB_INACTIVE,
COLOR_FILTER
};
// ---------------------------------------------------------------------------
// ncurses helpers
// ---------------------------------------------------------------------------
static void waddswstr(WINDOW* win, const wstring& s) {
waddnwstr(win, s.c_str(), (int)s.size());
}
static void mvwaddswstr(WINDOW* win, int y, int x, const wstring& s) {
wmove(win, y, x);
waddswstr(win, s);
}
// UTF-8 text helpers for the filter box (typed text arrives as raw bytes, so a
// pasted CJK query still forms a valid UTF-8 string).
static bool utf8_cont(unsigned char c) { return (c & 0xC0) == 0x80; }
static void utf8_pop_back(string& s) {
if (s.empty()) return;
size_t i = s.size() - 1;
while (i > 0 && utf8_cont((unsigned char)s[i])) --i;
s.erase(i);
}
// ---------------------------------------------------------------------------
// Sort modes
// ---------------------------------------------------------------------------
enum {
TAB_SESSIONS = 0,
TAB_SNAPSHOTS = 1,
TAB_DATABASE = 2
};
// Database maintenance actions that need a y/n confirmation first.
enum { MA_NONE = 0, MA_CLEAN_ORPHANS, MA_COMPACT, MA_VACUUM };
// Which fields the 's' key cycles through, per view.
static const SortField kSessionSortFields[] = {SORT_CREATED, SORT_UPDATED, SORT_MESSAGES,
SORT_NAME, SORT_LOCATION};
static const SortField kSnapshotSortFields[] = {SORT_SIZE, SORT_ID, SORT_NAME, SORT_STATUS};
static const int kSessionSortCount = (int)(sizeof(kSessionSortFields) / sizeof(SortField));
static const int kSnapshotSortCount = (int)(sizeof(kSnapshotSortFields) / sizeof(SortField));
// ---------------------------------------------------------------------------
// TUI application
// ---------------------------------------------------------------------------
static const string DB_PATH = db_path();
static const string DIFF_DIR = diff_dir();
static const string SNAPSHOT_DIR = snapshot_dir();
static const string DATA_DIR = data_dir();
// Snapshot sizes are computed a few per redraw so the UI never stalls on a large
// data directory (the GUI does the same, a frame at a time).
static const int SIZE_SCAN_PER_PUMP = 8;
class App {
public:
int tab = TAB_SESSIONS;
std::vector<Session> sessions;
std::vector<Snapshot> snapshots;
std::vector<int> view; // row -> index into sessions/snapshots
std::set<string> selected; // session id, or snapshot path
int cursor = 0;
int scroll = 0;
int page_rows = 10;
bool confirm_mode = false;
bool filter_mode = false;
string filter; // applied query
string filter_edit; // query being typed
bool orphans_only = false;
SortField session_sort = SORT_CREATED;
SortField snapshot_sort = SORT_SIZE;
bool session_desc = true;
bool snapshot_desc = true;
bool cleanup_on_exit = false;
size_t scan_next = 0;
size_t scan_pending = 0;
size_t scan_total = 0; // how many snapshots this scan set out to measure
string message;
bool running = true;
// database maintenance (the same background job the GUI uses)
MaintenanceJob job;
bool job_seen = true;
int db_scroll = 0;
int pending_action = MA_NONE;
bool preview_mode = false;
int preview_scroll = 0;
std::vector<PreviewMessage> preview;
string preview_for;
string preview_error;
void run() {
init_tui();
refresh_data(false);
while (running) {
draw();
// Poll while sizes or a maintenance job are still running, so both
// make progress without the user having to press a key.
bool busy = scan_pending > 0 || job.running();
if (preview_mode || pending_action != MA_NONE) busy = false;
if (busy) {
timeout(50);
int key = getch();
if (key == ERR) {
if (scan_pending) pump_sizes(SIZE_SCAN_PER_PUMP);
check_job();
continue;
}
handle_key(key);
} else {
timeout(-1);
handle_key(getch());
}
}
job.wait(); // never leave a worker mid-flight
cleanup_screen();
}
private:
void init_tui() {
curs_set(0);
start_color();
use_default_colors();
init_pair(COLOR_NORMAL, -1, -1);
init_pair(COLOR_SELECTED, COLOR_GREEN, -1);
init_pair(COLOR_HEADER, COLOR_BLACK, COLOR_CYAN);
init_pair(COLOR_HELP, COLOR_BLACK, COLOR_WHITE);
init_pair(COLOR_WARN, COLOR_RED, -1);
init_pair(COLOR_DIM, 8, -1);
init_pair(COLOR_TAB_ACTIVE, COLOR_BLACK, COLOR_GREEN);
init_pair(COLOR_TAB_INACTIVE, COLOR_BLACK, COLOR_CYAN);
init_pair(COLOR_FILTER, COLOR_YELLOW, -1);
cbreak();
noecho();
keypad(stdscr, TRUE);
}
void cleanup_screen() { endwin(); }
// -----------------------------------------------------------------------
// Background maintenance
// -----------------------------------------------------------------------
static string timestamp_string() {
time_t now = time(nullptr);
struct tm tmv;
#ifdef _WIN32
localtime_s(&tmv, &now);
#else
localtime_r(&now, &tmv);
#endif
char buf[32];
snprintf(buf, sizeof(buf), "%04d%02d%02d-%02d%02d%02d", tmv.tm_year + 1900, tmv.tm_mon + 1,
tmv.tm_mday, tmv.tm_hour, tmv.tm_min, tmv.tm_sec);
return buf;
}
void check_job() {
if (job.running() || job_seen) return;
JobStatus st = job.status();
job_seen = true;
if (!st.ok && !st.error.empty()) {
message = "Error: " + utf8_ellipsize(st.error, 120);
return;
}
char buf[256];
switch (st.type) {
case JobType::Report:
message = "Database scan finished (j/k or PgUp/PgDn to scroll).";
break;
case JobType::CleanupOrphans:
snprintf(buf, sizeof(buf), "Removed %d orphan event row(s) (%s). Press v to VACUUM.",
(int)st.result.rows, wide_to_utf8(format_size(st.result.bytes)).c_str());
message = buf;
refresh_data(true);
break;
case JobType::CompactEvents:
if (st.result.rows > 0) {
snprintf(buf, sizeof(buf), "Compacted %d row(s) (%s). Press v to VACUUM.",
(int)st.result.rows,
wide_to_utf8(format_size(st.result.bytes)).c_str());
refresh_data(true);
} else {
snprintf(buf, sizeof(buf), "Dry run: %d of %d rows redundant, %s reclaimable.",
(int)st.plan.removable_rows, (int)st.plan.total_rows,
wide_to_utf8(format_size(st.plan.removable_bytes)).c_str());
}
message = buf;
break;
case JobType::Vacuum:
snprintf(buf, sizeof(buf), "VACUUM: %s -> %s (freed %s)",
wide_to_utf8(format_size(st.result.file_before)).c_str(),
wide_to_utf8(format_size(st.result.file_after)).c_str(),
wide_to_utf8(format_size(st.result.bytes)).c_str());
message = buf;
break;
case JobType::Backup:
snprintf(buf, sizeof(buf), "Backup written (%s)",
wide_to_utf8(format_size(st.result.bytes)).c_str());
message = buf;
break;
default:
break;
}
}
void start_action(int action) {
switch (action) {
case MA_CLEAN_ORPHANS:
job.start(JobType::CleanupOrphans, DB_PATH);
break;
case MA_COMPACT: {
// Always back up first from the interactive UI: this rewrites the log.
string backup = DB_PATH + ".backup-" + timestamp_string();
job.start(JobType::CompactEvents, DB_PATH, backup);
message = "Compacting (backup: " + backup + ")";
break;
}
case MA_VACUUM:
if (database_is_busy(DB_PATH)) {
message = "Error: database is locked (is opencode running?).";
return;
}
job.start(JobType::Vacuum, DB_PATH);
break;
default:
return;
}
job_seen = false;
}
void export_selected() {
std::vector<string> ids(selected.begin(), selected.end());
if (ids.empty()) {
message = "Nothing selected to export.";
return;
}
string dir = path_join(data_dir(), "export-" + timestamp_string());
std::vector<string> written;
string err;
if (export_sessions_json(DB_PATH, ids, dir, &written, &err))
message = "Exported " + std::to_string(written.size()) + " session(s) to " + dir;
else
message = "Error: " + err;
}
void load_preview_now() {
preview.clear();
preview_error.clear();
preview_for.clear();
if (tab != TAB_SESSIONS) return;
string id = key_at(cursor);
if (id.empty()) return;
preview_for = id;
try {
preview = load_session_preview(DB_PATH, id, 30);
} catch (const std::exception& e) {
preview_error = e.what();
}
}
// -----------------------------------------------------------------------
// Database view
// -----------------------------------------------------------------------
bool handle_database_key(int key) {
switch (key) {
case 'r':
job.start(JobType::Report, DB_PATH);
job_seen = false;
message = "Scanning database (read-only)...";
return true;
case 'c':
job.start(JobType::CompactEvents, DB_PATH);
job_seen = false;
message = "Analysing event log (dry run)...";
return true;
case 'x':
pending_action = MA_CLEAN_ORPHANS;
return true;
case 'b':
pending_action = MA_COMPACT;
return true;
case 'v':
pending_action = MA_VACUUM;
return true;
case KEY_DOWN:
case 'j':
db_scroll++;
return true;
case KEY_UP:
case 'k':
if (db_scroll > 0) db_scroll--;
return true;
case KEY_NPAGE:
db_scroll += page_rows;
return true;
case KEY_PPAGE:
db_scroll -= page_rows;
if (db_scroll < 0) db_scroll = 0;
return true;
case KEY_HOME:
db_scroll = 0;
return true;
default:
return false;
}
}
void draw_database_view(int start_y, int end_y, int w) {
JobStatus st = job.status();
std::vector<wstring> lines;
const DbReport& r = st.report;
auto add = [&](const wstring& s) { lines.push_back(s); };
auto addf = [&](const char* fmt, ...) {
char buf[512];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
lines.push_back(utf8_to_wide(buf));
};
auto sz = [](long long b) { return wide_to_utf8(format_size(b)); };
if (st.running) {
addf(" %s [%d%%]", st.stage.c_str(), st.percent);
add(L"");
}
if (r.file_bytes <= 0) {
add(L" Press r to scan the database (read-only, takes a minute on a big file).");
add(L"");
add(L" In a real opencode database 90%+ of the file can be the append-only");
add(L" `event` log: it stores a complete snapshot of a message part on every");
add(L" update, and deleting sessions does not touch those rows - which is why");
add(L" the file never shrinks.");
add(L"");
add(L" r scan c analyse event log (dry run)");
add(L" x clean orphan events b compact (always backs up first)");
add(L" v VACUUM");
} else {
add(L" database file " + utf8_to_wide(sz(r.file_bytes)) + L" (" +
std::to_wstring(r.page_count) + L" pages x " + std::to_wstring(r.page_size) +
L" B)");
add(L" free pages " + utf8_to_wide(sz(r.free_bytes)) + L" <- VACUUM (v)");
add(L" event log " + utf8_to_wide(sz(r.event_bytes)) + L" (" +
std::to_wstring(r.event_rows) + L" rows)");
add(L" session/message/part rows: " + std::to_wstring(r.session_rows) + L" / " +
std::to_wstring(r.message_rows) + L" / " + std::to_wstring(r.part_rows));
add(L"");
add(L" orphan events (deleted sessions) " + utf8_to_wide(sz(r.orphan_event_bytes)) +
L" (" + std::to_wstring(r.orphan_event_rows) + L" rows) -> x");
add(L" safe to reclaim now " + utf8_to_wide(sz(r.reclaimable_safe())));
add(L"");
add(L" largest tables" + wstring(r.dbstat_available ? L" (dbstat)" : L" (estimated)"));
for (size_t i = 0; i < r.tables.size() && i < 8; ++i)
addf(" %-26s %10s", r.tables[i].name.c_str(), sz(r.tables[i].bytes).c_str());
add(L"");
add(L" event log by type");
for (size_t i = 0; i < r.event_types.size() && i < 8; ++i)
addf(" %-26s %8d rows %10s", r.event_types[i].name.c_str(),
(int)r.event_types[i].rows, sz(r.event_types[i].bytes).c_str());
add(L"");
add(L" top sessions by event footprint");
for (size_t i = 0; i < r.sessions.size() && i < 8; ++i)
addf(" %-30s %8d rows %10s %s", utf8_ellipsize(r.sessions[i].name, 30).c_str(),
(int)r.sessions[i].rows, sz(r.sessions[i].bytes).c_str(),
utf8_ellipsize(r.sessions[i].extra, 28).c_str());
if (!r.big_items.empty()) {
add(L"");
add(L" oversized objects");
for (size_t i = 0; i < r.big_items.size(); ++i)
addf(" %-50s %10s", utf8_ellipsize(r.big_items[i].name, 50).c_str(),
sz(r.big_items[i].bytes).c_str());
}
}
if (st.plan.total_rows > 0) {
add(L"");
add(L" event log compaction (dry run)");
addf(" %d of %d part.updated rows are redundant, %s reclaimable",
(int)st.plan.removable_rows, (int)st.plan.total_rows,
sz(st.plan.removable_bytes).c_str());
if (!st.plan.worst_parts.empty())
addf(" worst part: %s with %d versions", st.plan.worst_parts[0].name.c_str(),
(int)st.plan.worst_parts[0].rows);
add(L" b = apply (a backup is taken first)");
}
int visible = end_y - start_y;
if (visible < 1) visible = 1;
int max_scroll = (int)lines.size() - visible;
if (max_scroll < 0) max_scroll = 0;
if (db_scroll > max_scroll) db_scroll = max_scroll;
if (db_scroll < 0) db_scroll = 0;
wattrset(stdscr, COLOR_PAIR(COLOR_DIM));
for (int i = 0; i < visible && (size_t)(db_scroll + i) < lines.size(); ++i) {
const wstring& line = lines[(size_t)(db_scroll + i)];
bool highlight = line.find(L"->") != wstring::npos;
if (highlight) wattrset(stdscr, COLOR_PAIR(COLOR_WARN));
mvwaddswstr(stdscr, start_y + i, 0, truncate(line, (size_t)w));
if (highlight) wattrset(stdscr, COLOR_PAIR(COLOR_DIM));
}
wattrset(stdscr, A_NORMAL);
}
// -----------------------------------------------------------------------
// Data
// -----------------------------------------------------------------------
void refresh_data(bool keep_view) {
sessions = load_sessions(DB_PATH);
// List only: sizes are measured progressively by pump_sizes().
snapshots = load_snapshots(DB_PATH, SNAPSHOT_DIR, /*with_sizes=*/false);
scan_next = 0;
scan_total = 0;
for (auto& s : snapshots)
if (!s.size_known) ++scan_total;
scan_pending = scan_total;
if (!keep_view) {
selected.clear();
cursor = 0;
scroll = 0;
} else {
prune_selection();
}
rebuild_view();
}
void pump_sizes(int budget) {
const size_t n = snapshots.size();
if (!n || scan_pending == 0) return;
int done = 0, scanned = 0;
while (done < budget && scanned < (int)n) {
size_t i = scan_next % n;
scan_next = (i + 1) % n;
++scanned;
if (snapshots[i].size_known) continue;
snapshots[i].size = total_dir_size(snapshots[i].path);
snapshots[i].size_known = true;
--scan_pending;
++done;
}
// Re-sort only once the scan is complete, otherwise rows would move
// around under the cursor while sizes trickle in.
if (scan_pending == 0) {
if (tab == TAB_SNAPSHOTS && snapshot_sort == SORT_SIZE) rebuild_view();
}
}
// -----------------------------------------------------------------------
// Filtering / sorting / view
// -----------------------------------------------------------------------
// The query in effect: while typing it is the edit buffer, so Esc can drop
// the whole edit without ever having touched the applied filter.
const string& active_filter() const { return filter_mode ? filter_edit : filter; }
void rebuild_view() {
if (tab == TAB_DATABASE) {
view.clear();
cursor = 0;
scroll = 0;
return;
}
ViewQuery q;
q.filter = active_filter();
q.orphans_only = orphans_only;
if (tab == TAB_SESSIONS) {
q.field = session_sort;
q.descending = session_desc;
view = build_session_view(sessions, q);
} else {
q.field = snapshot_sort;
q.descending = snapshot_desc;
view = build_snapshot_view(snapshots, q);
}
clamp_state();
}
size_t total_rows() const {
if (tab == TAB_DATABASE) return 0;
return tab == TAB_SESSIONS ? sessions.size() : snapshots.size();
}
size_t visible_rows() const { return view.size(); }
string key_at(int row) const {
if (row < 0 || row >= (int)view.size()) return string();
int idx = view[(size_t)row];
return tab == TAB_SESSIONS ? sessions[(size_t)idx].id : snapshots[(size_t)idx].path;
}
void clamp_state() {
int n = (int)view.size();
if (n <= 0) {
cursor = 0;
scroll = 0;
return;
}
if (cursor > n - 1) cursor = n - 1;
if (cursor < 0) cursor = 0;
if (scroll < 0) scroll = 0;
if (scroll > cursor) scroll = cursor;
}
void prune_selection() {
std::set<string> alive;
for (auto& s : sessions) alive.insert(s.id);
for (auto& s : snapshots) alive.insert(s.path);
for (auto it = selected.begin(); it != selected.end();) {
if (!alive.count(*it)) it = selected.erase(it);
else ++it;
}
}
// -----------------------------------------------------------------------
// Input
// -----------------------------------------------------------------------
void handle_key(int key) {
if (key == ERR) return;
if (preview_mode) {
switch (key) {
case 'q':
case 27:
case 'p':
preview_mode = false;
break;
case KEY_DOWN:
case 'j':
preview_scroll++;
break;
case KEY_UP:
case 'k':
if (preview_scroll > 0) preview_scroll--;
break;
case KEY_NPAGE:
preview_scroll += page_rows;
break;
case KEY_PPAGE:
preview_scroll -= page_rows;
if (preview_scroll < 0) preview_scroll = 0;
break;
default:
break;
}
return;
}
if (pending_action != MA_NONE) {
int action = pending_action;
pending_action = MA_NONE;
if (key == 'y' || key == 'Y') start_action(action);
return;
}
if (filter_mode) {
handle_filter_key(key);
return;
}
if (confirm_mode) {
if (key == 'y' || key == 'Y') do_delete();
confirm_mode = false;
return;
}
if (tab == TAB_DATABASE && handle_database_key(key)) return;
switch (key) {
case 'q':
case 'Q':
running = false;
break;
case 27: // Esc: clear filter first, then quit
if (!filter.empty()) {
filter.clear();
rebuild_view();
message = "Filter cleared.";
} else {
running = false;
}
break; case '\t':
tab = (tab + 1) % 3;
selected.clear();
cursor = 0;
scroll = 0;
message.clear();
rebuild_view();
break;
case 'p':
if (tab == TAB_SESSIONS) {
preview_mode = true;
preview_scroll = 0;
load_preview_now();
} else {
message = "Preview is only available for sessions.";
}
break;
case 'e':
export_selected();
break;
case KEY_UP:
case 'k':
if (cursor > 0) cursor--;
break;
case KEY_DOWN:
case 'j':
if (cursor < (int)visible_rows() - 1) cursor++;
break;
case KEY_PPAGE:
cursor -= page_rows;
if (cursor < 0) cursor = 0;
break;
case KEY_NPAGE:
cursor += page_rows;
if (cursor > (int)visible_rows() - 1) cursor = (int)visible_rows() - 1;
if (cursor < 0) cursor = 0;
break;
case KEY_HOME:
cursor = 0;
break;
case KEY_END:
cursor = (int)visible_rows() - 1;
if (cursor < 0) cursor = 0;
break;
case ' ': {
string k = key_at(cursor);
if (!k.empty()) {
if (selected.count(k)) selected.erase(k);
else selected.insert(k);
}
break;
}
case 1: // Ctrl+A
selected.clear();
for (size_t i = 0; i < visible_rows(); ++i) selected.insert(key_at((int)i));
message = "Selected " + std::to_string(selected.size()) + " visible item(s).";
break;
case 4: // Ctrl+D
selected.clear();
break;
case '/':
filter_mode = true;
filter_edit = filter;
break;
case 's':
if (tab == TAB_SESSIONS) {
int i = 0;
while (i < kSessionSortCount && kSessionSortFields[i] != session_sort) ++i;
session_sort = kSessionSortFields[(i + 1) % kSessionSortCount];
} else {
int i = 0;
while (i < kSnapshotSortCount && kSnapshotSortFields[i] != snapshot_sort) ++i;
snapshot_sort = kSnapshotSortFields[(i + 1) % kSnapshotSortCount];
}
rebuild_view();
message = "Sort: " + string(sort_field_name(current_sort_field())) +
(current_sort_desc() ? " (desc)" : " (asc)");
break;
case 'S':
if (tab == TAB_SESSIONS) session_desc = !session_desc;
else snapshot_desc = !snapshot_desc;
rebuild_view();
message = "Sort: " + string(sort_field_name(current_sort_field())) +
(current_sort_desc() ? " (desc)" : " (asc)");
break;
case 'O':
orphans_only = !orphans_only;
if (tab != TAB_SNAPSHOTS) tab = TAB_SNAPSHOTS;
selected.clear();
cursor = 0;
scroll = 0;
rebuild_view();
message = orphans_only ? "Showing orphan snapshot directories only."
: "Showing all snapshot directories.";
break;
case 'c':
case 'C':
copy_command();
break;
case 'o':
jump_session();
break;
case 'r':
reveal_path();
break;
case 'x':
clean_orphan_diffs_now();
break;
case 5: // Ctrl+E
cleanup_on_exit = !cleanup_on_exit;
message = string("Cleanup orphan diffs on exit: ") + (cleanup_on_exit ? "ON" : "OFF");
break;
case 'd':
case 'D':
case 10:
case 13:
case KEY_ENTER:
if (!selected.empty()) confirm_mode = true;
else message = "Nothing selected.";
break;
case KEY_F(5):
refresh_data(true);
message = "Reloaded.";
break;
default:
break;
}
}
void handle_filter_key(int key) {
switch (key) {
case 10:
case 13:
case KEY_ENTER:
filter = filter_edit;
filter_mode = false;
rebuild_view();
cursor = 0;
scroll = 0;
message = filter.empty() ? "Filter cleared."
: "Filter: \"" + filter + "\" -> " +
std::to_string(visible_rows()) + " match(es)";
break;
case 27: // Esc cancels the edit
filter_edit = filter;
filter_mode = false;
rebuild_view();
clamp_state();
break;
case KEY_BACKSPACE:
case 127:
case 8:
utf8_pop_back(filter_edit);
break;
default:
// Printable bytes (including multi-byte UTF-8, so a pasted CJK query
// works). Filter live while typing.
if (key >= 32 && key < 256) {
filter_edit += (char)key;
rebuild_view();
clamp_state();
}
break;
}
}
void copy_command() {
if (tab != TAB_SESSIONS) {
message = "Resume command copy is only available for sessions.";
return;
}
if (view.empty()) return;
const Session& s = sessions[(size_t)view[(size_t)cursor]];
string cmd = "opencode -s " + s.id;
string err;
if (set_clipboard_text(cmd, &err)) message = "Copied: " + cmd;
else message = "Error: " + err;
}
void jump_session() {
if (tab != TAB_SESSIONS) {
message = "Jump is only available for sessions.";
return;
}
if (view.empty()) return;
const Session& s = sessions[(size_t)view[(size_t)cursor]];
string err;
if (launch_opencode_session(s.id, s.worktree, &err)) message = "Resumed session " + s.id;
else message = "Error: " + err;
}
void reveal_path() {
if (view.empty()) return;
string path, err;
if (tab == TAB_SESSIONS) {
path = sessions[(size_t)view[(size_t)cursor]].worktree;
if (path.empty()) {
message = "This session's project directory is unknown.";
return;
}
} else {
path = snapshots[(size_t)view[(size_t)cursor]].path;
}
if (reveal_in_explorer(path, &err)) message = "Opened in Explorer: " + path;
else message = "Error: " + err;
}
void clean_orphan_diffs_now() {
try {
std::vector<string> failed;
auto orphans = cleanup_orphan_diffs(DB_PATH, DIFF_DIR, &failed);
if (orphans.empty() && failed.empty())
message = "No orphan session_diff files to clean.";
else
message = (delete_to_recycle() ? "Moved " : "Removed ") +
std::to_string(orphans.size()) + " orphan diff file(s)" +
(failed.empty() ? "" : ", " + std::to_string(failed.size()) + " failed");
} catch (const std::exception& e) {
message = string("Error: ") + e.what();
}
}
void do_delete() {
if (tab == TAB_SESSIONS) delete_sessions_ui();
else delete_snapshots_ui();
}
void delete_sessions_ui() {
std::vector<string> ids(selected.begin(), selected.end());
if (ids.empty()) return;
try {
int n = delete_sessions(DB_PATH, ids);
std::vector<string> failed;
auto orphans = cleanup_orphan_diffs(DB_PATH, DIFF_DIR, &failed);
message = "Deleted " + std::to_string(n) + " session(s)";
if (!orphans.empty())
message += (delete_to_recycle() ? ", moved " : ", removed ") +
std::to_string(orphans.size()) + " orphan diff(s)";
if (!failed.empty())
message += ", " + std::to_string(failed.size()) + " diff(s) failed";
refresh_data(true);
} catch (const std::exception& e) {
message = string("Error: ") + e.what();
}
}
void delete_snapshots_ui() {
std::vector<string> paths;
long long total_size = 0;
for (auto& key : selected) {
for (auto& s : snapshots) {
if (s.path == key) {
paths.push_back(s.path);
total_size += s.size;
break;
}
}
}
if (paths.empty()) return;
size_t failed = 0;
string first_error;
for (auto& d : paths) {
try {
remove_tree(d);
} catch (const std::exception& e) {
if (failed == 0) first_error = e.what();
++failed;
}
}
if (failed == 0) {
string size_text = wide_to_utf8(format_size(total_size));
if (delete_to_recycle())
message = "Moved " + std::to_string(paths.size()) +
" snapshot(s) to the Recycle Bin (" + size_text + ")";
else
message = "Removed " + std::to_string(paths.size()) + " snapshot(s), freed " +
size_text;
} else if (failed == paths.size()) {
message = "Error: " + first_error;
} else {
string size_text = wide_to_utf8(format_size(total_size));
message = "Removed " + std::to_string(paths.size() - failed) + " snapshot(s) (" +
size_text + "), " + std::to_string(failed) +
" failed: " + utf8_ellipsize(first_error, 40);
}
refresh_data(true);
}
// -----------------------------------------------------------------------
// Drawing
// -----------------------------------------------------------------------
SortField current_sort_field() const {
return tab == TAB_SESSIONS ? session_sort : snapshot_sort;
}
bool current_sort_desc() const {
return tab == TAB_SESSIONS ? session_desc : snapshot_desc;
}
wstring sort_label() const {
if (tab == TAB_DATABASE) return L"-";
return utf8_to_wide(sort_field_name(current_sort_field()));
}
void draw() {
erase();
int h = 0, w = 0;
getmaxyx(stdscr, h, w);
if (w < 1) w = 1;
if (h < 1) h = 1;
draw_header(w);
if (h > 12) draw_scan_progress(1, w); // row 1 is free until the list starts
int list_start_y = 2;
int list_end_y = h - 5; // cursor info + 2 help lines + message below
if (list_end_y <= list_start_y) list_end_y = list_start_y + 1;
int visible = list_end_y - list_start_y;
page_rows = visible > 1 ? visible - 1 : 1;
if (tab == TAB_SESSIONS) draw_session_list(list_start_y, list_end_y, w);
else if (tab == TAB_SNAPSHOTS) draw_snapshot_list(list_start_y, list_end_y, w);
else draw_database_view(list_start_y, list_end_y, w);
draw_info_line(h - 4, w);
draw_help_lines(h - 3, w); // occupies h-3 and h-2
draw_message_line(h - 1, w);
if (confirm_mode) draw_confirm_dialog(h, w);
if (pending_action != MA_NONE) draw_action_prompt(h, w);
if (preview_mode) draw_preview_overlay(h, w);
wnoutrefresh(stdscr);
doupdate();
}
// Line 0: tabs, filter state and totals.
void draw_header(int w) {
wattrset(stdscr, A_NORMAL);
mvwaddswstr(stdscr, 0, 0, wstring((size_t)w, L' '));
wchar_t buf[128];
swprintf(buf, 128, L" Sessions (%d) ", (int)sessions.size());
wstring tab_s = buf;
swprintf(buf, 128, L" Snapshots (%d) ", (int)snapshots.size());
wstring tab_p = buf;
wstring tab_d = L" Database ";