-
-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathai_agent.cpp
More file actions
2617 lines (2410 loc) · 116 KB
/
Copy pathai_agent.cpp
File metadata and controls
2617 lines (2410 loc) · 116 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
#include <QAction>
#include <QApplication>
#include <QCheckBox>
#include <QClipboard>
#include <QCloseEvent>
#include <QColor>
#include <QComboBox>
#include <QDateTime>
#include <QDesktopServices>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QFontMetrics>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QJsonArray>
#include <QJsonDocument>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QMenu>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QProcess>
#include <QProcessEnvironment>
#include <QPushButton>
#include <QRegularExpression>
#include <QScrollBar>
#include <QShortcut>
#include <QShowEvent>
#include <QSpinBox>
#include <QStandardItemModel>
#include <QStandardPaths>
#include <QTextFrame>
#include <QTimer>
#include <QToolButton>
#include <QUuid>
#include <QUrl>
#include <QVBoxLayout>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include "ai_agent.hpp"
#include "cmd/ai.hpp"
#include "ui_ai_agent.h"
#include "mainwindow.h"
#include "tracking/tracking_window.h"
#include "TIPL/tipl.hpp"
constexpr qsizetype ai_debug_truncate_length = 300; // level 1 (truncated) caps each logged line to this many characters
bool is_valid_session_id(const QString& id)
{
return !QUuid(id).toString(QUuid::WithoutBraces).compare(id,Qt::CaseInsensitive);
}
void AIAgent::ai_log(QString text)
{
if(ai_debug_level <= 0)
return;
if(ai_debug_level == 1 && text.size() > ai_debug_truncate_length)
text = text.left(ai_debug_truncate_length)+"...";
auto prefix = QString("[DEBUG] ");
tipl::out() << (prefix+text.remove('\r').
replace('\n',"\n"+prefix)).toStdString();
}
AIAgent::AIAgent(MainWindow* parent):
QMainWindow(parent),main_window(*parent),ui(new Ui::AIAgent)
{
ui->setupUi(this);
ai_debug_level = settings.value("ai/debug",0).toInt();
ui->ai_work_dir->setText(main_window.work_dir());
// keeps the field in sync with the selected chat's own dispatch directory (model_settings["cwd"]),
// the same value run_shell's "cd" updates; also used as --add-dir when launching Codex/Claude
auto sync_work_dir = [this]
{
auto* info = selected_info();
if(!info)
return;
auto cwd = ui->ai_work_dir->text().trimmed();
if(info->model_settings["cwd"].toString() != cwd)
{
info->model_settings["cwd"] = cwd;
info->save_config();
}
};
connect(ui->ai_work_dir,&QLineEdit::editingFinished,this,sync_work_dir);
connect(ui->ai_browse_work_dir,&QPushButton::clicked,this,[this,sync_work_dir]
{
auto path = QFileDialog::getExistingDirectory(
this,"Select AI Work Directory",ui->ai_work_dir->text());
if(!path.isEmpty())
{
ui->ai_work_dir->setText(QDir::toNativeSeparators(path));
sync_work_dir();
}
});
ai_status_timer = new QTimer(this);
connect(ai_status_timer,&QTimer::timeout,this,[this]
{
bool running = false;
for(auto& entry : ai_infos)
{
auto& info = entry.second;
if(info.is_running())
{
running = true;
if(auto* row = ui->ai_project_list->itemWidget(info.project_items))
update_status_dot(row->findChild<QLabel*>("ai_project_status_dot"),
info.status,true);
}
}
if(!running)
ai_status_timer->stop();
if(auto* info = selected_info();info && info->is_running())
{
auto status = ui->ai_status->text();
ui->ai_status->setText(
status.endsWith("...") ? status.chopped(2) : status+".");
ui->ai_status->repaint();
}
});
ui->ai_status->hide();
github_timer.setSingleShot(true);
connect(&github_timer,&QTimer::timeout,this,&AIAgent::poll_github_issue);
refresh_agent_executables();
if(agent_entries[int(ai_provider::Codex)].executable.isEmpty() &&
!agent_entries[int(ai_provider::Claude)].executable.isEmpty())
current_agent_index = int(ai_provider::Claude);
update_agent_status_label();
// not refreshed here: agent_login_info() runs a blocking CLI subprocess per provider, and AIAgent is
// constructed eagerly at MainWindow startup whether or not this window is ever opened. showEvent()
// refreshes it before the buttons are ever actually seen -- the .ui defaults ("Sign in to Codex...",
// "Sign in to Claude...") are shown only in that brief unshown window, never rendered to the user.
for(auto [button,provider] : {std::pair{ui->ai_codex_login,ai_provider::Codex},
std::pair{ui->ai_claude_login,ai_provider::Claude}})
connect(button,&QPushButton::clicked,this,[this,provider]
{
if(agent_entries[int(provider)].executable.isEmpty()) // stale showEvent() check -- the window may have stayed open since before an install finished, so retry once before assuming it's still missing
refresh_agent_executables();
if(agent_entries[int(provider)].executable.isEmpty()) // still not installed -- nothing to sign into yet
QDesktopServices::openUrl(agent_install_url(provider));
else
run_agent_login(provider);
refresh_login_buttons();
});
auto* send = new QShortcut(
QKeySequence(Qt::CTRL|Qt::Key_Return),ui->ai_chat_input);
send->setContext(Qt::WidgetShortcut);
connect(send,&QShortcut::activated,
ui->ai_send_message,&QPushButton::click);
connect(ui->ai_chat_input,&QPlainTextEdit::textChanged,
this,&AIAgent::update_send_button);
ai_project_menu = new QMenu(this);
ai_project_menu->setStyleSheet(
"QMenu{background:#fff;border:1px solid #d9d9dc;padding:4px;}"
"QMenu::item{padding:6px 24px 6px 10px;border-radius:4px;}"
"QMenu::item:selected{background:#e9e9eb;}"
"QMenu::item:disabled{color:#9a9a9e;}"
"QMenu::separator{height:1px;background:#dedee1;margin:4px;}");
connect(ai_project_menu->addAction("Rename"),&QAction::triggered,this,[this]
{
auto* info = selected_info();
if(!info) // menu can only be reached via a row's own "..." button, but guard against it anyway rather than trust that indirectly
return;
bool okay;
auto title = QInputDialog::getText(
this,"Rename Chat","Chat name:",QLineEdit::Normal,
info->title(),&okay);
if(okay && info->save_title(title))
show_ai_project(*info);
else if(okay)
QMessageBox::warning(
this,"Rename Chat","The chat name could not be saved.");
});
connect(ai_project_menu->addAction("Details..."),
&QAction::triggered,this,[this]
{
auto* info = selected_info();
if(!info)
return;
QMessageBox details(
QMessageBox::Information,"Chat Details",
info->details(),
QMessageBox::Ok,this);
details.setTextInteractionFlags(
Qt::TextSelectableByMouse|Qt::TextSelectableByKeyboard);
details.exec();
});
ai_project_menu->addSeparator();
connect(ai_project_menu->addAction("Remove"),&QAction::triggered,this,[this]
{
auto row = ui->ai_project_list->currentRow();
if(row < 0)
return;
auto session = ui->ai_project_list->item(row)->data(Qt::UserRole).toString();
if(auto* found = ai_info::find(session);found && found->processes)
{
auto* process = found->processes;
process->disconnect(); process->kill(); process->deleteLater(); // kill(): a windowless console child never sees terminate()'s WM_CLOSE
}
if(session == web_agent_session_id)
disconnect_github_issue(); // otherwise the channel keeps polling and recreates this chat on the next request
QFile::remove(ai_info::history_file(session));
QFile::remove(ai_info::config_file(session));
settings.remove("ai/title/"+session);
ai_infos.erase(session);
auto* taken_item = ui->ai_project_list->takeItem(row); // defer delete: its row widget owns the "..." button whose menu action is still running
QTimer::singleShot(0,this,[taken_item]{delete taken_item;});
// keep a chat selected whenever one exists
if(ui->ai_project_list->count())
ui->ai_project_list->setCurrentRow(std::min(row,ui->ai_project_list->count()-1));
});
connect(ui->ai_project_list,&QListWidget::currentItemChanged,this,
[this](QListWidgetItem* item,QListWidgetItem* previous)
{
for(auto* i : {previous,item})
if(i) // itemWidget() is null for an item already detached from the list (e.g. mid-removal), so guard both calls
if(auto* widget = ui->ai_project_list->itemWidget(i))
if(auto* button = widget->findChild<QPushButton*>())
button->setStyleSheet(i == item ?
"color:#202124;background:#dce9f9;" : "");
if(!item)
{
ui->ai_chat_history->clear();
update_send_button();
return ui->ai_status->hide();
}
stop_blink(ui->ai_project_list->itemWidget(item));
auto* info = selected_info();
if(!info) // item is a real row, but guard anyway rather than trust that indirectly
return;
ui->ai_work_dir->setText(info->model_settings.contains("cwd") ?
info->model_settings["cwd"].toString() : main_window.work_dir());
// no longer copies the selected chat's agent/model into the app-wide default: update_agent_status_label()
// reads this chat's own model_settings directly, and merely looking at a chat shouldn't change what the
// next New Chat starts with
update_agent_status_label();
show_ai_project(*info);
update_send_button();
});
for(const auto& info : QDir(ai_project_dir).entryInfoList(
{"*.jsonl"},QDir::Files,QDir::Time|QDir::Reversed))
{
auto session = QUrl::fromPercentEncoding(
info.completeBaseName().toLatin1());
QList<QJsonObject> history;
QFile file(info.filePath());
if(!file.open(QIODevice::ReadOnly))
continue;
while(!file.atEnd())
if(auto doc = QJsonDocument::fromJson(file.readLine());doc.isObject())
history.append(doc.object());
if(history.isEmpty() || session.isEmpty())
continue;
auto first = history.first();
QJsonObject config;
if(QFile config_file(ai_info::config_file(session));config_file.open(QIODevice::ReadOnly))
config = QJsonDocument::fromJson(config_file.readAll()).object();
// config_file() is the current source of truth; fall back to the legacy fields once
// embedded in the first history entry, for chats saved before this file existed
auto agent = config.contains("agent") ? config["agent"].toString() : first["agent"].toString();
// never re-guess the provider from the name once it's been persisted -- that's exactly what
// misclassifies an AgentServer session; only a legacy config predating persistence falls back to a guess
auto* ai = config.contains("provider") ?
ai_info::create(session,agent,ai_provider(config["provider"].toInt())) :
ai_info::create(session,agent,ai_provider::Infer);
if(!ai)
continue;
// absent "established" means a config predating this field, from back when save_config() itself
// only ever wrote for an established session -- so absent defaults to true, same as those old files
// always implied. Present-and-false means a real, current record of a session that never got a
// backend thread; loading it as Completed/resumable would try to --resume an id nothing ever confirmed
bool established = config["established"].toBool(true);
set_ai_status(ai->sessions,established ? session_status::Completed : session_status::New,
established ? "Previous chat loaded." : "Previous attempt never connected.");
ai->model_settings = config.contains("model_settings") ?
config["model_settings"].toObject() : first["model_settings"].toObject();
ai->project_titles = settings.value("ai/title/"+session).toString();
ai->projects = std::move(history);
show_ai_project(*ai);
}
if(ui->ai_project_list->count())
ui->ai_project_list->setCurrentRow(0);
// GitHub issue channels are never auto-reconnected at startup; use Resume to reconnect a chat explicitly
}
AIAgent::~AIAgent()
{
delete ui;
}
// GitHub issue channel: the issue body carries the next request; one pinned comment (marked "dsi_session_result":true) carries the result
QNetworkRequest AIAgent::github_request(const QUrl& url) const
{
QNetworkRequest request(url);
request.setRawHeader("Authorization",("Bearer "+github_token).toUtf8());
request.setRawHeader("Accept","application/vnd.github+json");
request.setRawHeader("X-GitHub-Api-Version","2022-11-28");
request.setRawHeader("User-Agent","DSI-Studio");
request.setTransferTimeout(15000); // applies to every GET/POST/PATCH, blocking or async
return request;
}
bool AIAgent::connect_github_issue(const QString& url_text,QString& error)
{
// snapshot now, so a later new-chat edit cannot swap the identity mid-poll (github_request() uses this member for the whole session)
github_token = settings.value("ai/github_token").toString().trimmed();
if(github_token.isEmpty())
return error = "no GitHub token configured; set one when starting the ChatGPT Web agent "
"(GitHub requires an authenticated request for every write, "
"including editing a comment on a public issue)",false;
QUrl url(url_text.trimmed());
if(!url.isValid() || url.scheme().compare("https",Qt::CaseInsensitive) ||
url.host().compare("github.com",Qt::CaseInsensitive))
return error = "expected an https://github.com/... issue link",false;
auto parts = url.path().split('/',Qt::SkipEmptyParts);
bool number_ok = false;
qint64 issue_number = parts.size() == 4 ? parts[3].toLongLong(&number_ok) : 0;
if(parts.size() != 4 || parts[2] != "issues" || !number_ok || issue_number <= 0)
return error = "expected the form https://github.com/<owner>/<repository>/issues/<number>",false;
QString owner = parts[0];
QUrl issue_api("https://api.github.com/repos/"+owner+"/"+parts[1]+
"/issues/"+QString::number(issue_number));
ai_log("github connect: verifying token");
// identify who the token belongs to (need not be the repo owner); result-comment ownership is checked against this identity, not the issue's owner
bool ok = false;
auto authenticated_user = QJsonDocument::fromJson(
github_blocking(github_manager,github_request(QUrl("https://api.github.com/user")),
"GET",{},ok,error)).object()["login"].toString();
if(!ok)
return error = "cannot verify GitHub token: "+error,false;
if(authenticated_user.isEmpty())
return error = "cannot verify GitHub token: unexpected response from GitHub",false;
ai_log("github connect: token belongs to "+authenticated_user+"; fetching issue "+issue_api.toString());
auto issue = QJsonDocument::fromJson(
github_blocking(github_manager,github_request(issue_api),"GET",{},ok,error)).object();
if(!ok)
{
ai_log("github connect: fetching issue failed: "+error);
error += " (check that this token has access to this specific repository, e.g. a fine-grained PAT scoped to a different repo)";
return false;
}
ai_log("github connect: issue fetched, state="+issue["state"].toString()+
" owner="+issue["user"].toObject()["login"].toString());
if(issue.contains("pull_request"))
return error = "the link points to a pull request, not an issue",false;
if(issue["state"].toString() != "open")
return error = "issue is not open",false;
if(issue["user"].toObject()["login"].toString().compare(owner,Qt::CaseInsensitive))
return error = "issue creator must be the repository owner",false;
if(!issue["title"].toString().startsWith("DSI Studio session"))
return error = "issue title must start with \"DSI Studio session\"",false;
ai_log("github connect: fetching comments");
QJsonArray comments;
for(int page = 1;;++page)
{
auto batch = QJsonDocument::fromJson(
github_blocking(github_manager,github_request(QUrl(
issue_api.toString()+"/comments?per_page=100&page="+QString::number(page))),
"GET",{},ok,error)).array();
if(!ok)
{
ai_log("github connect: fetching comments failed: "+error);
error += " (check that this token has access to this specific repository)";
return false;
}
for(const auto& comment : batch)
comments.append(comment);
if(batch.size() < 100)
break;
}
ai_log("github connect: "+QString::number(comments.size())+" comment(s) fetched");
// find our own result comment (author must match the token's identity); if more than one matches, keep the highest last_id rather than just the first
QUrl result_api;
qint64 last_id = -1;
for(const auto& each : comments)
{
auto comment = each.toObject();
if(comment["user"].toObject()["login"].toString().compare(authenticated_user,Qt::CaseInsensitive))
continue;
auto body = QJsonDocument::fromJson(comment["body"].toString().toUtf8());
if(!body.isObject() || !body.object()["dsi_session_result"].toBool())
continue;
auto candidate_id = body.object()["last_id"].toInteger();
if(candidate_id > last_id)
{
last_id = candidate_id;
result_api = QUrl(comment["url"].toString());
}
}
if(result_api.isEmpty())
{
last_id = 0; // fresh session, no matching comment found
QJsonObject initial{{"state","idle"},{"last_id",0},{"dsi_session_result",true},{"issue",issue_number}};
QJsonObject post_body{{"body",QString::fromUtf8(QJsonDocument(initial).toJson(QJsonDocument::Compact))}};
auto post_request = github_request(QUrl(issue_api.toString()+"/comments"));
post_request.setRawHeader("Content-Type","application/json");
auto created = QJsonDocument::fromJson(
github_blocking(github_manager,post_request,"POST",
QJsonDocument(post_body).toJson(QJsonDocument::Compact),ok,error)).object();
if(!ok)
{
ai_log("github connect: creating result comment failed: "+error);
error += " (check that this token has write access to this specific repository)";
return false;
}
result_api = QUrl(created["url"].toString()); // GitHub's canonical .../issues/comments/<id> form
if(result_api.isEmpty())
return error = "cannot create the result comment",false;
}
++github_connection_id; // supersedes any callback still in flight from before
github_issue_api = issue_api;
github_result_api = result_api;
github_etag.clear();
github_last_id = last_id;
github_pending_result = QJsonObject();
github_timer.start(500);
update_send_button();
// a request can have been executed (side effects already ran) without its result ever being
// confirmed published, e.g. DSI Studio exited in between; the durable marker written just before
// execution survives that, so report the outcome as unknown here instead of silently re-running it
{
QSettings settings;
auto pending_issue = settings.value("ai/github_pending_issue").toString();
auto pending_id = settings.value("ai/github_pending_id",0).toLongLong();
if(!pending_issue.isEmpty() && pending_issue == issue_api.toString() && pending_id > last_id)
{
ai_log("github connect: request "+QString::number(pending_id)+
" was executing when DSI Studio last stopped; publishing an unknown-outcome result instead of re-running it");
settings.remove("ai/github_pending_issue");
settings.remove("ai/github_pending_id");
publish_github_result(QJsonObject{
{"id",pending_id},{"last_id",pending_id},{"dsi_session_result",true},{"issue",issue_number},
{"state","error"},
{"response",QJsonObject{{"status","error"},
{"error","previous execution outcome unknown after a DSI Studio restart; "
"the command may or may not have completed - verify manually before resending"}}}});
}
}
return true;
}
void AIAgent::disconnect_github_issue()
{
if(github_issue_api.isEmpty()) // nothing to do; callers no longer need to check this themselves
return;
++github_connection_id; // reject any callback still in flight from this connection
github_timer.stop();
github_issue_api.clear();
github_result_api.clear();
github_etag.clear();
github_token.clear();
github_last_id = 0;
github_pending_result = QJsonObject();
update_send_button(); // flips to "Resume" if still in a web-agent session
if(auto* info = ai_info::find(web_agent_session_id))
if(info->status != session_status::Failed) // a deliberate disconnect never replaces a real failure
set_ai_status(info->sessions,session_status::Completed,"GitHub issue channel stopped.");
}
bool AIAgent::handle_github_reply(QNetworkReply* reply,quint64 connection_id,int& status,QByteArray& data)
{
reply->deleteLater();
if(connection_id != github_connection_id)
return false; // this connection was superseded (disconnect, or a fresh reconnect)
status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
data = reply->readAll();
if(auto delay = github_retry_delay(reply,data))
{
if(!github_issue_api.isEmpty())
github_timer.start(delay); // rate limited (429, or 403 that means the same thing)
return false;
}
if(github_permanent_failure(status))
{
disconnect_github_issue();
if(auto* info = ai_info::find(web_agent_session_id)) // disconnect_github_issue() already set Completed -- this is a real failure, not a deliberate stop
set_ai_status(info->sessions,session_status::Failed,
"GitHub issue channel authorization failed.");
return false;
}
return true;
}
void AIAgent::poll_github_issue()
{
if(github_issue_api.isEmpty())
return;
github_timer.stop(); // at most one poll or publish in flight at a time
if(!github_pending_result.isEmpty())
return send_pending_result(); // a previous PATCH failed; retry it, never re-execute
auto request = github_request(github_issue_api);
if(!github_etag.isEmpty())
request.setRawHeader("If-None-Match",github_etag);
auto connection_id = github_connection_id;
auto* reply = github_manager.get(request);
connect(reply,&QNetworkReply::finished,this,[this,reply,connection_id]()
{
int status = 0;
QByteArray data;
if(!handle_github_reply(reply,connection_id,status,data))
return;
auto restart = [this](int delay_ms = 500)
{if(!github_issue_api.isEmpty()) github_timer.start(delay_ms);};
if(reply->error() != QNetworkReply::NoError && status != 304)
return restart(5000); // transient network error: back off, retry later
if(status == 304)
return restart(); // not modified
if(auto etag = reply->rawHeader("ETag");!etag.isEmpty())
github_etag = etag;
auto issue = QJsonDocument::fromJson(data).object(); // body already read above
if(issue["state"].toString() != "open")
return disconnect_github_issue(); // closed directly on GitHub; stop without republishing
auto envelope = QJsonDocument::fromJson(issue["body"].toString().toUtf8());
if(!envelope.isObject())
return restart(); // no command posted yet
auto request_obj = envelope.object();
auto id = request_obj["id"].toInteger();
if(id <= github_last_id)
return restart(); // already handled or not a new request
auto issue_number = issue["number"];
auto stamp = [&](QJsonObject result)
{
result["id"] = id;
result["last_id"] = id;
result["dsi_session_result"] = true;
result["issue"] = issue_number;
result["updated_at"] = QDateTime::currentDateTimeUtc().toString(Qt::ISODate);
return result;
};
if(request_obj["request"].toString() == "close")
// goes through the same retrying publish path as any result; send_pending_result() disconnects once this is confirmed published
return publish_github_result(stamp(QJsonObject{{"state","closed"}}));
if(request_obj["session"].toString().isEmpty())
return publish_github_result(stamp(QJsonObject{
{"state","error"},
{"response",QJsonObject{{"status","error"},
{"error","malformed request: missing session"}}}}));
if(!is_valid_session_id(request_obj["session"].toString()))
return publish_github_result(stamp(QJsonObject{
{"state","error"},
{"response",QJsonObject{{"status","error"},
{"error","malformed request: session must be a UUID"}}}}));
bool include_log = request_obj["include_log"].toBool();
request_obj.remove("id");
request_obj.remove("include_log");
request_obj["agent"] = "Codex/ChatGPT-GitHub";
auto session_id = request_obj["session"].toString();
bool set_title = !ai_info::find(session_id);
auto* web_info = ai_info::find(web_agent_session_id);
if(web_info && web_info->status == session_status::New)
assign_ai_session(web_agent_session_id,session_id);
web_agent_session_id = session_id;
if(auto* info = ai_info::create(session_id,"Codex/ChatGPT-GitHub",ai_provider::Infer)) // records which issue this session is bound to, so a restart can auto-resume polling it
{
set_ai_status(info->sessions,session_status::Thinking,"GitHub request received");
// stored as "<owner>/<repo>/issues/<number>"; github_issue_api is always
// "https://api.github.com/repos/<owner>/<repo>/issues/<number>", built by DSI Studio itself
info->model_settings["github_issue_url"] =
QString(github_issue_api.toString()).remove("https://api.github.com/repos/");
info->save_config();
}
// durable marker, survives a crash: if DSI Studio exits before the result below is confirmed
// published, the next connect_github_issue() sees this and reports the outcome as unknown
// instead of re-executing the same request
QSettings().setValue("ai/github_pending_issue",github_issue_api.toString());
QSettings().setValue("ai/github_pending_id",id);
auto started = QDateTime::currentMSecsSinceEpoch();
QByteArray reply_bytes;
ai_request(QJsonDocument(request_obj).toJson(QJsonDocument::Compact),reply_bytes);
auto response = QJsonDocument::fromJson(reply_bytes).object();
auto run_ai_command = [&](const QString& session,const QString& cmd_name,const QJsonValue& param = {})
{
QJsonObject command{{"cmd",cmd_name}};
if(!param.isUndefined())
command["param"] = param;
QByteArray bytes;
ai_request(QJsonDocument(QJsonObject{
{"session",session},{"command",command}}).toJson(QJsonDocument::Compact),bytes);
return QJsonDocument::fromJson(bytes).object();
};
if(set_title) // omits "agent" so set_title itself can never create a session
run_ai_command(session_id,"set_title",issue["title"].toString());
if(include_log)
response["log"] = run_ai_command(request_obj["session"].toString(),"log");
auto succeeded = [](const QJsonObject& reply)
{
if(reply["status"].toString() == "error")
return false;
for(const auto& value : reply["result"].toArray())
if(value.toObject()["status"].toString() == "error")
return false;
return true;
};
publish_github_result(stamp(QJsonObject{
{"state",succeeded(response) ? "done" : "error"},
{"duration_ms",QDateTime::currentMSecsSinceEpoch()-started},
{"response",response}}));
});
}
void AIAgent::publish_github_result(QJsonObject result)
{
constexpr qsizetype size_limit = 60*1024;
auto original_size = QJsonDocument(result).toJson(QJsonDocument::Compact).size();
if(original_size > size_limit)
{
result["state"] = "error";
result["response"] = QJsonObject{
{"error","response truncated: exceeds GitHub comment size limit"},
{"original_bytes",original_size}};
}
github_pending_result = result; // staged until PATCH is confirmed; retried, never re-executed
send_pending_result();
}
void AIAgent::send_pending_result()
{
if(github_result_api.isEmpty() || github_pending_result.isEmpty())
return;
auto connection_id = github_connection_id;
auto pending_id = github_pending_result["id"].toInteger();
QJsonObject body{{"body",QString::fromUtf8(
QJsonDocument(github_pending_result).toJson(QJsonDocument::Compact))}};
auto request = github_request(github_result_api);
request.setRawHeader("Content-Type","application/json");
auto* reply = github_manager.sendCustomRequest(request,"PATCH",QJsonDocument(body).toJson(QJsonDocument::Compact));
connect(reply,&QNetworkReply::finished,this,[this,reply,connection_id,pending_id]()
{
int status = 0;
QByteArray data;
if(!handle_github_reply(reply,connection_id,status,data))
return;
if(reply->error() != QNetworkReply::NoError)
{
tipl::warning() << "cannot publish result to GitHub issue comment: "
<< reply->errorString().toStdString();
if(!github_issue_api.isEmpty())
github_timer.start(5000); // back off; the pending result is retried, not lost
return;
}
bool closed = github_pending_result["state"].toString() == "closed";
github_last_id = pending_id;
github_pending_result = QJsonObject();
{
QSettings settings;
if(settings.value("ai/github_pending_id",0).toLongLong() == pending_id)
{
settings.remove("ai/github_pending_issue");
settings.remove("ai/github_pending_id");
}
}
if(closed)
return disconnect_github_issue();
if(!github_issue_api.isEmpty())
{
// published successfully and the channel stays open -- back to idle, waiting for the next
// request; otherwise this would sit in Thinking indefinitely with the animation still running
if(auto* info = ai_info::find(web_agent_session_id))
set_ai_status(info->sessions,session_status::WaitingUser,"Result published; monitoring GitHub issue");
github_timer.start(500);
}
});
}
void AIAgent::add_ai_reply(ai_info& info,const QString& chat,const QString& reasoning)
{
auto entry = info.record_reply(chat,reasoning);
set_ai_status(info.sessions,chat.isEmpty() ? session_status::Thinking : session_status::WaitingUser,
chat.isEmpty() ? "Agent is thinking" : "Agent replied; waiting for your message.");
show_ai_project(info,entry); // pass the entry so show_ai_project can see it's a new non-user reply and blink
}
void AIAgent::showEvent(QShowEvent* event)
{
QMainWindow::showEvent(event);
refresh_agent_executables(); // picks up a CLI installed since the window was last shown, before the two refreshes below read agent_entries[...].executable
refresh_codex_models();
refresh_login_buttons(); // re-checked every time this window is shown, so a login/logout done outside DSI Studio is picked up
auto* item = ui->ai_project_list->currentItem();
stop_blink(item ? ui->ai_project_list->itemWidget(item) : nullptr);
}
void AIAgent::closeEvent(QCloseEvent* event)
{
// let each process's own QProcess::finished handler (in prepare_ai()) run the real finish lifecycle --
// it already knows how to tell a fresh, never-established launch (reverts to New) from an established
// session being stopped (Completed) or a genuine crash (Failed), and handles pending prompts/history/UI.
// Setting this window's ai_infos to Completed unconditionally here bypassed all of that, e.g. wrongly
// marking a still-New placeholder (never a real Codex/Claude thread) as resumable
for(auto& entry : ai_infos)
if(auto* process = entry.second.processes)
{
process->setProperty("user_stopped",true); // finished()'s own handler clears queued prompts for a user_stopped session -- no auto-continue into a queued message right after this window tried to shut everything down
process->kill(); // kill(): a windowless console child never sees terminate()'s WM_CLOSE
}
disconnect_github_issue();
QMainWindow::closeEvent(event);
}
void AIAgent::set_ai_status(const QString& session,session_status status,QString message)
{
auto* info = ai_info::find(session);
if(!info)
return;
info->status = status;
info->status_message = std::move(message);
if(ai_debug_level)
tipl::out() << "[DEBUG] " << info->agent_name.toStdString() << "@"
<< session.toStdString() << " " << session_status_text(status).toStdString()
<< ": " << info->status_message.toStdString();
update_ai_status(*info,true);
}
void AIAgent::update_ai_status(const ai_info& info,bool pulse)
{
bool running = info.is_running();
if(info.project_items)
{
auto* row = ui->ai_project_list->itemWidget(info.project_items);
update_status_dot(row ? row->findChild<QLabel*>("ai_project_status_dot") : nullptr,
info.status,pulse && running);
}
if(running && !ai_status_timer->isActive())
ai_status_timer->start(500);
if(selected_info() != &info)
return;
// one line -- a multi-line stderr dump (Failed) must not grow the composer's height
auto text = (session_status_text(info.status)+": "+info.status_message).simplified();
if(running)
{
if(!text.endsWith('.'))
text += ".";
}
ui->ai_status->show();
ui->ai_status->setToolTip(text); // full message on hover -- the label itself may show a truncated "..." version
ui->ai_status->setText(QFontMetrics(ui->ai_status->font()).elidedText(
text,Qt::ElideRight,ui->ai_status->maximumWidth()-30)); // truncate -- an unbounded message here was pushing the whole window wider
ui->ai_status->repaint();
}
void AIAgent::ai_request(const QByteArray& data,QByteArray& reply)
{
auto status_reply = [](QString status,QString error = {})
{
QJsonObject reply{{"status",status}};
if(!error.isEmpty())
reply["error"] = error;
return QJsonDocument(reply).toJson(QJsonDocument::Compact);
};
QJsonParseError parse_error;
auto doc = QJsonDocument::fromJson(data,&parse_error);
auto request = doc.object();
auto session = request["session"].toString().trimmed();
if(!doc.isObject())
return void(reply = status_reply("error","invalid JSON: "+parse_error.errorString()));
if(session.isEmpty())
return void(reply = status_reply("error","missing session: provide resumable provider thread ID"));
if(!is_valid_session_id(session))
return void(reply = status_reply("error","invalid session: provide resumable provider thread ID"));
auto* found = ai_info::find(session);
if(!found)
{
auto agent = request["agent"].toString().trimmed();
if(agent.isEmpty())
return void(reply = status_reply("error","missing agent for new session"));
// AgentServer, never derived from the calling agent's own name: a pipe-dispatched session is always a
// log/routing record for this dispatcher, never a real local Codex/Claude subprocess, regardless of
// what the caller names itself -- it can't send a live chat message or have its model changed from
// the GUI (see current_send_action()/on_ai_agent_status_clicked())
found = ai_info::create(session,agent,ai_provider::AgentServer);
set_ai_status(found->sessions,session_status::Thinking,"Agent request received"); // save_config() skips a still-New session
if(auto model = request["model"].toString().trimmed();!model.isEmpty())
found->model_settings["model"] = model;
found->save_config();
}
ai_info& info = *found;
set_ai_status(session,session_status::Thinking,"Processing agent request");
reply.clear();
ai_log("received: "+QString::fromUtf8(data));
auto chat = request["chat"].toString().trimmed();
auto reasoning = request["reasoning"].toString().trimmed();
dispatching_info = &info;
auto result = main_window.dispatch_cmd(info,request); // MainWindow's command center handles everything
dispatching_info = nullptr;
// dispatch_cmd() only finished the DSI command itself -- a live local process is still mid-turn (it
// dispatched this as one of its own tool calls and is waiting on our reply to continue), so that's
// still Thinking, not idle. Only a transport with no ongoing turn of its own (GitHub, or nothing at
// all) settles to WaitingUser here
if(info.processes && info.processes->state() != QProcess::NotRunning)
set_ai_status(session,session_status::Thinking,
"Command completed; waiting for agent input");
else if(github_connected(info))
set_ai_status(session,session_status::WaitingUser,
"Request completed; monitoring GitHub issue");
else
set_ai_status(session,session_status::WaitingUser,
"Request completed; waiting for next request.");
{
auto entry = info.record_reply(chat,reasoning);
if(!info.prompts.isEmpty())
result["prompt"] = QJsonArray::fromStringList(info.prompts);
reply = QJsonDocument(result).toJson(QJsonDocument::Compact);
ai_log(QString("reply for %1@%2: %3 ...")
.arg(info.agent_name,session,
QString::fromUtf8(reply).left(32)));
info.prompts.clear();
show_ai_project(info,entry);
}
}
void AIAgent::update_current_window(QWidget* window)
{
if(dispatching_info)
dispatching_info->current_window = command_window_id(window);
}
void AIAgent::show_ai_project(ai_info& info,QJsonObject added_entry)
{
auto* item = info.project_items;
if(!item)
{
item = new QListWidgetItem;
item->setData(Qt::UserRole,info.sessions);
ui->ai_project_list->insertItem(0,item);
info.project_items = item;
auto* row = new QWidget;
auto* status_dot = new QLabel(row);
status_dot->setObjectName("ai_project_status_dot");
status_dot->setFixedSize(10,10);
auto* title = new QPushButton(row);
title->setFlat(true);
title->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Preferred);
auto* button = new QToolButton(row);
button->setObjectName("ai_project_menu_button");
button->setText("...");
button->setToolTip("Project actions");
button->setFixedSize(28,28);
button->setPopupMode(QToolButton::InstantPopup);
button->setMenu(ai_project_menu);
auto* layout = new QHBoxLayout(row);
layout->setContentsMargins(6,2,2,2);
layout->setSpacing(6);
layout->addWidget(status_dot);
layout->addWidget(title,1);
layout->addWidget(button);
ui->ai_project_list->setItemWidget(item,row);
auto* blink = new QTimer(row);
blink->setInterval(500);
connect(blink,&QTimer::timeout,row,[row]
{
row->setStyleSheet(row->styleSheet().isEmpty() ?
"background:#ffe082;border-radius:5px;" : "");
});
connect(title,&QPushButton::clicked,this,
[this,item]{ui->ai_project_list->setCurrentItem(item);});
connect(button,&QToolButton::pressed,this,
[this,item]{ui->ai_project_list->setCurrentItem(item);});
}
auto* row = ui->ai_project_list->itemWidget(item);
auto* title = row->findChild<QPushButton*>();
item->setText({});
// never touched (no content, no title) -- not "currently New", which a reconnecting, previously-used
// chat also transiently is (see session_status), and shouldn't flash back to this placeholder label for
auto chat_title = info.projects.isEmpty() && info.project_titles.isEmpty() ?
"New "+info.agent_name+" Chat" : info.title();
title->setText((info.provider == ai_provider::ChatGPT ? QString("🌐 ") : QString())+chat_title);
title->setToolTip(title->text());
item->setSizeHint(QSize(0,row->sizeHint().height()));
update_ai_status(info);
auto* current = ui->ai_project_list->currentItem();
const auto added_type = added_entry["type"].toString();
if(!current && added_type == "user") // the user just started this chat themselves (nothing else was selected): bring it up
{
ui->ai_project_list->setCurrentItem(item);
return; // currentItemChanged already rebuilt this chat's complete history
}
bool visible = current == item && isVisible();
if(!added_type.isEmpty() && added_type != "user" && !visible)
{
row->setStyleSheet("background:#ffe082;border-radius:5px;");
row->findChild<QTimer*>()->start();
}
if(current != item)
return;
show_ai_history(info,std::move(added_entry));
}
void AIAgent::show_ai_history(ai_info& info,QJsonObject added_entry)
{
const auto& history = info.projects;
const auto added_type = added_entry["type"].toString();
auto to_html = [](QString text)
{
return text.toHtmlEscaped().replace('\n',"<br>");
};
// renders chat/reasoning text as Markdown (bold, lists, code, links, ...) instead of plain escaped text;
// falls back to plain escaping if the body can't be extracted from QTextDocument's generated HTML
auto markdown_to_html = [&](const QString& text)
{
QTextDocument doc;
doc.setMarkdown(text);
auto html = doc.toHtml();
auto begin = html.indexOf("<body");
begin = begin < 0 ? -1 : html.indexOf('>',begin);
auto end = html.lastIndexOf("</body>");
if(begin < 0 || end < 0 || end <= begin)
return to_html(text);
static const QRegularExpression loose_margins(
"margin-top:\\d+px; margin-bottom:\\d+px;");
return html.mid(begin+1,end-begin-1).trimmed().replace(
loose_margins,"margin-top:0px; margin-bottom:6px;");
};
auto display_time = [](const QJsonValue& value)
{
return QDateTime::fromString(value.toString(),Qt::ISODate).
toString("MM/dd HH:mm:ss");
};
const bool show_reasoning = settings.value("ai/show_reasoning",false).toBool(); // read once: append() runs per history entry
auto append = [&](const QJsonObject& entry,const QStringList& activities = {})
{
bool user = entry["type"] == "user";
auto content = entry["text"].toString();