ragrig-gpui 0.9.0

Reusable GPUI components for Ragrig RAG chat, citations, managed local services, and reference ingestion
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
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
//! Shared Docker lifecycle for the managed external services.
//!
//! [`ExternalServices`] owns the containers created by the **External
//! services** settings page: GROBID, Ollama, and a llama.cpp server. It also
//! probes servers that are already running, so a user can switch between a
//! local container and an installation they maintain themselves.
//!
//! All Docker and HTTP work happens on a dedicated Tokio runtime thread. Do not
//! drive these futures from GPUI's executor.

use std::{
    collections::HashMap,
    path::Path,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    thread,
    time::{Duration, Instant},
};

use async_channel::{Sender, TrySendError};
use bollard::{
    Docker,
    container::LogOutput,
    models::{MountType, VolumeCreateRequest},
    query_parameters::{
        CreateContainerOptionsBuilder, CreateImageOptionsBuilder, LogsOptionsBuilder,
        RemoveContainerOptionsBuilder, StopContainerOptionsBuilder,
    },
};
use futures_util::StreamExt;
use gpui_kit::{App, Context, Entity, EventEmitter};
use reqwest::Client;

use crate::rag::{RagSettings, ServiceSource};

use super::spec::{self, MANAGED_OLLAMA_URL, Probe, ServiceKind, ServiceLaunch};

const CANCELLED: &str = "cancelled";

/// Whether Docker is reachable from this process.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum DockerStatus {
    /// Docker has not been checked yet.
    #[default]
    Unknown,
    /// The daemon is being contacted.
    Checking,
    /// The daemon answered and reported its version.
    Available {
        /// Docker Engine version.
        version: String,
    },
    /// The daemon could not be reached.
    Unavailable {
        /// Human-readable diagnosis and remediation hint.
        message: String,
    },
}

impl DockerStatus {
    /// One line for the settings page.
    pub fn summary(&self) -> String {
        match self {
            Self::Unknown => "Not checked".to_owned(),
            Self::Checking => "Checking Docker…".to_owned(),
            Self::Available { version } => format!("Docker {version} ready"),
            Self::Unavailable { message } => message.clone(),
        }
    }
}

/// Lifecycle of one managed container.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum ContainerStatus {
    /// The container has not been inspected yet.
    #[default]
    Unknown,
    /// Docker is being inspected.
    Checking,
    /// No managed container with this service's name exists.
    Missing,
    /// The managed container exists but is stopped.
    Stopped,
    /// An image pull is running.
    Pulling {
        /// Image reference being pulled.
        image: String,
        /// Bytes downloaded across all layers so far.
        received: u64,
        /// Total bytes across all layers, when Docker reported it.
        total: u64,
    },
    /// Models are being pulled into a running Ollama container.
    Provisioning {
        /// Model being pulled.
        model: String,
        /// Bytes downloaded so far.
        received: u64,
        /// Total bytes, when the server reported it.
        total: u64,
    },
    /// The container is starting and its health endpoint is polled.
    Starting,
    /// The service answers its health endpoint.
    Running,
    /// The container is being stopped.
    Stopping,
    /// The last operation failed.
    Failed {
        /// Human-readable failure.
        message: String,
    },
}

impl ContainerStatus {
    /// One line for the settings page.
    pub fn summary(&self) -> String {
        match self {
            Self::Unknown => "Not checked".to_owned(),
            Self::Checking => "Checking the container…".to_owned(),
            Self::Missing => "Container not created".to_owned(),
            Self::Stopped => "Container stopped".to_owned(),
            Self::Pulling {
                image,
                received,
                total,
            } if *total > 0 => {
                let percent = (*received as f64 / *total as f64 * 100.0).clamp(0.0, 100.0);
                format!(
                    "Pulling {image} — {percent:.0}% ({} of {})",
                    format_bytes(*received),
                    format_bytes(*total)
                )
            }
            Self::Pulling {
                image, received, ..
            } => format!("Pulling {image} — {}", format_bytes(*received)),
            Self::Provisioning {
                model,
                received,
                total,
            } if *total > 0 => {
                let percent = (*received as f64 / *total as f64 * 100.0).clamp(0.0, 100.0);
                format!(
                    "Pulling model {model} — {percent:.0}% ({} of {})",
                    format_bytes(*received),
                    format_bytes(*total)
                )
            }
            Self::Provisioning {
                model, received, ..
            } => {
                format!("Pulling model {model} — {}", format_bytes(*received))
            }
            Self::Starting => "Starting…".to_owned(),
            Self::Running => "Running".to_owned(),
            Self::Stopping => "Stopping…".to_owned(),
            Self::Failed { message } => format!("Failed: {message}"),
        }
    }
}

/// State of the last endpoint probe.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum ProbeStatus {
    /// No endpoint has been tested.
    #[default]
    Idle,
    /// A probe is running.
    Checking {
        /// Endpoint being tested.
        url: String,
    },
    /// The endpoint answered its health endpoint.
    Reachable {
        /// Normalized endpoint that answered.
        url: String,
        /// Version reported by the service, when available.
        version: Option<String>,
    },
    /// The endpoint did not answer as the expected service.
    Unreachable {
        /// Endpoint that was tested.
        url: String,
        /// Human-readable failure.
        message: String,
    },
}

impl ProbeStatus {
    /// One line for the settings page.
    pub fn summary(&self) -> String {
        match self {
            Self::Idle => "Not tested".to_owned(),
            Self::Checking { url } => format!("Testing {url}…"),
            Self::Reachable { url, version } => match version {
                Some(version) => format!("reachable at {url} ({version})"),
                None => format!("reachable at {url}"),
            },
            Self::Unreachable { url, message } => format!("{url}: {message}"),
        }
    }
}

/// Changes a host may want to observe.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExternalServiceEvent {
    /// Docker availability changed.
    Docker(DockerStatus),
    /// A managed container lifecycle changed.
    Container {
        /// Service the container belongs to.
        service: ServiceKind,
        /// New lifecycle state.
        status: ContainerStatus,
    },
    /// An endpoint probe changed.
    Probe {
        /// Service that was probed.
        service: ServiceKind,
        /// New probe state.
        status: ProbeStatus,
    },
    /// Localhost discovery found one or more servers.
    Discovered {
        /// Service that was discovered.
        service: ServiceKind,
        /// Servers found.
        probes: Vec<Probe>,
    },
    /// A managed container or an adopted server is ready.
    Ready {
        /// Service that is ready.
        service: ServiceKind,
        /// Base URL that answered.
        url: String,
        /// Version reported by the service, when available.
        version: Option<String>,
        /// Whether the app created or started the container.
        managed: bool,
        /// Source the service should keep after this start.
        source: ServiceSource,
    },
    /// The URL a host should persist for `service` changed.
    UrlChanged {
        /// Service whose URL changed.
        service: ServiceKind,
        /// New URL.
        url: String,
    },
    /// An operation failed with a user-facing message.
    Failed {
        /// Service the failure belongs to.
        service: ServiceKind,
        /// Human-readable failure.
        message: String,
    },
}

enum ServiceCommand {
    Inspect {
        kind: ServiceKind,
        container: String,
        adopt: bool,
    },
    Probe {
        kind: ServiceKind,
        url: String,
    },
    Discover {
        kind: ServiceKind,
    },
    PullAndStart {
        kind: ServiceKind,
        container: String,
        launch: ServiceLaunch,
    },
    StartExisting {
        kind: ServiceKind,
        container: String,
        url: String,
    },
    PullModels {
        models: Vec<String>,
    },
    Stop {
        kind: ServiceKind,
        container: String,
    },
    Remove {
        kind: ServiceKind,
        container: String,
    },
}

#[derive(Clone, Debug, Default)]
struct ServiceState {
    container: ContainerStatus,
    probe: ProbeStatus,
    discovered: Vec<Probe>,
    notice: Option<String>,
}

impl ServiceState {
    fn is_busy(&self) -> bool {
        matches!(
            &self.container,
            ContainerStatus::Pulling { .. }
                | ContainerStatus::Provisioning { .. }
                | ContainerStatus::Starting
                | ContainerStatus::Stopping
        )
    }
}

/// Owns the managed containers and probes existing servers.
///
/// Dropping the entity stops containers this service created or adopted in
/// managed mode. A server that is not a managed container is never touched.
pub struct ExternalServices {
    commands: Sender<ServiceCommand>,
    worker: Option<thread::JoinHandle<()>>,
    cancel: Arc<AtomicBool>,
    settings: Entity<RagSettings>,
    docker: DockerStatus,
    services: [ServiceState; ServiceKind::ALL.len()],
}

impl ExternalServices {
    /// Spawn the service worker and start inspecting the configured sources.
    pub fn new(settings: Entity<RagSettings>, cx: &mut Context<Self>) -> Result<Self, String> {
        let initial = settings.read(cx).clone();
        let (commands, command_rx) = async_channel::bounded(16);
        let (events_tx, events) = async_channel::bounded(128);
        let cancel = Arc::new(AtomicBool::new(false));

        // GPUI's test scheduler rejects wakes that arrive from a foreign
        // thread, and starting the worker would probe Docker and localhost on
        // every test. Tests drive `on_event` directly instead.
        let worker = if cx.is_test() {
            None
        } else {
            let worker_cancel = cancel.clone();
            let worker = thread::Builder::new()
                .name("ragrig-services".to_owned())
                .spawn(move || {
                    let runtime = tokio::runtime::Builder::new_multi_thread()
                        .worker_threads(2)
                        .enable_all()
                        .build();
                    match runtime {
                        Ok(runtime) => runtime.block_on(run(command_rx, events_tx, worker_cancel)),
                        Err(error) => {
                            let _ = events_tx.send_blocking(ExternalServiceEvent::Failed {
                                service: ServiceKind::Grobid,
                                message: format!(
                                    "cannot start the external services runtime: {error}"
                                ),
                            });
                        }
                    }
                })
                .map_err(|error| format!("cannot start the external services thread: {error}"))?;

            cx.spawn(async move |this, cx| {
                while let Ok(event) = events.recv().await {
                    if this
                        .update(cx, |service, cx| service.on_event(event, cx))
                        .is_err()
                    {
                        break;
                    }
                }
            })
            .detach();

            for kind in ServiceKind::ALL {
                let source = initial.service_source(kind);
                let container = match source {
                    ServiceSource::Managed => kind.container().to_owned(),
                    ServiceSource::ExistingContainer => {
                        initial.service_container(kind).trim().to_owned()
                    }
                    ServiceSource::Existing => String::new(),
                };
                match source {
                    ServiceSource::Managed => {
                        let _ = commands.try_send(ServiceCommand::Inspect {
                            kind,
                            container: container.clone(),
                            adopt: true,
                        });
                        let launch = ServiceLaunch::from_settings(&initial, kind);
                        if initial.service_auto_start(kind) && launch.missing_field(kind).is_none()
                        {
                            // `Inspect` runs first and reports the container
                            // state; this starts a stopped container or pulls
                            // the image when needed.
                            let _ = commands.try_send(ServiceCommand::PullAndStart {
                                kind,
                                container,
                                launch,
                            });
                        }
                    }
                    ServiceSource::ExistingContainer => {
                        let _ = commands.try_send(ServiceCommand::Inspect {
                            kind,
                            container: container.clone(),
                            adopt: false,
                        });
                        if initial.service_auto_start(kind) && !container.is_empty() {
                            let _ = commands.try_send(ServiceCommand::StartExisting {
                                kind,
                                container,
                                url: spec::existing_url(kind, &initial),
                            });
                        } else {
                            let _ = commands.try_send(ServiceCommand::Probe {
                                kind,
                                url: spec::existing_url(kind, &initial),
                            });
                        }
                    }
                    ServiceSource::Existing => {
                        let _ = commands.try_send(ServiceCommand::Probe {
                            kind,
                            url: spec::existing_url(kind, &initial),
                        });
                    }
                }
            }

            Some(worker)
        };

        Ok(Self {
            commands,
            worker,
            cancel,
            settings,
            docker: DockerStatus::Unknown,
            services: std::array::from_fn(|_| ServiceState::default()),
        })
    }

    /// Whether Docker is reachable.
    pub fn docker(&self) -> &DockerStatus {
        &self.docker
    }

    /// Managed container lifecycle for `kind`.
    pub fn container(&self, kind: ServiceKind) -> &ContainerStatus {
        &self.state(kind).container
    }

    /// State of the last endpoint probe for `kind`.
    pub fn probe(&self, kind: ServiceKind) -> &ProbeStatus {
        &self.state(kind).probe
    }

    /// Servers found by the last localhost discovery for `kind`.
    pub fn discovered(&self, kind: ServiceKind) -> &[Probe] {
        &self.state(kind).discovered
    }

    /// The last user-facing notice for `kind`.
    pub fn notice(&self, kind: ServiceKind) -> Option<&str> {
        self.state(kind).notice.as_deref()
    }

    /// Whether a container operation is in flight for `kind`.
    pub fn is_busy(&self, kind: ServiceKind) -> bool {
        self.state(kind).is_busy()
    }

    /// Whether the running pull or startup for `kind` can still be cancelled.
    pub fn is_cancellable(&self, kind: ServiceKind) -> bool {
        matches!(
            &self.state(kind).container,
            ContainerStatus::Pulling { .. }
                | ContainerStatus::Provisioning { .. }
                | ContainerStatus::Starting
        ) && !self.cancel.load(Ordering::Relaxed)
    }

    /// Whether a cancellation was requested and the worker has not reacted yet.
    pub fn is_cancelling(&self, kind: ServiceKind) -> bool {
        self.cancel.load(Ordering::Relaxed)
            && matches!(
                &self.state(kind).container,
                ContainerStatus::Pulling { .. }
                    | ContainerStatus::Provisioning { .. }
                    | ContainerStatus::Starting
            )
    }

    /// Ask the worker to abandon the current pull or startup for `kind`.
    pub fn cancel(&mut self, kind: ServiceKind, cx: &mut Context<Self>) {
        if self.is_cancellable(kind) {
            self.cancel.store(true, Ordering::Relaxed);
            self.state_mut(kind).notice = Some("cancelling…".to_owned());
            cx.notify();
        }
    }

    /// Re-inspect `kind` according to its configured source.
    pub fn refresh(&mut self, kind: ServiceKind, cx: &mut Context<Self>) {
        let (source, container) = {
            let settings = self.settings.read(cx);
            let source = settings.service_source(kind);
            let container = spec::command_container(kind, source, settings.service_container(kind))
                .unwrap_or_default();
            (source, container)
        };
        match source {
            ServiceSource::Managed => {
                self.send_quiet(
                    kind,
                    ServiceCommand::Inspect {
                        kind,
                        container,
                        adopt: true,
                    },
                    cx,
                );
            }
            ServiceSource::ExistingContainer => {
                self.send_quiet(
                    kind,
                    ServiceCommand::Inspect {
                        kind,
                        container,
                        adopt: false,
                    },
                    cx,
                );
                self.probe_existing(kind, cx);
            }
            ServiceSource::Existing => self.probe_existing(kind, cx),
        }
    }

    /// Re-inspect every managed source and probe every existing source.
    pub fn refresh_all(&mut self, cx: &mut Context<Self>) {
        for kind in ServiceKind::ALL {
            self.refresh(kind, cx);
        }
    }

    /// Probe the configured existing server for `kind`.
    pub fn probe_existing(&mut self, kind: ServiceKind, cx: &mut Context<Self>) {
        let url = spec::existing_url(kind, self.settings.read(cx));
        self.test_url(kind, url, cx);
    }

    /// Probe `url` without changing the configured URL until the probe succeeds.
    pub fn test_url(&mut self, kind: ServiceKind, url: impl Into<String>, cx: &mut Context<Self>) {
        let url = url.into();
        match spec::normalize_url(kind, &url) {
            Ok(url) => {
                self.state_mut(kind).probe = ProbeStatus::Checking { url: url.clone() };
                self.state_mut(kind).discovered.clear();
                self.state_mut(kind).notice = None;
                self.send_quiet(kind, ServiceCommand::Probe { kind, url }, cx);
            }
            Err(message) => {
                self.state_mut(kind).probe = ProbeStatus::Unreachable { url, message };
                cx.notify();
            }
        }
    }

    /// Probe the common localhost ports for `kind` and use the first server
    /// found.
    pub fn discover(&mut self, kind: ServiceKind, cx: &mut Context<Self>) {
        self.state_mut(kind).probe = ProbeStatus::Checking {
            url: "localhost".to_owned(),
        };
        self.state_mut(kind).discovered.clear();
        self.state_mut(kind).notice = None;
        self.send_quiet(kind, ServiceCommand::Discover { kind }, cx);
    }

    /// Pull `kind`'s image when needed, create the container, and wait for
    /// health. For an existing container, start it and wait for health without
    /// creating, recreating, or removing it.
    pub fn start(&mut self, kind: ServiceKind, cx: &mut Context<Self>) {
        let (source, container) = {
            let settings = self.settings.read(cx);
            let source = settings.service_source(kind);
            let container = spec::command_container(kind, source, settings.service_container(kind))
                .unwrap_or_default();
            (source, container)
        };
        match source {
            ServiceSource::Existing => {
                self.state_mut(kind).notice = Some(
                    "switch the source to Existing container or Docker container first".to_owned(),
                );
                cx.notify();
                return;
            }
            ServiceSource::ExistingContainer => {
                if container.is_empty() {
                    self.state_mut(kind).notice = Some("enter the container name first".to_owned());
                    cx.notify();
                    return;
                }
                let url = spec::existing_url(kind, self.settings.read(cx));
                self.state_mut(kind).notice = None;
                self.cancel.store(false, Ordering::Relaxed);
                self.send_quiet(
                    kind,
                    ServiceCommand::StartExisting {
                        kind,
                        container,
                        url,
                    },
                    cx,
                );
                return;
            }
            ServiceSource::Managed => {}
        }

        let launch = ServiceLaunch::from_settings(self.settings.read(cx), kind);
        if let Some(message) = launch.missing_field(kind) {
            self.state_mut(kind).notice = Some(message.to_owned());
            cx.notify();
            return;
        }
        if kind == ServiceKind::LlamaCpp {
            let model = Path::new(&launch.model);
            if model.is_absolute() && !model.is_file() {
                self.state_mut(kind).notice =
                    Some(format!("model file '{}' does not exist", model.display()));
                cx.notify();
                return;
            }
        }
        if container.is_empty() {
            self.state_mut(kind).notice = Some("enter the container name first".to_owned());
            cx.notify();
            return;
        }
        self.state_mut(kind).notice = None;
        self.cancel.store(false, Ordering::Relaxed);
        self.send_quiet(
            kind,
            ServiceCommand::PullAndStart {
                kind,
                container,
                launch,
            },
            cx,
        );
    }

    /// Pull the configured Ollama models into the running container.
    pub fn pull_models(&mut self, cx: &mut Context<Self>) {
        let models = self.pullable_models(cx);
        if models.is_empty() {
            self.state_mut(ServiceKind::Ollama).notice =
                Some("no Ollama models are configured".to_owned());
            cx.notify();
            return;
        }
        self.cancel.store(false, Ordering::Relaxed);
        self.send_quiet(
            ServiceKind::Ollama,
            ServiceCommand::PullModels { models },
            cx,
        );
    }

    /// The models [`Self::pull_models`] would request for the current settings.
    pub fn pullable_models(&self, cx: &App) -> Vec<String> {
        spec::ollama_models(self.settings.read(cx))
    }

    /// Stop the managed container for `kind` without removing it.
    pub fn stop(&mut self, kind: ServiceKind, cx: &mut Context<Self>) {
        let (source, container) = {
            let settings = self.settings.read(cx);
            let source = settings.service_source(kind);
            let container = spec::command_container(kind, source, settings.service_container(kind))
                .unwrap_or_default();
            (source, container)
        };
        if source == ServiceSource::Existing {
            self.state_mut(kind).notice =
                Some("there is no container Scico may stop for this source".to_owned());
            cx.notify();
            return;
        }
        if container.is_empty() {
            self.state_mut(kind).notice = Some("enter the container name first".to_owned());
            cx.notify();
            return;
        }
        self.state_mut(kind).container = ContainerStatus::Stopping;
        self.send_quiet(kind, ServiceCommand::Stop { kind, container }, cx);
    }

    /// Stop and remove a container Scico created.
    pub fn remove(&mut self, kind: ServiceKind, cx: &mut Context<Self>) {
        if self.settings.read(cx).service_source(kind) != ServiceSource::Managed {
            self.state_mut(kind).notice =
                Some("only a container Scico created can be removed".to_owned());
            cx.notify();
            return;
        }
        let container = kind.container().to_owned();
        self.state_mut(kind).container = ContainerStatus::Stopping;
        self.send_quiet(kind, ServiceCommand::Remove { kind, container }, cx);
    }

    /// Clear a stale endpoint probe after the URL was edited.
    pub fn clear_probe(&mut self, kind: ServiceKind, cx: &mut Context<Self>) {
        let state = self.state_mut(kind);
        if !matches!(state.probe, ProbeStatus::Idle) || !state.discovered.is_empty() {
            state.probe = ProbeStatus::Idle;
            state.discovered.clear();
            cx.notify();
        }
    }

    fn state(&self, kind: ServiceKind) -> &ServiceState {
        &self.services[kind.index()]
    }

    fn state_mut(&mut self, kind: ServiceKind) -> &mut ServiceState {
        &mut self.services[kind.index()]
    }

    fn send_quiet(&mut self, kind: ServiceKind, command: ServiceCommand, cx: &mut Context<Self>) {
        if let Err(error) = self.commands.try_send(command) {
            self.state_mut(kind).notice = Some(match error {
                TrySendError::Full(_) => "the service is busy; try again".to_owned(),
                TrySendError::Closed(_) => "the service stopped".to_owned(),
            });
        }
        cx.notify();
    }

    fn on_event(&mut self, event: ExternalServiceEvent, cx: &mut Context<Self>) {
        let mut changed_url = None;
        match &event {
            ExternalServiceEvent::Docker(status) => {
                self.docker = status.clone();
            }
            ExternalServiceEvent::Container { service, status } => {
                if !matches!(status, ContainerStatus::Failed { .. }) {
                    self.state_mut(*service).notice = None;
                }
                if matches!(
                    status,
                    ContainerStatus::Missing
                        | ContainerStatus::Stopped
                        | ContainerStatus::Running
                        | ContainerStatus::Failed { .. }
                ) {
                    self.cancel.store(false, Ordering::Relaxed);
                }
                self.state_mut(*service).container = status.clone();
            }
            ExternalServiceEvent::Probe { service, status } => {
                if matches!(status, ProbeStatus::Reachable { .. }) {
                    self.state_mut(*service).notice = None;
                }
                if let ProbeStatus::Reachable { url, .. } = status {
                    changed_url = Some((*service, url.clone()));
                }
                self.state_mut(*service).probe = status.clone();
            }
            ExternalServiceEvent::Discovered { service, probes } => {
                self.state_mut(*service).discovered = probes.clone();
                if let Some(first) = probes.first() {
                    changed_url = Some((*service, first.url.clone()));
                }
            }
            ExternalServiceEvent::Ready {
                service,
                url,
                version,
                managed,
                source,
            } => {
                let state = self.state_mut(*service);
                state.container = ContainerStatus::Running;
                state.probe = ProbeStatus::Reachable {
                    url: url.clone(),
                    version: version.clone(),
                };
                state.notice = if *managed {
                    None
                } else {
                    Some(format!(
                        "{url} already answers; using it instead of starting a container"
                    ))
                };
                if service.has_url_setting() {
                    changed_url = Some((*service, url.clone()));
                }
                self.settings.update(cx, |settings, cx| {
                    if settings.service_source(*service) != *source {
                        settings.set_service_source(*service, *source);
                        cx.notify();
                    }
                });
            }
            ExternalServiceEvent::UrlChanged { .. } => {}
            ExternalServiceEvent::Failed { service, message } => {
                self.state_mut(*service).notice = Some(message.clone());
            }
        }

        if let Some((service, url)) = changed_url
            && service.has_url_setting()
        {
            let url_for_settings = url.clone();
            let changed = self.settings.update(cx, |settings, cx| {
                let changed = settings.set_service_url(service, url_for_settings);
                if changed {
                    cx.notify();
                }
                changed
            });
            if changed {
                cx.emit(ExternalServiceEvent::UrlChanged { service, url });
            }
        }
        cx.notify();
        cx.emit(event);
    }
}

impl EventEmitter<ExternalServiceEvent> for ExternalServices {}

impl Drop for ExternalServices {
    fn drop(&mut self) {
        self.cancel.store(true, Ordering::Relaxed);
        self.commands.close();
        if let Some(worker) = self.worker.take() {
            let _ = worker.join();
        }
    }
}

impl RagSettings {
    /// Where the given service comes from.
    pub fn service_source(&self, kind: ServiceKind) -> ServiceSource {
        match kind {
            ServiceKind::Grobid => self.grobid_source,
            ServiceKind::Ollama => self.ollama_source,
            ServiceKind::LlamaCpp => self.llamacpp_source,
        }
    }

    /// Set where the given service comes from.
    pub fn set_service_source(&mut self, kind: ServiceKind, source: ServiceSource) {
        match kind {
            ServiceKind::Grobid => self.grobid_source = source,
            ServiceKind::Ollama => self.ollama_source = source,
            ServiceKind::LlamaCpp => self.llamacpp_source = source,
        }
    }

    /// Whether the given service starts automatically.
    pub fn service_auto_start(&self, kind: ServiceKind) -> bool {
        match kind {
            ServiceKind::Grobid => self.grobid_auto_start,
            ServiceKind::Ollama => self.ollama_auto_start,
            ServiceKind::LlamaCpp => self.llamacpp_auto_start,
        }
    }

    /// Set whether the given service starts automatically.
    pub fn set_service_auto_start(&mut self, kind: ServiceKind, auto_start: bool) {
        match kind {
            ServiceKind::Grobid => self.grobid_auto_start = auto_start,
            ServiceKind::Ollama => self.ollama_auto_start = auto_start,
            ServiceKind::LlamaCpp => self.llamacpp_auto_start = auto_start,
        }
    }

    /// Docker image configured for the given service.
    pub fn service_image(&self, kind: ServiceKind) -> &str {
        match kind {
            ServiceKind::Grobid => &self.grobid_image,
            ServiceKind::Ollama => &self.ollama_image,
            ServiceKind::LlamaCpp => &self.llamacpp_image,
        }
    }

    /// Set the Docker image configured for the given service.
    pub fn set_service_image(&mut self, kind: ServiceKind, image: impl Into<String>) {
        let image = image.into();
        match kind {
            ServiceKind::Grobid => self.grobid_image = image,
            ServiceKind::Ollama => self.ollama_image = image,
            ServiceKind::LlamaCpp => self.llamacpp_image = image,
        }
    }

    /// Container name configured for the given service.
    pub fn service_container(&self, kind: ServiceKind) -> &str {
        match kind {
            ServiceKind::Grobid => &self.grobid_container,
            ServiceKind::Ollama => &self.ollama_container,
            ServiceKind::LlamaCpp => &self.llamacpp_container,
        }
    }

    /// Set the container name configured for the given service.
    pub fn set_service_container(&mut self, kind: ServiceKind, container: impl Into<String>) {
        let container = container.into();
        match kind {
            ServiceKind::Grobid => self.grobid_container = container,
            ServiceKind::Ollama => self.ollama_container = container,
            ServiceKind::LlamaCpp => self.llamacpp_container = container,
        }
    }

    /// Update the URL field of `kind`. Returns `true` when the value changed.
    fn set_service_url(&mut self, kind: ServiceKind, url: String) -> bool {
        let field = match kind {
            ServiceKind::Grobid => &mut self.grobid_url,
            ServiceKind::LlamaCpp => &mut self.llamacpp_url,
            ServiceKind::Ollama => return false,
        };
        if *field == url {
            return false;
        }
        *field = url;
        true
    }
}

impl ServiceKind {
    /// Whether this service has a URL setting in the rag configuration.
    fn has_url_setting(self) -> bool {
        matches!(self, Self::Grobid | Self::LlamaCpp)
    }
}

async fn run(
    commands: async_channel::Receiver<ServiceCommand>,
    events: Sender<ExternalServiceEvent>,
    cancel: Arc<AtomicBool>,
) {
    let client = match Client::builder()
        .connect_timeout(Duration::from_secs(4))
        .build()
    {
        Ok(client) => client,
        Err(error) => {
            let _ = events
                .send(ExternalServiceEvent::Failed {
                    service: ServiceKind::Grobid,
                    message: format!("cannot build the service HTTP client: {error}"),
                })
                .await;
            return;
        }
    };
    let mut owned: [Option<String>; ServiceKind::ALL.len()] = std::array::from_fn(|_| None);

    while let Ok(command) = commands.recv().await {
        match command {
            ServiceCommand::Inspect {
                kind,
                container,
                adopt,
            } => {
                let present = inspect(&client, &events, kind, &container, adopt).await;
                if adopt {
                    owned[kind.index()] = present.then_some(container);
                }
            }
            ServiceCommand::Probe { kind, url } => {
                probe_command(&client, &url, kind, &events).await;
            }
            ServiceCommand::Discover { kind } => {
                discover(&client, &events, kind, &commands).await;
            }
            ServiceCommand::PullAndStart {
                kind,
                container,
                launch,
            } => {
                if pull_and_start(
                    &client, &launch, kind, &container, &events, &commands, &cancel,
                )
                .await
                {
                    owned[kind.index()] = Some(container);
                }
            }
            ServiceCommand::StartExisting {
                kind,
                container,
                url,
            } => {
                start_existing(&client, &events, kind, &container, &url, &commands, &cancel).await;
            }
            ServiceCommand::PullModels { models } => {
                pull_ollama_models(&client, &models, &events, &commands, &cancel).await;
            }
            ServiceCommand::Stop { kind, container } => {
                stop(&events, kind, &container).await;
            }
            ServiceCommand::Remove { kind, container } => {
                if !remove(&events, kind, &container).await {
                    owned[kind.index()] = None;
                }
            }
        }
    }

    if let Ok(docker) = connect_docker_quiet().await {
        for kind in ServiceKind::ALL {
            let Some(container) = owned[kind.index()].as_deref() else {
                continue;
            };
            let options = StopContainerOptionsBuilder::default().t(5).build();
            let _ = tokio::time::timeout(
                Duration::from_secs(8),
                docker.stop_container(container, Some(options)),
            )
            .await;
        }
    }
}

async fn inspect(
    client: &Client,
    events: &Sender<ExternalServiceEvent>,
    kind: ServiceKind,
    container: &str,
    adopt: bool,
) -> bool {
    send_container(events, kind, ContainerStatus::Checking).await;
    let Some(docker) = connect_docker(events, kind).await else {
        return false;
    };
    match docker.inspect_container(container, None).await {
        Ok(info) => {
            let running = info
                .state
                .as_ref()
                .and_then(|state| state.running)
                .unwrap_or(false);
            if running {
                send_container(events, kind, ContainerStatus::Running).await;
                if adopt
                    && let Ok(probe) =
                        spec::probe(client, kind, kind.managed_url(), Duration::from_secs(2)).await
                {
                    events
                        .send(ExternalServiceEvent::Ready {
                            service: kind,
                            url: probe.url,
                            version: probe.version,
                            managed: true,
                            source: ServiceSource::Managed,
                        })
                        .await
                        .ok();
                }
            } else {
                send_container(events, kind, ContainerStatus::Stopped).await;
            }
            true
        }
        Err(_) => {
            send_container(events, kind, ContainerStatus::Missing).await;
            false
        }
    }
}

async fn probe_command(
    client: &Client,
    url: &str,
    kind: ServiceKind,
    events: &Sender<ExternalServiceEvent>,
) {
    let normalized = match spec::normalize_url(kind, url) {
        Ok(url) => url,
        Err(message) => {
            events
                .send(ExternalServiceEvent::Probe {
                    service: kind,
                    status: ProbeStatus::Unreachable {
                        url: url.to_owned(),
                        message,
                    },
                })
                .await
                .ok();
            return;
        }
    };
    events
        .send(ExternalServiceEvent::Probe {
            service: kind,
            status: ProbeStatus::Checking {
                url: normalized.clone(),
            },
        })
        .await
        .ok();
    let status = match spec::probe(client, kind, &normalized, Duration::from_secs(3)).await {
        Ok(probe) => ProbeStatus::Reachable {
            url: probe.url,
            version: probe.version,
        },
        Err(message) => ProbeStatus::Unreachable {
            url: normalized,
            message,
        },
    };
    events
        .send(ExternalServiceEvent::Probe {
            service: kind,
            status,
        })
        .await
        .ok();
}

async fn discover(
    client: &Client,
    events: &Sender<ExternalServiceEvent>,
    kind: ServiceKind,
    commands: &async_channel::Receiver<ServiceCommand>,
) {
    events
        .send(ExternalServiceEvent::Probe {
            service: kind,
            status: ProbeStatus::Checking {
                url: "localhost".to_owned(),
            },
        })
        .await
        .ok();

    let mut found = Vec::new();
    for port in kind.discovery_ports() {
        for host in ["127.0.0.1", "localhost"] {
            if commands.is_closed() {
                return;
            }
            let url = format!("http://{host}:{port}");
            if let Ok(probe) = spec::probe(client, kind, &url, Duration::from_millis(900)).await {
                found.push(probe);
                break;
            }
        }
        if !found.is_empty() {
            break;
        }
    }

    if found.is_empty() {
        let ports = kind
            .discovery_ports()
            .iter()
            .map(u16::to_string)
            .collect::<Vec<_>>()
            .join(" or ");
        events
            .send(ExternalServiceEvent::Probe {
                service: kind,
                status: ProbeStatus::Unreachable {
                    url: "localhost".to_owned(),
                    message: format!("No {} server answered on ports {ports}", kind.label()),
                },
            })
            .await
            .ok();
        return;
    }

    events
        .send(ExternalServiceEvent::Probe {
            service: kind,
            status: ProbeStatus::Reachable {
                url: found[0].url.clone(),
                version: found[0].version.clone(),
            },
        })
        .await
        .ok();
    events
        .send(ExternalServiceEvent::Discovered {
            service: kind,
            probes: found,
        })
        .await
        .ok();
}

async fn pull_and_start(
    client: &Client,
    launch: &ServiceLaunch,
    kind: ServiceKind,
    container: &str,
    events: &Sender<ExternalServiceEvent>,
    commands: &async_channel::Receiver<ServiceCommand>,
    cancel: &AtomicBool,
) -> bool {
    if let Some(message) = launch.missing_field(kind) {
        fail(events, kind, message).await;
        return false;
    }
    if kind == ServiceKind::LlamaCpp {
        let model = Path::new(&launch.model);
        if model.is_absolute() && !model.is_file() {
            fail(
                events,
                kind,
                &format!("model file '{}' does not exist", model.display()),
            )
            .await;
            return false;
        }
    }
    let Some(docker) = connect_docker(events, kind).await else {
        return false;
    };

    let image_is_local = docker.inspect_image(&launch.image).await.is_ok();
    if !image_is_local && docker.inspect_container(&launch.image, None).await.is_ok() {
        fail(
            events,
            kind,
            &format!(
                "'{image}' is a container, not an image. Start it with Docker and select Existing server (recommended for a hand-configured container), or enter the image it was built from.",
                image = launch.image
            ),
        )
        .await;
        return false;
    }

    let inspected = docker.inspect_container(container, None).await.ok();
    let running = inspected.as_ref().is_some_and(|info| {
        info.state
            .as_ref()
            .and_then(|state| state.running)
            .unwrap_or(false)
    });
    if !running {
        // Never fight a server that already owns the port. It is not ours, so
        // the service adopts its URL without owning its lifecycle.
        if let Ok(probe) =
            spec::probe(client, kind, kind.managed_url(), Duration::from_millis(900)).await
        {
            events
                .send(ExternalServiceEvent::Ready {
                    service: kind,
                    url: probe.url,
                    version: probe.version,
                    managed: false,
                    source: ServiceSource::Existing,
                })
                .await
                .ok();
            return false;
        }
        if port_in_use(kind).await {
            fail(
                events,
                kind,
                &format!(
                    "port {} is already in use, but {} did not answer its health endpoint. Stop the process using it, or switch {} to Existing server.",
                    kind.port(),
                    kind.label(),
                    kind.label()
                ),
            )
            .await;
            return false;
        }
    }
    let existing = match inspected {
        Some(info) if spec::container_matches(kind, launch, &info) => Some(info),
        Some(_) => {
            // The image or llama.cpp command changed. Recreate the container
            // so Pull and start uses the settings currently on screen.
            let options = RemoveContainerOptionsBuilder::default().force(true).build();
            let _ = docker.remove_container(container, Some(options)).await;
            send_container(events, kind, ContainerStatus::Missing).await;
            None
        }
        None => None,
    };
    if existing.is_some() {
        if !running {
            send_container(events, kind, ContainerStatus::Starting).await;
            if let Err(error) = docker.start_container(container, None).await {
                let logs = container_logs(&docker, container).await;
                fail(
                    events,
                    kind,
                    &start_message(kind, &error.to_string(), logs.as_deref()),
                )
                .await;
                return true;
            }
        }
    } else {
        if !image_is_local {
            if let Err(error) =
                pull_image(&docker, kind, &launch.image, events, commands, cancel).await
            {
                if error == CANCELLED {
                    if !commands.is_closed() {
                        send_container(events, kind, ContainerStatus::Missing).await;
                        fail(events, kind, "pull cancelled").await;
                    }
                    return false;
                }
                fail(events, kind, &pull_message(kind, &launch.image, &error)).await;
                return false;
            }
            if cancelled(commands, cancel) {
                if !commands.is_closed() {
                    fail(events, kind, "pull cancelled").await;
                }
                return false;
            }
        }
        if let Err(error) = create_container(&docker, kind, container, launch).await {
            fail(events, kind, &create_message(kind, &error)).await;
            return false;
        }
        if let Err(error) = docker.start_container(container, None).await {
            let logs = container_logs(&docker, container).await;
            fail(
                events,
                kind,
                &start_message(kind, &error.to_string(), logs.as_deref()),
            )
            .await;
            return true;
        }
    }

    match wait_until_ready(
        ServiceRun {
            client,
            docker: &docker,
            events,
            kind,
            container,
            commands,
            cancel,
        },
        kind.managed_url(),
        ServiceSource::Managed,
    )
    .await
    {
        StartOutcome::Ready | StartOutcome::TimedOut => true,
        StartOutcome::Cancelled => {
            if commands.is_closed() {
                return true;
            }
            let options = StopContainerOptionsBuilder::default().t(5).build();
            let _ = docker.stop_container(container, Some(options)).await;
            send_container(events, kind, ContainerStatus::Stopped).await;
            fail(events, kind, "start cancelled").await;
            true
        }
    }
}

enum StartOutcome {
    Ready,
    TimedOut,
    Cancelled,
}

fn cancelled(commands: &async_channel::Receiver<ServiceCommand>, cancel: &AtomicBool) -> bool {
    commands.is_closed() || cancel.load(Ordering::Relaxed)
}

async fn pull_image(
    docker: &Docker,
    kind: ServiceKind,
    image: &str,
    events: &Sender<ExternalServiceEvent>,
    commands: &async_channel::Receiver<ServiceCommand>,
    cancel: &AtomicBool,
) -> Result<(), String> {
    let mut options = CreateImageOptionsBuilder::default().from_image(image);
    if let Some(platform) = kind.managed_platform(image) {
        options = options.platform(platform);
    }
    let mut stream = docker.create_image(Some(options.build()), None, None);
    let mut layers: HashMap<String, u64> = HashMap::new();
    let mut totals: HashMap<String, u64> = HashMap::new();
    let mut last_emit = Instant::now() - Duration::from_secs(1);

    while let Some(item) = stream.next().await {
        if cancelled(commands, cancel) {
            return Err(CANCELLED.to_owned());
        }
        let info = item.map_err(|error| error.to_string())?;
        if let Some(error) = info
            .error_detail
            .as_ref()
            .and_then(|detail| detail.message.clone())
        {
            return Err(error);
        }
        if let Some(detail) = info.progress_detail.as_ref() {
            let id = info.id.clone().unwrap_or_default();
            let current = detail.current.unwrap_or_default().max(0) as u64;
            let total = detail.total.unwrap_or_default().max(0) as u64;
            layers.insert(id.clone(), current);
            if total > 0 {
                totals.insert(id, total);
            }
        }

        if last_emit.elapsed() >= Duration::from_millis(120) {
            progress_container(
                events,
                kind,
                ContainerStatus::Pulling {
                    image: image.to_owned(),
                    received: layers.values().sum(),
                    total: totals.values().sum(),
                },
            )
            .await;
            last_emit = Instant::now();
        }
    }

    progress_container(
        events,
        kind,
        ContainerStatus::Pulling {
            image: image.to_owned(),
            received: layers.values().sum(),
            total: totals.values().sum(),
        },
    )
    .await;
    Ok(())
}

async fn pull_ollama_models(
    client: &Client,
    models: &[String],
    events: &Sender<ExternalServiceEvent>,
    commands: &async_channel::Receiver<ServiceCommand>,
    cancel: &AtomicBool,
) {
    for model in models {
        if cancelled(commands, cancel) {
            send_container(events, ServiceKind::Ollama, ContainerStatus::Running).await;
            notice(events, ServiceKind::Ollama, "model pull cancelled").await;
            return;
        }
        progress_container(
            events,
            ServiceKind::Ollama,
            ContainerStatus::Provisioning {
                model: model.clone(),
                received: 0,
                total: 0,
            },
        )
        .await;
        match pull_ollama_model(client, model, events, commands, cancel).await {
            Ok(()) => {}
            Err(error) if error == CANCELLED => {
                send_container(events, ServiceKind::Ollama, ContainerStatus::Running).await;
                notice(events, ServiceKind::Ollama, "model pull cancelled").await;
                return;
            }
            Err(error) => {
                fail(
                    events,
                    ServiceKind::Ollama,
                    &format!("cannot pull model '{model}': {error}"),
                )
                .await;
                return;
            }
        }
    }
    send_container(events, ServiceKind::Ollama, ContainerStatus::Running).await;
}

async fn pull_ollama_model(
    client: &Client,
    model: &str,
    events: &Sender<ExternalServiceEvent>,
    commands: &async_channel::Receiver<ServiceCommand>,
    cancel: &AtomicBool,
) -> Result<(), String> {
    let response = client
        .post(format!("{MANAGED_OLLAMA_URL}/api/pull"))
        .json(&serde_json::json!({ "model": model, "stream": true }))
        .send()
        .await
        .map_err(probe_error)?;
    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await.unwrap_or_default();
        let body = body.trim();
        return Err(if body.is_empty() {
            format!("HTTP {status}")
        } else {
            format!("HTTP {status}: {body}")
        });
    }
    let mut stream = response.bytes_stream();
    let mut pending: Vec<u8> = Vec::new();
    let mut received = 0;
    let mut total = 0;
    let mut last_emit = Instant::now() - Duration::from_secs(1);

    loop {
        if cancelled(commands, cancel) {
            return Err(CANCELLED.to_owned());
        }
        let chunk = match tokio::time::timeout(Duration::from_secs(120), stream.next()).await {
            Ok(Some(chunk)) => chunk.map_err(probe_error)?,
            Ok(None) => break,
            Err(_) => {
                return Err("the model pull stalled for two minutes".to_owned());
            }
        };
        pending.extend_from_slice(&chunk);
        while let Some(newline) = pending.iter().position(|byte| *byte == b'\n') {
            let line: Vec<u8> = pending.drain(..=newline).collect();
            let line = line.strip_suffix(b"\n").unwrap_or(&line);
            if line.iter().all(u8::is_ascii_whitespace) {
                continue;
            }
            let Ok(value) = serde_json::from_slice::<serde_json::Value>(line) else {
                continue;
            };
            if let Some(error) = value.get("error").and_then(|error| error.as_str()) {
                return Err(error.to_owned());
            }
            received = value
                .get("completed")
                .and_then(|completed| completed.as_u64())
                .unwrap_or(received);
            total = value
                .get("total")
                .and_then(|total| total.as_u64())
                .unwrap_or(total);
            if last_emit.elapsed() >= Duration::from_millis(120) {
                progress_container(
                    events,
                    ServiceKind::Ollama,
                    ContainerStatus::Provisioning {
                        model: model.to_owned(),
                        received,
                        total,
                    },
                )
                .await;
                last_emit = Instant::now();
            }
        }
    }

    progress_container(
        events,
        ServiceKind::Ollama,
        ContainerStatus::Provisioning {
            model: model.to_owned(),
            received,
            total,
        },
    )
    .await;
    Ok(())
}

async fn create_container(
    docker: &Docker,
    kind: ServiceKind,
    container: &str,
    launch: &ServiceLaunch,
) -> Result<(), String> {
    let mut options = CreateContainerOptionsBuilder::default().name(container);
    if let Some(platform) = kind.managed_platform(&launch.image) {
        options = options.platform(platform);
    }
    let config = spec::container_config(kind, launch)?;
    if let Some(mounts) = config
        .host_config
        .as_ref()
        .and_then(|host| host.mounts.as_ref())
    {
        for mount in mounts {
            if mount.typ != Some(MountType::VOLUME) {
                continue;
            }
            let Some(name) = &mount.source else {
                continue;
            };
            let request = VolumeCreateRequest {
                name: Some(name.clone()),
                ..VolumeCreateRequest::default()
            };
            if let Err(error) = docker.create_volume(request).await {
                let text = error.to_string();
                if !text.to_ascii_lowercase().contains("already exists") {
                    return Err(text);
                }
            }
        }
    }
    docker
        .create_container(Some(options.build()), config)
        .await
        .map(|_| ())
        .map_err(|error| error.to_string())
}

async fn start_existing(
    client: &Client,
    events: &Sender<ExternalServiceEvent>,
    kind: ServiceKind,
    container: &str,
    url: &str,
    commands: &async_channel::Receiver<ServiceCommand>,
    cancel: &AtomicBool,
) {
    if container.trim().is_empty() {
        fail(events, kind, "enter the container name").await;
        return;
    }
    let Some(docker) = connect_docker(events, kind).await else {
        return;
    };
    match docker.inspect_container(container, None).await {
        Ok(info) => {
            let running = info
                .state
                .as_ref()
                .and_then(|state| state.running)
                .unwrap_or(false);
            if !running {
                send_container(events, kind, ContainerStatus::Starting).await;
                if let Err(error) = docker.start_container(container, None).await {
                    let logs = container_logs(&docker, container).await;
                    fail(
                        events,
                        kind,
                        &start_message(kind, &error.to_string(), logs.as_deref()),
                    )
                    .await;
                    return;
                }
            }
        }
        Err(_) => {
            fail(
                events,
                kind,
                &format!(
                    "container '{container}' does not exist. Create it with Docker, or switch the source to Docker container so Scico can create it."
                ),
            )
            .await;
            return;
        }
    }

    match wait_until_ready(
        ServiceRun {
            client,
            docker: &docker,
            events,
            kind,
            container,
            commands,
            cancel,
        },
        url,
        ServiceSource::ExistingContainer,
    )
    .await
    {
        StartOutcome::Ready | StartOutcome::TimedOut => {}
        StartOutcome::Cancelled => {
            if !commands.is_closed() {
                fail(
                    events,
                    kind,
                    "start cancelled; the existing container is left running",
                )
                .await;
            }
        }
    }
}

struct ServiceRun<'a> {
    client: &'a Client,
    docker: &'a Docker,
    events: &'a Sender<ExternalServiceEvent>,
    kind: ServiceKind,
    container: &'a str,
    commands: &'a async_channel::Receiver<ServiceCommand>,
    cancel: &'a AtomicBool,
}

async fn wait_until_ready(run: ServiceRun<'_>, url: &str, source: ServiceSource) -> StartOutcome {
    send_container(run.events, run.kind, ContainerStatus::Starting).await;
    let timeout = run.kind.ready_timeout();
    let deadline = Instant::now() + timeout;

    loop {
        if cancelled(run.commands, run.cancel) {
            return StartOutcome::Cancelled;
        }
        if let Ok(probe) = spec::probe(run.client, run.kind, url, Duration::from_secs(2)).await {
            run.events
                .send(ExternalServiceEvent::Probe {
                    service: run.kind,
                    status: ProbeStatus::Reachable {
                        url: probe.url.clone(),
                        version: probe.version.clone(),
                    },
                })
                .await
                .ok();
            run.events
                .send(ExternalServiceEvent::Ready {
                    service: run.kind,
                    url: probe.url,
                    version: probe.version,
                    managed: true,
                    source,
                })
                .await
                .ok();
            return StartOutcome::Ready;
        }
        if Instant::now() >= deadline {
            let mut message = format!(
                "{} did not answer {url} within {} seconds",
                run.kind.label(),
                timeout.as_secs()
            );
            if let Some(logs) = container_logs(run.docker, run.container).await {
                message.push_str(". Last container output: ");
                message.push_str(&logs);
            }
            fail(run.events, run.kind, &message).await;
            return StartOutcome::TimedOut;
        }
        tokio::time::sleep(Duration::from_millis(750)).await;
    }
}

async fn container_logs(docker: &Docker, container: &str) -> Option<String> {
    let options = LogsOptionsBuilder::default()
        .stdout(true)
        .stderr(true)
        .tail("24")
        .build();
    let mut stream = docker.logs(container, Some(options));
    let mut text = String::new();
    while let Some(Ok(output)) = stream.next().await {
        match output {
            LogOutput::StdOut { message }
            | LogOutput::StdErr { message }
            | LogOutput::Console { message } => {
                text.push_str(&String::from_utf8_lossy(&message));
            }
            LogOutput::StdIn { .. } => {}
        }
        if text.chars().count() > 4000 {
            break;
        }
    }
    let text = text.trim();
    if text.is_empty() {
        return None;
    }
    let text: String = text
        .chars()
        .rev()
        .take(1200)
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    Some(text.replace('\n', " · "))
}

async fn stop(events: &Sender<ExternalServiceEvent>, kind: ServiceKind, container: &str) {
    let Some(docker) = connect_docker(events, kind).await else {
        return;
    };
    if docker.inspect_container(container, None).await.is_err() {
        send_container(events, kind, ContainerStatus::Missing).await;
        return;
    }
    let options = StopContainerOptionsBuilder::default().t(10).build();
    match docker.stop_container(container, Some(options)).await {
        Ok(()) => send_container(events, kind, ContainerStatus::Stopped).await,
        Err(error) => {
            fail(
                events,
                kind,
                &format!("cannot stop the {} container: {error}", kind.label()),
            )
            .await;
        }
    }
}

async fn remove(events: &Sender<ExternalServiceEvent>, kind: ServiceKind, container: &str) -> bool {
    let Some(docker) = connect_docker(events, kind).await else {
        return true;
    };
    let exists = docker.inspect_container(container, None).await.is_ok();
    if !exists {
        send_container(events, kind, ContainerStatus::Missing).await;
        return false;
    }
    let stop_options = StopContainerOptionsBuilder::default().t(5).build();
    let _ = docker.stop_container(container, Some(stop_options)).await;
    let options = RemoveContainerOptionsBuilder::default().force(true).build();
    match docker.remove_container(container, Some(options)).await {
        Ok(()) => {
            send_container(events, kind, ContainerStatus::Missing).await;
            false
        }
        Err(error) => {
            fail(
                events,
                kind,
                &format!("cannot remove the {} container: {error}", kind.label()),
            )
            .await;
            true
        }
    }
}

async fn connect_docker(
    events: &Sender<ExternalServiceEvent>,
    kind: ServiceKind,
) -> Option<Docker> {
    events
        .send(ExternalServiceEvent::Docker(DockerStatus::Checking))
        .await
        .ok();
    match connect_docker_quiet().await {
        Ok(docker) => {
            let version = docker
                .version()
                .await
                .ok()
                .and_then(|version| version.version)
                .unwrap_or_else(|| "unknown".to_owned());
            events
                .send(ExternalServiceEvent::Docker(DockerStatus::Available {
                    version,
                }))
                .await
                .ok();
            Some(docker)
        }
        Err(error) => {
            let message = docker_message(&error);
            events
                .send(ExternalServiceEvent::Docker(DockerStatus::Unavailable {
                    message: message.clone(),
                }))
                .await
                .ok();
            fail(events, kind, &message).await;
            None
        }
    }
}

async fn connect_docker_quiet() -> Result<Docker, String> {
    let connection = if std::env::var_os("DOCKER_HOST").is_some() {
        Docker::connect_with_defaults()
    } else {
        Docker::connect_with_local_defaults()
    };
    let docker = connection
        .map_err(|error| error.to_string())?
        .with_timeout(Duration::from_secs(3));
    docker.ping().await.map_err(|error| error.to_string())?;
    Ok(docker)
}

/// Whether something already listens on the service's loopback port.
///
/// A managed start must not pull a large image before discovering that the
/// port belongs to a server which is still loading.
async fn port_in_use(kind: ServiceKind) -> bool {
    tokio::time::timeout(
        Duration::from_millis(400),
        tokio::net::TcpStream::connect(("127.0.0.1", kind.port())),
    )
    .await
    .is_ok_and(|result| result.is_ok())
}

/// Turn a Docker connection error into an actionable message.
pub fn docker_message(error: &str) -> String {
    let lower = error.to_ascii_lowercase();
    if lower.contains("permission denied")
        || lower.contains("access denied")
        || lower.contains("access is denied")
    {
        "Docker is running but this user cannot access it. On Linux, run `sudo usermod -aG docker $USER`, then sign out and back in (or run `newgrp docker` for a terminal launch). On other systems, make sure Docker Desktop is running for this user.".to_owned()
    } else if lower.contains("connection refused")
        || lower.contains("is the docker daemon running")
        || lower.contains("cannot connect to the docker daemon")
    {
        "Docker is not running. Start Docker Desktop, or run `sudo systemctl start docker` on Linux, then press Refresh.".to_owned()
    } else if lower.contains("no such file or directory") {
        "Docker is not running or not installed. Install Docker Desktop (or the docker package), start it, then press Refresh.".to_owned()
    } else if lower.contains("timed out") || lower.contains("deadline exceeded") {
        "Docker did not answer in time. Check that the daemon is responsive, then press Refresh."
            .to_owned()
    } else {
        format!(
            "Docker is not reachable ({error}). Start Docker Desktop or the Docker daemon, then press Refresh."
        )
    }
}

/// Whether an error is the daemon refusing access to the Docker socket.
///
/// Container runtime errors can also contain "permission denied" (a missing
/// device, an unreadable bind mount, or a non-root image user). Only errors
/// that name the Docker socket or daemon are socket-access problems.
fn is_docker_access_error(error: &str) -> bool {
    let lower = error.to_ascii_lowercase();
    let names_daemon = lower.contains("docker daemon")
        || lower.contains("docker.sock")
        || lower.contains("docker_engine")
        || lower.contains("error during connect")
        || lower.contains("dial unix")
        || lower.contains("cannot connect to the docker");
    let denied = lower.contains("permission denied")
        || lower.contains("access denied")
        || lower.contains("access is denied")
        || lower.contains("connection refused")
        || lower.contains("no such file or directory");
    names_daemon && denied
}

fn start_message(kind: ServiceKind, error: &str, logs: Option<&str>) -> String {
    let lower = error.to_ascii_lowercase();
    if is_docker_access_error(error) {
        return docker_message(error);
    }
    let message = if lower.contains("mount")
        && (lower.contains("permission denied")
            || lower.contains("access denied")
            || lower.contains("not shared")
            || lower.contains("mounts denied"))
    {
        "Docker cannot read the model file. Share its folder with Docker Desktop, or move the .gguf file below your home directory, then press Start again.".to_owned()
    } else if lower.contains("port is already allocated")
        || lower.contains("address already in use")
    {
        format!(
            "port {} is already in use. Stop the process using it, or set {} to Existing server.",
            kind.port(),
            kind.label()
        )
    } else if lower.contains("exec format error") {
        format!(
            "Docker cannot run the {} image on this host. Choose an image built for this platform.",
            kind.label()
        )
    } else if lower.contains("permission denied")
        || lower.contains("access denied")
        || lower.contains("operation not permitted")
    {
        match kind {
            ServiceKind::Ollama => "The Ollama container could not start because its process was denied access to a file or device. A custom image often needs devices such as /dev/dri (SYCL) or a different user; the managed container only publishes port 11434 and mounts its own model volume. Use Existing server for a container you configured by hand.".to_owned(),
            ServiceKind::LlamaCpp => "The llama.cpp container could not start because its process was denied access to a file or device. Check the model file permissions and the container output.".to_owned(),
            ServiceKind::Grobid => "The GROBID container could not start because its process was denied access to a file or device. Check the container output.".to_owned(),
        }
    } else {
        format!("cannot start the {} container: {error}", kind.label())
    };
    with_logs(message, logs)
}

fn with_logs(mut message: String, logs: Option<&str>) -> String {
    if let Some(logs) = logs.map(str::trim).filter(|logs| !logs.is_empty()) {
        message.push_str(" Last container output: ");
        message.push_str(logs);
    }
    message
}

fn pull_message(kind: ServiceKind, image: &str, error: &str) -> String {
    let lower = error.to_ascii_lowercase();
    if is_docker_access_error(error) {
        return docker_message(error);
    }
    if lower.contains("no matching manifest")
        || lower.contains("does not match the detected host platform")
    {
        return format!(
            "the image '{image}' has no build for this platform. Choose a multi-architecture image for {}.",
            kind.label()
        );
    }
    if lower.contains("unauthorized")
        || lower.contains("pull access denied")
        || lower.contains("authentication required")
    {
        return format!(
            "Docker could not pull '{image}'. Check the image name and tag with `docker images`; a local image needs its tag (for example `ollama-sycl:local`), and a private registry needs `docker login`. If '{image}' is a container you created by hand, start it with Docker and select Existing server."
        );
    }
    format!("cannot pull '{image}': {error}")
}

fn create_message(kind: ServiceKind, error: &str) -> String {
    if is_docker_access_error(error) {
        docker_message(error)
    } else {
        format!("cannot create the {} container: {error}", kind.label())
    }
}

async fn fail(events: &Sender<ExternalServiceEvent>, kind: ServiceKind, message: &str) {
    events
        .send(ExternalServiceEvent::Container {
            service: kind,
            status: ContainerStatus::Failed {
                message: message.to_owned(),
            },
        })
        .await
        .ok();
    notice(events, kind, message).await;
}

async fn notice(events: &Sender<ExternalServiceEvent>, kind: ServiceKind, message: &str) {
    events
        .send(ExternalServiceEvent::Failed {
            service: kind,
            message: message.to_owned(),
        })
        .await
        .ok();
}

/// Container lifecycle events are droppable: a stalled UI must never block the
/// Docker worker while the app is shutting down and no longer drains the event
/// channel.
async fn send_container(
    events: &Sender<ExternalServiceEvent>,
    kind: ServiceKind,
    status: ContainerStatus,
) {
    events
        .send(ExternalServiceEvent::Container {
            service: kind,
            status,
        })
        .await
        .ok();
}

/// Image and model progress may be dropped; a full channel must not stall a
/// pull.
async fn progress_container(
    events: &Sender<ExternalServiceEvent>,
    kind: ServiceKind,
    status: ContainerStatus,
) {
    let _ = events.try_send(ExternalServiceEvent::Container {
        service: kind,
        status,
    });
}

fn probe_error(error: reqwest::Error) -> String {
    if error.is_connect() {
        "connection refused".to_owned()
    } else if error.is_timeout() {
        "timed out".to_owned()
    } else {
        error.to_string()
    }
}

fn format_bytes(bytes: u64) -> String {
    const UNITS: [&str; 4] = ["B", "KB", "MB", "GB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit + 1 < UNITS.len() {
        value /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes} B")
    } else {
        format!("{value:.1} {}", UNITS[unit])
    }
}

// Backwards-compatible names for the GROBID-only service.
/// Backwards-compatible alias for the shared Docker status.
#[cfg(feature = "grobid")]
pub type GrobidDockerStatus = DockerStatus;
/// Backwards-compatible alias for the shared container status.
#[cfg(feature = "grobid")]
pub type GrobidContainerStatus = ContainerStatus;
/// Backwards-compatible alias for the shared probe result.
#[cfg(feature = "grobid")]
pub type GrobidProbe = Probe;
/// Backwards-compatible alias for the shared probe status.
#[cfg(feature = "grobid")]
pub type GrobidProbeStatus = ProbeStatus;
/// Backwards-compatible alias for the shared event type.
#[cfg(feature = "grobid")]
pub type GrobidServiceEvent = ExternalServiceEvent;
/// Backwards-compatible alias for the shared controller.
#[cfg(feature = "grobid")]
pub type GrobidService = ExternalServices;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::services::spec::{
        GROBID_DISCOVERY_PORTS, MANAGED_GROBID_CONTAINER, MANAGED_GROBID_PORT, MANAGED_GROBID_URL,
    };

    #[test]
    fn docker_reports_a_stopped_daemon() {
        let message = docker_message(
            "Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?",
        );
        assert!(message.contains("not running"), "{message}");
        assert!(message.contains("Refresh"), "{message}");
    }

    #[test]
    fn docker_reports_missing_permissions() {
        let error = "Got permission denied while trying to connect to the Docker daemon socket";
        let message = docker_message(error);
        assert!(message.contains("usermod -aG docker"), "{message}");
        assert!(message.contains("sign out"), "{message}");
    }

    #[test]
    fn docker_reports_a_missing_socket() {
        let message = docker_message(
            "error connecting to unix socket: /var/run/docker.sock: No such file or directory",
        );
        assert!(message.contains("not installed"), "{message}");
        assert!(message.contains("Refresh"), "{message}");
    }

    #[test]
    fn unknown_docker_errors_keep_the_detail() {
        let message = docker_message("something unexpected");
        assert!(message.contains("something unexpected"), "{message}");
    }

    #[test]
    fn port_conflicts_name_the_service_and_the_fix() {
        let message = start_message(
            ServiceKind::Ollama,
            "Bind for 127.0.0.1:11434 failed: port is already allocated",
            None,
        );
        assert!(message.contains("11434"), "{message}");
        assert!(message.contains("Existing server"), "{message}");
    }

    #[test]
    fn mount_permission_errors_name_the_model_file() {
        let message = start_message(
            ServiceKind::LlamaCpp,
            "error while creating mount source path '/models/qwen.gguf': mkdir /models: permission denied",
            None,
        );
        assert!(message.contains("model file"), "{message}");
        assert!(message.contains("Docker Desktop"), "{message}");
    }

    #[test]
    fn pull_access_denied_is_not_a_docker_socket_error() {
        let message = pull_message(
            ServiceKind::Ollama,
            "ollama-sycl",
            "Error response from daemon: pull access denied for ollama-sycl, repository does not exist or may require 'docker login'",
        );
        assert!(!message.contains("usermod"), "{message}");
        assert!(message.contains("docker images"), "{message}");
        assert!(message.contains("Existing server"), "{message}");
    }

    #[test]
    fn a_container_runtime_permission_error_does_not_blame_the_socket() {
        let message = start_message(
            ServiceKind::Ollama,
            "failed to create task for container: error gathering device information while adding custom device \"/dev/dri\": permission denied",
            Some("SYCL device not found"),
        );
        assert!(!message.contains("usermod"), "{message}");
        assert!(message.contains("device"), "{message}");
        assert!(message.contains("SYCL device not found"), "{message}");
    }

    #[test]
    fn a_docker_socket_permission_error_names_the_group_fix() {
        let message = start_message(
            ServiceKind::Ollama,
            "Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock",
            None,
        );
        assert!(message.contains("usermod -aG docker"), "{message}");
    }

    #[test]
    fn container_summaries_include_progress() {
        let status = ContainerStatus::Pulling {
            image: "grobid/grobid:0.9.1-full".to_owned(),
            received: 512 * 1024 * 1024,
            total: 1024 * 1024 * 1024,
        };
        assert!(status.summary().contains("50%"));
        assert!(status.summary().contains("512.0 MB"));

        let status = ContainerStatus::Provisioning {
            model: "qwen3.5:9b".to_owned(),
            received: 0,
            total: 0,
        };
        assert!(status.summary().contains("qwen3.5:9b"));
    }

    #[test]
    fn managed_container_names_are_distinct() {
        let names: Vec<_> = ServiceKind::ALL
            .iter()
            .map(|kind| kind.container())
            .collect();
        assert_eq!(
            names,
            vec!["ragrig-grobid", "ragrig-ollama", "ragrig-llamacpp"]
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[ignore = "requires Docker and pulls the Ollama image; run with --ignored"]
    async fn the_managed_ollama_container_starts_answers_and_stops() {
        let docker = connect_docker_quiet().await.expect("docker daemon");
        if docker
            .inspect_container(ServiceKind::Ollama.container(), None)
            .await
            .is_ok()
        {
            eprintln!(
                "skipping: {} already exists",
                ServiceKind::Ollama.container()
            );
            return;
        }

        let image = std::env::var("RAGRIG_OLLAMA_TEST_IMAGE")
            .unwrap_or_else(|_| ServiceKind::Ollama.default_image().to_owned());
        if port_in_use(ServiceKind::Ollama).await {
            eprintln!(
                "skipping: port {} is already in use",
                ServiceKind::Ollama.port()
            );
            return;
        }
        let (commands_tx, commands) = async_channel::bounded(16);
        let (events_tx, events) = async_channel::bounded(256);
        let launch = ServiceLaunch {
            image: image.clone(),
            ..ServiceLaunch::default()
        };
        let client = Client::builder()
            .connect_timeout(Duration::from_secs(4))
            .build()
            .expect("client");
        let cancel = AtomicBool::new(false);
        let container = ServiceKind::Ollama.container();

        pull_image(
            &docker,
            ServiceKind::Ollama,
            &image,
            &events_tx,
            &commands,
            &cancel,
        )
        .await
        .expect("pull");
        create_container(&docker, ServiceKind::Ollama, container, &launch)
            .await
            .expect("create");
        if let Err(error) = docker.start_container(container, None).await {
            let options = RemoveContainerOptionsBuilder::default().force(true).build();
            let _ = docker.remove_container(container, Some(options)).await;
            panic!("start: {error}");
        }
        let outcome = wait_until_ready(
            ServiceRun {
                client: &client,
                docker: &docker,
                events: &events_tx,
                kind: ServiceKind::Ollama,
                container,
                commands: &commands,
                cancel: &cancel,
            },
            ServiceKind::Ollama.managed_url(),
            ServiceSource::Managed,
        )
        .await;
        stop(&events_tx, ServiceKind::Ollama, container).await;
        let removed = remove(&events_tx, ServiceKind::Ollama, container).await;

        assert!(matches!(outcome, StartOutcome::Ready));
        assert!(
            std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(
                event,
                ExternalServiceEvent::Ready {
                    service: ServiceKind::Ollama,
                    managed: true,
                    ..
                }
            )),
            "the managed container never reported ready"
        );
        assert!(!removed);
        drop(commands_tx);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[ignore = "requires Docker and a server on the Ollama port; run with --ignored"]
    async fn an_existing_ollama_is_adopted_without_a_container() {
        let docker = connect_docker_quiet().await.expect("docker daemon");
        if docker
            .inspect_container(ServiceKind::Ollama.container(), None)
            .await
            .is_ok()
        {
            eprintln!(
                "skipping: {} already exists",
                ServiceKind::Ollama.container()
            );
            return;
        }
        if !port_in_use(ServiceKind::Ollama).await {
            eprintln!(
                "skipping: nothing listens on port {}",
                ServiceKind::Ollama.port()
            );
            return;
        }

        let (commands_tx, commands) = async_channel::bounded(16);
        let (events_tx, events) = async_channel::bounded(64);
        let client = Client::builder()
            .connect_timeout(Duration::from_secs(4))
            .build()
            .expect("client");
        let launch = ServiceLaunch {
            image: ServiceKind::Ollama.default_image().to_owned(),
            ..ServiceLaunch::default()
        };

        let owned = pull_and_start(
            &client,
            &launch,
            ServiceKind::Ollama,
            ServiceKind::Ollama.container(),
            &events_tx,
            &commands,
            &AtomicBool::new(false),
        )
        .await;

        assert!(!owned, "an adopted server must not be owned");
        assert!(
            std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(
                event,
                ExternalServiceEvent::Ready {
                    service: ServiceKind::Ollama,
                    managed: false,
                    ..
                }
            )),
            "the existing server was not adopted"
        );
        assert!(
            docker
                .inspect_container(ServiceKind::Ollama.container(), None)
                .await
                .is_err(),
            "no managed container should have been created"
        );
        drop(commands_tx);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[ignore = "requires Docker and RAGRIG_OLLAMA_CONTAINER_TEST=<container>; run with --ignored"]
    async fn an_existing_container_is_started_by_name() {
        let Some(container) = std::env::var("RAGRIG_OLLAMA_CONTAINER_TEST")
            .ok()
            .map(|name| name.trim().to_owned())
            .filter(|name| !name.is_empty())
        else {
            eprintln!("skipping: set RAGRIG_OLLAMA_CONTAINER_TEST to a container name");
            return;
        };
        let docker = connect_docker_quiet().await.expect("docker daemon");
        let info = match docker.inspect_container(&container, None).await {
            Ok(info) => info,
            Err(_) => {
                eprintln!("skipping: container '{container}' does not exist");
                return;
            }
        };
        let was_running = info
            .state
            .as_ref()
            .and_then(|state| state.running)
            .unwrap_or(false);

        let (commands_tx, commands) = async_channel::bounded(16);
        let (events_tx, events) = async_channel::bounded(64);
        let client = Client::builder()
            .connect_timeout(Duration::from_secs(4))
            .build()
            .expect("client");

        start_existing(
            &client,
            &events_tx,
            ServiceKind::Ollama,
            &container,
            ServiceKind::Ollama.managed_url(),
            &commands,
            &AtomicBool::new(false),
        )
        .await;

        let events: Vec<_> = std::iter::from_fn(|| events.try_recv().ok()).collect();
        let ready = events.iter().any(|event| {
            matches!(
                event,
                ExternalServiceEvent::Ready {
                    service: ServiceKind::Ollama,
                    managed: true,
                    source: ServiceSource::ExistingContainer,
                    ..
                }
            )
        });
        if !was_running {
            stop(&events_tx, ServiceKind::Ollama, &container).await;
        }
        drop(commands_tx);

        assert!(
            ready,
            "the existing container never reported ready: {events:#?}"
        );
    }

    #[test]
    fn grobid_only_constants_are_re_exported() {
        assert_eq!(MANAGED_GROBID_CONTAINER, "ragrig-grobid");
        assert_eq!(MANAGED_GROBID_PORT, 8070);
        assert_eq!(MANAGED_GROBID_URL, "http://127.0.0.1:8070");
        assert_eq!(GROBID_DISCOVERY_PORTS, [8070, 8080]);
    }
}