-
-
Notifications
You must be signed in to change notification settings - Fork 385
Expand file tree
/
Copy pathcodex_core.rs
More file actions
1046 lines (957 loc) · 35.5 KB
/
codex_core.rs
File metadata and controls
1046 lines (957 loc) · 35.5 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
use base64::{engine::general_purpose::STANDARD, Engine as _};
use serde_json::{json, Map, Value};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::oneshot::error::TryRecvError;
use tokio::sync::{oneshot, Mutex};
use tokio::time::timeout;
use tokio::time::Instant;
use crate::backend::app_server::WorkspaceSession;
use crate::codex::config as codex_config;
use crate::codex::home::{resolve_default_codex_home, resolve_workspace_codex_home};
use crate::rules;
use crate::shared::account::{build_account_response, read_auth_account};
use crate::types::WorkspaceEntry;
const LOGIN_START_TIMEOUT: Duration = Duration::from_secs(30);
#[allow(dead_code)]
const MAX_INLINE_IMAGE_BYTES: u64 = 50 * 1024 * 1024;
const THREAD_LIST_SOURCE_KINDS: &[&str] = &[
"cli",
"vscode",
"appServer",
"subAgentReview",
"subAgentCompact",
"subAgentThreadSpawn",
"unknown",
];
#[allow(dead_code)]
fn image_extension_for_path(path: &str) -> Option<String> {
Path::new(path)
.extension()
.and_then(|value| value.to_str())
.map(|value| value.to_ascii_lowercase())
}
#[allow(dead_code)]
fn image_mime_type_for_path(path: &str) -> Option<&'static str> {
let extension = image_extension_for_path(path)?;
match extension.as_str() {
"png" => Some("image/png"),
"jpg" | "jpeg" => Some("image/jpeg"),
"gif" => Some("image/gif"),
"webp" => Some("image/webp"),
"bmp" => Some("image/bmp"),
"tiff" | "tif" => Some("image/tiff"),
_ => None,
}
}
#[allow(dead_code)]
fn should_inline_image_path_for_codex(path: &str) -> bool {
matches!(
image_extension_for_path(path).as_deref(),
Some("heic") | Some("heif")
)
}
#[cfg(target_os = "macos")]
fn temp_converted_image_path(path: &str, extension: &str) -> PathBuf {
let stem = Path::new(path)
.file_stem()
.and_then(|value| value.to_str())
.unwrap_or("image");
let safe_stem = stem
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
.collect::<String>();
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|value| value.as_millis())
.unwrap_or_default();
std::env::temp_dir().join(format!("codex-monitor-image-{safe_stem}-{ts}.{extension}"))
}
#[cfg(target_os = "macos")]
fn convert_heif_image_to_jpeg_bytes(path: &str) -> Result<Vec<u8>, String> {
let output_path = temp_converted_image_path(path, "jpg");
let status = std::process::Command::new("/usr/bin/sips")
.args(["-s", "format", "jpeg"])
.arg(path)
.arg("--out")
.arg(&output_path)
.status()
.map_err(|err| format!("Failed to launch HEIC/HEIF conversion for {path}: {err}"))?;
if !status.success() {
let _ = std::fs::remove_file(&output_path);
return Err(format!(
"Failed to convert HEIC/HEIF image into a Codex-compatible JPEG: {path}"
));
}
let bytes = std::fs::read(&output_path).map_err(|err| {
format!(
"Failed to read converted JPEG for {path} at {}: {err}",
output_path.display()
)
})?;
let _ = std::fs::remove_file(&output_path);
if bytes.is_empty() {
return Err(format!(
"Converted JPEG is empty after HEIC/HEIF conversion: {path}"
));
}
Ok(bytes)
}
#[allow(dead_code)]
pub(crate) fn normalize_file_path(raw: &str) -> String {
let path = raw.trim();
let file_uri_path = path
.strip_prefix("file://localhost")
.or_else(|| path.strip_prefix("file://"));
let Some(path) = file_uri_path else {
return path.to_string();
};
let mut decoded = Vec::with_capacity(path.len());
let bytes = path.as_bytes();
let mut index = 0usize;
while index < bytes.len() {
if bytes[index] == b'%' && index + 2 < bytes.len() {
let hi = bytes[index + 1];
let lo = bytes[index + 2];
let hi_value = match hi {
b'0'..=b'9' => Some(hi - b'0'),
b'a'..=b'f' => Some(hi - b'a' + 10),
b'A'..=b'F' => Some(hi - b'A' + 10),
_ => None,
};
let lo_value = match lo {
b'0'..=b'9' => Some(lo - b'0'),
b'a'..=b'f' => Some(lo - b'a' + 10),
b'A'..=b'F' => Some(lo - b'A' + 10),
_ => None,
};
if let (Some(hi_nibble), Some(lo_nibble)) = (hi_value, lo_value) {
decoded.push((hi_nibble << 4) | lo_nibble);
index += 3;
continue;
}
}
decoded.push(bytes[index]);
index += 1;
}
String::from_utf8_lossy(&decoded).into_owned()
}
#[allow(dead_code)]
pub(crate) fn read_image_as_data_url_core(path: &str) -> Result<String, String> {
let trimmed_path = normalize_file_path(path);
if trimmed_path.is_empty() {
return Err("Image path is required".to_string());
}
if should_inline_image_path_for_codex(&trimmed_path) {
#[cfg(target_os = "macos")]
{
let encoded = STANDARD.encode(convert_heif_image_to_jpeg_bytes(&trimmed_path)?);
return Ok(format!("data:image/jpeg;base64,{encoded}"));
}
#[cfg(not(target_os = "macos"))]
{
return Err(format!(
"HEIC/HEIF images are not supported on this platform; convert to JPEG or PNG first: {trimmed_path}"
));
}
}
let mime_type = image_mime_type_for_path(&trimmed_path).ok_or_else(|| {
format!("Unsupported or missing image extension for path: {trimmed_path}")
})?;
let metadata = std::fs::symlink_metadata(&trimmed_path)
.map_err(|err| format!("Failed to stat image file at {trimmed_path}: {err}"))?;
if metadata.file_type().is_symlink() {
return Err(format!("Image path must not be a symlink: {trimmed_path}"));
}
if !metadata.is_file() {
return Err(format!("Image path is not a file: {trimmed_path}"));
}
if metadata.len() > MAX_INLINE_IMAGE_BYTES {
return Err(format!(
"Image file exceeds maximum size of {MAX_INLINE_IMAGE_BYTES} bytes: {trimmed_path}"
));
}
let bytes = std::fs::read(&trimmed_path)
.map_err(|err| format!("Failed to read image file at {trimmed_path}: {err}"))?;
if bytes.is_empty() {
return Err(format!("Image file is empty: {trimmed_path}"));
}
let encoded = STANDARD.encode(bytes);
Ok(format!("data:{mime_type};base64,{encoded}"))
}
pub(crate) enum CodexLoginCancelState {
PendingStart(oneshot::Sender<()>),
LoginId(String),
}
async fn get_session_clone(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: &str,
) -> Result<Arc<WorkspaceSession>, String> {
let sessions = sessions.lock().await;
sessions
.get(workspace_id)
.cloned()
.ok_or_else(|| "workspace not connected".to_string())
}
async fn resolve_workspace_and_parent(
workspaces: &Mutex<HashMap<String, WorkspaceEntry>>,
workspace_id: &str,
) -> Result<(WorkspaceEntry, Option<WorkspaceEntry>), String> {
let workspaces = workspaces.lock().await;
let entry = workspaces
.get(workspace_id)
.cloned()
.ok_or_else(|| "workspace not found".to_string())?;
let parent_entry = entry
.parent_id
.as_ref()
.and_then(|parent_id| workspaces.get(parent_id))
.cloned();
Ok((entry, parent_entry))
}
async fn resolve_codex_home_for_workspace_core(
workspaces: &Mutex<HashMap<String, WorkspaceEntry>>,
workspace_id: &str,
) -> Result<PathBuf, String> {
let (entry, parent_entry) = resolve_workspace_and_parent(workspaces, workspace_id).await?;
resolve_workspace_codex_home(&entry, parent_entry.as_ref())
.or_else(resolve_default_codex_home)
.ok_or_else(|| "Unable to resolve CODEX_HOME".to_string())
}
async fn resolve_workspace_path_core(
workspaces: &Mutex<HashMap<String, WorkspaceEntry>>,
workspace_id: &str,
) -> Result<String, String> {
let workspaces = workspaces.lock().await;
let entry = workspaces
.get(workspace_id)
.ok_or_else(|| "workspace not found".to_string())?;
Ok(entry.path.clone())
}
pub(crate) async fn start_thread_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspaces: &Mutex<HashMap<String, WorkspaceEntry>>,
workspace_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let workspace_path = resolve_workspace_path_core(workspaces, &workspace_id).await?;
let params = json!({
"cwd": workspace_path,
"approvalPolicy": "on-request"
});
session
.send_request_for_workspace(&workspace_id, "thread/start", params)
.await
}
pub(crate) async fn resume_thread_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "threadId": thread_id });
session
.send_request_for_workspace(&workspace_id, "thread/resume", params)
.await
}
pub(crate) async fn read_thread_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "threadId": thread_id });
session
.send_request_for_workspace(&workspace_id, "thread/read", params)
.await
}
pub(crate) async fn thread_live_subscribe_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
) -> Result<(), String> {
if thread_id.trim().is_empty() {
return Err("threadId is required".to_string());
}
let _ = get_session_clone(sessions, &workspace_id).await?;
Ok(())
}
pub(crate) async fn thread_live_unsubscribe_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
) -> Result<(), String> {
if thread_id.trim().is_empty() {
return Err("threadId is required".to_string());
}
let _ = get_session_clone(sessions, &workspace_id).await?;
Ok(())
}
pub(crate) async fn fork_thread_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "threadId": thread_id });
session
.send_request_for_workspace(&workspace_id, "thread/fork", params)
.await
}
pub(crate) async fn list_threads_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
cursor: Option<String>,
limit: Option<u32>,
sort_key: Option<String>,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({
"cursor": cursor,
"limit": limit,
"sortKey": sort_key,
// Keep interactive and sub-agent sessions visible across CLI versions so
// thread/list refreshes do not drop valid historical conversations.
// Intentionally exclude generic "subAgent" so parentless internal jobs
// (for example memory consolidation) do not leak back into app state.
"sourceKinds": THREAD_LIST_SOURCE_KINDS
});
session
.send_request_for_workspace(&workspace_id, "thread/list", params)
.await
}
pub(crate) async fn list_mcp_server_status_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
cursor: Option<String>,
limit: Option<u32>,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "cursor": cursor, "limit": limit });
session
.send_request_for_workspace(&workspace_id, "mcpServerStatus/list", params)
.await
}
pub(crate) async fn archive_thread_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "threadId": thread_id });
session
.send_request_for_workspace(&workspace_id, "thread/archive", params)
.await
}
pub(crate) async fn rollback_thread_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
turn_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "threadId": thread_id, "turnId": turn_id });
session
.send_request_for_workspace(&workspace_id, "thread/rollback", params)
.await
}
pub(crate) async fn compact_thread_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "threadId": thread_id });
session
.send_request_for_workspace(&workspace_id, "thread/compact/start", params)
.await
}
pub(crate) async fn set_thread_name_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
name: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "threadId": thread_id, "name": name });
session
.send_request_for_workspace(&workspace_id, "thread/name/set", params)
.await
}
fn build_turn_input_items(
text: String,
images: Option<Vec<String>>,
app_mentions: Option<Vec<Value>>,
) -> Result<Vec<Value>, String> {
let trimmed_text = text.trim();
let mut input: Vec<Value> = Vec::new();
if !trimmed_text.is_empty() {
input.push(json!({ "type": "text", "text": trimmed_text }));
}
if let Some(paths) = images {
for path in paths {
let trimmed = path.trim();
if trimmed.is_empty() {
continue;
}
if trimmed.starts_with("data:")
|| trimmed.starts_with("http://")
|| trimmed.starts_with("https://")
{
input.push(json!({ "type": "image", "url": trimmed }));
} else if should_inline_image_path_for_codex(trimmed) {
input.push(json!({
"type": "image",
"url": read_image_as_data_url_core(trimmed)?,
}));
} else {
input.push(json!({ "type": "localImage", "path": trimmed }));
}
}
}
if let Some(mentions) = app_mentions {
let mut seen_paths: HashSet<String> = HashSet::new();
for mention in mentions {
let object = mention
.as_object()
.ok_or_else(|| "invalid app mention payload".to_string())?;
let name = object
.get("name")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| "invalid app mention name".to_string())?;
let path = object
.get("path")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| "invalid app mention path".to_string())?;
if !path.starts_with("app://") || path.len() <= "app://".len() {
return Err("invalid app mention path".to_string());
}
if !seen_paths.insert(path.to_string()) {
continue;
}
input.push(json!({ "type": "mention", "name": name, "path": path }));
}
}
if input.is_empty() {
return Err("empty user message".to_string());
}
Ok(input)
}
pub(crate) fn insert_optional_nullable_string(
params: &mut Map<String, Value>,
key: &str,
value: Option<Option<String>>,
) {
if let Some(value) = value {
params.insert(key.to_string(), json!(value));
}
}
pub(crate) async fn send_user_message_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspaces: &Mutex<HashMap<String, WorkspaceEntry>>,
workspace_id: String,
thread_id: String,
text: String,
model: Option<String>,
effort: Option<String>,
service_tier: Option<Option<String>>,
access_mode: Option<String>,
images: Option<Vec<String>>,
app_mentions: Option<Vec<Value>>,
collaboration_mode: Option<Value>,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let workspace_path = resolve_workspace_path_core(workspaces, &workspace_id).await?;
let access_mode = access_mode.unwrap_or_else(|| "current".to_string());
let sandbox_policy = match access_mode.as_str() {
"full-access" => json!({ "type": "dangerFullAccess" }),
"read-only" => json!({ "type": "readOnly" }),
_ => json!({
"type": "workspaceWrite",
"writableRoots": [workspace_path.clone()],
"networkAccess": true
}),
};
let approval_policy = if access_mode == "full-access" {
"never"
} else {
"on-request"
};
let input = build_turn_input_items(text, images, app_mentions)?;
let mut params = Map::new();
params.insert("threadId".to_string(), json!(thread_id));
params.insert("input".to_string(), json!(input));
params.insert("cwd".to_string(), json!(workspace_path));
params.insert("approvalPolicy".to_string(), json!(approval_policy));
params.insert("sandboxPolicy".to_string(), json!(sandbox_policy));
params.insert("model".to_string(), json!(model));
params.insert("effort".to_string(), json!(effort));
insert_optional_nullable_string(&mut params, "serviceTier", service_tier);
if let Some(mode) = collaboration_mode {
if !mode.is_null() {
params.insert("collaborationMode".to_string(), mode);
}
}
session
.send_request_for_workspace(&workspace_id, "turn/start", Value::Object(params))
.await
}
pub(crate) async fn turn_steer_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
turn_id: String,
text: String,
images: Option<Vec<String>>,
app_mentions: Option<Vec<Value>>,
) -> Result<Value, String> {
if turn_id.trim().is_empty() {
return Err("missing active turn id".to_string());
}
let session = get_session_clone(sessions, &workspace_id).await?;
let input = build_turn_input_items(text, images, app_mentions)?;
let params = json!({
"threadId": thread_id,
"expectedTurnId": turn_id,
"input": input
});
session
.send_request_for_workspace(&workspace_id, "turn/steer", params)
.await
}
pub(crate) async fn collaboration_mode_list_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
session
.send_request_for_workspace(&workspace_id, "collaborationMode/list", json!({}))
.await
}
pub(crate) async fn turn_interrupt_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
turn_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "threadId": thread_id, "turnId": turn_id });
session
.send_request_for_workspace(&workspace_id, "turn/interrupt", params)
.await
}
pub(crate) async fn start_review_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
thread_id: String,
target: Value,
delivery: Option<String>,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let mut params = Map::new();
params.insert("threadId".to_string(), json!(thread_id));
params.insert("target".to_string(), target);
if let Some(delivery) = delivery {
params.insert("delivery".to_string(), json!(delivery));
}
session
.send_request_for_workspace(&workspace_id, "review/start", Value::Object(params))
.await
}
pub(crate) async fn model_list_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
session
.send_request_for_workspace(&workspace_id, "model/list", json!({}))
.await
}
pub(crate) async fn experimental_feature_list_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
cursor: Option<String>,
limit: Option<u32>,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "cursor": cursor, "limit": limit });
session
.send_request_for_workspace(&workspace_id, "experimentalFeature/list", params)
.await
}
pub(crate) async fn account_rate_limits_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
session
.send_request_for_workspace(&workspace_id, "account/rateLimits/read", Value::Null)
.await
}
pub(crate) async fn account_read_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspaces: &Mutex<HashMap<String, WorkspaceEntry>>,
workspace_id: String,
) -> Result<Value, String> {
let session = {
let sessions = sessions.lock().await;
sessions.get(&workspace_id).cloned()
};
let response = if let Some(session) = session {
session
.send_request_for_workspace(&workspace_id, "account/read", Value::Null)
.await
.ok()
} else {
None
};
let (entry, parent_entry) = resolve_workspace_and_parent(workspaces, &workspace_id).await?;
let codex_home = resolve_workspace_codex_home(&entry, parent_entry.as_ref())
.or_else(resolve_default_codex_home);
let fallback = read_auth_account(codex_home);
Ok(build_account_response(response, fallback))
}
pub(crate) async fn codex_login_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
codex_login_cancels: &Mutex<HashMap<String, CodexLoginCancelState>>,
workspace_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
{
let mut cancels = codex_login_cancels.lock().await;
if let Some(existing) = cancels.remove(&workspace_id) {
match existing {
CodexLoginCancelState::PendingStart(tx) => {
let _ = tx.send(());
}
CodexLoginCancelState::LoginId(_) => {}
}
}
cancels.insert(
workspace_id.clone(),
CodexLoginCancelState::PendingStart(cancel_tx),
);
}
let start = Instant::now();
let mut cancel_rx = cancel_rx;
let workspace_for_request = workspace_id.clone();
let mut login_request: Pin<Box<_>> = Box::pin(session.send_request_for_workspace(
&workspace_for_request,
"account/login/start",
json!({ "type": "chatgpt" }),
));
let response = loop {
match cancel_rx.try_recv() {
Ok(_) => {
let mut cancels = codex_login_cancels.lock().await;
cancels.remove(&workspace_id);
return Err("Codex login canceled.".to_string());
}
Err(TryRecvError::Closed) => {
let mut cancels = codex_login_cancels.lock().await;
cancels.remove(&workspace_id);
return Err("Codex login canceled.".to_string());
}
Err(TryRecvError::Empty) => {}
}
let elapsed = start.elapsed();
if elapsed >= LOGIN_START_TIMEOUT {
let mut cancels = codex_login_cancels.lock().await;
cancels.remove(&workspace_id);
return Err("Codex login start timed out.".to_string());
}
let tick = Duration::from_millis(150);
let remaining = LOGIN_START_TIMEOUT.saturating_sub(elapsed);
let wait_for = remaining.min(tick);
match timeout(wait_for, &mut login_request).await {
Ok(result) => break result?,
Err(_elapsed) => continue,
}
};
let payload = response.get("result").unwrap_or(&response);
let login_id = payload
.get("loginId")
.or_else(|| payload.get("login_id"))
.and_then(Value::as_str)
.map(str::to_string)
.ok_or_else(|| "missing login id in account/login/start response".to_string())?;
let auth_url = payload
.get("authUrl")
.or_else(|| payload.get("auth_url"))
.and_then(Value::as_str)
.map(str::to_string)
.ok_or_else(|| "missing auth url in account/login/start response".to_string())?;
{
let mut cancels = codex_login_cancels.lock().await;
cancels.insert(
workspace_id,
CodexLoginCancelState::LoginId(login_id.clone()),
);
}
Ok(json!({
"loginId": login_id,
"authUrl": auth_url,
"raw": response,
}))
}
pub(crate) async fn codex_login_cancel_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
codex_login_cancels: &Mutex<HashMap<String, CodexLoginCancelState>>,
workspace_id: String,
) -> Result<Value, String> {
let cancel_state = {
let mut cancels = codex_login_cancels.lock().await;
cancels.remove(&workspace_id)
};
let Some(cancel_state) = cancel_state else {
return Ok(json!({ "canceled": false }));
};
match cancel_state {
CodexLoginCancelState::PendingStart(cancel_tx) => {
let _ = cancel_tx.send(());
return Ok(json!({
"canceled": true,
"status": "canceled",
}));
}
CodexLoginCancelState::LoginId(login_id) => {
let session = get_session_clone(sessions, &workspace_id).await?;
let response = session
.send_request_for_workspace(
&workspace_id,
"account/login/cancel",
json!({
"loginId": login_id,
}),
)
.await?;
let payload = response.get("result").unwrap_or(&response);
let status = payload
.get("status")
.and_then(Value::as_str)
.unwrap_or_default();
let canceled = status.eq_ignore_ascii_case("canceled");
Ok(json!({
"canceled": canceled,
"status": status,
"raw": response,
}))
}
}
}
pub(crate) async fn skills_list_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspaces: &Mutex<HashMap<String, WorkspaceEntry>>,
workspace_id: String,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let workspace_path = resolve_workspace_path_core(workspaces, &workspace_id).await?;
// Codex can discover project-scoped skills from `<workspace>/.agents/skills`.
// Some environments don't surface those reliably in CodexMonitor unless we
// pass the default project skills path explicitly.
let mut source_paths: Vec<String> = vec![];
let project_skills_dir = Path::new(&workspace_path).join(".agents").join("skills");
if project_skills_dir.is_dir() {
if let Some(p) = project_skills_dir.to_str() {
source_paths.push(p.to_string());
}
}
let params = if source_paths.is_empty() {
json!({ "cwd": workspace_path })
} else {
json!({ "cwd": workspace_path, "skillsPaths": source_paths })
};
let mut response = session
.send_request_for_workspace(&workspace_id, "skills/list", params)
.await?;
// Attach diagnostics for the UI (non-breaking: keep original response fields).
if let Value::Object(ref mut obj) = response {
obj.insert("sourcePaths".to_string(), json!(source_paths));
obj.insert("sourceErrors".to_string(), json!([]));
}
Ok(response)
}
pub(crate) async fn apps_list_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
cursor: Option<String>,
limit: Option<u32>,
thread_id: Option<String>,
) -> Result<Value, String> {
let session = get_session_clone(sessions, &workspace_id).await?;
let params = json!({ "cursor": cursor, "limit": limit, "threadId": thread_id });
session
.send_request_for_workspace(&workspace_id, "app/list", params)
.await
}
pub(crate) async fn respond_to_server_request_core(
sessions: &Mutex<HashMap<String, Arc<WorkspaceSession>>>,
workspace_id: String,
request_id: Value,
result: Value,
) -> Result<(), String> {
let session = get_session_clone(sessions, &workspace_id).await?;
session.send_response(request_id, result).await
}
pub(crate) async fn remember_approval_rule_core(
workspaces: &Mutex<HashMap<String, WorkspaceEntry>>,
workspace_id: String,
command: Vec<String>,
) -> Result<Value, String> {
let command = command
.into_iter()
.map(|item| item.trim().to_string())
.filter(|item| !item.is_empty())
.collect::<Vec<_>>();
if command.is_empty() {
return Err("empty command".to_string());
}
let codex_home = resolve_codex_home_for_workspace_core(workspaces, &workspace_id).await?;
let rules_path = rules::default_rules_path(&codex_home);
rules::append_prefix_rule(&rules_path, &command)?;
Ok(json!({
"ok": true,
"rulesPath": rules_path,
}))
}
pub(crate) async fn get_config_model_core(
workspaces: &Mutex<HashMap<String, WorkspaceEntry>>,
workspace_id: String,
) -> Result<Value, String> {
let codex_home = resolve_codex_home_for_workspace_core(workspaces, &workspace_id).await?;
let model = codex_config::read_config_model(Some(codex_home))?;
Ok(json!({ "model": model }))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::Value;
#[test]
fn normalize_strips_file_uri_prefix() {
assert_eq!(
normalize_file_path("file:///var/mobile/Containers/Data/photo.jpg"),
"/var/mobile/Containers/Data/photo.jpg"
);
}
#[test]
fn normalize_strips_file_localhost_prefix() {
assert_eq!(
normalize_file_path("file://localhost/Users/test/image.png"),
"/Users/test/image.png"
);
}
#[test]
fn normalize_decodes_percent_encoding() {
assert_eq!(
normalize_file_path("file:///var/mobile/path%20with%20spaces/img.jpg"),
"/var/mobile/path with spaces/img.jpg"
);
}
#[test]
fn normalize_plain_path_unchanged() {
assert_eq!(
normalize_file_path("/var/mobile/Containers/Data/photo.jpg"),
"/var/mobile/Containers/Data/photo.jpg"
);
}
#[test]
fn normalize_plain_path_percent_sequences_unchanged() {
assert_eq!(
normalize_file_path("/tmp/report%20final.png"),
"/tmp/report%20final.png"
);
}
#[test]
fn normalize_trims_whitespace() {
assert_eq!(normalize_file_path(" /tmp/image.png "), "/tmp/image.png");
}
#[test]
fn read_image_data_url_core_rejects_file_uri_that_does_not_exist() {
let result = read_image_as_data_url_core("file:///nonexistent/photo.png");
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
!err.contains("file://"),
"error should reference normalized path, got: {err}"
);
assert!(err.contains("/nonexistent/photo.png"));
}
#[test]
fn read_image_data_url_core_succeeds_with_file_uri_for_real_file() {
let dir = std::env::temp_dir().join("codex_monitor_test");
std::fs::create_dir_all(&dir).unwrap();
let img_path = dir.join("test_photo.png");
let png_bytes: &[u8] = &[
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00,
0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08,
0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, 0xBC,
0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
];
std::fs::write(&img_path, png_bytes).unwrap();
let file_uri = format!("file://{}", img_path.display());
let result = read_image_as_data_url_core(&file_uri);
assert!(
result.is_ok(),
"file:// URI for real file should succeed, got: {:?}",
result.err()
);
let data_url = result.unwrap();
assert!(data_url.starts_with("data:image/png;base64,"));
let space_dir = dir.join("path with spaces");
std::fs::create_dir_all(&space_dir).unwrap();
let space_img = space_dir.join("photo.png");
std::fs::write(&space_img, png_bytes).unwrap();
let encoded_uri = format!(
"file://{}",
space_img.display().to_string().replace(' ', "%20")
);
let result2 = read_image_as_data_url_core(&encoded_uri);
assert!(
result2.is_ok(),