nomoreide-daemon 0.20.1

The NoMoreIDE daemon: the local HTTP server, its route registry, and the embedded web dashboard.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
//! Terminal sessions: listing the tabs the daemon owns, opening one, and moving
//! an agent session between the web dock and macOS Terminal.app.
//!
//! The PTY data stream is not here — it belongs on a socket, and the tools that
//! reach these endpoints only ever ask about a session, never read from it.

use crate::server::app::AppState;
use crate::server::errors::{error, method_not_allowed};
use crate::server::routes::query::query_value;
use crate::server::sse;
use axum::body::Bytes;
use axum::extract::rejection::BytesRejection;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{DefaultBodyLimit, State};
use axum::http::{HeaderMap, StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, patch, post};
use axum::{Json, Router};
use chrono::{SecondsFormat, Utc};
use futures_util::StreamExt;
use nomoreide_core::agent_sessions::{
    default_store_path, save_agent_session, AgentSession as RecordedAgentSession,
};
use nomoreide_core::agent_transcripts::{
    default_transcript_homes, list_agent_transcripts, AgentTranscript, DEFAULT_TRANSCRIPT_LIMIT,
};
use nomoreide_core::config::Config;
use nomoreide_core::context_library::{ContextAttachment, ContextRef, CONTEXT_KINDS};
use nomoreide_core::one_time_skills::{
    compose_one_time_skill_prompt, resolve_one_time_skill, OneTimeSkillSelection,
};
use nomoreide_core::snapshot_manager::{SnapshotManager, DEFAULT_KEEP};
use nomoreide_core::terminal::{
    agent_binary, derive_agent_invocation, encode_agent_prompt_paste, normalize_agent_label,
    resolve_service_terminal, ServiceTerminal, TerminalSession, TerminalSpawnSpec,
    MAX_AGENT_PROMPT_BYTES,
};
use nomoreide_daemon_client::protocol::{
    TerminalExitInfo, TerminalSessionEnvelope, TerminalSessionInfo, TerminalSessionsEnvelope,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::ffi::OsString;

/// The settings file, read fresh per request.
///
/// Mirrors `routes/settings.rs`: one path, no cached handle, so a preference
/// changed in the dashboard takes effect on the next mirror rather than on the
/// next daemon restart.
fn settings_store() -> nomoreide_core::app_settings::AppSettingsStore {
    nomoreide_core::app_settings::AppSettingsStore::new(
        nomoreide_core::app_settings::default_settings_path(),
    )
}

/// Moving a session between the dock and an external terminal is a real change
/// to where a running agent is being driven from, so it is not something a
/// stray cross-origin form post should be able to trigger. A custom header
/// cannot be set by one, which is what makes requiring it worth anything.
const TERMINAL_CONTROL_HEADER: &str = "x-nomoreide-terminal-control";

pub(crate) fn routes() -> Router<AppState> {
    Router::new()
        // Exact paths, so a wrong method reaches the shell rather than a 405 —
        // the reference registers these two with a method and nothing else.
        .route("/api/terminal/capabilities", get(capabilities))
        .route("/api/terminal/events", get(events))
        .route("/api/terminal/socket", get(socket))
        .route("/api/terminal/transcripts", get(transcripts))
        .route(
            "/api/terminal/sessions",
            get(list_sessions).post(create_session),
        )
        // The rest mirror *pattern* routes, whose handlers check the method
        // themselves and answer 405 in the JSON envelope.
        .route(
            "/api/terminal/sessions/:id",
            patch(rename).delete(close).fallback(method_not_allowed),
        )
        .route(
            "/api/terminal/sessions/:id/open-system-terminal",
            post(open_system_terminal).fallback(method_not_allowed),
        )
        .route(
            "/api/terminal/sessions/:id/reclaim-dock",
            post(reclaim_dock).fallback(method_not_allowed),
        )
        .route(
            "/api/terminal/sessions/:id/insert-prompt",
            post(insert_prompt)
                .fallback(method_not_allowed)
                // The handler answers its own 413 with the reference's wording,
                // so an over-sized body has to reach it rather than being cut
                // off by the extractor's default limit.
                .layer(DefaultBodyLimit::max(MAX_INSERT_PROMPT_BODY_BYTES + 4_096)),
        )
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Capabilities {
    external_terminal: bool,
}

async fn capabilities() -> Response {
    Json(Capabilities {
        external_terminal: cfg!(target_os = "macos"),
    })
    .into_response()
}

/// The live session feed.
///
/// Its framing is the terminal's own — `: connected`, `: keepalive`, a charset,
/// and `x-accel-buffering` — not the one every other stream uses.
///
/// The manager already emits `terminal-session-changed` into the event sink on
/// every state change, so this subscribes to that rather than reaching into the
/// manager: opening, closing and moving a session to Terminal.app all arrive
/// here without any of them knowing about a stream.
async fn events(State(state): State<AppState>) -> Response {
    let replay: Vec<TerminalSessionInfo> = state
        .terminal
        .list_sessions()
        .into_iter()
        .map(wire)
        .collect();
    sse::stream(
        sse::CONNECTED_AND_KEEPALIVE,
        replay
            .into_iter()
            .map(|session| sse::named("session", session))
            .collect(),
        state.event_stream.clone(),
        |event| {
            if event.name != TERMINAL_SESSION_CHANGED {
                return None;
            }
            serde_json::from_value::<TerminalSession>(event.payload)
                .ok()
                .map(|session| sse::named("session", wire(session)))
        },
    )
}

/// The event name the terminal manager emits under.
const TERMINAL_SESSION_CHANGED: &str = "terminal-session-changed";

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
enum SocketCommand {
    Input { data: String },
    Resize { cols: u16, rows: u16 },
    Repair { cols: u16, rows: u16 },
    Restart { cols: u16, rows: u16 },
    Stop,
}

#[derive(Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
enum SocketMessage {
    State {
        state: String,
        cwd: String,
        shell: String,
        error: Option<String>,
        cols: u16,
        rows: u16,
    },
    Output {
        data: String,
    },
    Error {
        error: String,
    },
}

async fn socket(State(state): State<AppState>, uri: Uri, upgrade: WebSocketUpgrade) -> Response {
    let Some(id) = query_value(&uri, "id").filter(|id| is_existing_id(id)) else {
        return error(StatusCode::BAD_REQUEST, "Invalid terminal session id.");
    };
    if !state
        .terminal
        .list_sessions()
        .iter()
        .any(|session| session.id == id)
    {
        return error(
            StatusCode::NOT_FOUND,
            &format!("Unknown terminal session: {id}"),
        );
    }
    upgrade
        .protocols(["nomoreide"])
        .on_upgrade(move |socket| serve_socket(socket, state, id))
}

async fn serve_socket(mut socket: WebSocket, state: AppState, id: String) {
    let mut events = state.event_stream.subscribe();
    let Some(session) = state
        .terminal
        .list_sessions()
        .into_iter()
        .find(|session| session.id == id)
    else {
        let _ = send_socket_message(
            &mut socket,
            &SocketMessage::Error {
                error: format!("Unknown terminal session: {id}"),
            },
        )
        .await;
        return;
    };
    if send_socket_message(&mut socket, &socket_state(&session))
        .await
        .is_err()
    {
        return;
    }
    // Every attach replays, so a reconnecting socket redraws rather than
    // waiting for the child to say something next.
    if let Some(pending) = state.terminal.attach_output(&id) {
        if !pending.is_empty()
            && send_socket_message(
                &mut socket,
                &SocketMessage::Output {
                    data: String::from_utf8_lossy(&pending).into_owned(),
                },
            )
            .await
            .is_err()
        {
            return;
        }
    }

    loop {
        tokio::select! {
            incoming = socket.next() => {
                let Some(Ok(message)) = incoming else { return; };
                let Message::Text(text) = message else {
                    if matches!(message, Message::Close(_)) { return; }
                    continue;
                };
                let command = match serde_json::from_str::<SocketCommand>(&text) {
                    Ok(command) => command,
                    Err(_) => {
                        if send_socket_message(&mut socket, &SocketMessage::Error {
                            error: "Invalid terminal socket message.".to_string(),
                        }).await.is_err() { return; }
                        continue;
                    }
                };
                match run_socket_command(&state, &id, command).await {
                    Ok(Some(message)) => {
                        if send_socket_message(&mut socket, &message).await.is_err() { return; }
                    }
                    Ok(None) => {}
                    Err(message) => {
                        if send_socket_message(&mut socket, &SocketMessage::Error { error: message })
                            .await
                            .is_err()
                        {
                            return;
                        }
                    }
                }
            }
            event = events.recv() => {
                let event = match event {
                    Ok(event) => event,
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
                };
                let message = if event.name == format!("terminal-output-{id}") {
                    event.payload.as_str().map(|data| SocketMessage::Output { data: data.to_string() })
                } else if event.name == TERMINAL_SESSION_CHANGED {
                    serde_json::from_value::<TerminalSession>(event.payload)
                        .ok()
                        .filter(|session| session.id == id)
                        .map(|session| socket_state(&session))
                } else {
                    None
                };
                if let Some(message) = message {
                    if send_socket_message(&mut socket, &message).await.is_err() { return; }
                }
            }
        }
    }
}

async fn run_socket_command(
    state: &AppState,
    id: &str,
    command: SocketCommand,
) -> Result<Option<SocketMessage>, String> {
    match command {
        SocketCommand::Input { data } => {
            state.terminal.write_input(id, data.as_bytes())?;
            Ok(None)
        }
        SocketCommand::Resize { cols, rows } => {
            state.terminal.resize(id, cols, rows)?;
            Ok(None)
        }
        SocketCommand::Repair { cols, rows } | SocketCommand::Restart { cols, rows } => {
            let manager = state.terminal.clone();
            let sink = state.events.clone();
            let id = id.to_string();
            let session =
                tokio::task::spawn_blocking(move || manager.restart_session(sink, &id, cols, rows))
                    .await
                    .map_err(|error| error.to_string())??;
            Ok(Some(socket_state(&session)))
        }
        SocketCommand::Stop => {
            let mut session = state
                .terminal
                .list_sessions()
                .into_iter()
                .find(|session| session.id == id)
                .ok_or_else(|| format!("Unknown terminal session: {id}"))?;
            let manager = state.terminal.clone();
            let id = id.to_string();
            tokio::task::spawn_blocking(move || manager.close_session(&id))
                .await
                .map_err(|error| error.to_string())??;
            session.state = "exited".to_string();
            session.exit = None;
            Ok(Some(socket_state(&session)))
        }
    }
}

fn socket_state(session: &TerminalSession) -> SocketMessage {
    SocketMessage::State {
        state: session.state.clone(),
        cwd: session.cwd.clone(),
        shell: session.shell.clone(),
        error: session.error.clone(),
        cols: session.cols,
        rows: session.rows,
    }
}

async fn send_socket_message(
    socket: &mut WebSocket,
    message: &SocketMessage,
) -> Result<(), axum::Error> {
    socket
        .send(Message::Text(
            serde_json::to_string(message).expect("terminal socket messages serialize"),
        ))
        .await
}

async fn list_sessions(State(state): State<AppState>) -> Response {
    Json(TerminalSessionsEnvelope {
        ok: true,
        sessions: state
            .terminal
            .list_sessions()
            .into_iter()
            .map(wire)
            .collect(),
    })
    .into_response()
}

async fn open_system_terminal(
    State(state): State<AppState>,
    headers: HeaderMap,
    uri: Uri,
) -> Response {
    let id = match action_id(&headers, &uri) {
        Ok(id) => id,
        Err((status, message)) => return error(status, message),
    };
    // The preference is read here rather than held by the manager: it is a
    // user setting that can change between one mirror and the next, and the
    // manager has no business caching one. A settings file that will not load
    // falls back to `automatic` — refusing to open a terminal because a
    // preference could not be read would be the wrong end of the trade.
    let preference = settings_store()
        .load()
        .await
        .map(|settings| settings.terminal.external_terminal)
        .unwrap_or_else(|_| "automatic".to_string());
    let app = nomoreide_core::external_terminal::resolve_external_terminal(&preference);
    let manager = state.terminal.clone();
    let sink = state.events.clone();
    let opened =
        tokio::task::spawn_blocking(move || manager.open_in_terminal(sink, &id, app)).await;
    match opened {
        Ok(Ok(session)) => session_response(session),
        Ok(Err(message)) => session_failure(message),
        Err(join) => error(StatusCode::INTERNAL_SERVER_ERROR, &join.to_string()),
    }
}

async fn reclaim_dock(State(state): State<AppState>, headers: HeaderMap, uri: Uri) -> Response {
    let id = match action_id(&headers, &uri) {
        Ok(id) => id,
        Err((status, message)) => return error(status, message),
    };
    match state.terminal.reclaim_to_dock(state.events.as_ref(), &id) {
        Ok(session) => session_response(session),
        Err(message) => session_failure(message),
    }
}

/// A status and the wording that goes with it. Small on purpose: a `Response`
/// in an error position is large enough for clippy to object, and every refusal
/// here is one of a handful of fixed strings.
type Refusal = (StatusCode, &'static str);

/// The id one of the three control actions names.
///
/// The header is checked **first**. Checking the id first would tell an
/// unauthorised caller whether a session exists.
fn action_id(headers: &HeaderMap, uri: &Uri) -> Result<String, Refusal> {
    if headers
        .get(TERMINAL_CONTROL_HEADER)
        .and_then(|value| value.to_str().ok())
        != Some("1")
    {
        return Err((
            StatusCode::FORBIDDEN,
            "Terminal control header is required.",
        ));
    }
    session_id(uri)
        .filter(|id| is_action_id(id))
        .ok_or((StatusCode::BAD_REQUEST, "Invalid terminal session id."))
}

/// The id a rename or a close names.
///
/// No header: renaming a tab and closing one are what the dashboard does all
/// day, and neither drives a running agent from somewhere else. That is the
/// reference's split and it is the reason the two id rules differ.
fn existing_id(uri: &Uri) -> Result<String, Refusal> {
    session_id(uri)
        .filter(|id| is_existing_id(id))
        .ok_or((StatusCode::BAD_REQUEST, "Invalid terminal session id."))
}

/// The id segment, decoded the way the reference decodes it.
///
/// `decodeURIComponent` **throws** on a malformed escape, and the route turns
/// that into the same 400 an invalid id gets — it never passes the raw text
/// through. `Path<String>` is lossier than that, so the segment is taken raw
/// from the uri and decoded here.
fn session_id(uri: &Uri) -> Option<String> {
    let raw = uri.path().split('/').nth(4)?;
    let bytes = raw.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'%' {
            let hex = raw.get(index + 1..index + 3)?;
            if !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
                return None;
            }
            decoded.push(u8::from_str_radix(hex, 16).ok()?);
            index += 3;
        } else {
            decoded.push(bytes[index]);
            index += 1;
        }
    }
    // A percent-escape that decodes to invalid UTF-8 throws there too.
    String::from_utf8(decoded).ok()
}

/// The ids the control actions accept. A path separator would let an id reach a
/// different route, and a control character would let it forge a line in
/// anything that logs it.
fn is_action_id(id: &str) -> bool {
    !id.is_empty()
        && utf16_len(id) <= 200
        && !id.contains('/')
        && !id.contains('\\')
        && !has_control_characters(id)
}

/// The laxer rule the rename and close route uses. An id that names a session
/// that already exists can only match one the manager handed out, so the only
/// thing worth refusing is a character that would forge a log line.
fn is_existing_id(id: &str) -> bool {
    !id.is_empty() && utf16_len(id) <= 1_000 && !has_control_characters(id)
}

fn has_control_characters(value: &str) -> bool {
    value.chars().any(|character| {
        let code = character as u32;
        code <= 31 || code == 127
    })
}

/// Zod counts a string's length in UTF-16 code units, because that is what a
/// JavaScript string's `.length` is. An astral character is two of them and one
/// `char` here, so counting `chars()` would accept an id the reference refuses.
fn utf16_len(value: &str) -> usize {
    value.chars().map(char::len_utf16).sum()
}

/// The body cap an inserted prompt is read under.
///
/// Six times the prompt cap plus a kilobyte, because a multi-byte character
/// JSON-escapes to several bytes and the body is measured before it is parsed.
/// A prompt can therefore be over the *prompt* cap while its body is well under
/// this one: both answer 413, from different checks.
const MAX_INSERT_PROMPT_BODY_BYTES: usize = MAX_AGENT_PROMPT_BYTES * 6 + 1_024;

/// Paste a prompt into a running agent session without submitting it.
///
/// A prompt is measured three times on the way in, and the order is the
/// reference's: the body, then the prompt in UTF-8 bytes, then whether it can
/// be encoded as a paste at all. The last of those is what refuses a prompt
/// carrying a submit character, and it is a 400 rather than a 413 because
/// nothing about it is too large.
async fn insert_prompt(
    State(state): State<AppState>,
    headers: HeaderMap,
    uri: Uri,
    body: Result<Bytes, BytesRejection>,
) -> Response {
    let id = match action_id(&headers, &uri) {
        Ok(id) => id,
        Err((status, message)) => return error(status, message),
    };
    // The extractor's limit sits above the reference's, so anything it refuses
    // was already past the cap the reference reads under.
    let Ok(body) = body else {
        return error(StatusCode::PAYLOAD_TOO_LARGE, "Agent prompt is too large.");
    };
    if body.len() > MAX_INSERT_PROMPT_BODY_BYTES {
        return error(StatusCode::PAYLOAD_TOO_LARGE, "Agent prompt is too large.");
    }
    let Some(prompt) = insert_prompt_body(&parsed_body(&body)) else {
        return error(
            StatusCode::BAD_REQUEST,
            "A non-empty agent prompt is required.",
        );
    };
    if prompt.len() > MAX_AGENT_PROMPT_BYTES {
        return error(StatusCode::PAYLOAD_TOO_LARGE, "Agent prompt is too large.");
    }
    // The manager runs this check too, but the route runs it first so a prompt
    // that could never be pasted is refused for what it is rather than for
    // whatever state the session happens to be in.
    if let Err(reason) = encode_agent_prompt_paste(&prompt) {
        return error(StatusCode::BAD_REQUEST, &reason);
    }
    let manager = state.terminal.clone();
    match tokio::task::spawn_blocking(move || manager.insert_agent_prompt(&id, &prompt)).await {
        Ok(Ok(session)) => session_response(session),
        Ok(Err(message)) => session_failure(message),
        Err(join) => error(StatusCode::INTERNAL_SERVER_ERROR, &join.to_string()),
    }
}

async fn rename(State(state): State<AppState>, uri: Uri, body: Bytes) -> Response {
    let id = match existing_id(&uri) {
        Ok(id) => id,
        Err((status, message)) => return error(status, message),
    };
    let Some(label) = rename_label(&parsed_body(&body)) else {
        return error(
            StatusCode::BAD_REQUEST,
            "Terminal session label must be 1\u{2013}60 characters.",
        );
    };
    match state.terminal.rename_session(&id, label) {
        Ok(session) => session_response(session),
        // The reference's manager cannot fail any other way — its rename is a
        // map lookup and a setter, with no shutdown or closing guard. Anything
        // else here is this manager being stricter, reported the way the
        // control actions report a refusal.
        Err(message) => session_failure(message),
    }
}

/// Close a tab, and answer with what is left.
///
/// Always a 200: `ok` reports whether there *was* a session to close, which is
/// not a failure, and the listing that comes back is what the dashboard redraws
/// from either way.
async fn close(State(state): State<AppState>, uri: Uri) -> Response {
    let id = match existing_id(&uri) {
        Ok(id) => id,
        Err((status, message)) => return error(status, message),
    };
    // This manager treats closing a session it does not know as a no-op success,
    // where the reference's answers `false`. The lookup that tells them apart
    // therefore has to happen here rather than being read off the result.
    let manager = state.terminal.clone();
    let known = manager
        .list_sessions()
        .iter()
        .any(|session| session.id == id);
    // Closing signals a process group and waits for it to be reaped, which is
    // not work for the runtime's own thread.
    let closed = known && {
        let closing = manager.clone();
        matches!(
            tokio::task::spawn_blocking(move || closing.close_session(&id)).await,
            Ok(Ok(()))
        )
    };
    Json(TerminalSessionsEnvelope {
        ok: closed,
        sessions: manager.list_sessions().into_iter().map(wire).collect(),
    })
    .into_response()
}

/// `readJson` without a schema: an empty body, an unparseable one, and a scalar
/// all arrive as an empty object, so a malformed body is a schema failure rather
/// than a refusal of its own.
fn parsed_body(body: &[u8]) -> Value {
    serde_json::from_slice::<Value>(body).unwrap_or(Value::Null)
}

/// `z.object({ prompt: z.string().min(1) }).strict()`.
fn insert_prompt_body(payload: &Value) -> Option<String> {
    let object = payload.as_object()?;
    if object.keys().any(|key| key != "prompt") {
        return None;
    }
    let prompt = object.get("prompt")?.as_str()?;
    (!prompt.is_empty()).then(|| prompt.to_string())
}

/// `z.object({ label: z.string().trim().min(1).max(60) }).strict()`.
///
/// The trim is a **transform**, not a check: it runs before the bounds, and the
/// trimmed label is what gets stored. So a 60-character label arriving with
/// spaces around it is accepted rather than refused as 62.
fn rename_label(payload: &Value) -> Option<String> {
    let object = payload.as_object()?;
    if object.keys().any(|key| key != "label") {
        return None;
    }
    let label = object.get("label")?.as_str()?.trim();
    (!label.is_empty() && utf16_len(label) <= 60).then(|| label.to_string())
}

#[derive(Serialize)]
struct TranscriptsEnvelope {
    ok: bool,
    transcripts: Vec<AgentTranscript>,
}

/// Prior Claude and Codex sessions, for the selected repository or for every
/// project when the caller asks for `scope=all`.
///
/// The repository path here is **not** the workspace cwd the rest of this
/// module uses. `selected_git_cwd` confirms that `activeWorktreePath` really is
/// a worktree and falls back to the repository's own path when it is not; this
/// route reads the recorded path directly, as the reference does. A worktree
/// that has since been removed therefore scopes the listing to a directory no
/// session ever ran in, and the answer is empty. That is the behaviour, not an
/// oversight to quietly improve on — the picker showing nothing is how the
/// dashboard surfaces a stale selection.
async fn transcripts(State(state): State<AppState>, uri: Uri) -> Response {
    let repo_path = if query_value(&uri, "scope").as_deref() == Some("all") {
        None
    } else {
        Some(transcripts_repo_path(&state).await)
    };
    let (home, codex_home) = default_transcript_homes();
    // Every candidate transcript is opened and read, so this does not belong on
    // the runtime's thread.
    let listed = tokio::task::spawn_blocking(move || {
        list_agent_transcripts(
            &home,
            &codex_home,
            repo_path.as_deref(),
            DEFAULT_TRANSCRIPT_LIMIT,
        )
    })
    .await;
    match listed {
        Ok(transcripts) => Json(TranscriptsEnvelope {
            ok: true,
            transcripts,
        })
        .into_response(),
        Err(join) => error(StatusCode::INTERNAL_SERVER_ERROR, &join.to_string()),
    }
}

async fn transcripts_repo_path(state: &AppState) -> String {
    let fallback = std::env::current_dir()
        .map(|path| path.to_string_lossy().into_owned())
        .unwrap_or_default();
    let Ok(config) = state.config_store.load().await else {
        return fallback;
    };
    match nomoreide_core::config::selected_git_repository(&config) {
        Some(repository) => repository
            .active_worktree_path
            .clone()
            .unwrap_or_else(|| repository.path.clone()),
        None => fallback,
    }
}

/// A session the manager knows nothing about is a 404; a session it refuses to
/// move is a 409. Both carry the manager's own wording, which is what the tool
/// hands back to the caller.
fn session_failure(message: String) -> Response {
    let status = if message.starts_with("Unknown terminal session:") {
        StatusCode::NOT_FOUND
    } else {
        StatusCode::CONFLICT
    };
    error(status, &message)
}

fn session_response(session: TerminalSession) -> Response {
    Json(TerminalSessionEnvelope {
        ok: true,
        session: wire(session),
    })
    .into_response()
}

/// What the client may ask for. A session is described, never commanded: the
/// caller names a registered service or an agent provider, and the daemon
/// derives the program. Nothing here can name one.
///
/// The body arrives as a raw value rather than a typed struct because the
/// branch is decided by **whether an `agent` key is present at all**, not by
/// whether it parses. `{"agent": "codex"}` is an agent request that fails its
/// schema — a 400 — where a typed struct would fail to deserialize, fall back
/// to a default, and quietly open a plain shell instead.
async fn create_session(State(state): State<AppState>, body: Bytes) -> Response {
    let payload = parsed_body(&body);
    let workspace = state.workspace_cwd().await;

    // `Object.hasOwn`, which is true for an explicit `null` too.
    if let Some(agent) = payload.as_object().and_then(|object| object.get("agent")) {
        return create_agent_session(&state, agent, workspace).await;
    }

    let Some(service_name) = payload
        .get("serviceName")
        .and_then(Value::as_str)
        .map(|name| name.trim().to_string())
        .filter(|name| !name.is_empty())
    else {
        // No service named: the `+` tab, a plain shell in the workspace.
        let id = state.next_session_id();
        return spawn(&state, TerminalSpawnSpec::shell(id, workspace));
    };

    let config = match state.config_store.load().await {
        Ok(config) => config,
        Err(failure) => {
            return error(StatusCode::INTERNAL_SERVER_ERROR, &failure.to_string());
        }
    };
    let Some(service) = config
        .services
        .iter()
        .find(|service| service.name == service_name)
    else {
        return error(
            StatusCode::NOT_FOUND,
            &format!("Unknown service: {service_name}"),
        );
    };

    // A stable id per service, so reopening the tab reattaches to the same
    // shell instead of spawning a duplicate beside it.
    match resolve_service_terminal(service, format!("svc:{service_name}"), &workspace) {
        ServiceTerminal::Unreachable(reason) => error(StatusCode::BAD_REQUEST, &reason),
        ServiceTerminal::Spawn(spec) => spawn(&state, *spec),
    }
}

/// Which field of an agent request failed.
///
/// Zod reports the **first** issue, and the route picks its wording from that
/// issue's first path element — so what matters is not how many fields are
/// wrong but which of them the schema declares earliest. The declaration order
/// is `provider, prompt, label, oneTimeSkill, resumeId, model, context`, and
/// only two of those get wording of their own. `repository`, which the
/// reference never had, is read after all of them so that it cannot take a
/// refusal away from a field that came first.
#[derive(Debug)]
enum AgentField {
    Provider,
    ResumeId,
    Other,
}

struct AgentSession {
    provider: String,
    prompt: String,
    label: Option<String>,
    one_time_skill: Option<OneTimeSkillSelection>,
    resume_id: Option<String>,
    model: Option<String>,
    context: Option<ContextAttachment>,
    /// Which registered repository to run in. A *name*, resolved against the
    /// registry by [`agent_workspace`] — never a path.
    repository: Option<String>,
}

async fn create_agent_session(state: &AppState, agent: &Value, workspace: String) -> Response {
    let request = match agent_session(agent) {
        Ok(request) => request,
        Err(field) => {
            return error(
                StatusCode::BAD_REQUEST,
                match field {
                    AgentField::Provider => "Agent provider must be codex or claude.",
                    AgentField::ResumeId => "Agent resume id is invalid.",
                    AgentField::Other => "Invalid agent session request.",
                },
            )
        }
    };
    if request.resume_id.is_some() && request.one_time_skill.is_some() {
        return error(
            StatusCode::BAD_REQUEST,
            "A temporary skill cannot be attached to a resumed session.",
        );
    }

    // Resolved before anything is created: an unknown name must not cost a
    // restore point, and the snapshot below is taken in whichever tree wins.
    let workspace = match agent_workspace(state, request.repository.as_deref(), workspace).await {
        Ok(workspace) => workspace,
        Err(response) => return response,
    };

    let task_label = agent_task_label(&request.provider, request.label.as_deref(), &request.prompt);
    let snapshot_label = if request.prompt.lines().any(|line| !line.trim().is_empty()) {
        agent_task_label(&request.provider, None, &request.prompt)
    } else {
        task_label.clone()
    };
    let mut prompt = request.prompt;
    // **A validated context attachment is not yet assembled into the prompt.**
    // `assemble_prompt` needs the library's full item list — notes *and* the
    // items derived from config and the error inbox — and that listing does not
    // exist natively yet; it is the context-library slice's work. Validating it
    // here is not premature: the refusals are what this endpoint answers, and
    // they have to match today. What an accepted attachment does to the prompt
    // is invisible from this endpoint either way, since the response describes
    // the session and never the argv.
    let _ = &request.context;

    if let Some(skill) = &request.one_time_skill {
        // Everything that goes wrong loading a temporary skill is a 422, the
        // network included — it is the one part of opening a session that
        // reaches off the machine.
        prompt = match resolve_one_time_skill(skill).await {
            Ok(skill_prompt) => match compose_one_time_skill_prompt(&skill_prompt, &prompt) {
                Ok(composed) => composed,
                Err(message) => return error(StatusCode::UNPROCESSABLE_ENTITY, &message),
            },
            Err(message) => return error(StatusCode::UNPROCESSABLE_ENTITY, &message),
        };
    }

    // An explicit per-session model wins; otherwise the provider's saved pin
    // applies, and with neither the CLI picks for itself.
    let pinned = match state.config_store.load().await {
        Ok(config) => config.chat_models.as_ref().and_then(|models| {
            if request.provider == "codex" {
                models.codex.clone()
            } else {
                models.claude.clone()
            }
        }),
        Err(_) => None,
    };
    let model = request.model.or(pinned);

    let invocation = match derive_agent_invocation(
        &request.provider,
        &prompt,
        request.resume_id.as_deref(),
        model.as_deref(),
        &agent_binary("NOMOREIDE_CLAUDE_BIN", "claude"),
        &agent_binary("NOMOREIDE_CODEX_BIN", "codex"),
    ) {
        Ok(invocation) => invocation,
        Err(message) => return error(StatusCode::BAD_REQUEST, &message),
    };

    let session_id = state.next_session_id();
    let manager = SnapshotManager::new(workspace.clone());
    let checkpoint = manager.snapshot(&snapshot_label).await.ok();
    if checkpoint.is_some() {
        let _ = manager.prune(DEFAULT_KEEP).await;
    }

    let created = state.terminal.create(
        state.events.clone(),
        TerminalSpawnSpec {
            id: session_id.clone(),
            service_name: None,
            cwd: workspace.clone(),
            shell: OsString::from(invocation.executable),
            args: invocation.args,
            env: Vec::new(),
            label: Some(task_label.clone()),
            kind: Some("agent".to_string()),
            provider: Some(request.provider.clone()),
        },
    );

    match created {
        Ok(session) => {
            if let Some(snapshot) = checkpoint {
                let started_at = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true);
                let _ = save_agent_session(
                    &default_store_path(),
                    RecordedAgentSession {
                        id: session_id,
                        label: Some(snapshot_label),
                        provider: Some(request.provider),
                        repo_path: workspace,
                        snapshot_sha: Some(snapshot.sha),
                        snapshot_ref: Some(snapshot.reference),
                        started_at: started_at.clone(),
                        last_tool_at: started_at,
                        tool_count: 0,
                    },
                );
            }
            (
                StatusCode::CREATED,
                Json(TerminalSessionEnvelope {
                    ok: true,
                    session: wire(session),
                }),
            )
                .into_response()
        }
        Err(message) => {
            if let Some(snapshot) = checkpoint {
                let _ = manager.delete(&snapshot.sha).await;
            }
            error(StatusCode::INTERNAL_SERVER_ERROR, &message)
        }
    }
}

/// Which tree an agent session runs in.
///
/// A named repository is resolved the way `manager_for_repository` resolves one
/// for GitHub: by **name, against `git_repositories`**, never by a path the
/// caller supplied. That is what lets a remote caller choose a project folder
/// without being able to name a directory — the id is the machine's own, and
/// this is where it becomes a path.
///
/// The active worktree wins over the repository root, so an agent started this
/// way lands in the tree the dashboard is showing rather than beside it.
///
/// **Naming one does not select it.** The selection is shared with the desktop
/// dashboard, and starting an agent elsewhere is not a reason to move what
/// somebody else is looking at.
async fn agent_workspace(
    state: &AppState,
    repository: Option<&str>,
    selected: String,
) -> Result<String, Response> {
    let Some(name) = repository.map(str::trim).filter(|name| !name.is_empty()) else {
        return Ok(selected);
    };
    let config = match state.config_store.load().await {
        Ok(config) => config,
        Err(failure) => {
            return Err(error(
                StatusCode::INTERNAL_SERVER_ERROR,
                &failure.to_string(),
            ))
        }
    };
    match repository_workspace(&config, name) {
        Some(workspace) => Ok(workspace),
        None => Err(error(
            StatusCode::NOT_FOUND,
            &format!("Unknown repository: {name}"),
        )),
    }
}

/// The tree a registered repository's name points at, or `None` if the registry
/// does not hold that name.
///
/// Split out from [`agent_workspace`] because this is the whole rule — a name
/// becomes a path here and nowhere else — and a function over a `Config` can be
/// tested without standing up a daemon.
fn repository_workspace(config: &Config, name: &str) -> Option<String> {
    let found = config
        .git_repositories
        .iter()
        .find(|repository| repository.name == name)?;
    Some(
        found
            .active_worktree_path
            .clone()
            .unwrap_or_else(|| found.path.clone()),
    )
}

/// Keep the terminal tab, restore point, and change-set on one readable name.
/// API clients do not have to supply `label`: the first meaningful prompt line
/// is what the user recognises as the work they requested.
fn agent_task_label(provider: &str, explicit: Option<&str>, prompt: &str) -> String {
    let prompt_line = prompt.lines().map(str::trim).find(|line| !line.is_empty());
    normalize_agent_label(provider, explicit.or(prompt_line))
}

/// The reference's `agentSessionSchema`, checked in its declaration order.
///
/// Not `.strict()` at the top level, so an unknown key is *stripped* rather
/// than refused — but every nested object is strict, and every optional field
/// distinguishes absent from `null`: `undefined` takes the default or stays
/// absent, `null` is a type error.
fn agent_session(value: &Value) -> Result<AgentSession, AgentField> {
    let object = value.as_object().ok_or(AgentField::Other)?;
    let provider = object
        .get("provider")
        .and_then(Value::as_str)
        .filter(|provider| matches!(*provider, "codex" | "claude"))
        .ok_or(AgentField::Provider)?
        .to_string();
    // `z.string().default("")`: the default covers an absent key, not a null.
    let prompt = match object.get("prompt") {
        None => String::new(),
        Some(value) => value.as_str().ok_or(AgentField::Other)?.to_string(),
    };
    let label = match object.get("label") {
        None => None,
        Some(value) => Some(value.as_str().ok_or(AgentField::Other)?.to_string()),
    };
    let one_time_skill = match object.get("oneTimeSkill") {
        None => None,
        Some(value) => Some(one_time_skill(value).map_err(|()| AgentField::Other)?),
    };
    let resume_id = match object.get("resumeId") {
        None => None,
        Some(value) => Some(
            value
                .as_str()
                .filter(|id| is_resume_id(id))
                .ok_or(AgentField::ResumeId)?
                .to_string(),
        ),
    };
    let model = match object.get("model") {
        None => None,
        Some(value) => Some(bounded(value, 1, 64).map_err(|()| AgentField::Other)?),
    };
    let context = match object.get("context") {
        None => None,
        Some(value) => Some(attachment(value).map_err(|()| AgentField::Other)?),
    };
    // Read **last**, after every field the reference declared. Which field is
    // reported is decided by declaration order, so a key added at the front
    // would change the wording of refusals that have nothing to do with it.
    let repository = match object.get("repository") {
        None => None,
        Some(value) => Some(value.as_str().ok_or(AgentField::Other)?.to_string()),
    };
    Ok(AgentSession {
        provider,
        prompt,
        label,
        one_time_skill,
        resume_id,
        model,
        context,
        repository,
    })
}

fn one_time_skill(value: &Value) -> Result<OneTimeSkillSelection, ()> {
    let object = value.as_object().ok_or(())?;
    if object.keys().any(|key| key != "name" && key != "source") {
        return Err(());
    }
    Ok(OneTimeSkillSelection {
        name: bounded(object.get("name").ok_or(())?, 1, 200)?,
        source: bounded(object.get("source").ok_or(())?, 3, 400)?,
    })
}

fn attachment(value: &Value) -> Result<ContextAttachment, ()> {
    let object = value.as_object().ok_or(())?;
    if object
        .keys()
        .any(|key| key != "refs" && key != "includePinned")
    {
        return Err(());
    }
    let refs = object.get("refs").ok_or(())?.as_array().ok_or(())?;
    if refs.len() > 200 {
        return Err(());
    }
    Ok(ContextAttachment {
        refs: refs
            .iter()
            .map(context_ref)
            .collect::<Result<Vec<_>, ()>>()?,
        include_pinned: object.get("includePinned").ok_or(())?.as_bool().ok_or(())?,
    })
}

fn context_ref(value: &Value) -> Result<ContextRef, ()> {
    let object = value.as_object().ok_or(())?;
    if object.keys().any(|key| key != "kind" && key != "id") {
        return Err(());
    }
    let kind = object.get("kind").ok_or(())?.as_str().ok_or(())?;
    if !CONTEXT_KINDS.contains(&kind) {
        return Err(());
    }
    Ok(ContextRef {
        kind: kind.to_string(),
        id: bounded(object.get("id").ok_or(())?, 1, 1_000)?,
    })
}

/// `z.string().trim().min(a).max(b)`. The trim is a transform, so it runs first
/// and the bounds are on what survives it — and the trimmed text is what is
/// kept, not the original.
fn bounded(value: &Value, min: usize, max: usize) -> Result<String, ()> {
    let text = value.as_str().ok_or(())?.trim();
    let length = utf16_len(text);
    if length < min || length > max {
        return Err(());
    }
    Ok(text.to_string())
}

/// The reference's `z.string().regex(/^[0-9a-fA-F-]{8,64}$/)`.
fn is_resume_id(id: &str) -> bool {
    (8..=64).contains(&id.len())
        && id
            .chars()
            .all(|character| character.is_ascii_hexdigit() || character == '-')
}

pub(super) fn spawn(state: &AppState, spec: TerminalSpawnSpec) -> Response {
    match state.terminal.create(state.events.clone(), spec) {
        Ok(session) => (
            StatusCode::CREATED,
            Json(TerminalSessionEnvelope {
                ok: true,
                session: wire(session),
            }),
        )
            .into_response(),
        Err(message) => error(StatusCode::INTERNAL_SERVER_ERROR, &message),
    }
}

/// Core's session as the wire's. `serviceName` is dropped: the reference does
/// not carry it, and a caller that wants it reads `label`.
fn wire(session: TerminalSession) -> TerminalSessionInfo {
    TerminalSessionInfo {
        id: session.id,
        cols: session.cols,
        cwd: session.cwd,
        error: session.error,
        exit: session.exit.map(|exit| TerminalExitInfo {
            exit_code: exit.exit_code,
            signal: exit.signal,
        }),
        kind: session.kind,
        label: session.label,
        provider: session.provider,
        rows: session.rows,
        shell: session.shell,
        state: session.state,
        presentation: match session.presentation {
            nomoreide_core::terminal::TerminalPresentation::Dock => "dock",
            nomoreide_core::terminal::TerminalPresentation::TerminalLaunching => {
                "terminalLaunching"
            }
            nomoreide_core::terminal::TerminalPresentation::Terminal => "terminal",
        }
        .to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::{agent_session, agent_task_label, repository_workspace, AgentField};
    use nomoreide_core::config::Config;
    use serde_json::json;

    fn config_with_repositories(repositories: serde_json::Value) -> Config {
        serde_json::from_value(json!({
            "version": 1,
            "services": [],
            "bundles": [],
            "gitRepositories": repositories,
        }))
        .expect("config")
    }

    /// The whole rule in one test: a *name* the machine registered becomes a
    /// path, and nothing else does.
    #[test]
    fn a_registered_name_resolves_to_its_tree() {
        let config = config_with_repositories(json!([
            { "name": "nomoreide", "path": "/repos/nomoreide" },
            { "name": "platform", "path": "/repos/platform" },
        ]));
        assert_eq!(
            repository_workspace(&config, "platform").as_deref(),
            Some("/repos/platform")
        );
    }

    /// The active worktree is what the dashboard is showing, so it is where an
    /// agent started by name belongs — beside the work, not beside the repo.
    #[test]
    fn the_active_worktree_wins_over_the_repository_root() {
        let config = config_with_repositories(json!([{
            "name": "nomoreide",
            "path": "/repos/nomoreide",
            "activeWorktreePath": "/repos/nomoreide-wt/feature",
        }]));
        assert_eq!(
            repository_workspace(&config, "nomoreide").as_deref(),
            Some("/repos/nomoreide-wt/feature")
        );
    }

    /// A name the registry does not hold resolves to nothing, which the route
    /// turns into a 404. It must never fall back to the selected repository:
    /// silently starting an agent somewhere else is worse than refusing.
    #[test]
    fn an_unregistered_name_resolves_to_nothing() {
        let config = config_with_repositories(json!([
            { "name": "nomoreide", "path": "/repos/nomoreide" },
        ]));
        assert_eq!(repository_workspace(&config, "not-registered"), None);
    }

    /// A path is not a name. Nothing in the registry is keyed by one, so the
    /// obvious attempt to smuggle one through resolves to nothing like any
    /// other unknown name.
    #[test]
    fn a_path_is_not_a_name() {
        let config = config_with_repositories(json!([
            { "name": "nomoreide", "path": "/repos/nomoreide" },
        ]));
        assert_eq!(repository_workspace(&config, "/repos/nomoreide"), None);
        assert_eq!(repository_workspace(&config, "../../etc"), None);
    }

    /// A request that names no repository is the request every client sent
    /// before the field existed, and it must still parse.
    #[test]
    fn an_agent_request_without_a_repository_still_parses() {
        let request = agent_session(&json!({ "provider": "claude", "prompt": "hello" }))
            .expect("agent request");
        assert_eq!(request.repository, None);
    }

    #[test]
    fn an_agent_request_carries_the_repository_it_names() {
        let request = agent_session(&json!({
            "provider": "codex",
            "prompt": "hello",
            "repository": "platform",
        }))
        .expect("agent request");
        assert_eq!(request.repository.as_deref(), Some("platform"));
    }

    /// Read last, so it cannot change which field an existing bad request is
    /// refused for — the wording comes from the first failing field in
    /// declaration order.
    #[test]
    fn a_bad_repository_does_not_take_over_another_fields_refusal() {
        assert!(matches!(
            agent_session(&json!({ "provider": "nope", "repository": 7 })),
            Err(AgentField::Provider)
        ));
        assert!(matches!(
            agent_session(&json!({ "provider": "claude", "repository": 7 })),
            Err(AgentField::Other)
        ));
    }

    #[test]
    fn agent_task_names_follow_the_first_prompt_line() {
        assert_eq!(
            agent_task_label("codex", None, "\n  Fix service env scrolling\nMore context"),
            "Fix service env scrolling"
        );
        assert_eq!(
            agent_task_label("claude", Some("  Dependency graph  "), "ignored"),
            "Dependency graph"
        );
        assert_eq!(agent_task_label("codex", None, "\n\t"), "Codex task");
    }
}