Repository navigation
Expand file tree
/
Copy pathtest_mcp_bridge.cpp
More file actions
4334 lines (4158 loc) · 198 KB
/
Copy pathtest_mcp_bridge.cpp
File metadata and controls
4334 lines (4158 loc) · 198 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
// SPDX-License-Identifier: GPL-3.0-or-later
//
// MCP bridge protocol test. Offscreen-safe, Windows-safe (no POSIX
// headers), no QMessageBox paths. Drives a real QLocalServer round-trip
// against a fake editor host. Widget-hosting (QTEST_MAIN, not guiless):
// the write tier's human-approval card is a real QFrame this test finds
// and clicks programmatically.
//
// Server and client live in the SAME event loop, so every wait is a
// QTest::qWait pump loop with a hard timeout — never a blocking
// waitFor* on the client (that would starve the server side).
#include <QtTest>
#include <QApplication>
#include <QSqlDatabase>
#include <cstdio>
#include <cstdlib>
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QElapsedTimer>
#include <QFile>
#include <QFileInfo>
#include <QFrame>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QLocalSocket>
#include <QPushButton>
#include <QRegularExpression>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QTemporaryDir>
#include <QWidget>
#include "dbconnections.h"
#include "mcp_bridge.h"
namespace {
constexpr int kWaitMs = 10000;
struct FakeTab {
QString title;
QString path;
QString text;
bool modified = false;
QString language = QStringLiteral("Plain Text");
bool isDiagram = false; // v0.1.119 — .npd diagram tab
bool editable = true; // v0.1.121 — false for Welcome/diagram/… tabs
// v0.1.126 (NP-13) — stable identity, 0 until first observed. Lives in the
// struct so it MOVES WITH THE TAB when an earlier tab is removed, which is
// the whole property under test: the index shifts, the id does not.
qint64 id = 0;
};
// Crash-proof progress tracker. ctest DISCARDS a crashed test's captured stdout
// on Windows, so section progress is appended to the file named by
// NP_MCP_PROGRESS with an fopen/fprintf/fflush/fclose per line — it survives an
// access violation. No-op when the env var is unset (i.e. everywhere but CI).
void npWriteProgress(const char *phase, const char *detail) {
const QByteArray pf = qgetenv("NP_MCP_PROGRESS");
if (pf.isEmpty()) return;
if (FILE *f = fopen(pf.constData(), "a")) {
fprintf(f, "%s %s\n", phase, detail ? detail : "(none)");
fflush(f);
fclose(f);
}
}
} // namespace
class TestMcpBridge : public QObject {
Q_OBJECT
private:
QVector<FakeTab> m_fakeTabs;
// v0.1.126 (NP-13) — monotonic source for FakeTab::id. Never reused, so a
// reopened file is a genuinely different tab.
qint64 m_nextFakeTabId = 0;
QString m_selection;
int m_currentIndex = 0;
QString m_root;
McpBridge *m_bridge = nullptr;
QString m_name;
int m_seq = 0;
// v0.1.118 expansive-wave fake state.
int m_cursorLine = 1;
int m_cursorCol = 1;
QStringList m_recent;
QString m_notesRoot;
int m_compareCount = 0;
int m_lastGotoLine = -1;
// v0.1.118 write-tier fake state.
QWidget *m_hostWindow = nullptr;
QVector<int> m_savedTabs;
QString m_savedAsPath; // v0.1.121 — last save_tab "Save As" path
// v0.1.119 depth-wave fake state.
QJsonArray m_reminders; // raw reminders the host would return
bool m_gitFail = false; // runGit returns an error
bool m_gitHuge = false; // runGit returns > 256 KB
QString m_openedNote; // last open_note target
bool m_noterOpened = false; // open_noter fired
QString m_lastCreatedTitle;
QString m_lastCreatedBody;
QString m_lastCreatedPath;
QString m_appendedTo;
QString m_appendedText;
QString m_reminderFile;
QDateTime m_reminderDue;
QString m_exportedPath;
QString m_exportedFormat;
int m_sqlRows = 3; // rows the fake runSql returns for a SELECT
int m_sqlCellLen = 0; // when >0, the "name" cell is this many chars
// ── Phase 2 fake state ──
QJsonArray m_connections; // sanitized saved-connection list
QHash<QString, DbConnections::Record> m_namedRecords; // real records for run_query/list_tables
bool m_dataAnalystOpened = false;
bool m_hostHasWebEngine = false; // gated is the default posture
QJsonObject m_renderedSpec;
QString m_renderedTitle;
QString m_exportedChartPath;
QString m_exportedChartFormat;
int m_exportedChartScale = 0;
McpEditorHost makeHost() {
McpEditorHost h;
h.tabCount = [this] { return m_fakeTabs.size(); };
h.tabTitle = [this](int i) { return m_fakeTabs.value(i).title; };
h.tabPath = [this](int i) { return m_fakeTabs.value(i).path; };
h.tabModified = [this](int i) { return m_fakeTabs.value(i).modified; };
h.tabText = [this](int i) { return m_fakeTabs.value(i).text; };
// v0.1.121 (issue #1): a tab is editable unless the fixture says
// otherwise. value(i) default-constructs (editable=true) for an
// out-of-range index, matching the real host's nullptr→false only for
// in-range non-editor tabs.
h.tabEditable = [this](int i) {
return i >= 0 && i < m_fakeTabs.size() ? m_fakeTabs[i].editable
: true;
};
// v0.1.126 (NP-13). Lazy stamp-on-first-ask, mirroring the real host's
// QWidget property so the fake cannot pass a test the app would fail.
h.tabId = [this](int i) -> qint64 {
if (i < 0 || i >= m_fakeTabs.size()) return -1;
if (m_fakeTabs[i].id == 0) m_fakeTabs[i].id = ++m_nextFakeTabId;
return m_fakeTabs[i].id;
};
h.openFile = [this](const QString &p) -> int {
QFile f(p);
if (!f.open(QIODevice::ReadOnly)) return -1;
m_fakeTabs.append({QFileInfo(p).fileName(),
QFileInfo(p).absoluteFilePath(),
QString::fromUtf8(f.readAll()), false});
return m_fakeTabs.size() - 1;
};
h.selection = [this](int *tabIndex) {
if (tabIndex) *tabIndex = m_currentIndex;
return m_selection;
};
h.workspaceRoot = [this] { return m_root; };
// ── v0.1.118 expansive wave ──
h.currentTabIndex = [this] { return m_currentIndex; };
h.tabLanguage = [this](int i) { return m_fakeTabs.value(i).language; };
h.tabEncoding = [this](int i) {
return i >= 0 && i < m_fakeTabs.size() ? QStringLiteral("UTF-8")
: QString();
};
h.cursorPosition = [this](int *l, int *c) {
if (l) *l = m_cursorLine;
if (c) *c = m_cursorCol;
};
h.recentFiles = [this] { return m_recent; };
h.newTab = [this](const QString &text) {
m_fakeTabs.append({QStringLiteral("new %1")
.arg(m_fakeTabs.size() + 1),
QString(), text, !text.isEmpty()});
m_currentIndex = m_fakeTabs.size() - 1;
return m_currentIndex;
};
// Models the REAL Editor::gotoLine contract: clamp to the buffer and
// return the line actually landed on (-1 = could not target the tab).
//
// This stub used to return bool. Under the int-returning host hook that
// still COMPILES — true converts to 1 — so it would have reported
// "landed on line 1" for every successful jump and quietly asserted
// nothing about clamping. A stub that lies is worse than no stub.
h.gotoLine = [this](int idx, int line) -> int {
if (idx < 0 || idx >= m_fakeTabs.size() || line < 1) return -1;
const int total =
qMax(1, m_fakeTabs[idx].text.count(QLatin1Char('\n')) + 1);
const int landed = qBound(1, line, total);
m_currentIndex = idx;
m_lastGotoLine = landed;
return landed;
};
// v0.1.121 (issue #5): flatten the 1-based range to char offsets, set
// m_selection to the spanned text so a following replace_selection
// works, and focus the tab.
h.selectRange = [this](int idx, int sl, int sc, int el, int ec) {
if (idx < 0 || idx >= m_fakeTabs.size()) return false;
const QString &buf = m_fakeTabs[idx].text;
auto offsetOf = [&buf](int line, int col) -> int {
int cur = 1, off = 0;
while (cur < line) {
const int nl = buf.indexOf(QLatin1Char('\n'), off);
if (nl < 0) return -1; // line out of range
off = nl + 1;
++cur;
}
int lineEnd = buf.indexOf(QLatin1Char('\n'), off);
if (lineEnd < 0) lineEnd = buf.size();
return qMin(off + (col - 1), lineEnd);
};
const int a = offsetOf(sl, sc);
const int b = offsetOf(el, ec);
if (a < 0 || b < 0 || b < a) return false;
m_currentIndex = idx;
m_selection = buf.mid(a, b - a);
return true;
};
h.setLanguage = [this](int idx, const QString &lang) {
static const QStringList known = {
QStringLiteral("Plain Text"), QStringLiteral("Python"),
QStringLiteral("JSON"), QStringLiteral("C++"),
QStringLiteral("SQL")};
if (idx < 0 || idx >= m_fakeTabs.size() || !known.contains(lang))
return false;
m_fakeTabs[idx].language = lang;
return true;
};
h.compareTabs = [this](int a, int b) {
if (a < 0 || b < 0 || a >= m_fakeTabs.size() ||
b >= m_fakeTabs.size() || a == b)
return false;
++m_compareCount;
return true;
};
h.formatText = [](const QString &kind, const QString &text,
QString *err) -> QString {
if (kind == QLatin1String("json")) {
// v0.1.126 (NP-09): the fake used to accept anything starting
// with '{' and reject everything else — wrong in BOTH
// directions (it passed `{oops`, it failed `[1,2]`). The real
// host validates strictly before formatting; a fake looser
// than the thing it stands in for can only certify bugs.
QJsonParseError pe{};
QJsonDocument::fromJson(text.toUtf8(), &pe);
if (pe.error != QJsonParseError::NoError) {
if (err)
*err = QStringLiteral("invalid JSON: %1 at offset %2")
.arg(pe.errorString())
.arg(pe.offset);
return QString();
}
return QStringLiteral("FMT-JSON:") + text;
}
return kind.toUpper() + QLatin1Char(':') + text;
};
h.notesRoot = [this] { return m_notesRoot; };
// ── Phase 0A ──
h.knownLanguages = [] {
return QStringList{QStringLiteral("Plain Text"),
QStringLiteral("Python"), QStringLiteral("JSON"),
QStringLiteral("C++"), QStringLiteral("SQL")};
};
h.resolveLanguage = [](const QString &in) -> QString {
static const QStringList known = {
QStringLiteral("Plain Text"), QStringLiteral("Python"),
QStringLiteral("JSON"), QStringLiteral("C++"),
QStringLiteral("SQL")};
for (const QString &k : known)
if (k.compare(in, Qt::CaseInsensitive) == 0) return k;
if (in.compare(QStringLiteral("py"), Qt::CaseInsensitive) == 0)
return QStringLiteral("Python");
return QString();
};
// ── v0.1.118 write tier ──
h.approvalParent = [this]() -> QWidget * { return m_hostWindow; };
h.hasSelection = [this](int) { return !m_selection.isEmpty(); };
h.insertText = [this](int idx, int line, int col,
const QString &text) {
if (idx < 0 || idx >= m_fakeTabs.size()) return false;
QString &buf = m_fakeTabs[idx].text;
int pos = buf.size(); // fake cursor: end of buffer
if (line >= 1) {
int cur = 1, off = 0;
while (cur < line) {
const int nl = buf.indexOf(QLatin1Char('\n'), off);
if (nl < 0) return false; // line out of range
off = nl + 1;
++cur;
}
int lineEnd = buf.indexOf(QLatin1Char('\n'), off);
if (lineEnd < 0) lineEnd = buf.size();
pos = qMin(off + (col - 1), lineEnd);
}
buf.insert(pos, text);
m_fakeTabs[idx].modified = true;
return true;
};
h.replaceSelection = [this](int idx, const QString &text) {
if (idx < 0 || idx >= m_fakeTabs.size() || m_selection.isEmpty())
return false;
QString &buf = m_fakeTabs[idx].text;
const int at = buf.indexOf(m_selection);
if (at < 0) return false;
buf.replace(at, m_selection.size(), text);
m_selection.clear();
return true;
};
h.applyEdit = [this](int idx, const QString &find,
const QString &repl, bool all) {
if (idx < 0 || idx >= m_fakeTabs.size()) return -1;
QString &buf = m_fakeTabs[idx].text;
int count = 0, from = 0;
while (true) {
const int at = buf.indexOf(find, from);
if (at < 0) break;
buf.replace(at, find.size(), repl);
++count;
from = at + repl.size();
if (!all) break;
}
return count;
};
h.saveTab = [this](int idx) {
if (idx < 0 || idx >= m_fakeTabs.size() ||
m_fakeTabs[idx].path.isEmpty())
return false;
m_savedTabs.append(idx);
m_fakeTabs[idx].modified = false;
return true;
};
// v0.1.121 (issue #4): "Save As" — adopt the new path (the bridge has
// already validated it) and clear modified.
h.saveTabAs = [this](int idx, const QString &path) {
if (idx < 0 || idx >= m_fakeTabs.size()) return false;
m_fakeTabs[idx].path = path;
m_fakeTabs[idx].modified = false;
m_savedAsPath = path;
m_savedTabs.append(idx);
return true;
};
// ── v0.1.119 depth wave ──
h.reminders = [this] { return m_reminders; };
h.runGit = [this](const QString &sub, const QJsonObject &args,
QString *err) -> QString {
if (m_gitFail) {
if (err) *err = QStringLiteral("not_a_repo: not a git checkout");
return QString();
}
if (m_gitHuge)
return QString(300 * 1024, QLatin1Char('x'));
// Echo the fixed subcommand + the args the bridge forwarded so a
// test can prove path/limit/ref reach the git layer verbatim.
return QStringLiteral("git-%1|path=%2|limit=%3|ref=%4")
.arg(sub,
args.value(QLatin1String("path")).toString(),
QString::number(
args.value(QLatin1String("limit")).toInt(-1)),
args.value(QLatin1String("ref")).toString());
};
h.diagramSource = [this](int i, QString *out) -> bool {
if (i < 0 || i >= m_fakeTabs.size() || !m_fakeTabs[i].isDiagram)
return false;
if (out) *out = m_fakeTabs[i].text;
return true;
};
h.runSql = [this](const QString &sql, const QString &csvPath,
QString *err) -> QJsonObject {
// Faithful-enough stand-in for DbConnections::classifySql: reject
// any statement carrying a DML/DDL verb (this is what catches
// UPDATE / DELETE and the WITH ... DELETE trap), accept the rest.
static const QRegularExpression dml(
QStringLiteral("\\b(insert|update|delete|drop|create|alter|"
"replace|truncate|attach|copy)\\b"),
QRegularExpression::CaseInsensitiveOption);
if (dml.match(sql).hasMatch()) {
if (err)
*err = QStringLiteral(
"query rejected: statement is not read-only");
return QJsonObject();
}
QJsonArray cols;
cols.append(QStringLiteral("id"));
cols.append(QStringLiteral("name"));
QJsonArray rows;
for (int i = 0; i < m_sqlRows; ++i) {
QJsonArray r;
r.append(QString::number(i));
r.append(m_sqlCellLen > 0
? QString(m_sqlCellLen, QLatin1Char('X'))
: QStringLiteral("row%1").arg(i));
rows.append(r);
}
QJsonObject out;
out[QStringLiteral("columns")] = cols;
out[QStringLiteral("rows")] = rows;
out[QStringLiteral("truncated")] = false;
out[QStringLiteral("engine")] =
csvPath.isEmpty() ? QStringLiteral("sqlite")
: QStringLiteral("duckdb");
return out;
};
h.openNote = [this](const QString &absFile, QString *) -> QString {
m_openedNote = absFile;
return QFileInfo(absFile).completeBaseName();
};
h.createNote = [this](const QString &title, const QString &body,
QString *) -> QString {
m_lastCreatedTitle = title;
m_lastCreatedBody = body;
m_lastCreatedPath = m_notesRoot +
QStringLiteral("/Inbox/created-%1.html").arg(title);
return m_lastCreatedPath;
};
h.appendNote = [this](const QString &absFile, const QString &text,
QString *) -> bool {
m_appendedTo = absFile;
m_appendedText = text;
return true;
};
h.setReminder = [this](const QString &absFile, const QDateTime &due,
QString *) -> bool {
m_reminderFile = absFile;
m_reminderDue = due;
return true;
};
h.exportDiagram = [this](int, const QString &path,
const QString &format, QString *) -> bool {
m_exportedPath = path;
m_exportedFormat = format;
return true;
};
// ── Phase 1 ──
h.createDiagram = [this](const QString &src, const QString &title) {
m_fakeTabs.append({title.isEmpty() ? QStringLiteral("Diagram")
: title,
QString(), src, false,
QStringLiteral("Plain Text"), true});
m_currentIndex = m_fakeTabs.size() - 1;
return m_currentIndex;
};
h.setDiagramSource = [this](int i, const QString &src) {
if (i < 0 || i >= m_fakeTabs.size() || !m_fakeTabs[i].isDiagram)
return false;
m_fakeTabs[i].text = src;
return true;
};
h.openNoter = [this]() {
m_noterOpened = true;
return true;
};
// ── Phase 2 ──
h.listConnections = [this] { return m_connections; };
h.classifySqlReadOnly = [](const QString &sql, QString *reason) {
const auto v = DbConnections::classifySql(sql, /*restrict=*/true);
if (v.singleStatement && v.readOnly) return true;
if (reason) *reason = v.reason;
return false;
};
h.runNamedQuery = [this](const QString &name, const QString &sql,
int maxRows, QString *err) -> QJsonObject {
const auto v = DbConnections::classifySql(sql, /*restrict=*/true);
if (!(v.singleStatement && v.readOnly)) {
if (err)
*err = v.reason.isEmpty()
? QStringLiteral("query is not read-only (SELECT only)")
: QStringLiteral("query rejected: %1").arg(v.reason);
return QJsonObject();
}
if (!m_namedRecords.contains(name)) {
if (err) *err = QStringLiteral("no connection named: %1").arg(name);
return QJsonObject();
}
const DbConnections::Record rec = m_namedRecords.value(name);
const DbConnections::QueryResult qr =
DbConnections::runQuery(rec, sql, maxRows, false, nullptr);
if (!qr.ok) {
if (err)
*err = qr.error.isEmpty() ? QStringLiteral("query failed")
: qr.error;
return QJsonObject();
}
QJsonArray cols;
for (const QString &c : qr.columns) cols.append(c);
QJsonArray rows;
for (const QVector<QString> &row : qr.rows) {
QJsonArray jr;
for (const QString &cell : row) jr.append(cell);
rows.append(jr);
}
QJsonObject out;
out[QStringLiteral("columns")] = cols;
out[QStringLiteral("rows")] = rows;
out[QStringLiteral("truncated")] = qr.truncated;
out[QStringLiteral("engine")] =
rec.driver == QLatin1String("QSQLITE") ? QStringLiteral("sqlite")
: QStringLiteral("odbc");
return out;
};
h.listTables = [this](const QString &name, QString *err) -> QJsonArray {
if (!m_namedRecords.contains(name)) {
if (err) *err = QStringLiteral("no connection named: %1").arg(name);
return QJsonArray();
}
bool ok = true;
const QStringList tables =
DbConnections::listTables(m_namedRecords.value(name), &ok);
if (!ok) {
if (err) *err = QStringLiteral("could not connect to: %1").arg(name);
return QJsonArray();
}
QJsonArray out;
for (const QString &t : tables) out.append(t);
return out;
};
h.openDataAnalyst = [this] {
m_dataAnalystOpened = true;
return true;
};
// Charts fields are set ONLY when the fake reports WebEngine — the
// unset-field path IS the friendly gate the bridge answers pre-card.
if (m_hostHasWebEngine) {
h.renderChart = [this](const QJsonObject &spec, const QString &title,
QString *) -> QJsonObject {
m_renderedSpec = spec;
m_renderedTitle = title;
return QJsonObject{{QStringLiteral("chart_id"),
QStringLiteral("test-chart-1")},
{QStringLiteral("rendered"), true}};
};
h.exportChart = [this](const QJsonObject &, const QString &path,
const QString &format, int scale,
QString *err) -> bool {
m_exportedChartPath = path;
m_exportedChartFormat = format;
m_exportedChartScale = scale;
QFile f(path);
if (!f.open(QIODevice::WriteOnly)) {
if (err) *err = QStringLiteral("could not write");
return false;
}
f.write("FAKECHART");
f.close();
return true;
};
}
return h;
}
// Register a real QSQLITE connection record backed by a temp sqlite file
// with a table `t(id INTEGER, name TEXT)` pre-filled with `rows` rows.
QString makeSqliteFixture(QTemporaryDir &dir, const QString &connName,
int rows) {
const QString dbPath = dir.path() + QStringLiteral("/") + connName +
QStringLiteral(".db");
{
QSqlDatabase db =
QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"),
QStringLiteral("fixture-") + connName);
db.setDatabaseName(dbPath);
if (db.open()) {
QSqlQuery q(db);
q.exec(QStringLiteral("CREATE TABLE t(id INTEGER, name TEXT)"));
for (int i = 0; i < rows; ++i)
q.exec(QStringLiteral("INSERT INTO t VALUES(%1, 'name%1')")
.arg(i));
db.close();
}
}
QSqlDatabase::removeDatabase(QStringLiteral("fixture-") + connName);
DbConnections::Record rec;
rec.name = connName;
rec.driver = QStringLiteral("QSQLITE");
rec.database = dbPath;
m_namedRecords.insert(connName, rec);
return dbPath;
}
// Rebuild the bridge with a host that reports WebEngine (charts enabled).
void useWebEngineHost() {
delete m_bridge;
m_hostHasWebEngine = true;
m_bridge = new McpBridge(makeHost(), this, m_name);
QVERIFY(m_bridge->isListening());
}
// Write a minimal Noter-convention note (notepatra-title meta wins the
// title resolution). Returns the absolute path.
QString writeNote(const QString &absPath, const QString &title,
const QString &bodyText) {
QDir().mkpath(QFileInfo(absPath).absolutePath());
QFile f(absPath);
if (!f.open(QIODevice::WriteOnly)) return QString();
const QString html =
QStringLiteral("<html><head><meta name=\"notepatra-title\" "
"content=\"%1\"></head><body><h1>%1</h1>"
"<p>%2</p></body></html>")
.arg(title, bodyText);
f.write(html.toUtf8());
f.close();
return QFileInfo(absPath).absoluteFilePath();
}
bool connectClient(QLocalSocket &s) {
s.connectToServer(m_name);
QElapsedTimer t;
t.start();
while (s.state() != QLocalSocket::ConnectedState &&
t.elapsed() < kWaitMs)
QTest::qWait(10);
return s.state() == QLocalSocket::ConnectedState;
}
QByteArray readLine(QLocalSocket &s, int timeoutMs = kWaitMs) {
QElapsedTimer t;
t.start();
while (!s.canReadLine() && t.elapsed() < timeoutMs)
QTest::qWait(10);
return s.canReadLine() ? s.readLine().trimmed() : QByteArray();
}
QJsonObject readObj(QLocalSocket &s, int timeoutMs = kWaitMs) {
const QByteArray line = readLine(s, timeoutMs);
return QJsonDocument::fromJson(line).object();
}
// Reads and validates the greeting line. Returns it for extra checks.
QJsonObject readGreeting(QLocalSocket &s) { return readObj(s); }
void sendLine(QLocalSocket &s, const QByteArray &line) {
s.write(line + '\n');
s.flush();
}
QJsonObject call(QLocalSocket &s, int id, const QString &verb,
const QJsonObject &args = QJsonObject()) {
QJsonObject req;
req[QStringLiteral("id")] = id;
req[QStringLiteral("verb")] = verb;
req[QStringLiteral("args")] = args;
sendLine(s, QJsonDocument(req).toJson(QJsonDocument::Compact));
return readObj(s);
}
// ── v0.1.118 write-tier helpers ──
// Fire-and-forget request: write verbs don't answer until the human
// decides, so the caller reads the response separately.
void sendRequest(QLocalSocket &s, int id, const QString &verb,
const QJsonObject &args = QJsonObject()) {
QJsonObject req;
req[QStringLiteral("id")] = id;
req[QStringLiteral("verb")] = verb;
req[QStringLiteral("args")] = args;
sendLine(s, QJsonDocument(req).toJson(QJsonDocument::Compact));
}
// Returns the LIVE card — the visible one — never a stale predecessor.
//
// Why visibility matters: a dismissed card is hidden and then deleteLater()'d,
// so between those two events the object is still a child of the host window.
// A plain findChild<QFrame*>("mcpApprovalCard") returns the FIRST match, which
// in that window is the DEAD card. Clicking its buttons resolves nothing, the
// new request is never approved, and the test sees ok=false or an empty error.
// On Linux the pending deleteLater drains inside waitForCardGone()'s qWait, so
// the stale card is gone by the next call and the bug is invisible; on
// offscreen-Windows it survives, which is why three write-verb tests failed
// there and only there. Filtering on isVisible() makes the helper correct on
// both instead of accidentally correct on one.
QFrame *findCard() const {
if (!m_hostWindow) return nullptr;
const auto cards = m_hostWindow->findChildren<QFrame *>(
QStringLiteral("mcpApprovalCard"));
for (QFrame *c : cards)
if (c->isVisible()) return c;
return nullptr;
}
QFrame *waitForCard(int timeoutMs = kWaitMs) {
QElapsedTimer t;
t.start();
while (t.elapsed() < timeoutMs) {
if (QFrame *c = findCard()) return c;
QTest::qWait(10);
}
return nullptr;
}
// Waits for a card whose description label contains `needle` — needed
// when one card replaces another and a plain findChild could still see
// the deleteLater'd predecessor.
QFrame *waitForCardContaining(const QString &needle,
int timeoutMs = kWaitMs) {
QElapsedTimer t;
t.start();
while (t.elapsed() < timeoutMs) {
const auto cards = m_hostWindow->findChildren<QFrame *>(
QStringLiteral("mcpApprovalCard"));
for (QFrame *c : cards) {
if (!c->isVisible()) continue; // skip a dismissed predecessor
auto *d = c->findChild<QLabel *>(
QStringLiteral("mcpApprovalDesc"));
if (d && d->text().contains(needle)) return c;
}
QTest::qWait(10);
}
return nullptr;
}
bool waitForCardGone(int timeoutMs = kWaitMs) {
QElapsedTimer t;
t.start();
while (t.elapsed() < timeoutMs) {
const auto cards = m_hostWindow->findChildren<QFrame *>(
QStringLiteral("mcpApprovalCard"));
bool anyVisible = false;
for (QFrame *c : cards)
if (c->isVisible()) anyVisible = true;
if (!anyVisible) return true;
QTest::qWait(10);
}
return false;
}
// Whole write-verb round trip: request → live card → Approve → response.
// Returns an empty object if the card never appeared, so a caller that
// checks `ok` fails rather than hanging.
QJsonObject callAndApprove(QLocalSocket &s, int id, const QString &verb,
const QJsonObject &args) {
sendRequest(s, id, verb, args);
QFrame *card = waitForCard();
if (!card) return QJsonObject();
auto *approve =
card->findChild<QPushButton *>(QStringLiteral("mcpApproveBtn"));
if (!approve) return QJsonObject();
approve->click();
const QJsonObject resp = readObj(s);
waitForCardGone();
return resp;
}
private slots:
void init() {
// Crash-localizer: on offscreen-Windows CI a hard access violation
// makes ctest discard the test's captured output, hiding which section
// died. Append each section to a file (env NP_MCP_PROGRESS) flushed +
// closed so it survives the crash; the CI step prints it. No-op locally.
writeProgress("ENTER");
m_fakeTabs = {
{QStringLiteral("notes.txt"), QStringLiteral("/fake/notes.txt"),
QStringLiteral("hello world\nSecond Line with Needle\n"), false},
{QStringLiteral("Untitled 1"), QString(),
QStringLiteral("alpha\nbeta NEEDLE gamma\n"), true},
};
m_nextFakeTabId = 0;
m_selection.clear();
m_currentIndex = 0;
m_root.clear();
m_cursorLine = 1;
m_cursorCol = 1;
m_recent.clear();
m_notesRoot.clear();
m_compareCount = 0;
m_lastGotoLine = -1;
m_savedTabs.clear();
m_savedAsPath.clear();
m_reminders = QJsonArray();
m_gitFail = false;
m_gitHuge = false;
m_openedNote.clear();
m_noterOpened = false;
m_lastCreatedTitle.clear();
m_lastCreatedBody.clear();
m_lastCreatedPath.clear();
m_appendedTo.clear();
m_appendedText.clear();
m_reminderFile.clear();
m_reminderDue = QDateTime();
m_exportedPath.clear();
m_exportedFormat.clear();
m_sqlRows = 3;
m_sqlCellLen = 0;
m_connections = QJsonArray();
m_namedRecords.clear();
m_dataAnalystOpened = false;
m_hostHasWebEngine = false;
m_renderedSpec = QJsonObject();
m_renderedTitle.clear();
m_exportedChartPath.clear();
m_exportedChartFormat.clear();
m_exportedChartScale = 0;
m_hostWindow = new QWidget;
m_hostWindow->resize(640, 420);
m_hostWindow->show();
m_name = QStringLiteral("notepatra-mcp-selftest-%1-%2")
.arg(QCoreApplication::applicationPid())
.arg(++m_seq);
m_bridge = new McpBridge(makeHost(), this, m_name);
QVERIFY(m_bridge->isListening());
}
void cleanup() {
// Record the section's VERDICT, not merely that it finished: cleanup()
// runs after a failed QVERIFY too, so a bare "LEAVE" would not prove the
// section passed. CI only tolerates a teardown crash when every ENTER
// has a matching LEAVE and there is no FAILED line.
const bool failed = QTest::currentTestFailed();
delete m_bridge;
m_bridge = nullptr;
delete m_hostWindow;
m_hostWindow = nullptr;
writeProgress(failed ? "FAILED" : "LEAVE");
}
// Crash-localizer helper (see init()). Writes "<phase> <section>" to the
// file named by NP_MCP_PROGRESS, flushed + closed. No-op when unset.
static void writeProgress(const char *phase) {
npWriteProgress(phase, QTest::currentTestFunction());
}
void greeting_arrives_first() {
QLocalSocket s;
QVERIFY(connectClient(s));
// Fire a request immediately, BEFORE reading anything: the greeting
// must still be the first line on the wire (proof-of-life law).
sendLine(s, QByteArray(
R"({"id":1,"verb":"list_open_tabs","args":{}})"));
const QJsonObject greet = readObj(s);
QCOMPARE(greet.value(QLatin1String("notepatra_mcp")).toInt(), 1);
QCOMPARE(greet.value(QLatin1String("app")).toString(),
QStringLiteral("Notepatra"));
QVERIFY(!greet.value(QLatin1String("version")).toString().isEmpty());
const QJsonObject resp = readObj(s);
QCOMPARE(resp.value(QLatin1String("id")).toInt(), 1);
QVERIFY(resp.value(QLatin1String("ok")).toBool());
}
void list_open_tabs_shape() {
QLocalSocket s;
QVERIFY(connectClient(s));
readGreeting(s);
const QJsonObject resp = call(s, 2, QStringLiteral("list_open_tabs"));
QVERIFY(resp.value(QLatin1String("ok")).toBool());
const QJsonArray tabs = resp.value(QLatin1String("result"))
.toObject()
.value(QLatin1String("tabs"))
.toArray();
QCOMPARE(tabs.size(), 2);
const QJsonObject t0 = tabs.at(0).toObject();
QCOMPARE(t0.value(QLatin1String("index")).toInt(), 0);
QCOMPARE(t0.value(QLatin1String("title")).toString(),
QStringLiteral("notes.txt"));
QCOMPARE(t0.value(QLatin1String("path")).toString(),
QStringLiteral("/fake/notes.txt"));
QCOMPARE(t0.value(QLatin1String("modified")).toBool(), false);
const QJsonObject t1 = tabs.at(1).toObject();
QCOMPARE(t1.value(QLatin1String("index")).toInt(), 1);
QCOMPARE(t1.value(QLatin1String("path")).toString(), QString());
QCOMPARE(t1.value(QLatin1String("modified")).toBool(), true);
}
// v0.1.121 (issue #1): a non-editable tab (Welcome page) is flagged in
// list_open_tabs and rejected by the buffer-reading verbs.
void welcome_tab_marked_non_editable() {
// Prepend a Welcome tab at index 0, as the real app does.
m_fakeTabs.prepend({QStringLiteral("Welcome"), QString(), QString(),
false, QStringLiteral("Plain Text"),
/*isDiagram=*/false, /*editable=*/false});
QLocalSocket s;
QVERIFY(connectClient(s));
readGreeting(s);
const QJsonObject resp = call(s, 200, QStringLiteral("list_open_tabs"));
QVERIFY(resp.value(QLatin1String("ok")).toBool());
const QJsonArray tabs = resp.value(QLatin1String("result"))
.toObject()
.value(QLatin1String("tabs"))
.toArray();
QCOMPARE(tabs.size(), 3);
const QJsonObject welcome = tabs.at(0).toObject();
QCOMPARE(welcome.value(QLatin1String("title")).toString(),
QStringLiteral("Welcome"));
QCOMPARE(welcome.value(QLatin1String("editable")).toBool(), false);
// The editable text tabs are still marked editable.
QCOMPARE(tabs.at(1).toObject().value(QLatin1String("editable")).toBool(),
true);
// read_tab against the Welcome tab is refused (no text buffer).
QJsonObject args;
args[QStringLiteral("index")] = 0;
const QJsonObject bad = call(s, 201, QStringLiteral("read_tab"), args);
QCOMPARE(bad.value(QLatin1String("ok")).toBool(), false);
QVERIFY(bad.value(QLatin1String("error"))
.toString()
.contains(QLatin1String("not an editable")));
}
void read_tab_by_index() {
QLocalSocket s;
QVERIFY(connectClient(s));
readGreeting(s);
QJsonObject args;
args[QStringLiteral("index")] = 0;
const QJsonObject resp = call(s, 3, QStringLiteral("read_tab"), args);
QVERIFY(resp.value(QLatin1String("ok")).toBool());
const QJsonObject r = resp.value(QLatin1String("result")).toObject();
QCOMPARE(r.value(QLatin1String("title")).toString(),
QStringLiteral("notes.txt"));
QCOMPARE(r.value(QLatin1String("path")).toString(),
QStringLiteral("/fake/notes.txt"));
QCOMPARE(r.value(QLatin1String("text")).toString(),
m_fakeTabs[0].text);
// v0.1.126 (NP-10): `truncated` is now ALWAYS present. It used to be
// omitted on the complete-read path, so a caller had to know that
// absent means false — an inference every other bulk verb spares it.
QVERIFY(r.contains(QLatin1String("truncated")));
QCOMPARE(r.value(QLatin1String("truncated")).toBool(), false);
QCOMPARE(r.value(QLatin1String("total_chars")).toInt(),
m_fakeTabs[0].text.size());
}
void read_tab_by_title() {
QLocalSocket s;
QVERIFY(connectClient(s));
readGreeting(s);
QJsonObject args;
args[QStringLiteral("title")] = QStringLiteral("Untitled 1");
const QJsonObject resp = call(s, 4, QStringLiteral("read_tab"), args);
QVERIFY(resp.value(QLatin1String("ok")).toBool());
const QJsonObject r = resp.value(QLatin1String("result")).toObject();
QCOMPARE(r.value(QLatin1String("text")).toString(),
m_fakeTabs[1].text);
QCOMPARE(r.value(QLatin1String("path")).toString(), QString());
}
void read_tab_not_found() {
QLocalSocket s;
QVERIFY(connectClient(s));
readGreeting(s);
QJsonObject byIndex;
byIndex[QStringLiteral("index")] = 99;
QJsonObject r1 = call(s, 5, QStringLiteral("read_tab"), byIndex);
QCOMPARE(r1.value(QLatin1String("ok")).toBool(), false);
QVERIFY(!r1.value(QLatin1String("error")).toString().isEmpty());
QJsonObject byTitle;
byTitle[QStringLiteral("title")] = QStringLiteral("no such tab");
QJsonObject r2 = call(s, 6, QStringLiteral("read_tab"), byTitle);
QCOMPARE(r2.value(QLatin1String("ok")).toBool(), false);
QJsonObject r3 = call(s, 7, QStringLiteral("read_tab"));
QCOMPARE(r3.value(QLatin1String("ok")).toBool(), false);
}
void read_tab_truncates_at_5mb() {
const int cap = 5 * 1024 * 1024;
m_fakeTabs[1].text = QString(cap + 4096, QLatin1Char('x'));
QLocalSocket s;
QVERIFY(connectClient(s));
readGreeting(s);
QJsonObject args;
args[QStringLiteral("index")] = 1;
const QJsonObject resp = call(s, 8, QStringLiteral("read_tab"), args);
QVERIFY(resp.value(QLatin1String("ok")).toBool());
const QJsonObject r = resp.value(QLatin1String("result")).toObject();
QCOMPARE(r.value(QLatin1String("truncated")).toBool(), true);
QCOMPARE(r.value(QLatin1String("text")).toString().size(), cap);
}
// ── v0.1.126 · NP-10 ──────────────────────────────────────────────
//
// The 5 MB ceiling was the ONLY bound: a 2.7 MB buffer came back whole and
// could fill an assistant's entire context in one call, with no way to ask
// for less. Every other bulk verb on the surface is negotiable
// (search_project max_results, run_sql max_rows); read_tab was not.
void read_tab_honours_max_bytes() {
m_fakeTabs[1].text = QString(10000, QLatin1Char('y'));
QLocalSocket s;
QVERIFY(connectClient(s));
readGreeting(s);
QJsonObject args;
args[QStringLiteral("index")] = 1;
args[QStringLiteral("max_bytes")] = 100;
const QJsonObject r = call(s, 80, QStringLiteral("read_tab"), args)
.value(QLatin1String("result")).toObject();
QCOMPARE(r.value(QLatin1String("text")).toString().size(), 100);
QCOMPARE(r.value(QLatin1String("truncated")).toBool(), true);
// The caller must learn how much it did NOT get, or it cannot page.
QCOMPARE(r.value(QLatin1String("total_chars")).toInt(), 10000);
// A cap larger than the text is not a truncation.
QJsonObject big;
big[QStringLiteral("index")] = 1;
big[QStringLiteral("max_bytes")] = 99999;
const QJsonObject br = call(s, 81, QStringLiteral("read_tab"), big)
.value(QLatin1String("result")).toObject();
QCOMPARE(br.value(QLatin1String("text")).toString().size(), 10000);
QCOMPARE(br.value(QLatin1String("truncated")).toBool(), false);
// Nonsense caps are rejected, not clamped into silent success: a
// caller asking for 0 bytes has a bug it should hear about.
for (const int bad : {0, -5}) {