feat(mcp): local MCP server so agents can read chats and propose replies
- crates/mcp: Streamable HTTP server on 127.0.0.1 (rmcp 3.5.1), bearer token + Host/Origin check - Tools: list_chats, list_channels, read_messages, search_messages, propose_message, list_meetings, get_transcript, wait_for_event - Permissions: chats and channels All/Selected/None, propose, calendar, transcripts; enforced server-side - Proposal card above the composer (Send/Edit/Discard), stale once you answer, chat list hint - Settings > MCP with Server/Access/Install sub-tabs; one-click install for Claude Code, Codex, Copilot CLI, VS Code, Cursor, Windows + WSL - chatsvc: meeting transcripts via the recording share (Graph transcripts API is closed) - store: agent_proposals table, scoped search, messages_after Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -272,6 +272,7 @@ dependencies = [
272
272
"gpui-pre-reqwest-client",
273
273
"graph",
274
274
"image",
275
"mcp",
275
276
"raw-window-handle",
276
277
"regex",
277
278
"rodio",
@@ -683,6 +684,52 @@ dependencies = [
683
684
"pkg-config",
684
685
]
685
686
687
[[package]]
688
name = "axum"
689
version = "0.8.9"
690
source = "registry+https://github.com/rust-lang/crates.io-index"
691
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
692
dependencies = [
693
"axum-core",
694
"bytes",
695
"futures-util",
696
"http",
697
"http-body",
698
"http-body-util",
699
"hyper",
700
"hyper-util",
701
"itoa",
702
"matchit",
703
"memchr",
704
"mime",
705
"percent-encoding",
706
"pin-project-lite",
707
"serde_core",
708
"sync_wrapper",
709
"tokio",
710
"tower",
711
"tower-layer",
712
"tower-service",
713
]
714
715
[[package]]
716
name = "axum-core"
717
version = "0.5.6"
718
source = "registry+https://github.com/rust-lang/crates.io-index"
719
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
720
dependencies = [
721
"bytes",
722
"futures-core",
723
"http",
724
"http-body",
725
"http-body-util",
726
"mime",
727
"pin-project-lite",
728
"sync_wrapper",
729
"tower-layer",
730
"tower-service",
731
]
732
686
733
[[package]]
687
734
name = "backtrace"
688
735
version = "0.3.76"
@@ -1951,6 +1998,40 @@ dependencies = [
1951
1998
"syn 3.0.6",
1952
1999
]
1953
2000
2001
[[package]]
2002
name = "darling"
2003
version = "0.24.1"
2004
source = "registry+https://github.com/rust-lang/crates.io-index"
2005
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
2006
dependencies = [
2007
"darling_core",
2008
"darling_macro",
2009
]
2010
2011
[[package]]
2012
name = "darling_core"
2013
version = "0.24.1"
2014
source = "registry+https://github.com/rust-lang/crates.io-index"
2015
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
2016
dependencies = [
2017
"ident_case",
2018
"proc-macro2",
2019
"quote",
2020
"strsim",
2021
"syn 3.0.6",
2022
]
2023
2024
[[package]]
2025
name = "darling_macro"
2026
version = "0.24.1"
2027
source = "registry+https://github.com/rust-lang/crates.io-index"
2028
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
2029
dependencies = [
2030
"darling_core",
2031
"quote",
2032
"syn 3.0.6",
2033
]
2034
1954
2035
[[package]]
1955
2036
name = "dasp_sample"
1956
2037
version = "0.11.0"
@@ -3706,7 +3787,7 @@ dependencies = [
3706
3787
"url",
3707
3788
"wasm-bindgen",
3708
3789
"wasm-bindgen-futures",
3709
"wasm-streams",
3790
"wasm-streams 0.4.2",
3710
3791
"web-sys",
3711
3792
"windows-registry 0.4.0",
3712
3793
]
@@ -4212,6 +4293,12 @@ version = "1.10.1"
4212
4293
source = "registry+https://github.com/rust-lang/crates.io-index"
4213
4294
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
4214
4295
4296
[[package]]
4297
name = "httpdate"
4298
version = "1.0.3"
4299
source = "registry+https://github.com/rust-lang/crates.io-index"
4300
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
4301
4215
4302
[[package]]
4216
4303
name = "hybrid-array"
4217
4304
version = "0.4.15"
@@ -4235,6 +4322,7 @@ dependencies = [
4235
4322
"http",
4236
4323
"http-body",
4237
4324
"httparse",
4325
"httpdate",
4238
4326
"itoa",
4239
4327
"pin-project-lite",
4240
4328
"smallvec",
@@ -4389,6 +4477,12 @@ dependencies = [
4389
4477
"zerovec",
4390
4478
]
4391
4479
4480
[[package]]
4481
name = "ident_case"
4482
version = "1.0.1"
4483
source = "registry+https://github.com/rust-lang/crates.io-index"
4484
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
4485
4392
4486
[[package]]
4393
4487
name = "idna"
4394
4488
version = "1.1.0"
@@ -5207,6 +5301,12 @@ dependencies = [
5207
5301
"syn 2.0.119",
5208
5302
]
5209
5303
5304
[[package]]
5305
name = "matchit"
5306
version = "0.8.4"
5307
source = "registry+https://github.com/rust-lang/crates.io-index"
5308
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
5309
5210
5310
[[package]]
5211
5311
name = "matrixmultiply"
5212
5312
version = "0.3.11"
@@ -5227,6 +5327,28 @@ dependencies = [
5227
5327
"rayon",
5228
5328
]
5229
5329
5330
[[package]]
5331
name = "mcp"
5332
version = "0.1.0"
5333
dependencies = [
5334
"axum",
5335
"chrono",
5336
"percent-encoding",
5337
"rand 0.9.5",
5338
"reqwest 0.13.5",
5339
"rmcp",
5340
"serde",
5341
"serde_json",
5342
"store",
5343
"subtle",
5344
"tempfile",
5345
"thiserror 2.0.21",
5346
"tokio",
5347
"tokio-util",
5348
"toml_edit 0.22.27",
5349
"uuid",
5350
]
5351
5230
5352
[[package]]
5231
5353
name = "md-5"
5232
5354
version = "0.10.6"
@@ -6927,6 +7049,7 @@ version = "0.11.19"
6927
7049
source = "registry+https://github.com/rust-lang/crates.io-index"
6928
7050
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
6929
7051
dependencies = [
7052
"aws-lc-rs",
6930
7053
"bytes",
6931
7054
"getrandom 0.4.3",
6932
7055
"lru-slab",
@@ -7350,6 +7473,46 @@ dependencies = [
7350
7473
"web-sys",
7351
7474
]
7352
7475
7476
[[package]]
7477
name = "reqwest"
7478
version = "0.13.5"
7479
source = "registry+https://github.com/rust-lang/crates.io-index"
7480
checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"
7481
dependencies = [
7482
"base64 0.23.1",
7483
"bytes",
7484
"futures-core",
7485
"futures-util",
7486
"http",
7487
"http-body",
7488
"http-body-util",
7489
"hyper",
7490
"hyper-rustls",
7491
"hyper-util",
7492
"js-sys",
7493
"log",
7494
"percent-encoding",
7495
"pin-project-lite",
7496
"quinn",
7497
"rustls",
7498
"rustls-pki-types",
7499
"rustls-platform-verifier",
7500
"serde",
7501
"serde_json",
7502
"sync_wrapper",
7503
"tokio",
7504
"tokio-rustls",
7505
"tokio-util",
7506
"tower",
7507
"tower-http",
7508
"tower-service",
7509
"url",
7510
"wasm-bindgen",
7511
"wasm-bindgen-futures",
7512
"wasm-streams 0.5.0",
7513
"web-sys",
7514
]
7515
7353
7516
[[package]]
7354
7517
name = "resvg"
7355
7518
version = "0.45.1"
@@ -7407,6 +7570,52 @@ dependencies = [
7407
7570
"windows-sys 0.52.0",
7408
7571
]
7409
7572
7573
[[package]]
7574
name = "rmcp"
7575
version = "3.5.1"
7576
source = "registry+https://github.com/rust-lang/crates.io-index"
7577
checksum = "ab5023804cbe0304cbe06197ac16e645a0a0d0ffa2953bf735c15c2fa0213350"
7578
dependencies = [
7579
"async-trait",
7580
"base64 0.23.1",
7581
"bytes",
7582
"chrono",
7583
"futures",
7584
"http",
7585
"http-body",
7586
"http-body-util",
7587
"indexmap",
7588
"pastey 0.2.3",
7589
"pin-project-lite",
7590
"rand 0.10.3",
7591
"reqwest 0.13.5",
7592
"rmcp-macros",
7593
"schemars",
7594
"serde",
7595
"serde_json",
7596
"sse-stream",
7597
"thiserror 2.0.21",
7598
"tokio",
7599
"tokio-stream",
7600
"tokio-util",
7601
"tower-service",
7602
"tracing",
7603
"uuid",
7604
]
7605
7606
[[package]]
7607
name = "rmcp-macros"
7608
version = "3.5.1"
7609
source = "registry+https://github.com/rust-lang/crates.io-index"
7610
checksum = "a1da498700030856ba63114bceefa30ba21f5e278cb975e5b9de3529fe842b40"
7611
dependencies = [
7612
"darling",
7613
"proc-macro2",
7614
"quote",
7615
"serde_json",
7616
"syn 3.0.6",
7617
]
7618
7410
7619
[[package]]
7411
7620
name = "rodio"
7412
7621
version = "0.22.2"
@@ -7768,6 +7977,7 @@ version = "1.2.2"
7768
7977
source = "registry+https://github.com/rust-lang/crates.io-index"
7769
7978
checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"
7770
7979
dependencies = [
7980
"chrono",
7771
7981
"dyn-clone",
7772
7982
"indexmap",
7773
7983
"ref-cast",
@@ -8291,6 +8501,19 @@ dependencies = [
8291
8501
"bitflags 2.13.2",
8292
8502
]
8293
8503
8504
[[package]]
8505
name = "sse-stream"
8506
version = "0.2.6"
8507
source = "registry+https://github.com/rust-lang/crates.io-index"
8508
checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4"
8509
dependencies = [
8510
"bytes",
8511
"futures-util",
8512
"http-body",
8513
"http-body-util",
8514
"pin-project-lite",
8515
]
8516
8294
8517
[[package]]
8295
8518
name = "stable_deref_trait"
8296
8519
version = "1.2.1"
@@ -9920,6 +10143,19 @@ dependencies = [
9920
10143
"web-sys",
9921
10144
]
9922
10145
10146
[[package]]
10147
name = "wasm-streams"
10148
version = "0.5.0"
10149
source = "registry+https://github.com/rust-lang/crates.io-index"
10150
checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"
10151
dependencies = [
10152
"futures-util",
10153
"js-sys",
10154
"wasm-bindgen",
10155
"wasm-bindgen-futures",
10156
"web-sys",
10157
]
10158
9923
10159
[[package]]
9924
10160
name = "wasm_thread"
9925
10161
version = "0.3.3"
@@ -10093,7 +10329,7 @@ dependencies = [
10093
10329
"anyhow",
10094
10330
"fs2",
10095
10331
"regex",
10096
"reqwest",
10332
"reqwest 0.12.28",
10097
10333
"scratch",
10098
10334
"semver",
10099
10335
"zip",
@@ -272,6 +272,7 @@ dependencies = [272
"gpui-pre-reqwest-client",272
"gpui-pre-reqwest-client",273
"graph",273
"graph",274
"image",274
"image",275
"mcp",275
"raw-window-handle",276
"raw-window-handle",276
"regex",277
"regex",277
"rodio",278
"rodio",@@ -683,6 +684,52 @@ dependencies = [683
"pkg-config",684
"pkg-config",684
]685
]685
686
687
[[package]]688
name = "axum"689
version = "0.8.9"690
source = "registry+https://github.com/rust-lang/crates.io-index"691
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"692
dependencies = [693
"axum-core",694
"bytes",695
"futures-util",696
"http",697
"http-body",698
"http-body-util",699
"hyper",700
"hyper-util",701
"itoa",702
"matchit",703
"memchr",704
"mime",705
"percent-encoding",706
"pin-project-lite",707
"serde_core",708
"sync_wrapper",709
"tokio",710
"tower",711
"tower-layer",712
"tower-service",713
]714
715
[[package]]716
name = "axum-core"717
version = "0.5.6"718
source = "registry+https://github.com/rust-lang/crates.io-index"719
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"720
dependencies = [721
"bytes",722
"futures-core",723
"http",724
"http-body",725
"http-body-util",726
"mime",727
"pin-project-lite",728
"sync_wrapper",729
"tower-layer",730
"tower-service",731
]732
686
[[package]]733
[[package]]687
name = "backtrace"734
name = "backtrace"688
version = "0.3.76"735
version = "0.3.76"@@ -1951,6 +1998,40 @@ dependencies = [1951
"syn 3.0.6",1998
"syn 3.0.6",1952
]1999
]1953
2000
2001
[[package]]2002
name = "darling"2003
version = "0.24.1"2004
source = "registry+https://github.com/rust-lang/crates.io-index"2005
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"2006
dependencies = [2007
"darling_core",2008
"darling_macro",2009
]2010
2011
[[package]]2012
name = "darling_core"2013
version = "0.24.1"2014
source = "registry+https://github.com/rust-lang/crates.io-index"2015
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"2016
dependencies = [2017
"ident_case",2018
"proc-macro2",2019
"quote",2020
"strsim",2021
"syn 3.0.6",2022
]2023
2024
[[package]]2025
name = "darling_macro"2026
version = "0.24.1"2027
source = "registry+https://github.com/rust-lang/crates.io-index"2028
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"2029
dependencies = [2030
"darling_core",2031
"quote",2032
"syn 3.0.6",2033
]2034
1954
[[package]]2035
[[package]]1955
name = "dasp_sample"2036
name = "dasp_sample"1956
version = "0.11.0"2037
version = "0.11.0"@@ -3706,7 +3787,7 @@ dependencies = [3706
"url",3787
"url",3707
"wasm-bindgen",3788
"wasm-bindgen",3708
"wasm-bindgen-futures",3789
"wasm-bindgen-futures",3709
"wasm-streams",3790
"wasm-streams 0.4.2",3710
"web-sys",3791
"web-sys",3711
"windows-registry 0.4.0",3792
"windows-registry 0.4.0",3712
]3793
]@@ -4212,6 +4293,12 @@ version = "1.10.1"4212
source = "registry+https://github.com/rust-lang/crates.io-index"4293
source = "registry+https://github.com/rust-lang/crates.io-index"4213
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"4294
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"4214
4295
4296
[[package]]4297
name = "httpdate"4298
version = "1.0.3"4299
source = "registry+https://github.com/rust-lang/crates.io-index"4300
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"4301
4215
[[package]]4302
[[package]]4216
name = "hybrid-array"4303
name = "hybrid-array"4217
version = "0.4.15"4304
version = "0.4.15"@@ -4235,6 +4322,7 @@ dependencies = [4235
"http",4322
"http",4236
"http-body",4323
"http-body",4237
"httparse",4324
"httparse",4325
"httpdate",4238
"itoa",4326
"itoa",4239
"pin-project-lite",4327
"pin-project-lite",4240
"smallvec",4328
"smallvec",@@ -4389,6 +4477,12 @@ dependencies = [4389
"zerovec",4477
"zerovec",4390
]4478
]4391
4479
4480
[[package]]4481
name = "ident_case"4482
version = "1.0.1"4483
source = "registry+https://github.com/rust-lang/crates.io-index"4484
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"4485
4392
[[package]]4486
[[package]]4393
name = "idna"4487
name = "idna"4394
version = "1.1.0"4488
version = "1.1.0"@@ -5207,6 +5301,12 @@ dependencies = [5207
"syn 2.0.119",5301
"syn 2.0.119",5208
]5302
]5209
5303
5304
[[package]]5305
name = "matchit"5306
version = "0.8.4"5307
source = "registry+https://github.com/rust-lang/crates.io-index"5308
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"5309
5210
[[package]]5310
[[package]]5211
name = "matrixmultiply"5311
name = "matrixmultiply"5212
version = "0.3.11"5312
version = "0.3.11"@@ -5227,6 +5327,28 @@ dependencies = [5227
"rayon",5327
"rayon",5228
]5328
]5229
5329
5330
[[package]]5331
name = "mcp"5332
version = "0.1.0"5333
dependencies = [5334
"axum",5335
"chrono",5336
"percent-encoding",5337
"rand 0.9.5",5338
"reqwest 0.13.5",5339
"rmcp",5340
"serde",5341
"serde_json",5342
"store",5343
"subtle",5344
"tempfile",5345
"thiserror 2.0.21",5346
"tokio",5347
"tokio-util",5348
"toml_edit 0.22.27",5349
"uuid",5350
]5351
5230
[[package]]5352
[[package]]5231
name = "md-5"5353
name = "md-5"5232
version = "0.10.6"5354
version = "0.10.6"@@ -6927,6 +7049,7 @@ version = "0.11.19"6927
source = "registry+https://github.com/rust-lang/crates.io-index"7049
source = "registry+https://github.com/rust-lang/crates.io-index"6928
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"7050
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"6929
dependencies = [7051
dependencies = [7052
"aws-lc-rs",6930
"bytes",7053
"bytes",6931
"getrandom 0.4.3",7054
"getrandom 0.4.3",6932
"lru-slab",7055
"lru-slab",@@ -7350,6 +7473,46 @@ dependencies = [7350
"web-sys",7473
"web-sys",7351
]7474
]7352
7475
7476
[[package]]7477
name = "reqwest"7478
version = "0.13.5"7479
source = "registry+https://github.com/rust-lang/crates.io-index"7480
checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"7481
dependencies = [7482
"base64 0.23.1",7483
"bytes",7484
"futures-core",7485
"futures-util",7486
"http",7487
"http-body",7488
"http-body-util",7489
"hyper",7490
"hyper-rustls",7491
"hyper-util",7492
"js-sys",7493
"log",7494
"percent-encoding",7495
"pin-project-lite",7496
"quinn",7497
"rustls",7498
"rustls-pki-types",7499
"rustls-platform-verifier",7500
"serde",7501
"serde_json",7502
"sync_wrapper",7503
"tokio",7504
"tokio-rustls",7505
"tokio-util",7506
"tower",7507
"tower-http",7508
"tower-service",7509
"url",7510
"wasm-bindgen",7511
"wasm-bindgen-futures",7512
"wasm-streams 0.5.0",7513
"web-sys",7514
]7515
7353
[[package]]7516
[[package]]7354
name = "resvg"7517
name = "resvg"7355
version = "0.45.1"7518
version = "0.45.1"@@ -7407,6 +7570,52 @@ dependencies = [7407
"windows-sys 0.52.0",7570
"windows-sys 0.52.0",7408
]7571
]7409
7572
7573
[[package]]7574
name = "rmcp"7575
version = "3.5.1"7576
source = "registry+https://github.com/rust-lang/crates.io-index"7577
checksum = "ab5023804cbe0304cbe06197ac16e645a0a0d0ffa2953bf735c15c2fa0213350"7578
dependencies = [7579
"async-trait",7580
"base64 0.23.1",7581
"bytes",7582
"chrono",7583
"futures",7584
"http",7585
"http-body",7586
"http-body-util",7587
"indexmap",7588
"pastey 0.2.3",7589
"pin-project-lite",7590
"rand 0.10.3",7591
"reqwest 0.13.5",7592
"rmcp-macros",7593
"schemars",7594
"serde",7595
"serde_json",7596
"sse-stream",7597
"thiserror 2.0.21",7598
"tokio",7599
"tokio-stream",7600
"tokio-util",7601
"tower-service",7602
"tracing",7603
"uuid",7604
]7605
7606
[[package]]7607
name = "rmcp-macros"7608
version = "3.5.1"7609
source = "registry+https://github.com/rust-lang/crates.io-index"7610
checksum = "a1da498700030856ba63114bceefa30ba21f5e278cb975e5b9de3529fe842b40"7611
dependencies = [7612
"darling",7613
"proc-macro2",7614
"quote",7615
"serde_json",7616
"syn 3.0.6",7617
]7618
7410
[[package]]7619
[[package]]7411
name = "rodio"7620
name = "rodio"7412
version = "0.22.2"7621
version = "0.22.2"@@ -7768,6 +7977,7 @@ version = "1.2.2"7768
source = "registry+https://github.com/rust-lang/crates.io-index"7977
source = "registry+https://github.com/rust-lang/crates.io-index"7769
checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"7978
checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"7770
dependencies = [7979
dependencies = [7980
"chrono",7771
"dyn-clone",7981
"dyn-clone",7772
"indexmap",7982
"indexmap",7773
"ref-cast",7983
"ref-cast",@@ -8291,6 +8501,19 @@ dependencies = [8291
"bitflags 2.13.2",8501
"bitflags 2.13.2",8292
]8502
]8293
8503
8504
[[package]]8505
name = "sse-stream"8506
version = "0.2.6"8507
source = "registry+https://github.com/rust-lang/crates.io-index"8508
checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4"8509
dependencies = [8510
"bytes",8511
"futures-util",8512
"http-body",8513
"http-body-util",8514
"pin-project-lite",8515
]8516
8294
[[package]]8517
[[package]]8295
name = "stable_deref_trait"8518
name = "stable_deref_trait"8296
version = "1.2.1"8519
version = "1.2.1"@@ -9920,6 +10143,19 @@ dependencies = [9920
"web-sys",10143
"web-sys",9921
]10144
]9922
10145
10146
[[package]]10147
name = "wasm-streams"10148
version = "0.5.0"10149
source = "registry+https://github.com/rust-lang/crates.io-index"10150
checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"10151
dependencies = [10152
"futures-util",10153
"js-sys",10154
"wasm-bindgen",10155
"wasm-bindgen-futures",10156
"web-sys",10157
]10158
9923
[[package]]10159
[[package]]9924
name = "wasm_thread"10160
name = "wasm_thread"9925
version = "0.3.3"10161
version = "0.3.3"@@ -10093,7 +10329,7 @@ dependencies = [10093
"anyhow",10329
"anyhow",10094
"fs2",10330
"fs2",10095
"regex",10331
"regex",10096
"reqwest",10332
"reqwest 0.12.28",10097
"scratch",10333
"scratch",10098
"semver",10334
"semver",10099
"zip",10335
"zip",@@ -31,6 +31,7 @@ uuid = { version = "1", default-features = false, features = ["v4"] }
31
31
session = { path = "crates/session" }
32
32
graph = { path = "crates/graph" }
33
33
store = { path = "crates/store" }
34
mcp = { path = "crates/mcp" }
34
35
teams-core = { path = "crates/core" }
35
36
gpui-kit = "=0.7.1"
36
37
reqwest_client = { package = "gpui-pre-reqwest-client", version = "=0.3.8" }
@@ -31,6 +31,7 @@ uuid = { version = "1", default-features = false, features = ["v4"] }31
session = { path = "crates/session" }31
session = { path = "crates/session" }32
graph = { path = "crates/graph" }32
graph = { path = "crates/graph" }33
store = { path = "crates/store" }33
store = { path = "crates/store" }34
mcp = { path = "crates/mcp" }34
teams-core = { path = "crates/core" }35
teams-core = { path = "crates/core" }35
gpui-kit = "=0.7.1"36
gpui-kit = "=0.7.1"36
reqwest_client = { package = "gpui-pre-reqwest-client", version = "=0.3.8" }37
reqwest_client = { package = "gpui-pre-reqwest-client", version = "=0.3.8" }@@ -26,6 +26,7 @@ gpui-kit.workspace = true
26
26
regex.workspace = true
27
27
reqwest_client.workspace = true
28
28
graph.workspace = true
29
mcp.workspace = true
29
30
serde.workspace = true
30
31
serde_json.workspace = true
31
32
session.workspace = true
@@ -26,6 +26,7 @@ gpui-kit.workspace = true26
regex.workspace = true26
regex.workspace = true27
reqwest_client.workspace = true27
reqwest_client.workspace = true28
graph.workspace = true28
graph.workspace = true29
mcp.workspace = true29
serde.workspace = true30
serde.workspace = true30
serde_json.workspace = true31
serde_json.workspace = true31
session.workspace = true32
session.workspace = true@@ -0,0 +1,107 @@
1
use std::collections::HashMap;
2
use std::sync::Arc;
3
4
use chrono::{DateTime, Local, Utc};
5
use gpui_kit::*;
6
use mcp::{AgentHub, UiEvent};
7
use teams_core::CoreEvent;
8
use tokio::sync::mpsc::UnboundedReceiver;
9
10
use super::source::AppSource;
11
use super::{AgentApi, ProposalEntry, ProposalStatus};
12
use crate::backend::Engine;
13
use crate::runtime;
14
15
const PREVIEW_CHARACTERS: usize = 200;
16
const NEW_MESSAGE_BATCH: usize = 50;
17
18
pub fn drain_ui_events(
19
mut receiver: UnboundedReceiver<UiEvent>,
20
api: WeakEntity<AgentApi>,
21
cx: &mut App,
22
) {
23
cx.spawn(async move |cx| {
24
while let Some(event) = receiver.recv().await {
25
if api
26
.update(cx, |api, cx| api.apply_ui_event(event, cx))
27
.is_err()
28
{
29
return;
30
}
31
}
32
})
33
.detach();
34
}
35
36
pub fn apply(proposals: &mut HashMap<String, ProposalEntry>, event: UiEvent) {
37
match event {
38
UiEvent::ProposalChanged(proposal) => {
39
proposals.insert(
40
proposal.conversation_id.clone(),
41
ProposalEntry {
42
proposal,
43
status: ProposalStatus::Pending,
44
},
45
);
46
}
47
UiEvent::ProposalStale(proposal) => {
48
proposals.insert(
49
proposal.conversation_id.clone(),
50
ProposalEntry {
51
proposal,
52
status: ProposalStatus::Stale {
53
answered_at: Local::now(),
54
},
55
},
56
);
57
}
58
UiEvent::ProposalRemoved { conversation_id } => {
59
proposals.remove(&conversation_id);
60
}
61
}
62
}
63
64
pub fn spawn_message_bridge(engine: Arc<Engine>, hub: Arc<AgentHub>, source: Arc<AppSource>) {
65
let started_at = Utc::now();
66
drop(runtime::spawn(async move {
67
let mut receiver = engine.subscribe();
68
let mut watermarks: HashMap<String, DateTime<Utc>> = HashMap::new();
69
loop {
70
let conversation_id = match receiver.recv().await {
71
Ok(CoreEvent::MessagesChanged { conversation_id }) => conversation_id,
72
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
73
Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
74
};
75
let Ok(store) = mcp::TeamsSource::store(source.as_ref()) else {
76
continue;
77
};
78
let watermark = watermarks
79
.entry(conversation_id.clone())
80
.or_insert(started_at);
81
let Ok(messages) =
82
store.messages_after(&conversation_id, *watermark, NEW_MESSAGE_BATCH)
83
else {
84
continue;
85
};
86
let my_id = mcp::TeamsSource::me_id(source.as_ref());
87
for message in messages {
88
*watermark = (*watermark).max(message.created_at);
89
if message.deleted {
90
continue;
91
}
92
let sender_is_me = my_id.is_some() && message.sender_id == my_id;
93
let preview: String = store::plain_text(&message.body_html)
94
.chars()
95
.take(PREVIEW_CHARACTERS)
96
.collect();
97
hub.message_arrived(
98
&conversation_id,
99
&message.message_id,
100
sender_is_me,
101
message.sender_name,
102
&preview,
103
);
104
}
105
}
106
}));
107
}
@@ -0,0 +1,107 @@1
use std::collections::HashMap;2
use std::sync::Arc;3
4
use chrono::{DateTime, Local, Utc};5
use gpui_kit::*;6
use mcp::{AgentHub, UiEvent};7
use teams_core::CoreEvent;8
use tokio::sync::mpsc::UnboundedReceiver;9
10
use super::source::AppSource;11
use super::{AgentApi, ProposalEntry, ProposalStatus};12
use crate::backend::Engine;13
use crate::runtime;14
15
const PREVIEW_CHARACTERS: usize = 200;16
const NEW_MESSAGE_BATCH: usize = 50;17
18
pub fn drain_ui_events(19
mut receiver: UnboundedReceiver<UiEvent>,20
api: WeakEntity<AgentApi>,21
cx: &mut App,22
) {23
cx.spawn(async move |cx| {24
while let Some(event) = receiver.recv().await {25
if api26
.update(cx, |api, cx| api.apply_ui_event(event, cx))27
.is_err()28
{29
return;30
}31
}32
})33
.detach();34
}35
36
pub fn apply(proposals: &mut HashMap<String, ProposalEntry>, event: UiEvent) {37
match event {38
UiEvent::ProposalChanged(proposal) => {39
proposals.insert(40
proposal.conversation_id.clone(),41
ProposalEntry {42
proposal,43
status: ProposalStatus::Pending,44
},45
);46
}47
UiEvent::ProposalStale(proposal) => {48
proposals.insert(49
proposal.conversation_id.clone(),50
ProposalEntry {51
proposal,52
status: ProposalStatus::Stale {53
answered_at: Local::now(),54
},55
},56
);57
}58
UiEvent::ProposalRemoved { conversation_id } => {59
proposals.remove(&conversation_id);60
}61
}62
}63
64
pub fn spawn_message_bridge(engine: Arc<Engine>, hub: Arc<AgentHub>, source: Arc<AppSource>) {65
let started_at = Utc::now();66
drop(runtime::spawn(async move {67
let mut receiver = engine.subscribe();68
let mut watermarks: HashMap<String, DateTime<Utc>> = HashMap::new();69
loop {70
let conversation_id = match receiver.recv().await {71
Ok(CoreEvent::MessagesChanged { conversation_id }) => conversation_id,72
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,73
Err(tokio::sync::broadcast::error::RecvError::Closed) => return,74
};75
let Ok(store) = mcp::TeamsSource::store(source.as_ref()) else {76
continue;77
};78
let watermark = watermarks79
.entry(conversation_id.clone())80
.or_insert(started_at);81
let Ok(messages) =82
store.messages_after(&conversation_id, *watermark, NEW_MESSAGE_BATCH)83
else {84
continue;85
};86
let my_id = mcp::TeamsSource::me_id(source.as_ref());87
for message in messages {88
*watermark = (*watermark).max(message.created_at);89
if message.deleted {90
continue;91
}92
let sender_is_me = my_id.is_some() && message.sender_id == my_id;93
let preview: String = store::plain_text(&message.body_html)94
.chars()95
.take(PREVIEW_CHARACTERS)96
.collect();97
hub.message_arrived(98
&conversation_id,99
&message.message_id,100
sender_is_me,101
message.sender_name,102
&preview,103
);104
}105
}106
}));107
}@@ -0,0 +1,416 @@
1
mod bridge;
2
mod source;
3
4
use std::collections::{BTreeSet, HashMap};
5
use std::sync::Arc;
6
7
use chrono::{DateTime, Local};
8
use gpui_kit::*;
9
use mcp::{Access, AgentHub, AgentPolicy, McpEndpoint, Outcome, Proposal, ServerHandle};
10
use store::Store;
11
12
use crate::backend::Engine;
13
use crate::runtime;
14
use source::AppSource;
15
16
#[derive(Debug, Clone, PartialEq)]
17
pub enum ProposalStatus {
18
Pending,
19
Stale { answered_at: DateTime<Local> },
20
Failed { reason: String },
21
}
22
23
#[derive(Debug, Clone, PartialEq)]
24
pub struct ProposalEntry {
25
pub proposal: Proposal,
26
pub status: ProposalStatus,
27
}
28
29
#[derive(Debug, Clone, PartialEq, Eq)]
30
pub enum ServerStatus {
31
Off,
32
Starting,
33
Running(u16),
34
PortInUse(u16),
35
Failed(String),
36
}
37
38
pub struct AgentApi {
39
hub: Arc<AgentHub>,
40
source: Arc<AppSource>,
41
store: Arc<Store>,
42
token: String,
43
proposals: HashMap<String, ProposalEntry>,
44
server: Option<ServerHandle>,
45
status: ServerStatus,
46
generation: u64,
47
reinstall_note: Option<String>,
48
}
49
50
struct AgentApiHandle(Entity<AgentApi>);
51
52
impl Global for AgentApiHandle {}
53
54
const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";
55
56
pub fn endpoint_url(port: u16) -> String {
57
format!("http://127.0.0.1:{port}/mcp")
58
}
59
60
pub fn agent_label(agent: Option<&str>) -> &'static str {
61
match agent.map(str::to_ascii_lowercase).as_deref() {
62
Some("claude") => "Claude",
63
Some("copilot") => "Copilot",
64
Some("codex") => "Codex",
65
_ => "Agent",
66
}
67
}
68
69
pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
70
let (ui, receiver) = tokio::sync::mpsc::unbounded_channel();
71
let mut policy = mcp::load_policy(&store);
72
if demo
73
&& let Some(port) = std::env::var(DEMO_PORT_ENV)
74
.ok()
75
.and_then(|value| value.parse().ok())
76
{
77
policy.port = port;
78
}
79
let hub = AgentHub::new(store.clone(), policy, ui);
80
let token = mcp::load_or_create_token(&store).unwrap_or_default();
81
if demo {
82
println!("mcp: {} token={token}", endpoint_url(hub.policy().port));
83
}
84
let source = Arc::new(AppSource::new(store.clone()));
85
let api = cx.new(|_| AgentApi {
86
hub,
87
source,
88
store,
89
token,
90
proposals: HashMap::new(),
91
server: None,
92
status: ServerStatus::Off,
93
generation: 0,
94
reinstall_note: None,
95
});
96
bridge::drain_ui_events(receiver, api.downgrade(), cx);
97
api.update(cx, |api, cx| {
98
let _ = api.hub.restore_pending();
99
api.reconcile(cx);
100
});
101
cx.set_global(AgentApiHandle(api));
102
}
103
104
pub fn engine_ready(engine: Arc<Engine>, cx: &mut App) {
105
let Some(api) = handle(cx) else {
106
return;
107
};
108
let api = api.read(cx);
109
if api.source.set_engine(engine.clone()) {
110
bridge::spawn_message_bridge(engine, api.hub.clone(), api.source.clone());
111
}
112
}
113
114
pub fn handle(cx: &App) -> Option<Entity<AgentApi>> {
115
cx.try_global::<AgentApiHandle>()
116
.map(|handle| handle.0.clone())
117
}
118
119
pub fn mcp_endpoint(cx: &App) -> Option<McpEndpoint> {
120
let api = handle(cx)?.read(cx);
121
match api.status {
122
ServerStatus::Running(port) => Some(McpEndpoint {
123
url: endpoint_url(port),
124
token: api.token.clone(),
125
}),
126
_ => None,
127
}
128
}
129
130
pub fn configured_endpoint(cx: &App) -> Option<McpEndpoint> {
131
let api = handle(cx)?.read(cx);
132
Some(McpEndpoint {
133
url: endpoint_url(api.hub.policy().port),
134
token: api.token.clone(),
135
})
136
}
137
138
pub fn policy(cx: &App) -> AgentPolicy {
139
handle(cx)
140
.map(|api| api.read(cx).hub.policy())
141
.unwrap_or_default()
142
}
143
144
pub fn chat_allowed(conversation_id: &str, cx: &App) -> bool {
145
let Some(api) = handle(cx) else {
146
return false;
147
};
148
let api = api.read(cx);
149
let policy = api.hub.policy();
150
policy.propose && policy.can_read_any_kind(conversation_id)
151
}
152
153
pub fn allow_chat(conversation_id: &str, cx: &mut App) {
154
let Some(api) = handle(cx) else {
155
return;
156
};
157
let conversation_id = conversation_id.to_owned();
158
api.update(cx, |api, cx| {
159
let is_channel = api.store.channel(&conversation_id).ok().flatten().is_some();
160
api.update_policy(
161
move |policy| {
162
policy.enabled = true;
163
policy.propose = true;
164
let access = if is_channel {
165
&mut policy.channels
166
} else {
167
&mut policy.chats
168
};
169
match access {
170
Access::All => {}
171
Access::Selected(ids) => {
172
ids.insert(conversation_id);
173
}
174
Access::None => *access = Access::Selected(BTreeSet::from([conversation_id])),
175
}
176
},
177
cx,
178
);
179
});
180
}
181
182
pub fn update_policy(cx: &mut App, change: impl FnOnce(&mut AgentPolicy)) {
183
if let Some(api) = handle(cx) {
184
api.update(cx, |api, cx| api.update_policy(change, cx));
185
}
186
}
187
188
pub fn proposal(conversation_id: &str, cx: &App) -> Option<ProposalEntry> {
189
handle(cx)?.read(cx).proposals.get(conversation_id).cloned()
190
}
191
192
pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
193
let Some(api) = handle(cx) else {
194
return HashMap::new();
195
};
196
api.read(cx)
197
.proposals
198
.iter()
199
.filter(|(_, entry)| !matches!(entry.status, ProposalStatus::Stale { .. }))
200
.map(|(conversation_id, entry)| {
201
(
202
conversation_id.clone(),
203
agent_label(entry.proposal.agent.as_deref()),
204
)
205
})
206
.collect()
207
}
208
209
pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {
210
if let Some(api) = handle(cx) {
211
api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));
212
}
213
}
214
215
pub fn fail_proposal(conversation_id: &str, reason: String, cx: &mut App) {
216
if let Some(api) = handle(cx) {
217
api.update(cx, |api, cx| {
218
if let Some(entry) = api.proposals.get_mut(conversation_id) {
219
entry.status = ProposalStatus::Failed { reason };
220
cx.notify();
221
}
222
});
223
}
224
}
225
226
pub fn user_typing(conversation_id: &str, cx: &App) {
227
if let Some(api) = handle(cx) {
228
api.read(cx).hub.user_typing(conversation_id);
229
}
230
}
231
232
pub fn user_sent(conversation_id: &str, cx: &App) {
233
if let Some(api) = handle(cx) {
234
api.read(cx).hub.user_sent(conversation_id);
235
}
236
}
237
238
pub fn note_caption(meeting_chat_id: &str, caption_id: &str, speaker: &str, text: &str, cx: &App) {
239
let Some(api) = handle(cx) else {
240
return;
241
};
242
let hub = &api.read(cx).hub;
243
let policy = hub.policy();
244
if policy.enabled && policy.transcripts {
245
hub.push_caption(meeting_chat_id, caption_id, speaker, text);
246
}
247
}
248
249
pub fn clear_captions(meeting_chat_id: &str, cx: &App) {
250
if let Some(api) = handle(cx) {
251
api.read(cx).hub.clear_captions(meeting_chat_id);
252
}
253
}
254
255
impl AgentApi {
256
pub fn status(&self) -> &ServerStatus {
257
&self.status
258
}
259
260
pub fn token(&self) -> &str {
261
&self.token
262
}
263
264
pub fn regenerate_token(&mut self, cx: &mut Context<Self>) {
265
if let Ok(token) = mcp::regenerate_token(&self.store) {
266
self.token = token;
267
self.reinstall_agent_configs(cx);
268
if self.server.is_some() {
269
self.start_server(cx);
270
}
271
cx.notify();
272
}
273
}
274
275
pub fn reinstall_note(&self) -> Option<&str> {
276
self.reinstall_note.as_deref()
277
}
278
279
fn reinstall_agent_configs(&mut self, cx: &mut Context<Self>) {
280
let endpoint = McpEndpoint {
281
url: endpoint_url(self.hub.policy().port),
282
token: self.token.clone(),
283
};
284
let task = cx.background_spawn(async move {
285
mcp::install::reinstall_all(&endpoint, &mcp::install::Homes::detect())
286
});
287
cx.spawn(async move |this, cx| {
288
let results = task.await;
289
this.update(cx, |this, cx| {
290
this.reinstall_note = results.into_iter().find_map(|(target, result)| {
291
result
292
.err()
293
.map(|error| format!("Could not update {}: {error}", target.label()))
294
});
295
cx.notify();
296
})
297
.ok();
298
})
299
.detach();
300
}
301
302
pub fn update_policy(&mut self, change: impl FnOnce(&mut AgentPolicy), cx: &mut Context<Self>) {
303
let mut policy = self.hub.policy();
304
let previous_port = policy.port;
305
change(&mut policy);
306
let port_changed = policy.port != previous_port;
307
mcp::save_policy(&self.store, &policy);
308
self.hub.set_policy(policy);
309
self.reconcile(cx);
310
if port_changed {
311
self.reinstall_agent_configs(cx);
312
}
313
cx.notify();
314
}
315
316
fn apply_ui_event(&mut self, event: mcp::UiEvent, cx: &mut Context<Self>) {
317
bridge::apply(&mut self.proposals, event);
318
cx.notify();
319
}
320
321
fn resolve(&mut self, conversation_id: &str, outcome: Outcome, cx: &mut Context<Self>) {
322
let Some(entry) = self.proposals.remove(conversation_id) else {
323
return;
324
};
325
if !matches!(entry.status, ProposalStatus::Stale { .. }) {
326
self.hub.resolve(&entry.proposal.id, outcome);
327
}
328
cx.notify();
329
}
330
331
fn reconcile(&mut self, cx: &mut Context<Self>) {
332
let policy = self.hub.policy();
333
let wanted = policy.enabled;
334
match (wanted, &self.status) {
335
(false, ServerStatus::Off) => {}
336
(false, _) => self.stop_server(cx),
337
(true, ServerStatus::Running(port)) if *port == policy.port => {}
338
(true, _) => self.start_server(cx),
339
}
340
}
341
342
fn stop_server(&mut self, cx: &mut Context<Self>) {
343
self.generation += 1;
344
if let Some(server) = self.server.take() {
345
drop(runtime::spawn(server.shutdown()));
346
}
347
self.status = ServerStatus::Off;
348
cx.notify();
349
}
350
351
fn start_server(&mut self, cx: &mut Context<Self>) {
352
self.generation += 1;
353
let generation = self.generation;
354
let previous = self.server.take();
355
let (hub, source, token) = (self.hub.clone(), self.source.clone(), self.token.clone());
356
let port = self.hub.policy().port;
357
self.status = ServerStatus::Starting;
358
let receiver = runtime::spawn(async move {
359
if let Some(previous) = previous {
360
previous.shutdown().await;
361
}
362
mcp::start(hub, source, port, token).await
363
});
364
cx.spawn(async move |this, cx| {
365
let Ok(result) = receiver.await else {
366
return;
367
};
368
this.update(cx, |this, cx| {
369
this.finish_start(generation, port, result, cx)
370
})
371
.ok();
372
})
373
.detach();
374
cx.notify();
375
}
376
377
fn finish_start(
378
&mut self,
379
generation: u64,
380
port: u16,
381
result: Result<ServerHandle, mcp::ServerError>,
382
cx: &mut Context<Self>,
383
) {
384
if generation != self.generation {
385
if let Ok(server) = result {
386
drop(runtime::spawn(server.shutdown()));
387
}
388
return;
389
}
390
match result {
391
Ok(server) => {
392
self.server = Some(server);
393
self.status = ServerStatus::Running(port);
394
}
395
Err(mcp::ServerError::PortInUse { port }) => {
396
self.status = ServerStatus::PortInUse(port)
397
}
398
Err(error) => self.status = ServerStatus::Failed(error.to_string()),
399
}
400
cx.notify();
401
}
402
}
403
404
#[cfg(test)]
405
mod tests {
406
use super::agent_label;
407
408
#[test]
409
fn agent_labels_know_the_common_agents() {
410
assert_eq!(agent_label(Some("claude")), "Claude");
411
assert_eq!(agent_label(Some("Copilot")), "Copilot");
412
assert_eq!(agent_label(Some("codex")), "Codex");
413
assert_eq!(agent_label(Some("other")), "Agent");
414
assert_eq!(agent_label(None), "Agent");
415
}
416
}
@@ -0,0 +1,416 @@1
mod bridge;2
mod source;3
4
use std::collections::{BTreeSet, HashMap};5
use std::sync::Arc;6
7
use chrono::{DateTime, Local};8
use gpui_kit::*;9
use mcp::{Access, AgentHub, AgentPolicy, McpEndpoint, Outcome, Proposal, ServerHandle};10
use store::Store;11
12
use crate::backend::Engine;13
use crate::runtime;14
use source::AppSource;15
16
#[derive(Debug, Clone, PartialEq)]17
pub enum ProposalStatus {18
Pending,19
Stale { answered_at: DateTime<Local> },20
Failed { reason: String },21
}22
23
#[derive(Debug, Clone, PartialEq)]24
pub struct ProposalEntry {25
pub proposal: Proposal,26
pub status: ProposalStatus,27
}28
29
#[derive(Debug, Clone, PartialEq, Eq)]30
pub enum ServerStatus {31
Off,32
Starting,33
Running(u16),34
PortInUse(u16),35
Failed(String),36
}37
38
pub struct AgentApi {39
hub: Arc<AgentHub>,40
source: Arc<AppSource>,41
store: Arc<Store>,42
token: String,43
proposals: HashMap<String, ProposalEntry>,44
server: Option<ServerHandle>,45
status: ServerStatus,46
generation: u64,47
reinstall_note: Option<String>,48
}49
50
struct AgentApiHandle(Entity<AgentApi>);51
52
impl Global for AgentApiHandle {}53
54
const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";55
56
pub fn endpoint_url(port: u16) -> String {57
format!("http://127.0.0.1:{port}/mcp")58
}59
60
pub fn agent_label(agent: Option<&str>) -> &'static str {61
match agent.map(str::to_ascii_lowercase).as_deref() {62
Some("claude") => "Claude",63
Some("copilot") => "Copilot",64
Some("codex") => "Codex",65
_ => "Agent",66
}67
}68
69
pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {70
let (ui, receiver) = tokio::sync::mpsc::unbounded_channel();71
let mut policy = mcp::load_policy(&store);72
if demo73
&& let Some(port) = std::env::var(DEMO_PORT_ENV)74
.ok()75
.and_then(|value| value.parse().ok())76
{77
policy.port = port;78
}79
let hub = AgentHub::new(store.clone(), policy, ui);80
let token = mcp::load_or_create_token(&store).unwrap_or_default();81
if demo {82
println!("mcp: {} token={token}", endpoint_url(hub.policy().port));83
}84
let source = Arc::new(AppSource::new(store.clone()));85
let api = cx.new(|_| AgentApi {86
hub,87
source,88
store,89
token,90
proposals: HashMap::new(),91
server: None,92
status: ServerStatus::Off,93
generation: 0,94
reinstall_note: None,95
});96
bridge::drain_ui_events(receiver, api.downgrade(), cx);97
api.update(cx, |api, cx| {98
let _ = api.hub.restore_pending();99
api.reconcile(cx);100
});101
cx.set_global(AgentApiHandle(api));102
}103
104
pub fn engine_ready(engine: Arc<Engine>, cx: &mut App) {105
let Some(api) = handle(cx) else {106
return;107
};108
let api = api.read(cx);109
if api.source.set_engine(engine.clone()) {110
bridge::spawn_message_bridge(engine, api.hub.clone(), api.source.clone());111
}112
}113
114
pub fn handle(cx: &App) -> Option<Entity<AgentApi>> {115
cx.try_global::<AgentApiHandle>()116
.map(|handle| handle.0.clone())117
}118
119
pub fn mcp_endpoint(cx: &App) -> Option<McpEndpoint> {120
let api = handle(cx)?.read(cx);121
match api.status {122
ServerStatus::Running(port) => Some(McpEndpoint {123
url: endpoint_url(port),124
token: api.token.clone(),125
}),126
_ => None,127
}128
}129
130
pub fn configured_endpoint(cx: &App) -> Option<McpEndpoint> {131
let api = handle(cx)?.read(cx);132
Some(McpEndpoint {133
url: endpoint_url(api.hub.policy().port),134
token: api.token.clone(),135
})136
}137
138
pub fn policy(cx: &App) -> AgentPolicy {139
handle(cx)140
.map(|api| api.read(cx).hub.policy())141
.unwrap_or_default()142
}143
144
pub fn chat_allowed(conversation_id: &str, cx: &App) -> bool {145
let Some(api) = handle(cx) else {146
return false;147
};148
let api = api.read(cx);149
let policy = api.hub.policy();150
policy.propose && policy.can_read_any_kind(conversation_id)151
}152
153
pub fn allow_chat(conversation_id: &str, cx: &mut App) {154
let Some(api) = handle(cx) else {155
return;156
};157
let conversation_id = conversation_id.to_owned();158
api.update(cx, |api, cx| {159
let is_channel = api.store.channel(&conversation_id).ok().flatten().is_some();160
api.update_policy(161
move |policy| {162
policy.enabled = true;163
policy.propose = true;164
let access = if is_channel {165
&mut policy.channels166
} else {167
&mut policy.chats168
};169
match access {170
Access::All => {}171
Access::Selected(ids) => {172
ids.insert(conversation_id);173
}174
Access::None => *access = Access::Selected(BTreeSet::from([conversation_id])),175
}176
},177
cx,178
);179
});180
}181
182
pub fn update_policy(cx: &mut App, change: impl FnOnce(&mut AgentPolicy)) {183
if let Some(api) = handle(cx) {184
api.update(cx, |api, cx| api.update_policy(change, cx));185
}186
}187
188
pub fn proposal(conversation_id: &str, cx: &App) -> Option<ProposalEntry> {189
handle(cx)?.read(cx).proposals.get(conversation_id).cloned()190
}191
192
pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {193
let Some(api) = handle(cx) else {194
return HashMap::new();195
};196
api.read(cx)197
.proposals198
.iter()199
.filter(|(_, entry)| !matches!(entry.status, ProposalStatus::Stale { .. }))200
.map(|(conversation_id, entry)| {201
(202
conversation_id.clone(),203
agent_label(entry.proposal.agent.as_deref()),204
)205
})206
.collect()207
}208
209
pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {210
if let Some(api) = handle(cx) {211
api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));212
}213
}214
215
pub fn fail_proposal(conversation_id: &str, reason: String, cx: &mut App) {216
if let Some(api) = handle(cx) {217
api.update(cx, |api, cx| {218
if let Some(entry) = api.proposals.get_mut(conversation_id) {219
entry.status = ProposalStatus::Failed { reason };220
cx.notify();221
}222
});223
}224
}225
226
pub fn user_typing(conversation_id: &str, cx: &App) {227
if let Some(api) = handle(cx) {228
api.read(cx).hub.user_typing(conversation_id);229
}230
}231
232
pub fn user_sent(conversation_id: &str, cx: &App) {233
if let Some(api) = handle(cx) {234
api.read(cx).hub.user_sent(conversation_id);235
}236
}237
238
pub fn note_caption(meeting_chat_id: &str, caption_id: &str, speaker: &str, text: &str, cx: &App) {239
let Some(api) = handle(cx) else {240
return;241
};242
let hub = &api.read(cx).hub;243
let policy = hub.policy();244
if policy.enabled && policy.transcripts {245
hub.push_caption(meeting_chat_id, caption_id, speaker, text);246
}247
}248
249
pub fn clear_captions(meeting_chat_id: &str, cx: &App) {250
if let Some(api) = handle(cx) {251
api.read(cx).hub.clear_captions(meeting_chat_id);252
}253
}254
255
impl AgentApi {256
pub fn status(&self) -> &ServerStatus {257
&self.status258
}259
260
pub fn token(&self) -> &str {261
&self.token262
}263
264
pub fn regenerate_token(&mut self, cx: &mut Context<Self>) {265
if let Ok(token) = mcp::regenerate_token(&self.store) {266
self.token = token;267
self.reinstall_agent_configs(cx);268
if self.server.is_some() {269
self.start_server(cx);270
}271
cx.notify();272
}273
}274
275
pub fn reinstall_note(&self) -> Option<&str> {276
self.reinstall_note.as_deref()277
}278
279
fn reinstall_agent_configs(&mut self, cx: &mut Context<Self>) {280
let endpoint = McpEndpoint {281
url: endpoint_url(self.hub.policy().port),282
token: self.token.clone(),283
};284
let task = cx.background_spawn(async move {285
mcp::install::reinstall_all(&endpoint, &mcp::install::Homes::detect())286
});287
cx.spawn(async move |this, cx| {288
let results = task.await;289
this.update(cx, |this, cx| {290
this.reinstall_note = results.into_iter().find_map(|(target, result)| {291
result292
.err()293
.map(|error| format!("Could not update {}: {error}", target.label()))294
});295
cx.notify();296
})297
.ok();298
})299
.detach();300
}301
302
pub fn update_policy(&mut self, change: impl FnOnce(&mut AgentPolicy), cx: &mut Context<Self>) {303
let mut policy = self.hub.policy();304
let previous_port = policy.port;305
change(&mut policy);306
let port_changed = policy.port != previous_port;307
mcp::save_policy(&self.store, &policy);308
self.hub.set_policy(policy);309
self.reconcile(cx);310
if port_changed {311
self.reinstall_agent_configs(cx);312
}313
cx.notify();314
}315
316
fn apply_ui_event(&mut self, event: mcp::UiEvent, cx: &mut Context<Self>) {317
bridge::apply(&mut self.proposals, event);318
cx.notify();319
}320
321
fn resolve(&mut self, conversation_id: &str, outcome: Outcome, cx: &mut Context<Self>) {322
let Some(entry) = self.proposals.remove(conversation_id) else {323
return;324
};325
if !matches!(entry.status, ProposalStatus::Stale { .. }) {326
self.hub.resolve(&entry.proposal.id, outcome);327
}328
cx.notify();329
}330
331
fn reconcile(&mut self, cx: &mut Context<Self>) {332
let policy = self.hub.policy();333
let wanted = policy.enabled;334
match (wanted, &self.status) {335
(false, ServerStatus::Off) => {}336
(false, _) => self.stop_server(cx),337
(true, ServerStatus::Running(port)) if *port == policy.port => {}338
(true, _) => self.start_server(cx),339
}340
}341
342
fn stop_server(&mut self, cx: &mut Context<Self>) {343
self.generation += 1;344
if let Some(server) = self.server.take() {345
drop(runtime::spawn(server.shutdown()));346
}347
self.status = ServerStatus::Off;348
cx.notify();349
}350
351
fn start_server(&mut self, cx: &mut Context<Self>) {352
self.generation += 1;353
let generation = self.generation;354
let previous = self.server.take();355
let (hub, source, token) = (self.hub.clone(), self.source.clone(), self.token.clone());356
let port = self.hub.policy().port;357
self.status = ServerStatus::Starting;358
let receiver = runtime::spawn(async move {359
if let Some(previous) = previous {360
previous.shutdown().await;361
}362
mcp::start(hub, source, port, token).await363
});364
cx.spawn(async move |this, cx| {365
let Ok(result) = receiver.await else {366
return;367
};368
this.update(cx, |this, cx| {369
this.finish_start(generation, port, result, cx)370
})371
.ok();372
})373
.detach();374
cx.notify();375
}376
377
fn finish_start(378
&mut self,379
generation: u64,380
port: u16,381
result: Result<ServerHandle, mcp::ServerError>,382
cx: &mut Context<Self>,383
) {384
if generation != self.generation {385
if let Ok(server) = result {386
drop(runtime::spawn(server.shutdown()));387
}388
return;389
}390
match result {391
Ok(server) => {392
self.server = Some(server);393
self.status = ServerStatus::Running(port);394
}395
Err(mcp::ServerError::PortInUse { port }) => {396
self.status = ServerStatus::PortInUse(port)397
}398
Err(error) => self.status = ServerStatus::Failed(error.to_string()),399
}400
cx.notify();401
}402
}403
404
#[cfg(test)]405
mod tests {406
use super::agent_label;407
408
#[test]409
fn agent_labels_know_the_common_agents() {410
assert_eq!(agent_label(Some("claude")), "Claude");411
assert_eq!(agent_label(Some("Copilot")), "Copilot");412
assert_eq!(agent_label(Some("codex")), "Codex");413
assert_eq!(agent_label(Some("other")), "Agent");414
assert_eq!(agent_label(None), "Agent");415
}416
}@@ -0,0 +1,87 @@
1
use std::sync::{Arc, OnceLock};
2
3
use chatsvc::{Calendar, Transcripts};
4
use chrono::{DateTime, Utc};
5
use mcp::{Meeting, SourceError, SourceFuture, TeamsSource, Transcript, TranscriptTurn};
6
use store::Store;
7
8
use crate::backend::Engine;
9
10
pub struct AppSource {
11
store: Arc<Store>,
12
engine: OnceLock<Arc<Engine>>,
13
}
14
15
impl AppSource {
16
pub fn new(store: Arc<Store>) -> Self {
17
AppSource {
18
store,
19
engine: OnceLock::new(),
20
}
21
}
22
23
pub fn set_engine(&self, engine: Arc<Engine>) -> bool {
24
self.engine.set(engine).is_ok()
25
}
26
27
fn engine(&self) -> Result<&Arc<Engine>, SourceError> {
28
self.engine.get().ok_or(SourceError::NotConnected)
29
}
30
}
31
32
impl TeamsSource for AppSource {
33
fn store(&self) -> Result<Arc<Store>, SourceError> {
34
Ok(self.store.clone())
35
}
36
37
fn me_id(&self) -> Option<String> {
38
crate::data::me(&self.store).map(|person| person.user_id)
39
}
40
41
fn calendar(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> SourceFuture<'_, Vec<Meeting>> {
42
Box::pin(async move {
43
let engine = self.engine()?;
44
let events = Calendar::new(engine.remote().session())
45
.calendar_view(start, end)
46
.await
47
.map_err(|error| SourceError::Failed(error.to_string()))?;
48
Ok(events
49
.into_iter()
50
.filter(|event| !event.cancelled)
51
.map(|event| Meeting {
52
title: event.subject,
53
start: event.start,
54
end: event.end,
55
all_day: event.all_day,
56
organizer: event.organizer_name,
57
join_url: event.join_url,
58
meeting_chat_id: event.thread_id,
59
})
60
.collect())
61
})
62
}
63
64
fn transcript<'a>(&'a self, meeting_chat_id: &'a str) -> SourceFuture<'a, Transcript> {
65
Box::pin(async move {
66
let engine = self.engine()?;
67
let transcript = Transcripts::new(engine.remote().session())
68
.for_meeting_chat(meeting_chat_id)
69
.await
70
.map_err(|error| SourceError::Failed(error.to_string()))?;
71
Ok(Transcript {
72
recording_name: transcript.recording_name,
73
created_at: transcript.created_at,
74
turns: transcript
75
.turns
76
.into_iter()
77
.map(|turn| TranscriptTurn {
78
speaker: turn.speaker,
79
start_seconds: turn.start_seconds,
80
end_seconds: turn.end_seconds,
81
text: turn.text,
82
})
83
.collect(),
84
})
85
})
86
}
87
}
@@ -0,0 +1,87 @@1
use std::sync::{Arc, OnceLock};2
3
use chatsvc::{Calendar, Transcripts};4
use chrono::{DateTime, Utc};5
use mcp::{Meeting, SourceError, SourceFuture, TeamsSource, Transcript, TranscriptTurn};6
use store::Store;7
8
use crate::backend::Engine;9
10
pub struct AppSource {11
store: Arc<Store>,12
engine: OnceLock<Arc<Engine>>,13
}14
15
impl AppSource {16
pub fn new(store: Arc<Store>) -> Self {17
AppSource {18
store,19
engine: OnceLock::new(),20
}21
}22
23
pub fn set_engine(&self, engine: Arc<Engine>) -> bool {24
self.engine.set(engine).is_ok()25
}26
27
fn engine(&self) -> Result<&Arc<Engine>, SourceError> {28
self.engine.get().ok_or(SourceError::NotConnected)29
}30
}31
32
impl TeamsSource for AppSource {33
fn store(&self) -> Result<Arc<Store>, SourceError> {34
Ok(self.store.clone())35
}36
37
fn me_id(&self) -> Option<String> {38
crate::data::me(&self.store).map(|person| person.user_id)39
}40
41
fn calendar(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> SourceFuture<'_, Vec<Meeting>> {42
Box::pin(async move {43
let engine = self.engine()?;44
let events = Calendar::new(engine.remote().session())45
.calendar_view(start, end)46
.await47
.map_err(|error| SourceError::Failed(error.to_string()))?;48
Ok(events49
.into_iter()50
.filter(|event| !event.cancelled)51
.map(|event| Meeting {52
title: event.subject,53
start: event.start,54
end: event.end,55
all_day: event.all_day,56
organizer: event.organizer_name,57
join_url: event.join_url,58
meeting_chat_id: event.thread_id,59
})60
.collect())61
})62
}63
64
fn transcript<'a>(&'a self, meeting_chat_id: &'a str) -> SourceFuture<'a, Transcript> {65
Box::pin(async move {66
let engine = self.engine()?;67
let transcript = Transcripts::new(engine.remote().session())68
.for_meeting_chat(meeting_chat_id)69
.await70
.map_err(|error| SourceError::Failed(error.to_string()))?;71
Ok(Transcript {72
recording_name: transcript.recording_name,73
created_at: transcript.created_at,74
turns: transcript75
.turns76
.into_iter()77
.map(|turn| TranscriptTurn {78
speaker: turn.speaker,79
start_seconds: turn.start_seconds,80
end_seconds: turn.end_seconds,81
text: turn.text,82
})83
.collect(),84
})85
})86
}87
}@@ -139,13 +139,7 @@ impl Global for AppHandle {}
139
139
impl EventEmitter<AppEvent> for AppState {}
140
140
141
141
pub fn chat_title(chat: &ChatRecord) -> String {
142
if !chat.title.trim().is_empty() {
143
chat.title.clone()
144
} else if !chat.member_summary.trim().is_empty() {
145
chat.member_summary.clone()
146
} else {
147
"Chat".to_owned()
148
}
142
chat.display_title()
149
143
}
150
144
151
145
pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
@@ -750,6 +744,7 @@ impl AppState {
750
744
BackendEvent::Ring(event) => self.on_engine_event(event, cx),
751
745
BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),
752
746
BackendEvent::Engine(engine) => {
747
crate::agent_api::engine_ready(engine.clone(), cx);
753
748
self.engine = Some(engine);
754
749
self.resend_outbox(cx);
755
750
self.refresh_scheduled(cx);
@@ -139,13 +139,7 @@ impl Global for AppHandle {}139
impl EventEmitter<AppEvent> for AppState {}139
impl EventEmitter<AppEvent> for AppState {}140
140
141
pub fn chat_title(chat: &ChatRecord) -> String {141
pub fn chat_title(chat: &ChatRecord) -> String {142
if !chat.title.trim().is_empty() {142
chat.display_title()143
chat.title.clone()144
} else if !chat.member_summary.trim().is_empty() {145
chat.member_summary.clone()146
} else {147
"Chat".to_owned()148
}149
}143
}150
144
151
pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {145
pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {@@ -750,6 +744,7 @@ impl AppState {750
BackendEvent::Ring(event) => self.on_engine_event(event, cx),744
BackendEvent::Ring(event) => self.on_engine_event(event, cx),751
BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),745
BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),752
BackendEvent::Engine(engine) => {746
BackendEvent::Engine(engine) => {747
crate::agent_api::engine_ready(engine.clone(), cx);753
self.engine = Some(engine);748
self.engine = Some(engine);754
self.resend_outbox(cx);749
self.resend_outbox(cx);755
self.refresh_scheduled(cx);750
self.refresh_scheduled(cx);@@ -258,6 +258,14 @@ impl AppState {
258
258
}
259
259
_ => {}
260
260
}
261
if let (CallUpdate::Caption(entry), Some(thread)) = (&update, call.chat_thread()) {
262
let speaker = if entry.display_name.is_empty() {
263
"Someone"
264
} else {
265
&entry.display_name
266
};
267
crate::agent_api::note_caption(thread, &entry.id, speaker, &entry.text, cx);
268
}
261
269
call.model.apply(update);
262
270
if call.model.screen_sharer.is_none() {
263
271
call.stage_fullscreen = false;
@@ -276,6 +284,9 @@ impl AppState {
276
284
let next_move = call.pending_move.take().or_else(|| room_closed_move(call, &reason));
277
285
let consult = call.consult.take();
278
286
call.pictures.clear(cx);
287
if let Some(thread) = call.chat_thread() {
288
crate::agent_api::clear_captions(thread, cx);
289
}
279
290
self.call = None;
280
291
if let Some(consult) = consult {
281
292
let _ = consult.commands.send(CallCommand::Hangup);
@@ -258,6 +258,14 @@ impl AppState {258
}258
}259
_ => {}259
_ => {}260
}260
}261
if let (CallUpdate::Caption(entry), Some(thread)) = (&update, call.chat_thread()) {262
let speaker = if entry.display_name.is_empty() {263
"Someone"264
} else {265
&entry.display_name266
};267
crate::agent_api::note_caption(thread, &entry.id, speaker, &entry.text, cx);268
}261
call.model.apply(update);269
call.model.apply(update);262
if call.model.screen_sharer.is_none() {270
if call.model.screen_sharer.is_none() {263
call.stage_fullscreen = false;271
call.stage_fullscreen = false;@@ -276,6 +284,9 @@ impl AppState {276
let next_move = call.pending_move.take().or_else(|| room_closed_move(call, &reason));284
let next_move = call.pending_move.take().or_else(|| room_closed_move(call, &reason));277
let consult = call.consult.take();285
let consult = call.consult.take();278
call.pictures.clear(cx);286
call.pictures.clear(cx);287
if let Some(thread) = call.chat_thread() {288
crate::agent_api::clear_captions(thread, cx);289
}279
self.call = None;290
self.call = None;280
if let Some(consult) = consult {291
if let Some(consult) = consult {281
let _ = consult.commands.send(CallCommand::Hangup);292
let _ = consult.commands.send(CallCommand::Hangup);@@ -771,6 +771,37 @@ pub fn seed(store: &Store) {
771
771
let _ = store.upsert_messages(&priority_messages());
772
772
let _ = store.upsert_messages(&meeting_link_messages());
773
773
let _ = store.upsert_messages(&bot_messages());
774
seed_agent_access(store);
775
}
776
777
const AGENT_DEMO_PROPOSAL: &str = "I ran the regression suite on staging: 412 passed, 0 failed. The release candidate is good to ship.";
778
779
fn seed_agent_access(store: &Store) {
780
let selected =
781
|ids: &[&str]| mcp::Access::Selected(ids.iter().map(|id| (*id).to_owned()).collect());
782
mcp::save_policy(
783
store,
784
&mcp::AgentPolicy {
785
enabled: true,
786
chats: selected(&[RELEASE_CHAT, "demo-chat-mara", "demo-chat-meeting-standup"]),
787
channels: selected(&["demo-channel-1-1"]),
788
propose: true,
789
calendar: true,
790
transcripts: false,
791
..mcp::AgentPolicy::default()
792
},
793
);
794
let _ = store.insert_agent_proposal(&store::AgentProposalRecord {
795
id: "demo-proposal".to_owned(),
796
conversation_id: RELEASE_CHAT.to_owned(),
797
reply_to_message_id: Some("m1".to_owned()),
798
text: AGENT_DEMO_PROPOSAL.to_owned(),
799
agent: Some("claude".to_owned()),
800
session_id: None,
801
created_at: Utc::now() - Duration::minutes(1),
802
state: "pending".to_owned(),
803
resolved_at: None,
804
});
774
805
}
775
806
776
807
fn photo(palette: &Palette) -> Arc<Image> {
@@ -771,6 +771,37 @@ pub fn seed(store: &Store) {771
let _ = store.upsert_messages(&priority_messages());771
let _ = store.upsert_messages(&priority_messages());772
let _ = store.upsert_messages(&meeting_link_messages());772
let _ = store.upsert_messages(&meeting_link_messages());773
let _ = store.upsert_messages(&bot_messages());773
let _ = store.upsert_messages(&bot_messages());774
seed_agent_access(store);775
}776
777
const AGENT_DEMO_PROPOSAL: &str = "I ran the regression suite on staging: 412 passed, 0 failed. The release candidate is good to ship.";778
779
fn seed_agent_access(store: &Store) {780
let selected =781
|ids: &[&str]| mcp::Access::Selected(ids.iter().map(|id| (*id).to_owned()).collect());782
mcp::save_policy(783
store,784
&mcp::AgentPolicy {785
enabled: true,786
chats: selected(&[RELEASE_CHAT, "demo-chat-mara", "demo-chat-meeting-standup"]),787
channels: selected(&["demo-channel-1-1"]),788
propose: true,789
calendar: true,790
transcripts: false,791
..mcp::AgentPolicy::default()792
},793
);794
let _ = store.insert_agent_proposal(&store::AgentProposalRecord {795
id: "demo-proposal".to_owned(),796
conversation_id: RELEASE_CHAT.to_owned(),797
reply_to_message_id: Some("m1".to_owned()),798
text: AGENT_DEMO_PROPOSAL.to_owned(),799
agent: Some("claude".to_owned()),800
session_id: None,801
created_at: Utc::now() - Duration::minutes(1),802
state: "pending".to_owned(),803
resolved_at: None,804
});774
}805
}775
806
776
fn photo(palette: &Palette) -> Arc<Image> {807
fn photo(palette: &Palette) -> Arc<Image> {@@ -4,6 +4,7 @@
4
4
)]
5
5
6
6
mod activity;
7
mod agent_api;
7
8
mod app_state;
8
9
mod assets;
9
10
mod avatar_image;
@@ -245,6 +246,7 @@ fn main() {
245
246
state
246
247
});
247
248
cx.set_global(app_state::AppHandle(state.clone()));
249
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
248
250
if arguments.demo {
249
251
state.update(cx, |state, cx| {
250
252
demo::seed_directory(state);
@@ -4,6 +4,7 @@4
)]4
)]5
5
6
mod activity;6
mod activity;7
mod agent_api;7
mod app_state;8
mod app_state;8
mod assets;9
mod assets;9
mod avatar_image;10
mod avatar_image;@@ -245,6 +246,7 @@ fn main() {245
state246
state246
});247
});247
cx.set_global(app_state::AppHandle(state.clone()));248
cx.set_global(app_state::AppHandle(state.clone()));249
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);248
if arguments.demo {250
if arguments.demo {249
state.update(cx, |state, cx| {251
state.update(cx, |state, cx| {250
demo::seed_directory(state);252
demo::seed_directory(state);@@ -857,8 +857,8 @@ impl NotificationCenter {
857
857
// open_window draws once right away, and SettingsView reads this entity while rendering.
858
858
cx.defer(move |cx| {
859
859
let view_center = center.clone();
860
let opened = gpui_kit::open_window(options, cx, move |_, cx| {
861
cx.new(|cx| SettingsView::new(view_center, cx))
860
let opened = gpui_kit::open_window(options, cx, move |window, cx| {
861
cx.new(|cx| SettingsView::new(view_center, window, cx))
862
862
});
863
863
center.update(cx, |this, _| {
864
864
this.settings_opening = false;
@@ -857,8 +857,8 @@ impl NotificationCenter {857
// open_window draws once right away, and SettingsView reads this entity while rendering.857
// open_window draws once right away, and SettingsView reads this entity while rendering.858
cx.defer(move |cx| {858
cx.defer(move |cx| {859
let view_center = center.clone();859
let view_center = center.clone();860
let opened = gpui_kit::open_window(options, cx, move |_, cx| {860
let opened = gpui_kit::open_window(options, cx, move |window, cx| {861
cx.new(|cx| SettingsView::new(view_center, cx))861
cx.new(|cx| SettingsView::new(view_center, window, cx))862
});862
});863
center.update(cx, |this, _| {863
center.update(cx, |this, _| {864
this.settings_opening = false;864
this.settings_opening = false;@@ -10,6 +10,7 @@ mod ring_tone;
10
10
mod ring_view;
11
11
mod rules;
12
12
mod settings;
13
mod settings_mcp;
13
14
mod settings_view;
14
15
mod stack;
15
16
mod text;
@@ -10,6 +10,7 @@ mod ring_tone;10
mod ring_view;10
mod ring_view;11
mod rules;11
mod rules;12
mod settings;12
mod settings;13
mod settings_mcp;13
mod settings_view;14
mod settings_view;14
mod stack;15
mod stack;15
mod text;16
mod text;@@ -0,0 +1,1096 @@
1
use std::collections::{BTreeSet, HashMap};
2
use std::time::Duration;
3
4
use gpui_kit::assets::IconName;
5
use gpui_kit::component::{
6
ActiveTheme as _, h_flex,
7
input::{Input, InputEvent, InputState},
8
v_flex,
9
};
10
use gpui_kit::prelude::FluentBuilder as _;
11
use gpui_kit::*;
12
use mcp::install::{Homes, InstallReport, InstallState, Location, Target};
13
use mcp::{Access, AgentPolicy};
14
15
use super::settings_view::{control_row, switch, titled_with};
16
use crate::agent_api::{self, ServerStatus};
17
use crate::app_state::AppState;
18
use crate::data::is_one_on_one;
19
use crate::fuzzy;
20
use crate::theme;
21
use crate::views::switcher::{Candidate, candidate_avatar, candidates_from};
22
use crate::views::widgets::icon;
23
24
const COPIED_SHOWN: Duration = Duration::from_millis(1500);
25
const PORT_WIDTH: f32 = 72.;
26
const FIELD_HEIGHT: f32 = 36.;
27
const SMALL_BUTTON_HEIGHT: f32 = 28.;
28
const PICKER_ROW_HEIGHT: f32 = 30.;
29
const PICKER_MAX_ROWS: usize = 6;
30
const PICKER_RESULTS: usize = 40;
31
const TOKEN_TAIL: usize = 4;
32
const CHIP_MAX_WIDTH: f32 = 180.;
33
const WSL_WARNING: &str = "WSL agents cannot reach 127.0.0.1 on Windows. Add networkingMode=mirrored to .wslconfig and run wsl --shutdown.";
34
35
#[derive(Clone, Copy, PartialEq, Eq)]
36
enum McpTab {
37
Server,
38
Access,
39
Install,
40
}
41
42
impl McpTab {
43
const ALL: [McpTab; 3] = [McpTab::Server, McpTab::Access, McpTab::Install];
44
45
fn label(self) -> &'static str {
46
match self {
47
McpTab::Server => "Server",
48
McpTab::Access => "Access",
49
McpTab::Install => "Install",
50
}
51
}
52
}
53
54
#[derive(Clone, Copy, PartialEq, Eq)]
55
enum Scope {
56
Chats,
57
Channels,
58
}
59
60
impl Scope {
61
fn access(self, policy: &AgentPolicy) -> &Access {
62
match self {
63
Scope::Chats => &policy.chats,
64
Scope::Channels => &policy.channels,
65
}
66
}
67
68
fn access_mut(self, policy: &mut AgentPolicy) -> &mut Access {
69
match self {
70
Scope::Chats => &mut policy.chats,
71
Scope::Channels => &mut policy.channels,
72
}
73
}
74
75
fn title(self) -> &'static str {
76
match self {
77
Scope::Chats => "Chats",
78
Scope::Channels => "Channels",
79
}
80
}
81
82
fn add_label(self) -> &'static str {
83
match self {
84
Scope::Chats => "+ Add chat",
85
Scope::Channels => "+ Add channel",
86
}
87
}
88
89
fn contains(self, candidate: &Candidate) -> bool {
90
use crate::app_state::Selection;
91
matches!(
92
(self, &candidate.selection),
93
(Scope::Chats, Selection::Chat(_)) | (Scope::Channels, Selection::Channel(_))
94
)
95
}
96
}
97
98
#[derive(Clone, Copy, PartialEq, Eq)]
99
enum Copied {
100
Url,
101
Token,
102
Manual,
103
}
104
105
#[derive(Clone, Copy, PartialEq, Eq)]
106
enum InstallAction {
107
Install,
108
Update,
109
Remove,
110
}
111
112
impl InstallAction {
113
fn label(self) -> &'static str {
114
match self {
115
InstallAction::Install => "Install",
116
InstallAction::Update => "Update",
117
InstallAction::Remove => "Remove",
118
}
119
}
120
121
fn busy_label(self) -> &'static str {
122
match self {
123
InstallAction::Install => "Installing...",
124
InstallAction::Update => "Updating...",
125
InstallAction::Remove => "Removing...",
126
}
127
}
128
}
129
130
fn target_logo(target: Target) -> &'static str {
131
match target {
132
Target::ClaudeCode => "CC",
133
Target::Codex => "CX",
134
Target::CopilotCli => "GH",
135
Target::VsCode => "VS",
136
Target::Cursor => "CU",
137
}
138
}
139
140
fn target_action(state: &InstallState) -> Option<InstallAction> {
141
if state.stale {
142
Some(InstallAction::Update)
143
} else if !state.installed_at.is_empty() {
144
Some(InstallAction::Remove)
145
} else if state.available {
146
Some(InstallAction::Install)
147
} else {
148
None
149
}
150
}
151
152
fn locations_label(locations: &[Location]) -> &'static str {
153
let windows = locations.contains(&Location::Windows);
154
let wsl = locations
155
.iter()
156
.any(|location| matches!(location, Location::Wsl { .. }));
157
match (windows, wsl) {
158
(true, true) => "Windows + WSL",
159
(true, false) => "Windows",
160
(false, true) => "WSL",
161
(false, false) => "Installed",
162
}
163
}
164
165
fn install_detail(target: Target, state: Option<&InstallState>) -> AnyElement {
166
let muted = |text: &'static str| {
167
div()
168
.text_size(px(12.))
169
.text_color(theme::text_muted())
170
.child(text)
171
.into_any_element()
172
};
173
let Some(state) = state else {
174
return muted(target.config_hint());
175
};
176
if state.stale {
177
return div()
178
.text_size(px(12.))
179
.text_color(theme::amber())
180
.child("Out of date - Update")
181
.into_any_element();
182
}
183
if !state.installed_at.is_empty() {
184
return h_flex()
185
.gap(px(6.))
186
.items_center()
187
.text_size(px(12.))
188
.text_color(theme::green())
189
.child(div().size(px(6.)).rounded_full().bg(theme::green()))
190
.child(locations_label(&state.installed_at))
191
.into_any_element();
192
}
193
if state.available {
194
muted(target.config_hint())
195
} else {
196
muted("Not installed")
197
}
198
}
199
200
fn wsl_warning() -> Div {
201
note_box(
202
h_flex()
203
.gap(px(8.))
204
.items_start()
205
.child(
206
div()
207
.font_weight(FontWeight::BOLD)
208
.text_color(theme::amber())
209
.child("!"),
210
)
211
.child(div().flex_1().child(WSL_WARNING)),
212
4.,
213
)
214
}
215
216
pub struct McpView {
217
app: Entity<AppState>,
218
tab: McpTab,
219
picker: Option<Scope>,
220
port_input: Entity<InputState>,
221
search_input: Entity<InputState>,
222
copied: Option<Copied>,
223
install_states: Option<Vec<InstallState>>,
224
install_busy: Option<(Target, InstallAction)>,
225
install_errors: HashMap<Target, String>,
226
wsl_unreachable: bool,
227
_subscriptions: Vec<Subscription>,
228
}
229
230
impl McpView {
231
pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
232
let port = agent_api::policy(cx).port;
233
let port_input = cx.new(|cx| InputState::new(window, cx));
234
port_input.update(cx, |input, cx| {
235
input.set_value(port.to_string(), window, cx)
236
});
237
let search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Search"));
238
let mut subscriptions = vec![
239
cx.subscribe_in(&port_input, window, Self::on_port_event),
240
cx.subscribe_in(&search_input, window, |_, _, event, _, cx| {
241
if matches!(event, InputEvent::Change) {
242
cx.notify();
243
}
244
}),
245
];
246
if let Some(api) = agent_api::handle(cx) {
247
subscriptions.push(cx.observe(&api, |_, _, cx| cx.notify()));
248
}
249
let mut view = McpView {
250
app,
251
tab: McpTab::Server,
252
picker: None,
253
port_input,
254
search_input,
255
copied: None,
256
install_states: None,
257
install_busy: None,
258
install_errors: HashMap::new(),
259
wsl_unreachable: false,
260
_subscriptions: subscriptions,
261
};
262
view.refresh_wsl(cx);
263
view
264
}
265
266
fn on_port_event(
267
&mut self,
268
input: &Entity<InputState>,
269
event: &InputEvent,
270
window: &mut Window,
271
cx: &mut Context<Self>,
272
) {
273
if !matches!(event, InputEvent::Blur | InputEvent::PressEnter { .. }) {
274
return;
275
}
276
let current = agent_api::policy(cx).port;
277
let typed = input.read(cx).value().trim().parse::<u16>().ok();
278
match typed.filter(|port| *port != 0) {
279
Some(port) if port != current => {
280
agent_api::update_policy(cx, |policy| policy.port = port)
281
}
282
Some(_) => {}
283
None => input.update(cx, |input, cx| {
284
input.set_value(current.to_string(), window, cx)
285
}),
286
}
287
self.refresh_wsl(cx);
288
}
289
290
fn refresh_wsl(&mut self, cx: &mut Context<Self>) {
291
let port = agent_api::policy(cx).port;
292
let task = cx.background_spawn(async move { mcp::install::wsl_reachable(port) });
293
cx.spawn(async move |this, cx| {
294
let reachable = task.await;
295
this.update(cx, |this, cx| {
296
this.wsl_unreachable = reachable == Some(false);
297
cx.notify();
298
})
299
.ok();
300
})
301
.detach();
302
}
303
304
fn refresh_installs(&mut self, cx: &mut Context<Self>) {
305
let Some(endpoint) = agent_api::configured_endpoint(cx) else {
306
return;
307
};
308
let task = cx.background_spawn(async move {
309
let homes = Homes::detect();
310
Target::ALL
311
.map(|target| mcp::install::status(target, &endpoint, &homes))
312
.to_vec()
313
});
314
cx.spawn(async move |this, cx| {
315
let states = task.await;
316
this.update(cx, |this, cx| {
317
this.install_states = Some(states);
318
cx.notify();
319
})
320
.ok();
321
})
322
.detach();
323
}
324
325
fn run_install_action(
326
&mut self,
327
target: Target,
328
action: InstallAction,
329
cx: &mut Context<Self>,
330
) {
331
let Some(endpoint) = agent_api::configured_endpoint(cx) else {
332
return;
333
};
334
self.install_busy = Some((target, action));
335
self.install_errors.remove(&target);
336
let task = cx.background_spawn(async move {
337
let homes = Homes::detect();
338
match action {
339
InstallAction::Remove => mcp::install::uninstall(target, &homes).map(|_| None),
340
_ => mcp::install::install(target, &endpoint, &homes).map(Some),
341
}
342
});
343
cx.spawn(async move |this, cx| {
344
let result = task.await;
345
this.update(cx, |this, cx| {
346
this.install_busy = None;
347
match result {
348
Ok(Some(InstallReport::OpenUrl(url))) => cx.open_url(&url),
349
Ok(_) => {}
350
Err(error) => {
351
this.install_errors.insert(target, error.to_string());
352
}
353
}
354
this.refresh_installs(cx);
355
cx.notify();
356
})
357
.ok();
358
})
359
.detach();
360
cx.notify();
361
}
362
363
fn select_tab(&mut self, tab: McpTab, cx: &mut Context<Self>) {
364
self.tab = tab;
365
self.picker = None;
366
match tab {
367
McpTab::Install => {
368
self.refresh_installs(cx);
369
self.refresh_wsl(cx);
370
}
371
McpTab::Server => self.refresh_wsl(cx),
372
McpTab::Access => {}
373
}
374
cx.notify();
375
}
376
377
fn copy(&mut self, target: Copied, text: String, cx: &mut Context<Self>) {
378
cx.write_to_clipboard(ClipboardItem::new_string(text));
379
self.copied = Some(target);
380
cx.spawn(async move |this, cx| {
381
cx.background_executor().timer(COPIED_SHOWN).await;
382
this.update(cx, |this, cx| {
383
this.copied = None;
384
cx.notify();
385
})
386
.ok();
387
})
388
.detach();
389
cx.notify();
390
}
391
392
fn open_picker(&mut self, scope: Scope, window: &mut Window, cx: &mut Context<Self>) {
393
self.picker = if self.picker == Some(scope) {
394
None
395
} else {
396
Some(scope)
397
};
398
self.search_input
399
.update(cx, |input, cx| input.set_value("", window, cx));
400
if self.picker.is_some() {
401
self.search_input
402
.update(cx, |input, cx| input.focus(window, cx));
403
}
404
cx.notify();
405
}
406
}
407
408
fn small_button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Stateful<Div> {
409
inert_button(id, label)
410
.cursor_pointer()
411
.text_color(theme::text())
412
.hover(|button| button.bg(theme::popup_hover()))
413
}
414
415
fn inert_button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Stateful<Div> {
416
div()
417
.id(id)
418
.h(px(SMALL_BUTTON_HEIGHT))
419
.px(px(12.))
420
.flex_none()
421
.flex()
422
.items_center()
423
.rounded(px(7.))
424
.bg(theme::surface_raised())
425
.text_size(px(12.))
426
.font_weight(FontWeight::SEMIBOLD)
427
.text_color(theme::text_faint())
428
.child(label.into())
429
}
430
431
fn caption(label: &'static str) -> Div {
432
div()
433
.px(px(20.))
434
.pt(px(16.))
435
.pb(px(4.))
436
.text_size(px(12.))
437
.font_weight(FontWeight::SEMIBOLD)
438
.text_color(theme::text_muted())
439
.child(label)
440
}
441
442
fn toggle_row(
443
id: &'static str,
444
title: &'static str,
445
detail: &'static str,
446
detail_color: Hsla,
447
on: bool,
448
) -> Stateful<Div> {
449
h_flex()
450
.id(id)
451
.w_full()
452
.px(px(20.))
453
.py(px(10.))
454
.gap(px(12.))
455
.items_center()
456
.cursor_pointer()
457
.hover(|row| row.bg(theme::row_hover()))
458
.child(titled_with(title, detail, detail_color))
459
.child(switch(on))
460
}
461
462
fn note_box(content: impl IntoElement, margin_top: f32) -> Div {
463
h_flex()
464
.mx(px(20.))
465
.mt(px(margin_top))
466
.mb(px(12.))
467
.px(px(12.))
468
.py(px(10.))
469
.gap(px(8.))
470
.rounded(px(8.))
471
.bg(theme::row_hover())
472
.text_size(px(12.))
473
.text_color(theme::text_muted())
474
.child(content)
475
}
476
477
fn masked_token(token: &str) -> String {
478
let tail: String = token
479
.chars()
480
.rev()
481
.take(TOKEN_TAIL)
482
.collect::<Vec<_>>()
483
.into_iter()
484
.rev()
485
.collect();
486
format!("****...{tail}")
487
}
488
489
fn chat_kind_label(state: &AppState, conversation_id: &str) -> Option<&'static str> {
490
let chat = state
491
.sidebar
492
.chats
493
.iter()
494
.find(|chat| chat.id == conversation_id)?;
495
Some(if chat.kind.eq_ignore_ascii_case("meeting") {
496
"Meeting"
497
} else if is_one_on_one(chat) {
498
"Chat"
499
} else {
500
"Group"
501
})
502
}
503
504
impl Render for McpView {
505
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
506
let view = cx.entity();
507
let tabs = h_flex()
508
.mx(px(20.))
509
.mt(px(12.))
510
.mb(px(4.))
511
.p(px(2.))
512
.rounded(px(8.))
513
.bg(theme::surface())
514
.children(McpTab::ALL.map(|tab| {
515
let active = tab == self.tab;
516
let view = view.clone();
517
div()
518
.id(tab.label())
519
.flex_1()
520
.h(px(SMALL_BUTTON_HEIGHT))
521
.flex()
522
.items_center()
523
.justify_center()
524
.rounded(px(6.))
525
.cursor_pointer()
526
.text_size(px(12.))
527
.font_weight(FontWeight::SEMIBOLD)
528
.text_color(if active {
529
theme::text()
530
} else {
531
theme::text_muted()
532
})
533
.when(active, |tab| tab.bg(theme::surface_raised()))
534
.child(tab.label())
535
.on_click(move |_, _, cx| view.update(cx, |view, cx| view.select_tab(tab, cx)))
536
}));
537
let body = match self.tab {
538
McpTab::Server => self.server_tab(cx).into_any_element(),
539
McpTab::Access => self.access_tab(cx).into_any_element(),
540
McpTab::Install => self.install_tab(cx).into_any_element(),
541
};
542
v_flex().w_full().flex_1().min_h_0().child(tabs).child(
543
div()
544
.id("mcp-body")
545
.w_full()
546
.flex_1()
547
.min_h_0()
548
.overflow_y_scroll()
549
.child(body),
550
)
551
}
552
}
553
554
impl McpView {
555
fn field_row(
556
&self,
557
label: &'static str,
558
value: String,
559
buttons: Vec<AnyElement>,
560
cx: &App,
561
) -> Div {
562
v_flex()
563
.w_full()
564
.px(px(20.))
565
.pb(px(8.))
566
.gap(px(4.))
567
.child(
568
div()
569
.text_size(px(11.))
570
.text_color(theme::text_faint())
571
.child(label),
572
)
573
.child(
574
h_flex()
575
.w_full()
576
.gap(px(8.))
577
.items_center()
578
.child(
579
div()
580
.flex_1()
581
.min_w_0()
582
.h(px(FIELD_HEIGHT))
583
.px(px(12.))
584
.flex()
585
.items_center()
586
.rounded(px(8.))
587
.bg(theme::surface())
588
.font_family(cx.theme().mono_font_family.clone())
589
.text_size(px(12.))
590
.text_color(theme::text_soft())
591
.child(div().truncate().child(value)),
592
)
593
.children(buttons),
594
)
595
}
596
597
fn copy_button(
598
&self,
599
id: &'static str,
600
target: Copied,
601
text: String,
602
cx: &mut Context<Self>,
603
) -> AnyElement {
604
let label = if self.copied == Some(target) {
605
"Copied"
606
} else {
607
"Copy"
608
};
609
small_button(id, label)
610
.on_click(cx.listener(move |this, _, _, cx| this.copy(target, text.clone(), cx)))
611
.into_any_element()
612
}
613
614
fn server_tab(&self, cx: &mut Context<Self>) -> Div {
615
let policy = agent_api::policy(cx);
616
let (status, token) = match agent_api::handle(cx) {
617
Some(api) => {
618
let api = api.read(cx);
619
(api.status().clone(), api.token().to_owned())
620
}
621
None => (ServerStatus::Off, String::new()),
622
};
623
let failed = matches!(status, ServerStatus::PortInUse(_) | ServerStatus::Failed(_));
624
let (detail, detail_color) = match (policy.enabled, failed) {
625
(false, _) => ("Off - agents cannot reach Rusty Teams", theme::text_muted()),
626
(true, true) => ("Could not start", theme::red_soft()),
627
(true, false) => (
628
"Agents on this computer can read and propose",
629
theme::text_muted(),
630
),
631
};
632
let enabled = policy.enabled;
633
let running = matches!(status, ServerStatus::Running(_));
634
let reinstall_note =
635
agent_api::handle(cx).and_then(|api| api.read(cx).reinstall_note().map(str::to_owned));
636
let warning = match &status {
637
ServerStatus::PortInUse(port) => Some(format!(
638
"Port {port} is in use by another program. Pick another port, then press Install again for each agent."
639
)),
640
ServerStatus::Failed(reason) => Some(reason.clone()),
641
_ => None,
642
}
643
.or(reinstall_note);
644
let url = agent_api::endpoint_url(policy.port);
645
let regenerate = small_button("mcp-token-new", "New")
646
.on_click(cx.listener(|_, _, _, cx| {
647
if let Some(api) = agent_api::handle(cx) {
648
api.update(cx, |api, cx| api.regenerate_token(cx));
649
}
650
}))
651
.into_any_element();
652
v_flex()
653
.w_full()
654
.child(
655
toggle_row("mcp-enabled", "MCP server", detail, detail_color, enabled).on_click(
656
cx.listener(move |_, _, _, cx| {
657
agent_api::update_policy(cx, |policy| policy.enabled = !enabled)
658
}),
659
),
660
)
661
.children(warning.map(|text| {
662
note_box(
663
h_flex()
664
.gap(px(8.))
665
.items_start()
666
.child(
667
div()
668
.font_weight(FontWeight::BOLD)
669
.text_color(theme::red_soft())
670
.child("!"),
671
)
672
.child(div().flex_1().child(text)),
673
4.,
674
)
675
}))
676
.child(control_row(
677
"Port",
678
"Only this computer can connect",
679
div()
680
.w(px(PORT_WIDTH))
681
.flex_none()
682
.child(Input::new(&self.port_input)),
683
))
684
.when(running && self.wsl_unreachable, |tab| {
685
tab.child(wsl_warning())
686
})
687
.child(caption("CONNECTION"))
688
.child(self.field_row(
689
"URL",
690
url.clone(),
691
vec![self.copy_button("mcp-url-copy", Copied::Url, url, cx)],
692
cx,
693
))
694
.child(self.field_row(
695
"Token",
696
masked_token(&token),
697
vec![
698
self.copy_button("mcp-token-copy", Copied::Token, token, cx),
699
regenerate,
700
],
701
cx,
702
))
703
}
704
705
fn segmented(&self, scope: Scope, access: &Access, cx: &mut Context<Self>) -> Div {
706
let options: [(&'static str, bool, fn() -> Access); 3] = [
707
("All", matches!(access, Access::All), || Access::All),
708
("Selected", matches!(access, Access::Selected(_)), || {
709
Access::Selected(BTreeSet::new())
710
}),
711
("None", matches!(access, Access::None), || Access::None),
712
];
713
h_flex()
714
.flex_none()
715
.p(px(2.))
716
.rounded(px(8.))
717
.bg(theme::surface_raised())
718
.children(options.map(|(label, active, make)| {
719
div()
720
.id(SharedString::from(format!("{}-{label}", scope.title())))
721
.h(px(24.))
722
.px(px(10.))
723
.flex()
724
.items_center()
725
.rounded(px(6.))
726
.cursor_pointer()
727
.text_size(px(12.))
728
.font_weight(FontWeight::SEMIBOLD)
729
.text_color(if active {
730
theme::text()
731
} else {
732
theme::text_muted()
733
})
734
.when(active, |item| item.bg(theme::popup_hover()))
735
.child(label)
736
.on_click(cx.listener(move |this, _, _, cx| {
737
if !active {
738
this.picker = None;
739
agent_api::update_policy(cx, |policy| {
740
*scope.access_mut(policy) = make()
741
});
742
}
743
}))
744
}))
745
}
746
747
fn scope_detail(scope: Scope, access: &Access) -> String {
748
match (scope, access) {
749
(Scope::Chats, Access::All) => "All chats".to_owned(),
750
(Scope::Channels, Access::All) => "All channels".to_owned(),
751
(Scope::Chats, Access::None) => "No chat visible".to_owned(),
752
(Scope::Channels, Access::None) => "No channel visible".to_owned(),
753
(Scope::Chats, Access::Selected(ids)) => {
754
format!("{} selected, incl. meeting chats", ids.len())
755
}
756
(Scope::Channels, Access::Selected(ids)) => format!("{} selected", ids.len()),
757
}
758
}
759
760
fn scope_block(
761
&self,
762
scope: Scope,
763
policy: &AgentPolicy,
764
titles: &HashMap<String, String>,
765
cx: &mut Context<Self>,
766
) -> Div {
767
let access = scope.access(policy);
768
let header = control_row(
769
scope.title(),
770
Self::scope_detail(scope, access),
771
self.segmented(scope, access, cx),
772
);
773
let Access::Selected(ids) = access else {
774
return v_flex().w_full().child(header);
775
};
776
let chips = ids.iter().map(|conversation_id| {
777
let title = titles
778
.get(conversation_id)
779
.cloned()
780
.unwrap_or_else(|| "Unknown".to_owned());
781
let conversation_id = conversation_id.clone();
782
h_flex()
783
.h(px(24.))
784
.pl(px(8.))
785
.gap(px(4.))
786
.items_center()
787
.rounded(px(6.))
788
.bg(theme::surface_raised())
789
.text_size(px(12.))
790
.text_color(theme::text_strong())
791
.child(div().max_w(px(CHIP_MAX_WIDTH)).truncate().child(title))
792
.child(
793
div()
794
.id(SharedString::from(format!("remove-{conversation_id}")))
795
.w(px(16.))
796
.h_full()
797
.flex()
798
.items_center()
799
.justify_center()
800
.cursor_pointer()
801
.child(icon(IconName::X, 10., theme::text_faint()))
802
.on_click(cx.listener(move |_, _, _, cx| {
803
let conversation_id = conversation_id.clone();
804
agent_api::update_policy(cx, |policy| {
805
if let Access::Selected(ids) = scope.access_mut(policy) {
806
ids.remove(&conversation_id);
807
}
808
})
809
})),
810
)
811
});
812
let add = div()
813
.id(SharedString::from(format!("add-{}", scope.title())))
814
.h(px(24.))
815
.px(px(8.))
816
.flex()
817
.items_center()
818
.rounded(px(6.))
819
.border_1()
820
.border_dashed()
821
.border_color(theme::border_strong())
822
.cursor_pointer()
823
.text_size(px(12.))
824
.text_color(theme::accent_text())
825
.child(scope.add_label())
826
.on_click(cx.listener(move |this, _, window, cx| this.open_picker(scope, window, cx)));
827
v_flex()
828
.w_full()
829
.child(header)
830
.child(
831
h_flex()
832
.w_full()
833
.flex_wrap()
834
.gap(px(6.))
835
.px(px(20.))
836
.pb(px(8.))
837
.children(chips)
838
.child(add),
839
)
840
.children(
841
self.picker
842
.filter(|open| *open == scope)
843
.map(|_| self.picker_panel(scope, ids, cx)),
844
)
845
}
846
847
fn picker_panel(
848
&self,
849
scope: Scope,
850
selected: &BTreeSet<String>,
851
cx: &mut Context<Self>,
852
) -> Div {
853
let query = self.search_input.read(cx).value().to_string();
854
let state = self.app.read(cx);
855
let candidates: Vec<(String, Candidate)> = candidates_from(state)
856
.into_iter()
857
.filter(|(_, candidate)| scope.contains(candidate))
858
.collect();
859
let results = fuzzy::rank(&query, &candidates, PICKER_RESULTS);
860
let rows: Vec<AnyElement> = results
861
.into_iter()
862
.map(|candidate| {
863
let conversation_id = candidate.selection.conversation_id().to_owned();
864
let added = selected.contains(&conversation_id);
865
let kind = match scope {
866
Scope::Chats => chat_kind_label(state, &conversation_id)
867
.unwrap_or("Chat")
868
.to_owned(),
869
Scope::Channels => candidate.subtitle.clone(),
870
};
871
h_flex()
872
.id(SharedString::from(format!("pick-{conversation_id}")))
873
.h(px(PICKER_ROW_HEIGHT))
874
.flex_none()
875
.px(px(6.))
876
.gap(px(8.))
877
.items_center()
878
.rounded(px(6.))
879
.cursor_pointer()
880
.hover(|row| row.bg(theme::popup_hover()))
881
.child(candidate_avatar(
882
&state.directory,
883
&candidate.avatar,
884
20.,
885
theme::popup(),
886
))
887
.child(
888
div()
889
.flex_1()
890
.min_w_0()
891
.truncate()
892
.text_size(px(13.))
893
.text_color(theme::text())
894
.child(candidate.title.clone()),
895
)
896
.child(
897
div()
898
.flex_none()
899
.text_size(px(11.))
900
.text_color(if added {
901
theme::accent_text()
902
} else {
903
theme::text_faint()
904
})
905
.child(if added { "Added".to_owned() } else { kind }),
906
)
907
.on_click(cx.listener(move |this, _, _, cx| {
908
let conversation_id = conversation_id.clone();
909
this.picker = None;
910
agent_api::update_policy(cx, |policy| {
911
if let Access::Selected(ids) = scope.access_mut(policy) {
912
ids.insert(conversation_id);
913
}
914
});
915
}))
916
.into_any_element()
917
})
918
.collect();
919
v_flex()
920
.mx(px(20.))
921
.mb(px(8.))
922
.p(px(6.))
923
.gap(px(4.))
924
.rounded(px(8.))
925
.bg(theme::popup())
926
.border_1()
927
.border_color(theme::border())
928
.child(
929
h_flex()
930
.h(px(30.))
931
.px(px(6.))
932
.gap(px(6.))
933
.items_center()
934
.child(icon(IconName::Search, 14., theme::text_muted()))
935
.child(
936
div().flex_1().child(
937
Input::new(&self.search_input)
938
.appearance(false)
939
.bordered(false),
940
),
941
),
942
)
943
.child(
944
v_flex()
945
.id("mcp-picker-list")
946
.w_full()
947
.max_h(px(PICKER_ROW_HEIGHT * PICKER_MAX_ROWS as f32))
948
.overflow_y_scroll()
949
.children(rows),
950
)
951
}
952
953
fn access_tab(&self, cx: &mut Context<Self>) -> Div {
954
let policy = agent_api::policy(cx);
955
let titles: HashMap<String, String> = candidates_from(self.app.read(cx))
956
.into_iter()
957
.map(|(label, candidate)| (candidate.selection.conversation_id().to_owned(), label))
958
.collect();
959
let toggles: [(
960
&'static str,
961
&'static str,
962
&'static str,
963
Hsla,
964
bool,
965
fn(&mut AgentPolicy),
966
); 3] = [
967
(
968
"mcp-propose",
969
"Propose messages",
970
"Card above the composer, you send",
971
theme::text_muted(),
972
policy.propose,
973
|policy| policy.propose = !policy.propose,
974
),
975
(
976
"mcp-calendar",
977
"Calendar and meetings",
978
"Times, titles, organizers, join links",
979
theme::text_muted(),
980
policy.calendar,
981
|policy| policy.calendar = !policy.calendar,
982
),
983
(
984
"mcp-transcripts",
985
"Meeting transcripts",
986
"Spoken text goes to the agent's provider",
987
theme::amber(),
988
policy.transcripts,
989
|policy| policy.transcripts = !policy.transcripts,
990
),
991
];
992
v_flex()
993
.w_full()
994
.child(self.scope_block(Scope::Chats, &policy, &titles, cx))
995
.child(self.scope_block(Scope::Channels, &policy, &titles, cx))
996
.children(toggles.map(|(id, title, detail, color, on, flip)| {
997
toggle_row(id, title, detail, color, on)
998
.on_click(cx.listener(move |_, _, _, cx| agent_api::update_policy(cx, flip)))
999
}))
1000
.child(note_box(
1001
"Agents only see what is allowed here. They never send - you do.",
1002
4.,
1003
))
1004
}
1005
1006
fn install_row(&self, index: usize, target: Target, cx: &mut Context<Self>) -> Div {
1007
let state = self
1008
.install_states
1009
.as_ref()
1010
.and_then(|states| states.get(index));
1011
let busy = self.install_busy;
1012
let action = state.and_then(target_action);
1013
let button = match (busy, action) {
1014
(Some((busy_target, busy_action)), _) if busy_target == target => {
1015
inert_button(target.label(), busy_action.busy_label()).into_any_element()
1016
}
1017
(None, Some(action)) => small_button(target.label(), action.label())
1018
.on_click(
1019
cx.listener(move |this, _, _, cx| this.run_install_action(target, action, cx)),
1020
)
1021
.into_any_element(),
1022
_ => inert_button(target.label(), InstallAction::Install.label()).into_any_element(),
1023
};
1024
v_flex()
1025
.w_full()
1026
.child(
1027
h_flex()
1028
.w_full()
1029
.px(px(20.))
1030
.py(px(8.))
1031
.gap(px(12.))
1032
.items_center()
1033
.child(
1034
div()
1035
.size(px(28.))
1036
.flex_none()
1037
.flex()
1038
.items_center()
1039
.justify_center()
1040
.rounded(px(7.))
1041
.bg(theme::surface_raised())
1042
.text_size(px(11.))
1043
.font_weight(FontWeight::BOLD)
1044
.text_color(theme::text_soft())
1045
.child(target_logo(target)),
1046
)
1047
.child(
1048
v_flex()
1049
.flex_1()
1050
.child(
1051
div()
1052
.text_size(px(14.))
1053
.font_weight(FontWeight::SEMIBOLD)
1054
.text_color(theme::text())
1055
.child(target.label()),
1056
)
1057
.child(install_detail(target, state)),
1058
)
1059
.child(button),
1060
)
1061
.children(self.install_errors.get(&target).map(|message| {
1062
div()
1063
.px(px(20.))
1064
.pb(px(4.))
1065
.pl(px(60.))
1066
.text_size(px(12.))
1067
.text_color(theme::red_soft())
1068
.child(message.clone())
1069
}))
1070
}
1071
1072
fn install_tab(&self, cx: &mut Context<Self>) -> Div {
1073
let url = agent_api::endpoint_url(agent_api::policy(cx).port);
1074
let running = agent_api::handle(cx)
1075
.is_some_and(|api| matches!(api.read(cx).status(), ServerStatus::Running(_)));
1076
let rows: Vec<Div> = Target::ALL
1077
.into_iter()
1078
.enumerate()
1079
.map(|(index, target)| self.install_row(index, target, cx))
1080
.collect();
1081
v_flex()
1082
.w_full()
1083
.pt(px(8.))
1084
.children(rows)
1085
.child(caption("MANUAL"))
1086
.child(self.field_row(
1087
"URL",
1088
url.clone(),
1089
vec![self.copy_button("mcp-manual-copy", Copied::Manual, url, cx)],
1090
cx,
1091
))
1092
.when(running && self.wsl_unreachable, |tab| {
1093
tab.child(wsl_warning())
1094
})
1095
}
1096
}
@@ -0,0 +1,1096 @@1
use std::collections::{BTreeSet, HashMap};2
use std::time::Duration;3
4
use gpui_kit::assets::IconName;5
use gpui_kit::component::{6
ActiveTheme as _, h_flex,7
input::{Input, InputEvent, InputState},8
v_flex,9
};10
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;12
use mcp::install::{Homes, InstallReport, InstallState, Location, Target};13
use mcp::{Access, AgentPolicy};14
15
use super::settings_view::{control_row, switch, titled_with};16
use crate::agent_api::{self, ServerStatus};17
use crate::app_state::AppState;18
use crate::data::is_one_on_one;19
use crate::fuzzy;20
use crate::theme;21
use crate::views::switcher::{Candidate, candidate_avatar, candidates_from};22
use crate::views::widgets::icon;23
24
const COPIED_SHOWN: Duration = Duration::from_millis(1500);25
const PORT_WIDTH: f32 = 72.;26
const FIELD_HEIGHT: f32 = 36.;27
const SMALL_BUTTON_HEIGHT: f32 = 28.;28
const PICKER_ROW_HEIGHT: f32 = 30.;29
const PICKER_MAX_ROWS: usize = 6;30
const PICKER_RESULTS: usize = 40;31
const TOKEN_TAIL: usize = 4;32
const CHIP_MAX_WIDTH: f32 = 180.;33
const WSL_WARNING: &str = "WSL agents cannot reach 127.0.0.1 on Windows. Add networkingMode=mirrored to .wslconfig and run wsl --shutdown.";34
35
#[derive(Clone, Copy, PartialEq, Eq)]36
enum McpTab {37
Server,38
Access,39
Install,40
}41
42
impl McpTab {43
const ALL: [McpTab; 3] = [McpTab::Server, McpTab::Access, McpTab::Install];44
45
fn label(self) -> &'static str {46
match self {47
McpTab::Server => "Server",48
McpTab::Access => "Access",49
McpTab::Install => "Install",50
}51
}52
}53
54
#[derive(Clone, Copy, PartialEq, Eq)]55
enum Scope {56
Chats,57
Channels,58
}59
60
impl Scope {61
fn access(self, policy: &AgentPolicy) -> &Access {62
match self {63
Scope::Chats => &policy.chats,64
Scope::Channels => &policy.channels,65
}66
}67
68
fn access_mut(self, policy: &mut AgentPolicy) -> &mut Access {69
match self {70
Scope::Chats => &mut policy.chats,71
Scope::Channels => &mut policy.channels,72
}73
}74
75
fn title(self) -> &'static str {76
match self {77
Scope::Chats => "Chats",78
Scope::Channels => "Channels",79
}80
}81
82
fn add_label(self) -> &'static str {83
match self {84
Scope::Chats => "+ Add chat",85
Scope::Channels => "+ Add channel",86
}87
}88
89
fn contains(self, candidate: &Candidate) -> bool {90
use crate::app_state::Selection;91
matches!(92
(self, &candidate.selection),93
(Scope::Chats, Selection::Chat(_)) | (Scope::Channels, Selection::Channel(_))94
)95
}96
}97
98
#[derive(Clone, Copy, PartialEq, Eq)]99
enum Copied {100
Url,101
Token,102
Manual,103
}104
105
#[derive(Clone, Copy, PartialEq, Eq)]106
enum InstallAction {107
Install,108
Update,109
Remove,110
}111
112
impl InstallAction {113
fn label(self) -> &'static str {114
match self {115
InstallAction::Install => "Install",116
InstallAction::Update => "Update",117
InstallAction::Remove => "Remove",118
}119
}120
121
fn busy_label(self) -> &'static str {122
match self {123
InstallAction::Install => "Installing...",124
InstallAction::Update => "Updating...",125
InstallAction::Remove => "Removing...",126
}127
}128
}129
130
fn target_logo(target: Target) -> &'static str {131
match target {132
Target::ClaudeCode => "CC",133
Target::Codex => "CX",134
Target::CopilotCli => "GH",135
Target::VsCode => "VS",136
Target::Cursor => "CU",137
}138
}139
140
fn target_action(state: &InstallState) -> Option<InstallAction> {141
if state.stale {142
Some(InstallAction::Update)143
} else if !state.installed_at.is_empty() {144
Some(InstallAction::Remove)145
} else if state.available {146
Some(InstallAction::Install)147
} else {148
None149
}150
}151
152
fn locations_label(locations: &[Location]) -> &'static str {153
let windows = locations.contains(&Location::Windows);154
let wsl = locations155
.iter()156
.any(|location| matches!(location, Location::Wsl { .. }));157
match (windows, wsl) {158
(true, true) => "Windows + WSL",159
(true, false) => "Windows",160
(false, true) => "WSL",161
(false, false) => "Installed",162
}163
}164
165
fn install_detail(target: Target, state: Option<&InstallState>) -> AnyElement {166
let muted = |text: &'static str| {167
div()168
.text_size(px(12.))169
.text_color(theme::text_muted())170
.child(text)171
.into_any_element()172
};173
let Some(state) = state else {174
return muted(target.config_hint());175
};176
if state.stale {177
return div()178
.text_size(px(12.))179
.text_color(theme::amber())180
.child("Out of date - Update")181
.into_any_element();182
}183
if !state.installed_at.is_empty() {184
return h_flex()185
.gap(px(6.))186
.items_center()187
.text_size(px(12.))188
.text_color(theme::green())189
.child(div().size(px(6.)).rounded_full().bg(theme::green()))190
.child(locations_label(&state.installed_at))191
.into_any_element();192
}193
if state.available {194
muted(target.config_hint())195
} else {196
muted("Not installed")197
}198
}199
200
fn wsl_warning() -> Div {201
note_box(202
h_flex()203
.gap(px(8.))204
.items_start()205
.child(206
div()207
.font_weight(FontWeight::BOLD)208
.text_color(theme::amber())209
.child("!"),210
)211
.child(div().flex_1().child(WSL_WARNING)),212
4.,213
)214
}215
216
pub struct McpView {217
app: Entity<AppState>,218
tab: McpTab,219
picker: Option<Scope>,220
port_input: Entity<InputState>,221
search_input: Entity<InputState>,222
copied: Option<Copied>,223
install_states: Option<Vec<InstallState>>,224
install_busy: Option<(Target, InstallAction)>,225
install_errors: HashMap<Target, String>,226
wsl_unreachable: bool,227
_subscriptions: Vec<Subscription>,228
}229
230
impl McpView {231
pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {232
let port = agent_api::policy(cx).port;233
let port_input = cx.new(|cx| InputState::new(window, cx));234
port_input.update(cx, |input, cx| {235
input.set_value(port.to_string(), window, cx)236
});237
let search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Search"));238
let mut subscriptions = vec![239
cx.subscribe_in(&port_input, window, Self::on_port_event),240
cx.subscribe_in(&search_input, window, |_, _, event, _, cx| {241
if matches!(event, InputEvent::Change) {242
cx.notify();243
}244
}),245
];246
if let Some(api) = agent_api::handle(cx) {247
subscriptions.push(cx.observe(&api, |_, _, cx| cx.notify()));248
}249
let mut view = McpView {250
app,251
tab: McpTab::Server,252
picker: None,253
port_input,254
search_input,255
copied: None,256
install_states: None,257
install_busy: None,258
install_errors: HashMap::new(),259
wsl_unreachable: false,260
_subscriptions: subscriptions,261
};262
view.refresh_wsl(cx);263
view264
}265
266
fn on_port_event(267
&mut self,268
input: &Entity<InputState>,269
event: &InputEvent,270
window: &mut Window,271
cx: &mut Context<Self>,272
) {273
if !matches!(event, InputEvent::Blur | InputEvent::PressEnter { .. }) {274
return;275
}276
let current = agent_api::policy(cx).port;277
let typed = input.read(cx).value().trim().parse::<u16>().ok();278
match typed.filter(|port| *port != 0) {279
Some(port) if port != current => {280
agent_api::update_policy(cx, |policy| policy.port = port)281
}282
Some(_) => {}283
None => input.update(cx, |input, cx| {284
input.set_value(current.to_string(), window, cx)285
}),286
}287
self.refresh_wsl(cx);288
}289
290
fn refresh_wsl(&mut self, cx: &mut Context<Self>) {291
let port = agent_api::policy(cx).port;292
let task = cx.background_spawn(async move { mcp::install::wsl_reachable(port) });293
cx.spawn(async move |this, cx| {294
let reachable = task.await;295
this.update(cx, |this, cx| {296
this.wsl_unreachable = reachable == Some(false);297
cx.notify();298
})299
.ok();300
})301
.detach();302
}303
304
fn refresh_installs(&mut self, cx: &mut Context<Self>) {305
let Some(endpoint) = agent_api::configured_endpoint(cx) else {306
return;307
};308
let task = cx.background_spawn(async move {309
let homes = Homes::detect();310
Target::ALL311
.map(|target| mcp::install::status(target, &endpoint, &homes))312
.to_vec()313
});314
cx.spawn(async move |this, cx| {315
let states = task.await;316
this.update(cx, |this, cx| {317
this.install_states = Some(states);318
cx.notify();319
})320
.ok();321
})322
.detach();323
}324
325
fn run_install_action(326
&mut self,327
target: Target,328
action: InstallAction,329
cx: &mut Context<Self>,330
) {331
let Some(endpoint) = agent_api::configured_endpoint(cx) else {332
return;333
};334
self.install_busy = Some((target, action));335
self.install_errors.remove(&target);336
let task = cx.background_spawn(async move {337
let homes = Homes::detect();338
match action {339
InstallAction::Remove => mcp::install::uninstall(target, &homes).map(|_| None),340
_ => mcp::install::install(target, &endpoint, &homes).map(Some),341
}342
});343
cx.spawn(async move |this, cx| {344
let result = task.await;345
this.update(cx, |this, cx| {346
this.install_busy = None;347
match result {348
Ok(Some(InstallReport::OpenUrl(url))) => cx.open_url(&url),349
Ok(_) => {}350
Err(error) => {351
this.install_errors.insert(target, error.to_string());352
}353
}354
this.refresh_installs(cx);355
cx.notify();356
})357
.ok();358
})359
.detach();360
cx.notify();361
}362
363
fn select_tab(&mut self, tab: McpTab, cx: &mut Context<Self>) {364
self.tab = tab;365
self.picker = None;366
match tab {367
McpTab::Install => {368
self.refresh_installs(cx);369
self.refresh_wsl(cx);370
}371
McpTab::Server => self.refresh_wsl(cx),372
McpTab::Access => {}373
}374
cx.notify();375
}376
377
fn copy(&mut self, target: Copied, text: String, cx: &mut Context<Self>) {378
cx.write_to_clipboard(ClipboardItem::new_string(text));379
self.copied = Some(target);380
cx.spawn(async move |this, cx| {381
cx.background_executor().timer(COPIED_SHOWN).await;382
this.update(cx, |this, cx| {383
this.copied = None;384
cx.notify();385
})386
.ok();387
})388
.detach();389
cx.notify();390
}391
392
fn open_picker(&mut self, scope: Scope, window: &mut Window, cx: &mut Context<Self>) {393
self.picker = if self.picker == Some(scope) {394
None395
} else {396
Some(scope)397
};398
self.search_input399
.update(cx, |input, cx| input.set_value("", window, cx));400
if self.picker.is_some() {401
self.search_input402
.update(cx, |input, cx| input.focus(window, cx));403
}404
cx.notify();405
}406
}407
408
fn small_button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Stateful<Div> {409
inert_button(id, label)410
.cursor_pointer()411
.text_color(theme::text())412
.hover(|button| button.bg(theme::popup_hover()))413
}414
415
fn inert_button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Stateful<Div> {416
div()417
.id(id)418
.h(px(SMALL_BUTTON_HEIGHT))419
.px(px(12.))420
.flex_none()421
.flex()422
.items_center()423
.rounded(px(7.))424
.bg(theme::surface_raised())425
.text_size(px(12.))426
.font_weight(FontWeight::SEMIBOLD)427
.text_color(theme::text_faint())428
.child(label.into())429
}430
431
fn caption(label: &'static str) -> Div {432
div()433
.px(px(20.))434
.pt(px(16.))435
.pb(px(4.))436
.text_size(px(12.))437
.font_weight(FontWeight::SEMIBOLD)438
.text_color(theme::text_muted())439
.child(label)440
}441
442
fn toggle_row(443
id: &'static str,444
title: &'static str,445
detail: &'static str,446
detail_color: Hsla,447
on: bool,448
) -> Stateful<Div> {449
h_flex()450
.id(id)451
.w_full()452
.px(px(20.))453
.py(px(10.))454
.gap(px(12.))455
.items_center()456
.cursor_pointer()457
.hover(|row| row.bg(theme::row_hover()))458
.child(titled_with(title, detail, detail_color))459
.child(switch(on))460
}461
462
fn note_box(content: impl IntoElement, margin_top: f32) -> Div {463
h_flex()464
.mx(px(20.))465
.mt(px(margin_top))466
.mb(px(12.))467
.px(px(12.))468
.py(px(10.))469
.gap(px(8.))470
.rounded(px(8.))471
.bg(theme::row_hover())472
.text_size(px(12.))473
.text_color(theme::text_muted())474
.child(content)475
}476
477
fn masked_token(token: &str) -> String {478
let tail: String = token479
.chars()480
.rev()481
.take(TOKEN_TAIL)482
.collect::<Vec<_>>()483
.into_iter()484
.rev()485
.collect();486
format!("****...{tail}")487
}488
489
fn chat_kind_label(state: &AppState, conversation_id: &str) -> Option<&'static str> {490
let chat = state491
.sidebar492
.chats493
.iter()494
.find(|chat| chat.id == conversation_id)?;495
Some(if chat.kind.eq_ignore_ascii_case("meeting") {496
"Meeting"497
} else if is_one_on_one(chat) {498
"Chat"499
} else {500
"Group"501
})502
}503
504
impl Render for McpView {505
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {506
let view = cx.entity();507
let tabs = h_flex()508
.mx(px(20.))509
.mt(px(12.))510
.mb(px(4.))511
.p(px(2.))512
.rounded(px(8.))513
.bg(theme::surface())514
.children(McpTab::ALL.map(|tab| {515
let active = tab == self.tab;516
let view = view.clone();517
div()518
.id(tab.label())519
.flex_1()520
.h(px(SMALL_BUTTON_HEIGHT))521
.flex()522
.items_center()523
.justify_center()524
.rounded(px(6.))525
.cursor_pointer()526
.text_size(px(12.))527
.font_weight(FontWeight::SEMIBOLD)528
.text_color(if active {529
theme::text()530
} else {531
theme::text_muted()532
})533
.when(active, |tab| tab.bg(theme::surface_raised()))534
.child(tab.label())535
.on_click(move |_, _, cx| view.update(cx, |view, cx| view.select_tab(tab, cx)))536
}));537
let body = match self.tab {538
McpTab::Server => self.server_tab(cx).into_any_element(),539
McpTab::Access => self.access_tab(cx).into_any_element(),540
McpTab::Install => self.install_tab(cx).into_any_element(),541
};542
v_flex().w_full().flex_1().min_h_0().child(tabs).child(543
div()544
.id("mcp-body")545
.w_full()546
.flex_1()547
.min_h_0()548
.overflow_y_scroll()549
.child(body),550
)551
}552
}553
554
impl McpView {555
fn field_row(556
&self,557
label: &'static str,558
value: String,559
buttons: Vec<AnyElement>,560
cx: &App,561
) -> Div {562
v_flex()563
.w_full()564
.px(px(20.))565
.pb(px(8.))566
.gap(px(4.))567
.child(568
div()569
.text_size(px(11.))570
.text_color(theme::text_faint())571
.child(label),572
)573
.child(574
h_flex()575
.w_full()576
.gap(px(8.))577
.items_center()578
.child(579
div()580
.flex_1()581
.min_w_0()582
.h(px(FIELD_HEIGHT))583
.px(px(12.))584
.flex()585
.items_center()586
.rounded(px(8.))587
.bg(theme::surface())588
.font_family(cx.theme().mono_font_family.clone())589
.text_size(px(12.))590
.text_color(theme::text_soft())591
.child(div().truncate().child(value)),592
)593
.children(buttons),594
)595
}596
597
fn copy_button(598
&self,599
id: &'static str,600
target: Copied,601
text: String,602
cx: &mut Context<Self>,603
) -> AnyElement {604
let label = if self.copied == Some(target) {605
"Copied"606
} else {607
"Copy"608
};609
small_button(id, label)610
.on_click(cx.listener(move |this, _, _, cx| this.copy(target, text.clone(), cx)))611
.into_any_element()612
}613
614
fn server_tab(&self, cx: &mut Context<Self>) -> Div {615
let policy = agent_api::policy(cx);616
let (status, token) = match agent_api::handle(cx) {617
Some(api) => {618
let api = api.read(cx);619
(api.status().clone(), api.token().to_owned())620
}621
None => (ServerStatus::Off, String::new()),622
};623
let failed = matches!(status, ServerStatus::PortInUse(_) | ServerStatus::Failed(_));624
let (detail, detail_color) = match (policy.enabled, failed) {625
(false, _) => ("Off - agents cannot reach Rusty Teams", theme::text_muted()),626
(true, true) => ("Could not start", theme::red_soft()),627
(true, false) => (628
"Agents on this computer can read and propose",629
theme::text_muted(),630
),631
};632
let enabled = policy.enabled;633
let running = matches!(status, ServerStatus::Running(_));634
let reinstall_note =635
agent_api::handle(cx).and_then(|api| api.read(cx).reinstall_note().map(str::to_owned));636
let warning = match &status {637
ServerStatus::PortInUse(port) => Some(format!(638
"Port {port} is in use by another program. Pick another port, then press Install again for each agent."639
)),640
ServerStatus::Failed(reason) => Some(reason.clone()),641
_ => None,642
}643
.or(reinstall_note);644
let url = agent_api::endpoint_url(policy.port);645
let regenerate = small_button("mcp-token-new", "New")646
.on_click(cx.listener(|_, _, _, cx| {647
if let Some(api) = agent_api::handle(cx) {648
api.update(cx, |api, cx| api.regenerate_token(cx));649
}650
}))651
.into_any_element();652
v_flex()653
.w_full()654
.child(655
toggle_row("mcp-enabled", "MCP server", detail, detail_color, enabled).on_click(656
cx.listener(move |_, _, _, cx| {657
agent_api::update_policy(cx, |policy| policy.enabled = !enabled)658
}),659
),660
)661
.children(warning.map(|text| {662
note_box(663
h_flex()664
.gap(px(8.))665
.items_start()666
.child(667
div()668
.font_weight(FontWeight::BOLD)669
.text_color(theme::red_soft())670
.child("!"),671
)672
.child(div().flex_1().child(text)),673
4.,674
)675
}))676
.child(control_row(677
"Port",678
"Only this computer can connect",679
div()680
.w(px(PORT_WIDTH))681
.flex_none()682
.child(Input::new(&self.port_input)),683
))684
.when(running && self.wsl_unreachable, |tab| {685
tab.child(wsl_warning())686
})687
.child(caption("CONNECTION"))688
.child(self.field_row(689
"URL",690
url.clone(),691
vec![self.copy_button("mcp-url-copy", Copied::Url, url, cx)],692
cx,693
))694
.child(self.field_row(695
"Token",696
masked_token(&token),697
vec![698
self.copy_button("mcp-token-copy", Copied::Token, token, cx),699
regenerate,700
],701
cx,702
))703
}704
705
fn segmented(&self, scope: Scope, access: &Access, cx: &mut Context<Self>) -> Div {706
let options: [(&'static str, bool, fn() -> Access); 3] = [707
("All", matches!(access, Access::All), || Access::All),708
("Selected", matches!(access, Access::Selected(_)), || {709
Access::Selected(BTreeSet::new())710
}),711
("None", matches!(access, Access::None), || Access::None),712
];713
h_flex()714
.flex_none()715
.p(px(2.))716
.rounded(px(8.))717
.bg(theme::surface_raised())718
.children(options.map(|(label, active, make)| {719
div()720
.id(SharedString::from(format!("{}-{label}", scope.title())))721
.h(px(24.))722
.px(px(10.))723
.flex()724
.items_center()725
.rounded(px(6.))726
.cursor_pointer()727
.text_size(px(12.))728
.font_weight(FontWeight::SEMIBOLD)729
.text_color(if active {730
theme::text()731
} else {732
theme::text_muted()733
})734
.when(active, |item| item.bg(theme::popup_hover()))735
.child(label)736
.on_click(cx.listener(move |this, _, _, cx| {737
if !active {738
this.picker = None;739
agent_api::update_policy(cx, |policy| {740
*scope.access_mut(policy) = make()741
});742
}743
}))744
}))745
}746
747
fn scope_detail(scope: Scope, access: &Access) -> String {748
match (scope, access) {749
(Scope::Chats, Access::All) => "All chats".to_owned(),750
(Scope::Channels, Access::All) => "All channels".to_owned(),751
(Scope::Chats, Access::None) => "No chat visible".to_owned(),752
(Scope::Channels, Access::None) => "No channel visible".to_owned(),753
(Scope::Chats, Access::Selected(ids)) => {754
format!("{} selected, incl. meeting chats", ids.len())755
}756
(Scope::Channels, Access::Selected(ids)) => format!("{} selected", ids.len()),757
}758
}759
760
fn scope_block(761
&self,762
scope: Scope,763
policy: &AgentPolicy,764
titles: &HashMap<String, String>,765
cx: &mut Context<Self>,766
) -> Div {767
let access = scope.access(policy);768
let header = control_row(769
scope.title(),770
Self::scope_detail(scope, access),771
self.segmented(scope, access, cx),772
);773
let Access::Selected(ids) = access else {774
return v_flex().w_full().child(header);775
};776
let chips = ids.iter().map(|conversation_id| {777
let title = titles778
.get(conversation_id)779
.cloned()780
.unwrap_or_else(|| "Unknown".to_owned());781
let conversation_id = conversation_id.clone();782
h_flex()783
.h(px(24.))784
.pl(px(8.))785
.gap(px(4.))786
.items_center()787
.rounded(px(6.))788
.bg(theme::surface_raised())789
.text_size(px(12.))790
.text_color(theme::text_strong())791
.child(div().max_w(px(CHIP_MAX_WIDTH)).truncate().child(title))792
.child(793
div()794
.id(SharedString::from(format!("remove-{conversation_id}")))795
.w(px(16.))796
.h_full()797
.flex()798
.items_center()799
.justify_center()800
.cursor_pointer()801
.child(icon(IconName::X, 10., theme::text_faint()))802
.on_click(cx.listener(move |_, _, _, cx| {803
let conversation_id = conversation_id.clone();804
agent_api::update_policy(cx, |policy| {805
if let Access::Selected(ids) = scope.access_mut(policy) {806
ids.remove(&conversation_id);807
}808
})809
})),810
)811
});812
let add = div()813
.id(SharedString::from(format!("add-{}", scope.title())))814
.h(px(24.))815
.px(px(8.))816
.flex()817
.items_center()818
.rounded(px(6.))819
.border_1()820
.border_dashed()821
.border_color(theme::border_strong())822
.cursor_pointer()823
.text_size(px(12.))824
.text_color(theme::accent_text())825
.child(scope.add_label())826
.on_click(cx.listener(move |this, _, window, cx| this.open_picker(scope, window, cx)));827
v_flex()828
.w_full()829
.child(header)830
.child(831
h_flex()832
.w_full()833
.flex_wrap()834
.gap(px(6.))835
.px(px(20.))836
.pb(px(8.))837
.children(chips)838
.child(add),839
)840
.children(841
self.picker842
.filter(|open| *open == scope)843
.map(|_| self.picker_panel(scope, ids, cx)),844
)845
}846
847
fn picker_panel(848
&self,849
scope: Scope,850
selected: &BTreeSet<String>,851
cx: &mut Context<Self>,852
) -> Div {853
let query = self.search_input.read(cx).value().to_string();854
let state = self.app.read(cx);855
let candidates: Vec<(String, Candidate)> = candidates_from(state)856
.into_iter()857
.filter(|(_, candidate)| scope.contains(candidate))858
.collect();859
let results = fuzzy::rank(&query, &candidates, PICKER_RESULTS);860
let rows: Vec<AnyElement> = results861
.into_iter()862
.map(|candidate| {863
let conversation_id = candidate.selection.conversation_id().to_owned();864
let added = selected.contains(&conversation_id);865
let kind = match scope {866
Scope::Chats => chat_kind_label(state, &conversation_id)867
.unwrap_or("Chat")868
.to_owned(),869
Scope::Channels => candidate.subtitle.clone(),870
};871
h_flex()872
.id(SharedString::from(format!("pick-{conversation_id}")))873
.h(px(PICKER_ROW_HEIGHT))874
.flex_none()875
.px(px(6.))876
.gap(px(8.))877
.items_center()878
.rounded(px(6.))879
.cursor_pointer()880
.hover(|row| row.bg(theme::popup_hover()))881
.child(candidate_avatar(882
&state.directory,883
&candidate.avatar,884
20.,885
theme::popup(),886
))887
.child(888
div()889
.flex_1()890
.min_w_0()891
.truncate()892
.text_size(px(13.))893
.text_color(theme::text())894
.child(candidate.title.clone()),895
)896
.child(897
div()898
.flex_none()899
.text_size(px(11.))900
.text_color(if added {901
theme::accent_text()902
} else {903
theme::text_faint()904
})905
.child(if added { "Added".to_owned() } else { kind }),906
)907
.on_click(cx.listener(move |this, _, _, cx| {908
let conversation_id = conversation_id.clone();909
this.picker = None;910
agent_api::update_policy(cx, |policy| {911
if let Access::Selected(ids) = scope.access_mut(policy) {912
ids.insert(conversation_id);913
}914
});915
}))916
.into_any_element()917
})918
.collect();919
v_flex()920
.mx(px(20.))921
.mb(px(8.))922
.p(px(6.))923
.gap(px(4.))924
.rounded(px(8.))925
.bg(theme::popup())926
.border_1()927
.border_color(theme::border())928
.child(929
h_flex()930
.h(px(30.))931
.px(px(6.))932
.gap(px(6.))933
.items_center()934
.child(icon(IconName::Search, 14., theme::text_muted()))935
.child(936
div().flex_1().child(937
Input::new(&self.search_input)938
.appearance(false)939
.bordered(false),940
),941
),942
)943
.child(944
v_flex()945
.id("mcp-picker-list")946
.w_full()947
.max_h(px(PICKER_ROW_HEIGHT * PICKER_MAX_ROWS as f32))948
.overflow_y_scroll()949
.children(rows),950
)951
}952
953
fn access_tab(&self, cx: &mut Context<Self>) -> Div {954
let policy = agent_api::policy(cx);955
let titles: HashMap<String, String> = candidates_from(self.app.read(cx))956
.into_iter()957
.map(|(label, candidate)| (candidate.selection.conversation_id().to_owned(), label))958
.collect();959
let toggles: [(960
&'static str,961
&'static str,962
&'static str,963
Hsla,964
bool,965
fn(&mut AgentPolicy),966
); 3] = [967
(968
"mcp-propose",969
"Propose messages",970
"Card above the composer, you send",971
theme::text_muted(),972
policy.propose,973
|policy| policy.propose = !policy.propose,974
),975
(976
"mcp-calendar",977
"Calendar and meetings",978
"Times, titles, organizers, join links",979
theme::text_muted(),980
policy.calendar,981
|policy| policy.calendar = !policy.calendar,982
),983
(984
"mcp-transcripts",985
"Meeting transcripts",986
"Spoken text goes to the agent's provider",987
theme::amber(),988
policy.transcripts,989
|policy| policy.transcripts = !policy.transcripts,990
),991
];992
v_flex()993
.w_full()994
.child(self.scope_block(Scope::Chats, &policy, &titles, cx))995
.child(self.scope_block(Scope::Channels, &policy, &titles, cx))996
.children(toggles.map(|(id, title, detail, color, on, flip)| {997
toggle_row(id, title, detail, color, on)998
.on_click(cx.listener(move |_, _, _, cx| agent_api::update_policy(cx, flip)))999
}))1000
.child(note_box(1001
"Agents only see what is allowed here. They never send - you do.",1002
4.,1003
))1004
}1005
1006
fn install_row(&self, index: usize, target: Target, cx: &mut Context<Self>) -> Div {1007
let state = self1008
.install_states1009
.as_ref()1010
.and_then(|states| states.get(index));1011
let busy = self.install_busy;1012
let action = state.and_then(target_action);1013
let button = match (busy, action) {1014
(Some((busy_target, busy_action)), _) if busy_target == target => {1015
inert_button(target.label(), busy_action.busy_label()).into_any_element()1016
}1017
(None, Some(action)) => small_button(target.label(), action.label())1018
.on_click(1019
cx.listener(move |this, _, _, cx| this.run_install_action(target, action, cx)),1020
)1021
.into_any_element(),1022
_ => inert_button(target.label(), InstallAction::Install.label()).into_any_element(),1023
};1024
v_flex()1025
.w_full()1026
.child(1027
h_flex()1028
.w_full()1029
.px(px(20.))1030
.py(px(8.))1031
.gap(px(12.))1032
.items_center()1033
.child(1034
div()1035
.size(px(28.))1036
.flex_none()1037
.flex()1038
.items_center()1039
.justify_center()1040
.rounded(px(7.))1041
.bg(theme::surface_raised())1042
.text_size(px(11.))1043
.font_weight(FontWeight::BOLD)1044
.text_color(theme::text_soft())1045
.child(target_logo(target)),1046
)1047
.child(1048
v_flex()1049
.flex_1()1050
.child(1051
div()1052
.text_size(px(14.))1053
.font_weight(FontWeight::SEMIBOLD)1054
.text_color(theme::text())1055
.child(target.label()),1056
)1057
.child(install_detail(target, state)),1058
)1059
.child(button),1060
)1061
.children(self.install_errors.get(&target).map(|message| {1062
div()1063
.px(px(20.))1064
.pb(px(4.))1065
.pl(px(60.))1066
.text_size(px(12.))1067
.text_color(theme::red_soft())1068
.child(message.clone())1069
}))1070
}1071
1072
fn install_tab(&self, cx: &mut Context<Self>) -> Div {1073
let url = agent_api::endpoint_url(agent_api::policy(cx).port);1074
let running = agent_api::handle(cx)1075
.is_some_and(|api| matches!(api.read(cx).status(), ServerStatus::Running(_)));1076
let rows: Vec<Div> = Target::ALL1077
.into_iter()1078
.enumerate()1079
.map(|(index, target)| self.install_row(index, target, cx))1080
.collect();1081
v_flex()1082
.w_full()1083
.pt(px(8.))1084
.children(rows)1085
.child(caption("MANUAL"))1086
.child(self.field_row(1087
"URL",1088
url.clone(),1089
vec![self.copy_button("mcp-manual-copy", Copied::Manual, url, cx)],1090
cx,1091
))1092
.when(running && self.wsl_unreachable, |tab| {1093
tab.child(wsl_warning())1094
})1095
}1096
}@@ -16,6 +16,7 @@ use super::center::NotificationCenter;
16
16
use super::platform;
17
17
use super::ring_tone::Ringtone;
18
18
use super::rules::Settings;
19
use super::settings_mcp::McpView;
19
20
use crate::app_state::AppState;
20
21
use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};
21
22
use crate::theme;
@@ -35,15 +36,17 @@ fn camera_in_call(state: &AppState) -> bool {
35
36
enum Section {
36
37
Notifications,
37
38
Devices,
39
Mcp,
38
40
}
39
41
40
42
impl Section {
41
const ALL: [Section; 2] = [Section::Notifications, Section::Devices];
43
const ALL: [Section; 3] = [Section::Notifications, Section::Devices, Section::Mcp];
42
44
43
45
fn label(self) -> &'static str {
44
46
match self {
45
47
Section::Notifications => "Notifications",
46
48
Section::Devices => "Devices",
49
Section::Mcp => "MCP",
47
50
}
48
51
}
49
52
}
@@ -87,6 +90,7 @@ const ROWS: [Row; 5] = [
87
90
pub struct SettingsView {
88
91
center: Entity<NotificationCenter>,
89
92
section: Section,
93
mcp: Entity<McpView>,
90
94
preview: CameraPreview,
91
95
cameras: Vec<DeviceEntry>,
92
96
cameras_requested: bool,
@@ -102,12 +106,17 @@ impl SettingsView {
102
106
pub const WIDTH: f32 = 420.;
103
107
pub const HEIGHT: f32 = 540.;
104
108
105
pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {
109
pub fn new(
110
center: Entity<NotificationCenter>,
111
window: &mut Window,
112
cx: &mut Context<Self>,
113
) -> Self {
106
114
let subscription = cx.observe(¢er, |_, _, cx| cx.notify());
107
115
let app = center.read(cx).app().clone();
108
116
let app_subscription = cx.observe(&app, |view, _, cx| view.sync_preview_block(cx));
109
117
let release = cx.on_release(|view, cx| view.preview.stop(cx));
110
118
let (preview, mut updates) = CameraPreview::new();
119
let mcp = cx.new(|cx| McpView::new(app.clone(), window, cx));
111
120
let state = app.read(cx);
112
121
let camera = state.call_camera.clone();
113
122
let preview_blocked = camera_in_call(state);
@@ -134,6 +143,7 @@ impl SettingsView {
134
143
SettingsView {
135
144
center,
136
145
section: Section::Notifications,
146
mcp,
137
147
preview,
138
148
cameras: camera_entries(&[]),
139
149
cameras_requested: false,
@@ -170,7 +180,7 @@ impl SettingsView {
170
180
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
171
181
self.start_preview();
172
182
}
173
Section::Notifications => self.preview.stop(cx),
183
Section::Notifications | Section::Mcp => self.preview.stop(cx),
174
184
}
175
185
cx.notify();
176
186
}
@@ -234,7 +244,7 @@ impl SettingsView {
234
244
}
235
245
}
236
246
237
fn switch(on: bool) -> Div {
247
pub(super) fn switch(on: bool) -> Div {
238
248
div()
239
249
.w(px(36.))
240
250
.h(px(20.))
@@ -275,7 +285,15 @@ fn button(label: &'static str) -> Stateful<Div> {
275
285
.child(label)
276
286
}
277
287
278
fn titled(title: &'static str, detail: &'static str) -> Div {
288
fn titled(title: &'static str, detail: impl Into<SharedString>) -> Div {
289
titled_with(title, detail, theme::text_muted())
290
}
291
292
pub(super) fn titled_with(
293
title: &'static str,
294
detail: impl Into<SharedString>,
295
detail_color: Hsla,
296
) -> Div {
279
297
v_flex()
280
298
.flex_1()
281
299
.child(
@@ -288,12 +306,16 @@ fn titled(title: &'static str, detail: &'static str) -> Div {
288
306
.child(
289
307
div()
290
308
.text_size(px(12.))
291
.text_color(theme::text_muted())
292
.child(detail),
309
.text_color(detail_color)
310
.child(detail.into()),
293
311
)
294
312
}
295
313
296
fn control_row(title: &'static str, detail: &'static str, control: impl IntoElement) -> Div {
314
pub(super) fn control_row(
315
title: &'static str,
316
detail: impl Into<SharedString>,
317
control: impl IntoElement,
318
) -> Div {
297
319
h_flex()
298
320
.w_full()
299
321
.px(px(20.))
@@ -467,6 +489,7 @@ impl Render for SettingsView {
467
489
let body = match self.section {
468
490
Section::Notifications => self.notifications_section(cx).into_any_element(),
469
491
Section::Devices => self.devices_section(cx).into_any_element(),
492
Section::Mcp => self.mcp.clone().into_any_element(),
470
493
};
471
494
v_flex()
472
495
.size_full()
@@ -16,6 +16,7 @@ use super::center::NotificationCenter;16
use super::platform;16
use super::platform;17
use super::ring_tone::Ringtone;17
use super::ring_tone::Ringtone;18
use super::rules::Settings;18
use super::rules::Settings;19
use super::settings_mcp::McpView;19
use crate::app_state::AppState;20
use crate::app_state::AppState;20
use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};21
use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};21
use crate::theme;22
use crate::theme;@@ -35,15 +36,17 @@ fn camera_in_call(state: &AppState) -> bool {35
enum Section {36
enum Section {36
Notifications,37
Notifications,37
Devices,38
Devices,39
Mcp,38
}40
}39
41
40
impl Section {42
impl Section {41
const ALL: [Section; 2] = [Section::Notifications, Section::Devices];43
const ALL: [Section; 3] = [Section::Notifications, Section::Devices, Section::Mcp];42
44
43
fn label(self) -> &'static str {45
fn label(self) -> &'static str {44
match self {46
match self {45
Section::Notifications => "Notifications",47
Section::Notifications => "Notifications",46
Section::Devices => "Devices",48
Section::Devices => "Devices",49
Section::Mcp => "MCP",47
}50
}48
}51
}49
}52
}@@ -87,6 +90,7 @@ const ROWS: [Row; 5] = [87
pub struct SettingsView {90
pub struct SettingsView {88
center: Entity<NotificationCenter>,91
center: Entity<NotificationCenter>,89
section: Section,92
section: Section,93
mcp: Entity<McpView>,90
preview: CameraPreview,94
preview: CameraPreview,91
cameras: Vec<DeviceEntry>,95
cameras: Vec<DeviceEntry>,92
cameras_requested: bool,96
cameras_requested: bool,@@ -102,12 +106,17 @@ impl SettingsView {102
pub const WIDTH: f32 = 420.;106
pub const WIDTH: f32 = 420.;103
pub const HEIGHT: f32 = 540.;107
pub const HEIGHT: f32 = 540.;104
108
105
pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {109
pub fn new(110
center: Entity<NotificationCenter>,111
window: &mut Window,112
cx: &mut Context<Self>,113
) -> Self {106
let subscription = cx.observe(¢er, |_, _, cx| cx.notify());114
let subscription = cx.observe(¢er, |_, _, cx| cx.notify());107
let app = center.read(cx).app().clone();115
let app = center.read(cx).app().clone();108
let app_subscription = cx.observe(&app, |view, _, cx| view.sync_preview_block(cx));116
let app_subscription = cx.observe(&app, |view, _, cx| view.sync_preview_block(cx));109
let release = cx.on_release(|view, cx| view.preview.stop(cx));117
let release = cx.on_release(|view, cx| view.preview.stop(cx));110
let (preview, mut updates) = CameraPreview::new();118
let (preview, mut updates) = CameraPreview::new();119
let mcp = cx.new(|cx| McpView::new(app.clone(), window, cx));111
let state = app.read(cx);120
let state = app.read(cx);112
let camera = state.call_camera.clone();121
let camera = state.call_camera.clone();113
let preview_blocked = camera_in_call(state);122
let preview_blocked = camera_in_call(state);@@ -134,6 +143,7 @@ impl SettingsView {134
SettingsView {143
SettingsView {135
center,144
center,136
section: Section::Notifications,145
section: Section::Notifications,146
mcp,137
preview,147
preview,138
cameras: camera_entries(&[]),148
cameras: camera_entries(&[]),139
cameras_requested: false,149
cameras_requested: false,@@ -170,7 +180,7 @@ impl SettingsView {170
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));180
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));171
self.start_preview();181
self.start_preview();172
}182
}173
Section::Notifications => self.preview.stop(cx),183
Section::Notifications | Section::Mcp => self.preview.stop(cx),174
}184
}175
cx.notify();185
cx.notify();176
}186
}@@ -234,7 +244,7 @@ impl SettingsView {234
}244
}235
}245
}236
246
237
fn switch(on: bool) -> Div {247
pub(super) fn switch(on: bool) -> Div {238
div()248
div()239
.w(px(36.))249
.w(px(36.))240
.h(px(20.))250
.h(px(20.))@@ -275,7 +285,15 @@ fn button(label: &'static str) -> Stateful<Div> {275
.child(label)285
.child(label)276
}286
}277
287
278
fn titled(title: &'static str, detail: &'static str) -> Div {288
fn titled(title: &'static str, detail: impl Into<SharedString>) -> Div {289
titled_with(title, detail, theme::text_muted())290
}291
292
pub(super) fn titled_with(293
title: &'static str,294
detail: impl Into<SharedString>,295
detail_color: Hsla,296
) -> Div {279
v_flex()297
v_flex()280
.flex_1()298
.flex_1()281
.child(299
.child(@@ -288,12 +306,16 @@ fn titled(title: &'static str, detail: &'static str) -> Div {288
.child(306
.child(289
div()307
div()290
.text_size(px(12.))308
.text_size(px(12.))291
.text_color(theme::text_muted())309
.text_color(detail_color)292
.child(detail),310
.child(detail.into()),293
)311
)294
}312
}295
313
296
fn control_row(title: &'static str, detail: &'static str, control: impl IntoElement) -> Div {314
pub(super) fn control_row(315
title: &'static str,316
detail: impl Into<SharedString>,317
control: impl IntoElement,318
) -> Div {297
h_flex()319
h_flex()298
.w_full()320
.w_full()299
.px(px(20.))321
.px(px(20.))@@ -467,6 +489,7 @@ impl Render for SettingsView {467
let body = match self.section {489
let body = match self.section {468
Section::Notifications => self.notifications_section(cx).into_any_element(),490
Section::Notifications => self.notifications_section(cx).into_any_element(),469
Section::Devices => self.devices_section(cx).into_any_element(),491
Section::Devices => self.devices_section(cx).into_any_element(),492
Section::Mcp => self.mcp.clone().into_any_element(),470
};493
};471
v_flex()494
v_flex()472
.size_full()495
.size_full()@@ -21,6 +21,7 @@ use teams_core::{ExecuteAction, FileCard, LinkPreview};
21
21
22
22
mod feed;
23
23
mod pins;
24
mod proposal;
24
25
mod render_env;
25
26
mod scheduled;
26
27
mod shared;
@@ -615,6 +616,7 @@ impl ConversationView {
615
616
window: &mut Window,
616
617
cx: &mut Context<Self>,
617
618
) {
619
self.report_composer_activity(event, cx);
618
620
match event {
619
621
ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx),
620
622
ComposerEvent::Schedule { outgoing, send_at } => {
@@ -1067,23 +1069,16 @@ impl ConversationView {
1067
1069
}
1068
1070
}
1069
1071
1070
fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1071
let Some(conversation_id) = self
1072
.current
1073
.as_ref()
1074
.map(|current| current.selection.conversation_id().to_owned())
1075
else {
1076
return;
1077
};
1078
let store = self.app.read(cx).store.clone();
1079
let record = store
1072
fn reply_target(&self, message_id: &str, cx: &App) -> Option<(MessageRecord, ReplyPreview)> {
1073
let conversation_id = self.conversation_id()?;
1074
let record = self
1075
.app
1076
.read(cx)
1077
.store
1080
1078
.messages_by_id(&conversation_id, &[message_id.to_owned()])
1081
1079
.ok()
1082
1080
.and_then(|mut found| found.remove(message_id))
1083
.filter(|record| !record.deleted);
1084
let Some(record) = record else {
1085
return;
1086
};
1081
.filter(|record| !record.deleted)?;
1087
1082
let preview = ReplyPreview {
1088
1083
message_id: record.message_id.clone(),
1089
1084
author: record
@@ -1092,6 +1087,13 @@ impl ConversationView {
1092
1087
.unwrap_or_else(|| "Unknown".to_owned()),
1093
1088
excerpt: reply_excerpt(&record),
1094
1089
};
1090
Some((record, preview))
1091
}
1092
1093
fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1094
let Some((record, preview)) = self.reply_target(message_id, cx) else {
1095
return;
1096
};
1095
1097
if self.in_feed() {
1096
1098
let root_id = record
1097
1099
.reply_to_id
@@ -3215,6 +3217,7 @@ impl Render for ConversationView {
3215
3217
.when(!in_feed, |column| {
3216
3218
column
3217
3219
.child(self.render_typing_line(cx))
3220
.children(self.render_proposal_card(cx))
3218
3221
.child(self.composer.clone())
3219
3222
})
3220
3223
.child(self.render_drop_overlay(cx)),
@@ -21,6 +21,7 @@ use teams_core::{ExecuteAction, FileCard, LinkPreview};21
21
22
mod feed;22
mod feed;23
mod pins;23
mod pins;24
mod proposal;24
mod render_env;25
mod render_env;25
mod scheduled;26
mod scheduled;26
mod shared;27
mod shared;@@ -615,6 +616,7 @@ impl ConversationView {615
window: &mut Window,616
window: &mut Window,616
cx: &mut Context<Self>,617
cx: &mut Context<Self>,617
) {618
) {619
self.report_composer_activity(event, cx);618
match event {620
match event {619
ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx),621
ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx),620
ComposerEvent::Schedule { outgoing, send_at } => {622
ComposerEvent::Schedule { outgoing, send_at } => {@@ -1067,23 +1069,16 @@ impl ConversationView {1067
}1069
}1068
}1070
}1069
1071
1070
fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {1072
fn reply_target(&self, message_id: &str, cx: &App) -> Option<(MessageRecord, ReplyPreview)> {1071
let Some(conversation_id) = self1073
let conversation_id = self.conversation_id()?;1072
.current1074
let record = self1073
.as_ref()1075
.app1074
.map(|current| current.selection.conversation_id().to_owned())1076
.read(cx)1075
else {1077
.store1076
return;1077
};1078
let store = self.app.read(cx).store.clone();1079
let record = store1080
.messages_by_id(&conversation_id, &[message_id.to_owned()])1078
.messages_by_id(&conversation_id, &[message_id.to_owned()])1081
.ok()1079
.ok()1082
.and_then(|mut found| found.remove(message_id))1080
.and_then(|mut found| found.remove(message_id))1083
.filter(|record| !record.deleted);1081
.filter(|record| !record.deleted)?;1084
let Some(record) = record else {1085
return;1086
};1087
let preview = ReplyPreview {1082
let preview = ReplyPreview {1088
message_id: record.message_id.clone(),1083
message_id: record.message_id.clone(),1089
author: record1084
author: record@@ -1092,6 +1087,13 @@ impl ConversationView {1092
.unwrap_or_else(|| "Unknown".to_owned()),1087
.unwrap_or_else(|| "Unknown".to_owned()),1093
excerpt: reply_excerpt(&record),1088
excerpt: reply_excerpt(&record),1094
};1089
};1090
Some((record, preview))1091
}1092
1093
fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {1094
let Some((record, preview)) = self.reply_target(message_id, cx) else {1095
return;1096
};1095
if self.in_feed() {1097
if self.in_feed() {1096
let root_id = record1098
let root_id = record1097
.reply_to_id1099
.reply_to_id@@ -3215,6 +3217,7 @@ impl Render for ConversationView {3215
.when(!in_feed, |column| {3217
.when(!in_feed, |column| {3216
column3218
column3217
.child(self.render_typing_line(cx))3219
.child(self.render_typing_line(cx))3220
.children(self.render_proposal_card(cx))3218
.child(self.composer.clone())3221
.child(self.composer.clone())3219
})3222
})3220
.child(self.render_drop_overlay(cx)),3223
.child(self.render_drop_overlay(cx)),@@ -177,6 +177,7 @@ impl ConversationView {
177
177
window: &mut Window,
178
178
cx: &mut Context<Self>,
179
179
) {
180
self.report_composer_activity(event, cx);
180
181
match event {
181
182
ComposerEvent::Submit(outgoing) => {
182
183
let Some(root_id) = self.reply_root.clone() else {
@@ -218,33 +219,40 @@ impl ConversationView {
218
219
if !self.in_feed() || self.pane != ChannelPane::Posts {
219
220
return None;
220
221
}
222
let proposal_card = self.render_proposal_card(cx);
221
223
if !self.new_post_open {
222
224
return Some(
223
h_flex()
225
v_flex()
224
226
.w_full()
225
227
.flex_none()
226
.px(px(24.))
227
.pt(px(2.))
228
.pb(px(4.))
228
.children(proposal_card)
229
229
.child(
230
230
h_flex()
231
.id("new-post")
232
.h(px(32.))
233
.px(px(12.))
234
.gap(px(6.))
235
.items_center()
236
.rounded(px(8.))
237
.bg(theme::accent())
238
.text_color(theme::on_accent())
239
.text_size(px(13.))
240
.font_weight(FontWeight::SEMIBOLD)
241
.cursor_pointer()
242
.hover(|button| button.bg(theme::accent_text()))
243
.on_click(
244
cx.listener(|this, _, window, cx| this.open_new_post(window, cx)),
245
)
246
.child(icon(IconName::Plus, 14., theme::on_accent()))
247
.child("New post"),
231
.w_full()
232
.flex_none()
233
.px(px(24.))
234
.pt(px(2.))
235
.pb(px(4.))
236
.child(
237
h_flex()
238
.id("new-post")
239
.h(px(32.))
240
.px(px(12.))
241
.gap(px(6.))
242
.items_center()
243
.rounded(px(8.))
244
.bg(theme::accent())
245
.text_color(theme::on_accent())
246
.text_size(px(13.))
247
.font_weight(FontWeight::SEMIBOLD)
248
.cursor_pointer()
249
.hover(|button| button.bg(theme::accent_text()))
250
.on_click(cx.listener(|this, _, window, cx| {
251
this.open_new_post(window, cx)
252
}))
253
.child(icon(IconName::Plus, 14., theme::on_accent()))
254
.child("New post"),
255
),
248
256
)
249
257
.into_any_element(),
250
258
);
@@ -283,6 +291,7 @@ impl ConversationView {
283
291
.w_full()
284
292
.flex_none()
285
293
.children(subject)
294
.children(proposal_card)
286
295
.child(self.composer.clone())
287
296
.child(
288
297
h_flex()
@@ -177,6 +177,7 @@ impl ConversationView {177
window: &mut Window,177
window: &mut Window,178
cx: &mut Context<Self>,178
cx: &mut Context<Self>,179
) {179
) {180
self.report_composer_activity(event, cx);180
match event {181
match event {181
ComposerEvent::Submit(outgoing) => {182
ComposerEvent::Submit(outgoing) => {182
let Some(root_id) = self.reply_root.clone() else {183
let Some(root_id) = self.reply_root.clone() else {@@ -218,33 +219,40 @@ impl ConversationView {218
if !self.in_feed() || self.pane != ChannelPane::Posts {219
if !self.in_feed() || self.pane != ChannelPane::Posts {219
return None;220
return None;220
}221
}222
let proposal_card = self.render_proposal_card(cx);221
if !self.new_post_open {223
if !self.new_post_open {222
return Some(224
return Some(223
h_flex()225
v_flex()224
.w_full()226
.w_full()225
.flex_none()227
.flex_none()226
.px(px(24.))228
.children(proposal_card)227
.pt(px(2.))228
.pb(px(4.))229
.child(229
.child(230
h_flex()230
h_flex()231
.id("new-post")231
.w_full()232
.h(px(32.))232
.flex_none()233
.px(px(12.))233
.px(px(24.))234
.gap(px(6.))234
.pt(px(2.))235
.items_center()235
.pb(px(4.))236
.rounded(px(8.))236
.child(237
.bg(theme::accent())237
h_flex()238
.text_color(theme::on_accent())238
.id("new-post")239
.text_size(px(13.))239
.h(px(32.))240
.font_weight(FontWeight::SEMIBOLD)240
.px(px(12.))241
.cursor_pointer()241
.gap(px(6.))242
.hover(|button| button.bg(theme::accent_text()))242
.items_center()243
.on_click(243
.rounded(px(8.))244
cx.listener(|this, _, window, cx| this.open_new_post(window, cx)),244
.bg(theme::accent())245
)245
.text_color(theme::on_accent())246
.child(icon(IconName::Plus, 14., theme::on_accent()))246
.text_size(px(13.))247
.child("New post"),247
.font_weight(FontWeight::SEMIBOLD)248
.cursor_pointer()249
.hover(|button| button.bg(theme::accent_text()))250
.on_click(cx.listener(|this, _, window, cx| {251
this.open_new_post(window, cx)252
}))253
.child(icon(IconName::Plus, 14., theme::on_accent()))254
.child("New post"),255
),248
)256
)249
.into_any_element(),257
.into_any_element(),250
);258
);@@ -283,6 +291,7 @@ impl ConversationView {283
.w_full()291
.w_full()284
.flex_none()292
.flex_none()285
.children(subject)293
.children(subject)294
.children(proposal_card)286
.child(self.composer.clone())295
.child(self.composer.clone())287
.child(296
.child(288
h_flex()297
h_flex()@@ -0,0 +1,137 @@
1
use std::rc::Rc;
2
3
use chrono::Utc;
4
use gpui_kit::*;
5
use mcp::Outcome;
6
use teams_core::Draft;
7
8
use super::ConversationView;
9
use crate::agent_api::{self, ProposalEntry};
10
use crate::views::composer::{ComposerEvent, Outgoing};
11
use crate::views::proposal_card::{self, CardAction, CardActions};
12
13
const QUOTE_CHARS: usize = 80;
14
15
impl ConversationView {
16
pub(super) fn render_proposal_card(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
17
if self.draft_active {
18
return None;
19
}
20
let conversation_id = self.conversation_id()?;
21
let entry = agent_api::proposal(&conversation_id, cx)?;
22
let quote = entry
23
.proposal
24
.reply_to_message_id
25
.as_deref()
26
.and_then(|message_id| self.reply_target(message_id, cx))
27
.map(|(_, preview)| {
28
let excerpt: String = preview.excerpt.chars().take(QUOTE_CHARS).collect();
29
format!("{}: {excerpt}", preview.author)
30
});
31
let view = cx.entity();
32
let action = |handler: fn(&mut Self, &mut Window, &mut Context<Self>)| -> CardAction {
33
let view = view.clone();
34
Rc::new(move |window, cx| view.update(cx, |this, cx| handler(this, window, cx)))
35
};
36
let actions = CardActions {
37
send: action(Self::send_proposal),
38
edit: action(Self::edit_proposal),
39
discard: action(Self::discard_proposal),
40
};
41
Some(proposal_card::render(&entry, quote, actions, Utc::now()).into_any_element())
42
}
43
44
pub(super) fn report_composer_activity(&self, event: &ComposerEvent, cx: &App) {
45
let Some(conversation_id) = self.conversation_id().filter(|_| !self.draft_active) else {
46
return;
47
};
48
match event {
49
ComposerEvent::Typing(true) => agent_api::user_typing(&conversation_id, cx),
50
ComposerEvent::Submit(_) => agent_api::user_sent(&conversation_id, cx),
51
_ => {}
52
}
53
}
54
55
fn pending_proposal(&self, cx: &App) -> Option<(String, ProposalEntry)> {
56
let conversation_id = self.conversation_id()?;
57
let entry = agent_api::proposal(&conversation_id, cx)?;
58
Some((conversation_id, entry))
59
}
60
61
fn send_proposal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
62
let Some((conversation_id, entry)) = self.pending_proposal(cx) else {
63
return;
64
};
65
let state = self.app.read(cx);
66
let refusal = if state.mode.read_only || state.mode.demo {
67
Some("read-only mode")
68
} else if state.engine.is_none() {
69
Some("not connected yet")
70
} else {
71
None
72
};
73
if let Some(reason) = refusal {
74
agent_api::fail_proposal(&conversation_id, reason.to_owned(), cx);
75
return;
76
}
77
let target = entry
78
.proposal
79
.reply_to_message_id
80
.as_deref()
81
.and_then(|message_id| self.reply_target(message_id, cx));
82
let thread_root = target
83
.as_ref()
84
.filter(|_| self.in_feed())
85
.map(|(record, _)| {
86
record
87
.reply_to_id
88
.clone()
89
.unwrap_or_else(|| record.message_id.clone())
90
});
91
let quote = target
92
.filter(|(record, _)| !self.in_feed() || record.reply_to_id.is_some())
93
.map(|(_, preview)| preview);
94
let outgoing = Outgoing {
95
draft: Draft::from_markdown(entry.proposal.text.trim()),
96
subject: None,
97
mentions: Vec::new(),
98
reply: quote,
99
edit: None,
100
images: Vec::new(),
101
files: Vec::new(),
102
link_preview: None,
103
};
104
match thread_root {
105
Some(root_id) => self.send_in_thread(root_id, outgoing, window, cx),
106
None => self.send(outgoing, window, cx),
107
}
108
agent_api::resolve_proposal(&conversation_id, Outcome::Sent, cx);
109
}
110
111
fn edit_proposal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
112
let Some((conversation_id, entry)) = self.pending_proposal(cx) else {
113
return;
114
};
115
let reply_to = entry.proposal.reply_to_message_id.as_deref();
116
if let Some(message_id) = reply_to {
117
self.begin_reply(message_id, window, cx);
118
} else if self.in_feed() {
119
self.open_new_post(window, cx);
120
}
121
let composer = match self.reply_composer.clone() {
122
Some(reply_composer) if self.in_feed() && reply_to.is_some() => reply_composer,
123
_ => self.composer.clone(),
124
};
125
composer.update(cx, |composer, cx| {
126
composer.set_text(&entry.proposal.text, window, cx);
127
composer.focus(window, cx);
128
});
129
agent_api::resolve_proposal(&conversation_id, Outcome::Edited, cx);
130
}
131
132
fn discard_proposal(&mut self, _: &mut Window, cx: &mut Context<Self>) {
133
if let Some(conversation_id) = self.conversation_id() {
134
agent_api::resolve_proposal(&conversation_id, Outcome::Discarded, cx);
135
}
136
}
137
}
@@ -0,0 +1,137 @@1
use std::rc::Rc;2
3
use chrono::Utc;4
use gpui_kit::*;5
use mcp::Outcome;6
use teams_core::Draft;7
8
use super::ConversationView;9
use crate::agent_api::{self, ProposalEntry};10
use crate::views::composer::{ComposerEvent, Outgoing};11
use crate::views::proposal_card::{self, CardAction, CardActions};12
13
const QUOTE_CHARS: usize = 80;14
15
impl ConversationView {16
pub(super) fn render_proposal_card(&self, cx: &mut Context<Self>) -> Option<AnyElement> {17
if self.draft_active {18
return None;19
}20
let conversation_id = self.conversation_id()?;21
let entry = agent_api::proposal(&conversation_id, cx)?;22
let quote = entry23
.proposal24
.reply_to_message_id25
.as_deref()26
.and_then(|message_id| self.reply_target(message_id, cx))27
.map(|(_, preview)| {28
let excerpt: String = preview.excerpt.chars().take(QUOTE_CHARS).collect();29
format!("{}: {excerpt}", preview.author)30
});31
let view = cx.entity();32
let action = |handler: fn(&mut Self, &mut Window, &mut Context<Self>)| -> CardAction {33
let view = view.clone();34
Rc::new(move |window, cx| view.update(cx, |this, cx| handler(this, window, cx)))35
};36
let actions = CardActions {37
send: action(Self::send_proposal),38
edit: action(Self::edit_proposal),39
discard: action(Self::discard_proposal),40
};41
Some(proposal_card::render(&entry, quote, actions, Utc::now()).into_any_element())42
}43
44
pub(super) fn report_composer_activity(&self, event: &ComposerEvent, cx: &App) {45
let Some(conversation_id) = self.conversation_id().filter(|_| !self.draft_active) else {46
return;47
};48
match event {49
ComposerEvent::Typing(true) => agent_api::user_typing(&conversation_id, cx),50
ComposerEvent::Submit(_) => agent_api::user_sent(&conversation_id, cx),51
_ => {}52
}53
}54
55
fn pending_proposal(&self, cx: &App) -> Option<(String, ProposalEntry)> {56
let conversation_id = self.conversation_id()?;57
let entry = agent_api::proposal(&conversation_id, cx)?;58
Some((conversation_id, entry))59
}60
61
fn send_proposal(&mut self, window: &mut Window, cx: &mut Context<Self>) {62
let Some((conversation_id, entry)) = self.pending_proposal(cx) else {63
return;64
};65
let state = self.app.read(cx);66
let refusal = if state.mode.read_only || state.mode.demo {67
Some("read-only mode")68
} else if state.engine.is_none() {69
Some("not connected yet")70
} else {71
None72
};73
if let Some(reason) = refusal {74
agent_api::fail_proposal(&conversation_id, reason.to_owned(), cx);75
return;76
}77
let target = entry78
.proposal79
.reply_to_message_id80
.as_deref()81
.and_then(|message_id| self.reply_target(message_id, cx));82
let thread_root = target83
.as_ref()84
.filter(|_| self.in_feed())85
.map(|(record, _)| {86
record87
.reply_to_id88
.clone()89
.unwrap_or_else(|| record.message_id.clone())90
});91
let quote = target92
.filter(|(record, _)| !self.in_feed() || record.reply_to_id.is_some())93
.map(|(_, preview)| preview);94
let outgoing = Outgoing {95
draft: Draft::from_markdown(entry.proposal.text.trim()),96
subject: None,97
mentions: Vec::new(),98
reply: quote,99
edit: None,100
images: Vec::new(),101
files: Vec::new(),102
link_preview: None,103
};104
match thread_root {105
Some(root_id) => self.send_in_thread(root_id, outgoing, window, cx),106
None => self.send(outgoing, window, cx),107
}108
agent_api::resolve_proposal(&conversation_id, Outcome::Sent, cx);109
}110
111
fn edit_proposal(&mut self, window: &mut Window, cx: &mut Context<Self>) {112
let Some((conversation_id, entry)) = self.pending_proposal(cx) else {113
return;114
};115
let reply_to = entry.proposal.reply_to_message_id.as_deref();116
if let Some(message_id) = reply_to {117
self.begin_reply(message_id, window, cx);118
} else if self.in_feed() {119
self.open_new_post(window, cx);120
}121
let composer = match self.reply_composer.clone() {122
Some(reply_composer) if self.in_feed() && reply_to.is_some() => reply_composer,123
_ => self.composer.clone(),124
};125
composer.update(cx, |composer, cx| {126
composer.set_text(&entry.proposal.text, window, cx);127
composer.focus(window, cx);128
});129
agent_api::resolve_proposal(&conversation_id, Outcome::Edited, cx);130
}131
132
fn discard_proposal(&mut self, _: &mut Window, cx: &mut Context<Self>) {133
if let Some(conversation_id) = self.conversation_id() {134
agent_api::resolve_proposal(&conversation_id, Outcome::Discarded, cx);135
}136
}137
}@@ -36,6 +36,7 @@ pub mod new_chat;
36
36
pub mod pin_banner;
37
37
pub mod post_card;
38
38
pub mod profile_card;
39
pub mod proposal_card;
39
40
pub mod rail;
40
41
pub mod reaction_picker;
41
42
pub mod reaction_pills;
@@ -36,6 +36,7 @@ pub mod new_chat;36
pub mod pin_banner;36
pub mod pin_banner;37
pub mod post_card;37
pub mod post_card;38
pub mod profile_card;38
pub mod profile_card;39
pub mod proposal_card;39
pub mod rail;40
pub mod rail;40
pub mod reaction_picker;41
pub mod reaction_picker;41
pub mod reaction_pills;42
pub mod reaction_pills;@@ -0,0 +1,239 @@
1
use std::rc::Rc;
2
3
use chrono::{DateTime, Utc};
4
use gpui_kit::assets::IconName;
5
use gpui_kit::component::{h_flex, v_flex};
6
use gpui_kit::prelude::FluentBuilder as _;
7
use gpui_kit::*;
8
9
use crate::agent_api::{ProposalEntry, ProposalStatus, agent_label};
10
use crate::theme;
11
use crate::views::widgets::icon;
12
13
const CARD_MARGIN_X: f32 = 20.;
14
const CARD_MARGIN_BOTTOM: f32 = 8.;
15
const CARD_PADDING: f32 = 12.;
16
const CARD_RADIUS: f32 = 10.;
17
const CARD_GAP: f32 = 8.;
18
const BUTTON_HEIGHT: f32 = 28.;
19
const BUTTON_RADIUS: f32 = 7.;
20
const BODY_LINE_HEIGHT: f32 = 20.;
21
const BODY_MAX_LINES: f32 = 4.;
22
const QUOTE_BAR_WIDTH: f32 = 2.;
23
24
pub type CardAction = Rc<dyn Fn(&mut Window, &mut App)>;
25
26
#[derive(Clone)]
27
pub struct CardActions {
28
pub send: CardAction,
29
pub edit: CardAction,
30
pub discard: CardAction,
31
}
32
33
fn open_session_available() -> bool {
34
false
35
}
36
37
fn open_session(_session_id: &str, _window: &mut Window, _cx: &mut App) {}
38
39
pub fn age_label(created_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
40
let minutes = (now - created_at).num_minutes().max(0);
41
match minutes {
42
0 => "just now".to_owned(),
43
1..=59 => format!("{minutes} min ago"),
44
60..=1439 => format!("{} h ago", minutes / 60),
45
_ => format!("{} d ago", minutes / 1440),
46
}
47
}
48
49
fn card_button(
50
id: &'static str,
51
label: &'static str,
52
background: Hsla,
53
color: Hsla,
54
action: CardAction,
55
) -> Stateful<Div> {
56
div()
57
.id(id)
58
.h(px(BUTTON_HEIGHT))
59
.px(px(12.))
60
.flex()
61
.items_center()
62
.rounded(px(BUTTON_RADIUS))
63
.cursor_pointer()
64
.text_size(px(12.))
65
.font_weight(FontWeight::SEMIBOLD)
66
.bg(background)
67
.text_color(color)
68
.hover(|button| button.opacity(0.85))
69
.child(label)
70
.on_click(move |_, window, cx| action(window, cx))
71
}
72
73
fn header_text(entry: &ProposalEntry, now: DateTime<Utc>) -> (String, Hsla, Option<String>) {
74
let agent = agent_label(entry.proposal.agent.as_deref());
75
match &entry.status {
76
ProposalStatus::Pending => (
77
format!("{agent} proposes a reply"),
78
theme::accent_text(),
79
Some(format!(" - {}", age_label(entry.proposal.created_at, now))),
80
),
81
ProposalStatus::Stale { answered_at } => (
82
format!(
83
"{agent}'s reply is outdated - you answered at {}",
84
answered_at.format("%H:%M")
85
),
86
theme::text_muted(),
87
None,
88
),
89
ProposalStatus::Failed { reason } => (
90
format!("Could not send - {reason}"),
91
theme::red_soft(),
92
None,
93
),
94
}
95
}
96
97
pub fn render(
98
entry: &ProposalEntry,
99
quote: Option<String>,
100
actions: CardActions,
101
now: DateTime<Utc>,
102
) -> Div {
103
let stale = matches!(entry.status, ProposalStatus::Stale { .. });
104
let failed = matches!(entry.status, ProposalStatus::Failed { .. });
105
let (title, title_color, age) = header_text(entry, now);
106
let close = actions.discard.clone();
107
let header = h_flex()
108
.w_full()
109
.items_center()
110
.gap(px(4.))
111
.child(
112
h_flex()
113
.flex_1()
114
.min_w_0()
115
.items_baseline()
116
.overflow_hidden()
117
.text_size(px(12.))
118
.child(
119
div()
120
.truncate()
121
.font_weight(FontWeight::SEMIBOLD)
122
.text_color(title_color)
123
.child(title),
124
)
125
.children(
126
age.map(|age| div().flex_none().text_color(theme::text_faint()).child(age)),
127
),
128
)
129
.child(
130
div()
131
.id("proposal-close")
132
.size(px(BUTTON_HEIGHT))
133
.flex_none()
134
.flex()
135
.items_center()
136
.justify_center()
137
.rounded(px(BUTTON_RADIUS))
138
.cursor_pointer()
139
.hover(|button| button.bg(theme::surface_raised()))
140
.child(icon(IconName::Close, 14., theme::text_muted()))
141
.on_click(move |_, window, cx| close(window, cx)),
142
);
143
let quote = quote.map(|quote| {
144
div()
145
.w_full()
146
.truncate()
147
.pl(px(8.))
148
.border_l(px(QUOTE_BAR_WIDTH))
149
.border_color(theme::border_strong())
150
.text_size(px(12.))
151
.text_color(theme::text_muted())
152
.child(quote)
153
});
154
let body = div()
155
.w_full()
156
.max_h(px(BODY_LINE_HEIGHT * BODY_MAX_LINES))
157
.overflow_hidden()
158
.text_size(px(14.))
159
.line_height(px(BODY_LINE_HEIGHT))
160
.text_color(if stale {
161
theme::text_faint()
162
} else {
163
theme::text()
164
})
165
.child(entry.proposal.text.clone());
166
let session = entry
167
.proposal
168
.session_id
169
.clone()
170
.filter(|_| open_session_available());
171
let buttons = h_flex()
172
.w_full()
173
.items_center()
174
.gap(px(8.))
175
.when(!stale, |row| {
176
row.child(card_button(
177
"proposal-send",
178
if failed { "Retry" } else { "Send" },
179
theme::accent(),
180
theme::on_accent(),
181
actions.send.clone(),
182
))
183
})
184
.child(card_button(
185
"proposal-edit",
186
"Edit",
187
theme::surface_raised(),
188
theme::text(),
189
actions.edit.clone(),
190
))
191
.child(card_button(
192
"proposal-discard",
193
"Discard",
194
theme::surface_raised(),
195
theme::text(),
196
actions.discard.clone(),
197
))
198
.children(session.map(|session_id| {
199
div()
200
.id("proposal-open-session")
201
.ml_auto()
202
.cursor_pointer()
203
.text_size(px(12.))
204
.text_color(theme::accent_text())
205
.child("Open session")
206
.on_click(move |_, window, cx| open_session(&session_id, window, cx))
207
}));
208
v_flex()
209
.flex_none()
210
.mx(px(CARD_MARGIN_X))
211
.mb(px(CARD_MARGIN_BOTTOM))
212
.p(px(CARD_PADDING))
213
.gap(px(CARD_GAP))
214
.rounded(px(CARD_RADIUS))
215
.bg(theme::row_hover())
216
.child(header)
217
.children(quote)
218
.child(body)
219
.child(buttons)
220
}
221
222
#[cfg(test)]
223
mod tests {
224
use chrono::{Duration, Utc};
225
226
use super::age_label;
227
228
#[test]
229
fn age_labels_follow_the_elapsed_time() {
230
let now = Utc::now();
231
let label = |minutes: i64| age_label(now - Duration::minutes(minutes), now);
232
assert_eq!(label(0), "just now");
233
assert_eq!(label(1), "1 min ago");
234
assert_eq!(label(59), "59 min ago");
235
assert_eq!(label(120), "2 h ago");
236
assert_eq!(label(3000), "2 d ago");
237
assert_eq!(age_label(now + Duration::minutes(5), now), "just now");
238
}
239
}
@@ -0,0 +1,239 @@1
use std::rc::Rc;2
3
use chrono::{DateTime, Utc};4
use gpui_kit::assets::IconName;5
use gpui_kit::component::{h_flex, v_flex};6
use gpui_kit::prelude::FluentBuilder as _;7
use gpui_kit::*;8
9
use crate::agent_api::{ProposalEntry, ProposalStatus, agent_label};10
use crate::theme;11
use crate::views::widgets::icon;12
13
const CARD_MARGIN_X: f32 = 20.;14
const CARD_MARGIN_BOTTOM: f32 = 8.;15
const CARD_PADDING: f32 = 12.;16
const CARD_RADIUS: f32 = 10.;17
const CARD_GAP: f32 = 8.;18
const BUTTON_HEIGHT: f32 = 28.;19
const BUTTON_RADIUS: f32 = 7.;20
const BODY_LINE_HEIGHT: f32 = 20.;21
const BODY_MAX_LINES: f32 = 4.;22
const QUOTE_BAR_WIDTH: f32 = 2.;23
24
pub type CardAction = Rc<dyn Fn(&mut Window, &mut App)>;25
26
#[derive(Clone)]27
pub struct CardActions {28
pub send: CardAction,29
pub edit: CardAction,30
pub discard: CardAction,31
}32
33
fn open_session_available() -> bool {34
false35
}36
37
fn open_session(_session_id: &str, _window: &mut Window, _cx: &mut App) {}38
39
pub fn age_label(created_at: DateTime<Utc>, now: DateTime<Utc>) -> String {40
let minutes = (now - created_at).num_minutes().max(0);41
match minutes {42
0 => "just now".to_owned(),43
1..=59 => format!("{minutes} min ago"),44
60..=1439 => format!("{} h ago", minutes / 60),45
_ => format!("{} d ago", minutes / 1440),46
}47
}48
49
fn card_button(50
id: &'static str,51
label: &'static str,52
background: Hsla,53
color: Hsla,54
action: CardAction,55
) -> Stateful<Div> {56
div()57
.id(id)58
.h(px(BUTTON_HEIGHT))59
.px(px(12.))60
.flex()61
.items_center()62
.rounded(px(BUTTON_RADIUS))63
.cursor_pointer()64
.text_size(px(12.))65
.font_weight(FontWeight::SEMIBOLD)66
.bg(background)67
.text_color(color)68
.hover(|button| button.opacity(0.85))69
.child(label)70
.on_click(move |_, window, cx| action(window, cx))71
}72
73
fn header_text(entry: &ProposalEntry, now: DateTime<Utc>) -> (String, Hsla, Option<String>) {74
let agent = agent_label(entry.proposal.agent.as_deref());75
match &entry.status {76
ProposalStatus::Pending => (77
format!("{agent} proposes a reply"),78
theme::accent_text(),79
Some(format!(" - {}", age_label(entry.proposal.created_at, now))),80
),81
ProposalStatus::Stale { answered_at } => (82
format!(83
"{agent}'s reply is outdated - you answered at {}",84
answered_at.format("%H:%M")85
),86
theme::text_muted(),87
None,88
),89
ProposalStatus::Failed { reason } => (90
format!("Could not send - {reason}"),91
theme::red_soft(),92
None,93
),94
}95
}96
97
pub fn render(98
entry: &ProposalEntry,99
quote: Option<String>,100
actions: CardActions,101
now: DateTime<Utc>,102
) -> Div {103
let stale = matches!(entry.status, ProposalStatus::Stale { .. });104
let failed = matches!(entry.status, ProposalStatus::Failed { .. });105
let (title, title_color, age) = header_text(entry, now);106
let close = actions.discard.clone();107
let header = h_flex()108
.w_full()109
.items_center()110
.gap(px(4.))111
.child(112
h_flex()113
.flex_1()114
.min_w_0()115
.items_baseline()116
.overflow_hidden()117
.text_size(px(12.))118
.child(119
div()120
.truncate()121
.font_weight(FontWeight::SEMIBOLD)122
.text_color(title_color)123
.child(title),124
)125
.children(126
age.map(|age| div().flex_none().text_color(theme::text_faint()).child(age)),127
),128
)129
.child(130
div()131
.id("proposal-close")132
.size(px(BUTTON_HEIGHT))133
.flex_none()134
.flex()135
.items_center()136
.justify_center()137
.rounded(px(BUTTON_RADIUS))138
.cursor_pointer()139
.hover(|button| button.bg(theme::surface_raised()))140
.child(icon(IconName::Close, 14., theme::text_muted()))141
.on_click(move |_, window, cx| close(window, cx)),142
);143
let quote = quote.map(|quote| {144
div()145
.w_full()146
.truncate()147
.pl(px(8.))148
.border_l(px(QUOTE_BAR_WIDTH))149
.border_color(theme::border_strong())150
.text_size(px(12.))151
.text_color(theme::text_muted())152
.child(quote)153
});154
let body = div()155
.w_full()156
.max_h(px(BODY_LINE_HEIGHT * BODY_MAX_LINES))157
.overflow_hidden()158
.text_size(px(14.))159
.line_height(px(BODY_LINE_HEIGHT))160
.text_color(if stale {161
theme::text_faint()162
} else {163
theme::text()164
})165
.child(entry.proposal.text.clone());166
let session = entry167
.proposal168
.session_id169
.clone()170
.filter(|_| open_session_available());171
let buttons = h_flex()172
.w_full()173
.items_center()174
.gap(px(8.))175
.when(!stale, |row| {176
row.child(card_button(177
"proposal-send",178
if failed { "Retry" } else { "Send" },179
theme::accent(),180
theme::on_accent(),181
actions.send.clone(),182
))183
})184
.child(card_button(185
"proposal-edit",186
"Edit",187
theme::surface_raised(),188
theme::text(),189
actions.edit.clone(),190
))191
.child(card_button(192
"proposal-discard",193
"Discard",194
theme::surface_raised(),195
theme::text(),196
actions.discard.clone(),197
))198
.children(session.map(|session_id| {199
div()200
.id("proposal-open-session")201
.ml_auto()202
.cursor_pointer()203
.text_size(px(12.))204
.text_color(theme::accent_text())205
.child("Open session")206
.on_click(move |_, window, cx| open_session(&session_id, window, cx))207
}));208
v_flex()209
.flex_none()210
.mx(px(CARD_MARGIN_X))211
.mb(px(CARD_MARGIN_BOTTOM))212
.p(px(CARD_PADDING))213
.gap(px(CARD_GAP))214
.rounded(px(CARD_RADIUS))215
.bg(theme::row_hover())216
.child(header)217
.children(quote)218
.child(body)219
.child(buttons)220
}221
222
#[cfg(test)]223
mod tests {224
use chrono::{Duration, Utc};225
226
use super::age_label;227
228
#[test]229
fn age_labels_follow_the_elapsed_time() {230
let now = Utc::now();231
let label = |minutes: i64| age_label(now - Duration::minutes(minutes), now);232
assert_eq!(label(0), "just now");233
assert_eq!(label(1), "1 min ago");234
assert_eq!(label(59), "59 min ago");235
assert_eq!(label(120), "2 h ago");236
assert_eq!(label(3000), "2 d ago");237
assert_eq!(age_label(now + Duration::minutes(5), now), "just now");238
}239
}@@ -34,6 +34,7 @@ use crate::theme;
34
34
const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
35
35
pub const SIDEBAR_WIDTH: f32 = 300.;
36
36
const ROW_HEIGHT: f32 = 54.;
37
const PROPOSAL_DOT_SIZE: f32 = 8.;
37
38
const PINNED_CHANNEL_HEIGHT: f32 = 48.;
38
39
const SECTION_HEIGHT: f32 = 30.;
39
40
const SECTION_GAP: f32 = 4.;
@@ -293,6 +294,7 @@ pub struct SidebarView {
293
294
calls_scroll: ScrollHandle,
294
295
_subscription: Subscription,
295
296
_state_observation: Subscription,
297
_agent_observation: Option<Subscription>,
296
298
}
297
299
298
300
fn preview_text(preview: &Preview) -> Option<(String, bool)> {
@@ -370,6 +372,8 @@ impl SidebarView {
370
372
}
371
373
});
372
374
let state_observation = cx.observe(&state, |_, _, cx| cx.notify());
375
let agent_observation =
376
crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
373
377
let tab = if state.read(cx).start_on_channels {
374
378
SidebarTab::Channels
375
379
} else {
@@ -403,6 +407,7 @@ impl SidebarView {
403
407
calls_scroll: ScrollHandle::new(),
404
408
_subscription: subscription,
405
409
_state_observation: state_observation,
410
_agent_observation: agent_observation,
406
411
}
407
412
}
408
413
@@ -658,6 +663,7 @@ impl SidebarView {
658
663
item: &ChatItem,
659
664
selected: bool,
660
665
local_preview: Option<&LocalPreview>,
666
proposal_agent: Option<&'static str>,
661
667
directory: &Directory,
662
668
menu: &MenuContext,
663
669
) -> AnyElement {
@@ -715,9 +721,18 @@ impl SidebarView {
715
721
} else {
716
722
theme::text_muted()
717
723
};
718
let preview = match local_preview {
719
Some(local) => Some(local_preview_row(local, preview_color)),
720
None => preview_text(&item.preview).map(|(text, italic)| {
724
let preview = match (proposal_agent, local_preview) {
725
(Some(agent), _) => Some(
726
h_flex()
727
.flex_1()
728
.min_w_0()
729
.overflow_hidden()
730
.text_size(px(12.5))
731
.text_color(theme::accent_text())
732
.child(div().truncate().child(format!("Proposal from {agent}"))),
733
),
734
(None, Some(local)) => Some(local_preview_row(local, preview_color)),
735
(None, None) => preview_text(&item.preview).map(|(text, italic)| {
721
736
let glyph = preview_icon(&text);
722
737
h_flex()
723
738
.flex_1()
@@ -749,7 +764,18 @@ impl SidebarView {
749
764
.gap(px(8.))
750
765
.items_center()
751
766
.child(preview.unwrap_or_else(|| div().flex_1()))
752
.children(unread_marker(item.unread, item.muted)),
767
.children(match proposal_agent {
768
Some(_) => Some(
769
div()
770
.size(px(PROPOSAL_DOT_SIZE))
771
.flex_none()
772
.rounded_full()
773
.bg(theme::accent())
774
.into_any_element(),
775
),
776
None => unread_marker(item.unread, item.muted)
777
.map(IntoElement::into_any_element),
778
}),
753
779
);
754
780
let state = self.state.clone();
755
781
let chat_id = item.id.clone();
@@ -796,6 +822,7 @@ impl SidebarView {
796
822
}
797
823
798
824
fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {
825
let proposal_agents = crate::agent_api::pending_agents(cx);
799
826
let (sections, menu, local_previews) = {
800
827
let state = self.state.read(cx);
801
828
let now = Utc::now();
@@ -872,6 +899,7 @@ impl SidebarView {
872
899
item,
873
900
is_selected,
874
901
local_preview,
902
proposal_agents.get(&item.id).copied(),
875
903
directory,
876
904
&menu,
877
905
));
@@ -34,6 +34,7 @@ use crate::theme;34
const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";34
const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";35
pub const SIDEBAR_WIDTH: f32 = 300.;35
pub const SIDEBAR_WIDTH: f32 = 300.;36
const ROW_HEIGHT: f32 = 54.;36
const ROW_HEIGHT: f32 = 54.;37
const PROPOSAL_DOT_SIZE: f32 = 8.;37
const PINNED_CHANNEL_HEIGHT: f32 = 48.;38
const PINNED_CHANNEL_HEIGHT: f32 = 48.;38
const SECTION_HEIGHT: f32 = 30.;39
const SECTION_HEIGHT: f32 = 30.;39
const SECTION_GAP: f32 = 4.;40
const SECTION_GAP: f32 = 4.;@@ -293,6 +294,7 @@ pub struct SidebarView {293
calls_scroll: ScrollHandle,294
calls_scroll: ScrollHandle,294
_subscription: Subscription,295
_subscription: Subscription,295
_state_observation: Subscription,296
_state_observation: Subscription,297
_agent_observation: Option<Subscription>,296
}298
}297
299
298
fn preview_text(preview: &Preview) -> Option<(String, bool)> {300
fn preview_text(preview: &Preview) -> Option<(String, bool)> {@@ -370,6 +372,8 @@ impl SidebarView {370
}372
}371
});373
});372
let state_observation = cx.observe(&state, |_, _, cx| cx.notify());374
let state_observation = cx.observe(&state, |_, _, cx| cx.notify());375
let agent_observation =376
crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));373
let tab = if state.read(cx).start_on_channels {377
let tab = if state.read(cx).start_on_channels {374
SidebarTab::Channels378
SidebarTab::Channels375
} else {379
} else {@@ -403,6 +407,7 @@ impl SidebarView {403
calls_scroll: ScrollHandle::new(),407
calls_scroll: ScrollHandle::new(),404
_subscription: subscription,408
_subscription: subscription,405
_state_observation: state_observation,409
_state_observation: state_observation,410
_agent_observation: agent_observation,406
}411
}407
}412
}408
413
@@ -658,6 +663,7 @@ impl SidebarView {658
item: &ChatItem,663
item: &ChatItem,659
selected: bool,664
selected: bool,660
local_preview: Option<&LocalPreview>,665
local_preview: Option<&LocalPreview>,666
proposal_agent: Option<&'static str>,661
directory: &Directory,667
directory: &Directory,662
menu: &MenuContext,668
menu: &MenuContext,663
) -> AnyElement {669
) -> AnyElement {@@ -715,9 +721,18 @@ impl SidebarView {715
} else {721
} else {716
theme::text_muted()722
theme::text_muted()717
};723
};718
let preview = match local_preview {724
let preview = match (proposal_agent, local_preview) {719
Some(local) => Some(local_preview_row(local, preview_color)),725
(Some(agent), _) => Some(720
None => preview_text(&item.preview).map(|(text, italic)| {726
h_flex()727
.flex_1()728
.min_w_0()729
.overflow_hidden()730
.text_size(px(12.5))731
.text_color(theme::accent_text())732
.child(div().truncate().child(format!("Proposal from {agent}"))),733
),734
(None, Some(local)) => Some(local_preview_row(local, preview_color)),735
(None, None) => preview_text(&item.preview).map(|(text, italic)| {721
let glyph = preview_icon(&text);736
let glyph = preview_icon(&text);722
h_flex()737
h_flex()723
.flex_1()738
.flex_1()@@ -749,7 +764,18 @@ impl SidebarView {749
.gap(px(8.))764
.gap(px(8.))750
.items_center()765
.items_center()751
.child(preview.unwrap_or_else(|| div().flex_1()))766
.child(preview.unwrap_or_else(|| div().flex_1()))752
.children(unread_marker(item.unread, item.muted)),767
.children(match proposal_agent {768
Some(_) => Some(769
div()770
.size(px(PROPOSAL_DOT_SIZE))771
.flex_none()772
.rounded_full()773
.bg(theme::accent())774
.into_any_element(),775
),776
None => unread_marker(item.unread, item.muted)777
.map(IntoElement::into_any_element),778
}),753
);779
);754
let state = self.state.clone();780
let state = self.state.clone();755
let chat_id = item.id.clone();781
let chat_id = item.id.clone();@@ -796,6 +822,7 @@ impl SidebarView {796
}822
}797
823
798
fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {824
fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {825
let proposal_agents = crate::agent_api::pending_agents(cx);799
let (sections, menu, local_previews) = {826
let (sections, menu, local_previews) = {800
let state = self.state.read(cx);827
let state = self.state.read(cx);801
let now = Utc::now();828
let now = Utc::now();@@ -872,6 +899,7 @@ impl SidebarView {872
item,899
item,873
is_selected,900
is_selected,874
local_preview,901
local_preview,902
proposal_agents.get(&item.id).copied(),875
directory,903
directory,876
&menu,904
&menu,877
));905
));@@ -18,6 +18,7 @@ pub mod realtime;
18
18
pub mod receipts;
19
19
pub mod saved;
20
20
pub mod settings;
21
pub mod transcripts;
21
22
pub mod translate;
22
23
23
24
pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
@@ -55,6 +56,7 @@ pub use realtime::{
55
56
pub use receipts::{MemberHorizon, Receipts};
56
57
pub use saved::SavedMessage;
57
58
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};
59
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};
58
60
pub use translate::{
59
61
Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
60
62
TranslationStatus, TranslationTrigger, Translator, language_code,
@@ -18,6 +18,7 @@ pub mod realtime;18
pub mod receipts;18
pub mod receipts;19
pub mod saved;19
pub mod saved;20
pub mod settings;20
pub mod settings;21
pub mod transcripts;21
pub mod translate;22
pub mod translate;22
23
23
pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};24
pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};@@ -55,6 +56,7 @@ pub use realtime::{55
pub use receipts::{MemberHorizon, Receipts};56
pub use receipts::{MemberHorizon, Receipts};56
pub use saved::SavedMessage;57
pub use saved::SavedMessage;57
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};58
pub use settings::{ChatSection, ChatSectionSettings, UserSettings};59
pub use transcripts::{MeetingTranscript, TranscriptError, TranscriptTurn, Transcripts};58
pub use translate::{60
pub use translate::{59
Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,61
Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,60
TranslationStatus, TranslationTrigger, Translator, language_code,62
TranslationStatus, TranslationTrigger, Translator, language_code,@@ -0,0 +1,372 @@
1
use base64::Engine as _;
2
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
3
use serde_json::Value;
4
use session::{Scope, Session};
5
6
use crate::messages::encode;
7
8
const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail";
9
const RECORDING_SUCCESS: &str = "success";
10
const MESSAGES_SCOPE: &str = "Chat.Read";
11
const SITE_SCOPE: &str = ".default";
12
const MAX_MESSAGE_PAGES: usize = 40;
13
const UNKNOWN_SPEAKER: &str = "?";
14
15
#[derive(Debug, Clone, PartialEq)]
16
pub struct TranscriptTurn {
17
pub speaker: String,
18
pub start_seconds: f64,
19
pub end_seconds: f64,
20
pub text: String,
21
}
22
23
#[derive(Debug, Clone, PartialEq)]
24
pub struct MeetingTranscript {
25
pub meeting_thread_id: String,
26
pub recording_name: Option<String>,
27
pub created_at: Option<String>,
28
pub turns: Vec<TranscriptTurn>,
29
}
30
31
#[derive(Debug, thiserror::Error)]
32
pub enum TranscriptError {
33
#[error("no finished recording in this meeting chat")]
34
NoRecording,
35
#[error("the recording has no transcript")]
36
NoTranscript,
37
#[error("no access to the recording or its transcript")]
38
AccessDenied,
39
#[error(transparent)]
40
Request(session::Error),
41
}
42
43
#[derive(Debug, Clone, PartialEq, Eq)]
44
pub struct Recording {
45
pub url: String,
46
pub name: Option<String>,
47
}
48
49
#[derive(Debug, Clone, PartialEq, Eq)]
50
pub struct TranscriptInfo {
51
pub id: String,
52
pub created_at: Option<String>,
53
}
54
55
pub struct Transcripts<'a> {
56
session: &'a Session,
57
}
58
59
impl<'a> Transcripts<'a> {
60
pub fn new(session: &'a Session) -> Self {
61
Transcripts { session }
62
}
63
64
pub async fn for_meeting_chat(
65
&self,
66
thread_id: &str,
67
) -> Result<MeetingTranscript, TranscriptError> {
68
let recording = self.find_recording(thread_id).await?;
69
let site = site_origin(&recording.url);
70
let site_scope = Scope::new(site.clone(), SITE_SCOPE);
71
let item_url = self.item_url(&recording.url, &site, &site_scope).await?;
72
let listing = self
73
.get(
74
&format!("{item_url}/media/transcripts"),
75
&site_scope,
76
TranscriptError::NoTranscript,
77
)
78
.await?;
79
let transcript = newest_transcript(parse_transcript_list(&listing))
80
.ok_or(TranscriptError::NoTranscript)?;
81
let content = self
82
.get(
83
&format!(
84
"{item_url}/media/transcripts/{}/streamContent?format=json",
85
encode(&transcript.id)
86
),
87
&site_scope,
88
TranscriptError::NoTranscript,
89
)
90
.await?;
91
Ok(MeetingTranscript {
92
meeting_thread_id: thread_id.to_owned(),
93
recording_name: recording.name,
94
created_at: transcript.created_at,
95
turns: parse_turns(&content),
96
})
97
}
98
99
async fn find_recording(&self, thread_id: &str) -> Result<Recording, TranscriptError> {
100
let scope = Scope::graph(MESSAGES_SCOPE);
101
let mut url = format!(
102
"{}/v1.0/chats/{}/messages?$top=50&$orderby=createdDateTime desc",
103
session::GRAPH,
104
encode(thread_id)
105
);
106
for _ in 0..MAX_MESSAGE_PAGES {
107
let page = self.get(&url, &scope, TranscriptError::NoRecording).await?;
108
if let Some(recording) = find_recording(&page) {
109
return Ok(recording);
110
}
111
match page.get("@odata.nextLink").and_then(Value::as_str) {
112
Some(next) => url = next.to_owned(),
113
None => break,
114
}
115
}
116
Err(TranscriptError::NoRecording)
117
}
118
119
async fn item_url(
120
&self,
121
recording_url: &str,
122
site: &str,
123
site_scope: &Scope,
124
) -> Result<String, TranscriptError> {
125
let item = self
126
.get(
127
&format!(
128
"{site}/_api/v2.1/shares/{}/driveItem?$select=id,parentReference",
129
share_id(recording_url)
130
),
131
site_scope,
132
TranscriptError::NoRecording,
133
)
134
.await?;
135
let drive_id = item
136
.pointer("/parentReference/driveId")
137
.and_then(Value::as_str);
138
let item_id = item.get("id").and_then(Value::as_str);
139
match (drive_id, item_id) {
140
(Some(drive_id), Some(item_id)) => Ok(format!(
141
"{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"
142
)),
143
_ => Err(TranscriptError::NoRecording),
144
}
145
}
146
147
async fn get(
148
&self,
149
url: &str,
150
scope: &Scope,
151
not_found: TranscriptError,
152
) -> Result<Value, TranscriptError> {
153
match self
154
.session
155
.request(session::Method::Get, url, scope, None)
156
.await
157
{
158
Ok(answer) => Ok(answer.body),
159
Err(session::Error::Api {
160
status: 403 | 401, ..
161
}) => Err(TranscriptError::AccessDenied),
162
Err(session::Error::Api { status: 404, .. }) => Err(not_found),
163
Err(error) => Err(TranscriptError::Request(error)),
164
}
165
}
166
}
167
168
pub fn find_recording(messages_json: &Value) -> Option<Recording> {
169
messages_json
170
.get("value")?
171
.as_array()?
172
.iter()
173
.find_map(|message| {
174
let detail = message.get("eventDetail")?;
175
let matches = detail.get("@odata.type").and_then(Value::as_str)
176
== Some(RECORDING_EVENT)
177
&& detail.get("callRecordingStatus").and_then(Value::as_str)
178
== Some(RECORDING_SUCCESS);
179
let url = detail.get("callRecordingUrl").and_then(Value::as_str)?;
180
if !matches || !url.starts_with("https://") {
181
return None;
182
}
183
Some(Recording {
184
url: url.to_owned(),
185
name: detail
186
.get("callRecordingDisplayName")
187
.and_then(Value::as_str)
188
.filter(|name| !name.is_empty())
189
.map(str::to_owned),
190
})
191
})
192
}
193
194
pub fn find_recording_url(messages_json: &Value) -> Option<String> {
195
find_recording(messages_json).map(|recording| recording.url)
196
}
197
198
pub fn share_id(url: &str) -> String {
199
format!("u!{}", URL_SAFE_NO_PAD.encode(url))
200
}
201
202
pub fn site_origin(url: &str) -> String {
203
let (scheme, rest) = url.split_once("://").unwrap_or(("https", url));
204
let host = rest.split(['/', '?', '#']).next().unwrap_or(rest);
205
format!("{scheme}://{host}")
206
}
207
208
pub fn parse_transcript_list(listing_json: &Value) -> Vec<TranscriptInfo> {
209
listing_json
210
.get("value")
211
.and_then(Value::as_array)
212
.into_iter()
213
.flatten()
214
.filter(|entry| {
215
entry
216
.get("isVisible")
217
.and_then(Value::as_bool)
218
.unwrap_or(true)
219
})
220
.filter_map(|entry| {
221
Some(TranscriptInfo {
222
id: entry
223
.get("id")?
224
.as_str()
225
.filter(|id| !id.is_empty())?
226
.to_owned(),
227
created_at: entry
228
.get("createdDateTime")
229
.and_then(Value::as_str)
230
.map(str::to_owned),
231
})
232
})
233
.collect()
234
}
235
236
pub fn newest_transcript(transcripts: Vec<TranscriptInfo>) -> Option<TranscriptInfo> {
237
transcripts
238
.into_iter()
239
.max_by(|left, right| left.created_at.cmp(&right.created_at))
240
}
241
242
pub fn parse_turns(content_json: &Value) -> Vec<TranscriptTurn> {
243
let turns = content_json
244
.get("entries")
245
.and_then(Value::as_array)
246
.into_iter()
247
.flatten()
248
.filter_map(|entry| {
249
let text = entry.get("text").and_then(Value::as_str)?.trim();
250
if text.is_empty() {
251
return None;
252
}
253
let speaker = entry
254
.get("speakerDisplayName")
255
.and_then(Value::as_str)
256
.filter(|name| !name.is_empty())
257
.unwrap_or(UNKNOWN_SPEAKER);
258
Some(TranscriptTurn {
259
speaker: speaker.to_owned(),
260
start_seconds: offset_seconds(entry.get("startOffset")),
261
end_seconds: offset_seconds(entry.get("endOffset")),
262
text: text.to_owned(),
263
})
264
})
265
.collect();
266
merge_consecutive_turns(turns)
267
}
268
269
pub fn merge_consecutive_turns(turns: Vec<TranscriptTurn>) -> Vec<TranscriptTurn> {
270
let mut merged: Vec<TranscriptTurn> = Vec::new();
271
for turn in turns {
272
match merged.last_mut() {
273
Some(last) if last.speaker == turn.speaker => {
274
last.text.push(' ');
275
last.text.push_str(&turn.text);
276
last.end_seconds = turn.end_seconds;
277
}
278
_ => merged.push(turn),
279
}
280
}
281
merged
282
}
283
284
fn offset_seconds(offset: Option<&Value>) -> f64 {
285
offset
286
.and_then(Value::as_str)
287
.map(|text| {
288
text.split(':').fold(0.0, |total, part| {
289
total * 60.0 + part.parse::<f64>().unwrap_or(0.0)
290
})
291
})
292
.unwrap_or(0.0)
293
}
294
295
#[cfg(test)]
296
mod tests {
297
use super::*;
298
299
fn fixture(name: &str) -> Value {
300
let path = format!(
301
"{}/tests/fixtures/transcripts/{name}",
302
env!("CARGO_MANIFEST_DIR")
303
);
304
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
305
}
306
307
#[test]
308
fn finds_the_successful_recording_only() {
309
let recording = find_recording(&fixture("messages.json")).unwrap();
310
assert!(recording.url.ends_with("Weekly%20sync.mp4"));
311
assert_eq!(
312
recording.name.as_deref(),
313
Some("Weekly sync-20260302_100000-Meeting Recording.mp4")
314
);
315
assert_eq!(
316
find_recording_url(&fixture("messages.json")),
317
Some(recording.url)
318
);
319
}
320
321
#[test]
322
fn no_recording_in_chat_without_event() {
323
assert_eq!(
324
find_recording_url(&serde_json::json!({"value": [{"id": "1"}]})),
325
None
326
);
327
assert_eq!(find_recording_url(&serde_json::json!({})), None);
328
}
329
330
#[test]
331
fn share_id_is_unpadded_base64url() {
332
assert_eq!(
333
share_id("https://a.example/x?y=>>"),
334
"u!aHR0cHM6Ly9hLmV4YW1wbGUveD95PT4-"
335
);
336
assert!(!share_id("https://a.example/ab").contains('='));
337
}
338
339
#[test]
340
fn site_origin_drops_path() {
341
assert_eq!(
342
site_origin("https://contoso-my.sharepoint.com/personal/a/b.mp4?e=1"),
343
"https://contoso-my.sharepoint.com"
344
);
345
}
346
347
#[test]
348
fn list_skips_hidden_and_idless_and_picks_newest() {
349
let transcripts = parse_transcript_list(&fixture("list.json"));
350
assert_eq!(transcripts.len(), 2);
351
assert_eq!(newest_transcript(transcripts).unwrap().id, "t-new");
352
assert_eq!(newest_transcript(Vec::new()), None);
353
}
354
355
#[test]
356
fn turns_merge_same_speaker_and_parse_offsets() {
357
let turns = parse_turns(&fixture("content.json"));
358
assert_eq!(turns.len(), 4);
359
assert_eq!(turns[0].speaker, "Alex Example");
360
assert_eq!(turns[0].text, "Welcome everyone. Let us start.");
361
assert_eq!(turns[0].start_seconds, 1.5);
362
assert_eq!(turns[0].end_seconds, 7.0);
363
assert_eq!(turns[1].end_seconds, 69.25);
364
assert_eq!(turns[2].speaker, "?");
365
assert_eq!(turns[2].start_seconds, 3600.0);
366
}
367
368
#[test]
369
fn missing_entries_give_no_turns() {
370
assert!(parse_turns(&serde_json::json!({})).is_empty());
371
}
372
}
@@ -0,0 +1,372 @@1
use base64::Engine as _;2
use base64::engine::general_purpose::URL_SAFE_NO_PAD;3
use serde_json::Value;4
use session::{Scope, Session};5
6
use crate::messages::encode;7
8
const RECORDING_EVENT: &str = "#microsoft.graph.callRecordingEventMessageDetail";9
const RECORDING_SUCCESS: &str = "success";10
const MESSAGES_SCOPE: &str = "Chat.Read";11
const SITE_SCOPE: &str = ".default";12
const MAX_MESSAGE_PAGES: usize = 40;13
const UNKNOWN_SPEAKER: &str = "?";14
15
#[derive(Debug, Clone, PartialEq)]16
pub struct TranscriptTurn {17
pub speaker: String,18
pub start_seconds: f64,19
pub end_seconds: f64,20
pub text: String,21
}22
23
#[derive(Debug, Clone, PartialEq)]24
pub struct MeetingTranscript {25
pub meeting_thread_id: String,26
pub recording_name: Option<String>,27
pub created_at: Option<String>,28
pub turns: Vec<TranscriptTurn>,29
}30
31
#[derive(Debug, thiserror::Error)]32
pub enum TranscriptError {33
#[error("no finished recording in this meeting chat")]34
NoRecording,35
#[error("the recording has no transcript")]36
NoTranscript,37
#[error("no access to the recording or its transcript")]38
AccessDenied,39
#[error(transparent)]40
Request(session::Error),41
}42
43
#[derive(Debug, Clone, PartialEq, Eq)]44
pub struct Recording {45
pub url: String,46
pub name: Option<String>,47
}48
49
#[derive(Debug, Clone, PartialEq, Eq)]50
pub struct TranscriptInfo {51
pub id: String,52
pub created_at: Option<String>,53
}54
55
pub struct Transcripts<'a> {56
session: &'a Session,57
}58
59
impl<'a> Transcripts<'a> {60
pub fn new(session: &'a Session) -> Self {61
Transcripts { session }62
}63
64
pub async fn for_meeting_chat(65
&self,66
thread_id: &str,67
) -> Result<MeetingTranscript, TranscriptError> {68
let recording = self.find_recording(thread_id).await?;69
let site = site_origin(&recording.url);70
let site_scope = Scope::new(site.clone(), SITE_SCOPE);71
let item_url = self.item_url(&recording.url, &site, &site_scope).await?;72
let listing = self73
.get(74
&format!("{item_url}/media/transcripts"),75
&site_scope,76
TranscriptError::NoTranscript,77
)78
.await?;79
let transcript = newest_transcript(parse_transcript_list(&listing))80
.ok_or(TranscriptError::NoTranscript)?;81
let content = self82
.get(83
&format!(84
"{item_url}/media/transcripts/{}/streamContent?format=json",85
encode(&transcript.id)86
),87
&site_scope,88
TranscriptError::NoTranscript,89
)90
.await?;91
Ok(MeetingTranscript {92
meeting_thread_id: thread_id.to_owned(),93
recording_name: recording.name,94
created_at: transcript.created_at,95
turns: parse_turns(&content),96
})97
}98
99
async fn find_recording(&self, thread_id: &str) -> Result<Recording, TranscriptError> {100
let scope = Scope::graph(MESSAGES_SCOPE);101
let mut url = format!(102
"{}/v1.0/chats/{}/messages?$top=50&$orderby=createdDateTime desc",103
session::GRAPH,104
encode(thread_id)105
);106
for _ in 0..MAX_MESSAGE_PAGES {107
let page = self.get(&url, &scope, TranscriptError::NoRecording).await?;108
if let Some(recording) = find_recording(&page) {109
return Ok(recording);110
}111
match page.get("@odata.nextLink").and_then(Value::as_str) {112
Some(next) => url = next.to_owned(),113
None => break,114
}115
}116
Err(TranscriptError::NoRecording)117
}118
119
async fn item_url(120
&self,121
recording_url: &str,122
site: &str,123
site_scope: &Scope,124
) -> Result<String, TranscriptError> {125
let item = self126
.get(127
&format!(128
"{site}/_api/v2.1/shares/{}/driveItem?$select=id,parentReference",129
share_id(recording_url)130
),131
site_scope,132
TranscriptError::NoRecording,133
)134
.await?;135
let drive_id = item136
.pointer("/parentReference/driveId")137
.and_then(Value::as_str);138
let item_id = item.get("id").and_then(Value::as_str);139
match (drive_id, item_id) {140
(Some(drive_id), Some(item_id)) => Ok(format!(141
"{site}/_api/v2.1/drives/{drive_id}/items/{item_id}"142
)),143
_ => Err(TranscriptError::NoRecording),144
}145
}146
147
async fn get(148
&self,149
url: &str,150
scope: &Scope,151
not_found: TranscriptError,152
) -> Result<Value, TranscriptError> {153
match self154
.session155
.request(session::Method::Get, url, scope, None)156
.await157
{158
Ok(answer) => Ok(answer.body),159
Err(session::Error::Api {160
status: 403 | 401, ..161
}) => Err(TranscriptError::AccessDenied),162
Err(session::Error::Api { status: 404, .. }) => Err(not_found),163
Err(error) => Err(TranscriptError::Request(error)),164
}165
}166
}167
168
pub fn find_recording(messages_json: &Value) -> Option<Recording> {169
messages_json170
.get("value")?171
.as_array()?172
.iter()173
.find_map(|message| {174
let detail = message.get("eventDetail")?;175
let matches = detail.get("@odata.type").and_then(Value::as_str)176
== Some(RECORDING_EVENT)177
&& detail.get("callRecordingStatus").and_then(Value::as_str)178
== Some(RECORDING_SUCCESS);179
let url = detail.get("callRecordingUrl").and_then(Value::as_str)?;180
if !matches || !url.starts_with("https://") {181
return None;182
}183
Some(Recording {184
url: url.to_owned(),185
name: detail186
.get("callRecordingDisplayName")187
.and_then(Value::as_str)188
.filter(|name| !name.is_empty())189
.map(str::to_owned),190
})191
})192
}193
194
pub fn find_recording_url(messages_json: &Value) -> Option<String> {195
find_recording(messages_json).map(|recording| recording.url)196
}197
198
pub fn share_id(url: &str) -> String {199
format!("u!{}", URL_SAFE_NO_PAD.encode(url))200
}201
202
pub fn site_origin(url: &str) -> String {203
let (scheme, rest) = url.split_once("://").unwrap_or(("https", url));204
let host = rest.split(['/', '?', '#']).next().unwrap_or(rest);205
format!("{scheme}://{host}")206
}207
208
pub fn parse_transcript_list(listing_json: &Value) -> Vec<TranscriptInfo> {209
listing_json210
.get("value")211
.and_then(Value::as_array)212
.into_iter()213
.flatten()214
.filter(|entry| {215
entry216
.get("isVisible")217
.and_then(Value::as_bool)218
.unwrap_or(true)219
})220
.filter_map(|entry| {221
Some(TranscriptInfo {222
id: entry223
.get("id")?224
.as_str()225
.filter(|id| !id.is_empty())?226
.to_owned(),227
created_at: entry228
.get("createdDateTime")229
.and_then(Value::as_str)230
.map(str::to_owned),231
})232
})233
.collect()234
}235
236
pub fn newest_transcript(transcripts: Vec<TranscriptInfo>) -> Option<TranscriptInfo> {237
transcripts238
.into_iter()239
.max_by(|left, right| left.created_at.cmp(&right.created_at))240
}241
242
pub fn parse_turns(content_json: &Value) -> Vec<TranscriptTurn> {243
let turns = content_json244
.get("entries")245
.and_then(Value::as_array)246
.into_iter()247
.flatten()248
.filter_map(|entry| {249
let text = entry.get("text").and_then(Value::as_str)?.trim();250
if text.is_empty() {251
return None;252
}253
let speaker = entry254
.get("speakerDisplayName")255
.and_then(Value::as_str)256
.filter(|name| !name.is_empty())257
.unwrap_or(UNKNOWN_SPEAKER);258
Some(TranscriptTurn {259
speaker: speaker.to_owned(),260
start_seconds: offset_seconds(entry.get("startOffset")),261
end_seconds: offset_seconds(entry.get("endOffset")),262
text: text.to_owned(),263
})264
})265
.collect();266
merge_consecutive_turns(turns)267
}268
269
pub fn merge_consecutive_turns(turns: Vec<TranscriptTurn>) -> Vec<TranscriptTurn> {270
let mut merged: Vec<TranscriptTurn> = Vec::new();271
for turn in turns {272
match merged.last_mut() {273
Some(last) if last.speaker == turn.speaker => {274
last.text.push(' ');275
last.text.push_str(&turn.text);276
last.end_seconds = turn.end_seconds;277
}278
_ => merged.push(turn),279
}280
}281
merged282
}283
284
fn offset_seconds(offset: Option<&Value>) -> f64 {285
offset286
.and_then(Value::as_str)287
.map(|text| {288
text.split(':').fold(0.0, |total, part| {289
total * 60.0 + part.parse::<f64>().unwrap_or(0.0)290
})291
})292
.unwrap_or(0.0)293
}294
295
#[cfg(test)]296
mod tests {297
use super::*;298
299
fn fixture(name: &str) -> Value {300
let path = format!(301
"{}/tests/fixtures/transcripts/{name}",302
env!("CARGO_MANIFEST_DIR")303
);304
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()305
}306
307
#[test]308
fn finds_the_successful_recording_only() {309
let recording = find_recording(&fixture("messages.json")).unwrap();310
assert!(recording.url.ends_with("Weekly%20sync.mp4"));311
assert_eq!(312
recording.name.as_deref(),313
Some("Weekly sync-20260302_100000-Meeting Recording.mp4")314
);315
assert_eq!(316
find_recording_url(&fixture("messages.json")),317
Some(recording.url)318
);319
}320
321
#[test]322
fn no_recording_in_chat_without_event() {323
assert_eq!(324
find_recording_url(&serde_json::json!({"value": [{"id": "1"}]})),325
None326
);327
assert_eq!(find_recording_url(&serde_json::json!({})), None);328
}329
330
#[test]331
fn share_id_is_unpadded_base64url() {332
assert_eq!(333
share_id("https://a.example/x?y=>>"),334
"u!aHR0cHM6Ly9hLmV4YW1wbGUveD95PT4-"335
);336
assert!(!share_id("https://a.example/ab").contains('='));337
}338
339
#[test]340
fn site_origin_drops_path() {341
assert_eq!(342
site_origin("https://contoso-my.sharepoint.com/personal/a/b.mp4?e=1"),343
"https://contoso-my.sharepoint.com"344
);345
}346
347
#[test]348
fn list_skips_hidden_and_idless_and_picks_newest() {349
let transcripts = parse_transcript_list(&fixture("list.json"));350
assert_eq!(transcripts.len(), 2);351
assert_eq!(newest_transcript(transcripts).unwrap().id, "t-new");352
assert_eq!(newest_transcript(Vec::new()), None);353
}354
355
#[test]356
fn turns_merge_same_speaker_and_parse_offsets() {357
let turns = parse_turns(&fixture("content.json"));358
assert_eq!(turns.len(), 4);359
assert_eq!(turns[0].speaker, "Alex Example");360
assert_eq!(turns[0].text, "Welcome everyone. Let us start.");361
assert_eq!(turns[0].start_seconds, 1.5);362
assert_eq!(turns[0].end_seconds, 7.0);363
assert_eq!(turns[1].end_seconds, 69.25);364
assert_eq!(turns[2].speaker, "?");365
assert_eq!(turns[2].start_seconds, 3600.0);366
}367
368
#[test]369
fn missing_entries_give_no_turns() {370
assert!(parse_turns(&serde_json::json!({})).is_empty());371
}372
}@@ -0,0 +1,10 @@
1
{
2
"entries": [
3
{"speakerDisplayName": "Alex Example", "startOffset": "00:00:01.5000000", "endOffset": "00:00:04.0000000", "text": "Welcome everyone."},
4
{"speakerDisplayName": "Alex Example", "startOffset": "00:00:04.2000000", "endOffset": "00:00:07.0000000", "text": " Let us start. "},
5
{"speakerDisplayName": "Sam Sample", "startOffset": "00:00:07.5000000", "endOffset": "00:01:09.2500000", "text": "Sounds good."},
6
{"speakerDisplayName": "Sam Sample", "startOffset": "00:01:10.0000000", "endOffset": "00:01:11.0000000", "text": " "},
7
{"startOffset": "01:00:00.0000000", "endOffset": "01:00:02.0000000", "text": "Who is this?"},
8
{"speakerDisplayName": "Alex Example", "startOffset": "01:00:03.0000000", "endOffset": "01:00:04.0000000", "text": "Back again."}
9
]
10
}
@@ -0,0 +1,10 @@1
{2
"entries": [3
{"speakerDisplayName": "Alex Example", "startOffset": "00:00:01.5000000", "endOffset": "00:00:04.0000000", "text": "Welcome everyone."},4
{"speakerDisplayName": "Alex Example", "startOffset": "00:00:04.2000000", "endOffset": "00:00:07.0000000", "text": " Let us start. "},5
{"speakerDisplayName": "Sam Sample", "startOffset": "00:00:07.5000000", "endOffset": "00:01:09.2500000", "text": "Sounds good."},6
{"speakerDisplayName": "Sam Sample", "startOffset": "00:01:10.0000000", "endOffset": "00:01:11.0000000", "text": " "},7
{"startOffset": "01:00:00.0000000", "endOffset": "01:00:02.0000000", "text": "Who is this?"},8
{"speakerDisplayName": "Alex Example", "startOffset": "01:00:03.0000000", "endOffset": "01:00:04.0000000", "text": "Back again."}9
]10
}@@ -0,0 +1,8 @@
1
{
2
"value": [
3
{"id": "t-old", "createdDateTime": "2026-03-02T10:31:00Z", "isVisible": true},
4
{"id": "t-new", "createdDateTime": "2026-03-02T11:05:00Z", "isVisible": true},
5
{"id": "t-hidden", "createdDateTime": "2026-03-02T12:00:00Z", "isVisible": false},
6
{"createdDateTime": "2026-03-02T13:00:00Z"}
7
]
8
}
@@ -0,0 +1,8 @@1
{2
"value": [3
{"id": "t-old", "createdDateTime": "2026-03-02T10:31:00Z", "isVisible": true},4
{"id": "t-new", "createdDateTime": "2026-03-02T11:05:00Z", "isVisible": true},5
{"id": "t-hidden", "createdDateTime": "2026-03-02T12:00:00Z", "isVisible": false},6
{"createdDateTime": "2026-03-02T13:00:00Z"}7
]8
}@@ -0,0 +1,28 @@
1
{
2
"value": [
3
{
4
"id": "1003",
5
"createdDateTime": "2026-03-02T10:30:00Z",
6
"eventDetail": {
7
"@odata.type": "#microsoft.graph.callRecordingEventMessageDetail",
8
"callRecordingStatus": "success",
9
"callRecordingDisplayName": "Weekly sync-20260302_100000-Meeting Recording.mp4",
10
"callRecordingUrl": "https://contoso-my.sharepoint.com/personal/alex_example_contoso_com/Documents/Recordings/Weekly%20sync.mp4"
11
}
12
},
13
{
14
"id": "1002",
15
"createdDateTime": "2026-03-02T10:29:00Z",
16
"eventDetail": {
17
"@odata.type": "#microsoft.graph.callRecordingEventMessageDetail",
18
"callRecordingStatus": "chunkFinished",
19
"callRecordingUrl": "https://contoso-my.sharepoint.com/chunk"
20
}
21
},
22
{
23
"id": "1001",
24
"createdDateTime": "2026-03-02T10:00:00Z",
25
"eventDetail": {"@odata.type": "#microsoft.graph.callStartedEventMessageDetail"}
26
}
27
]
28
}
@@ -0,0 +1,28 @@1
{2
"value": [3
{4
"id": "1003",5
"createdDateTime": "2026-03-02T10:30:00Z",6
"eventDetail": {7
"@odata.type": "#microsoft.graph.callRecordingEventMessageDetail",8
"callRecordingStatus": "success",9
"callRecordingDisplayName": "Weekly sync-20260302_100000-Meeting Recording.mp4",10
"callRecordingUrl": "https://contoso-my.sharepoint.com/personal/alex_example_contoso_com/Documents/Recordings/Weekly%20sync.mp4"11
}12
},13
{14
"id": "1002",15
"createdDateTime": "2026-03-02T10:29:00Z",16
"eventDetail": {17
"@odata.type": "#microsoft.graph.callRecordingEventMessageDetail",18
"callRecordingStatus": "chunkFinished",19
"callRecordingUrl": "https://contoso-my.sharepoint.com/chunk"20
}21
},22
{23
"id": "1001",24
"createdDateTime": "2026-03-02T10:00:00Z",25
"eventDetail": {"@odata.type": "#microsoft.graph.callStartedEventMessageDetail"}26
}27
]28
}@@ -0,0 +1,27 @@
1
[package]
2
name = "mcp"
3
edition.workspace = true
4
version.workspace = true
5
license.workspace = true
6
publish.workspace = true
7
8
[dependencies]
9
axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] }
10
chrono.workspace = true
11
percent-encoding.workspace = true
12
rand = "0.9"
13
rmcp = { version = "=3.5.1", features = ["server", "macros", "transport-streamable-http-server"] }
14
serde.workspace = true
15
serde_json = { workspace = true, features = ["raw_value"] }
16
store.workspace = true
17
subtle = "2"
18
thiserror.workspace = true
19
toml_edit = "0.22"
20
tokio.workspace = true
21
tokio-util = "0.7"
22
uuid.workspace = true
23
24
[dev-dependencies]
25
reqwest = { version = "0.13", default-features = false, features = ["rustls"] }
26
rmcp = { version = "=3.5.1", features = ["client", "transport-streamable-http-client-reqwest"] }
27
tempfile.workspace = true
@@ -0,0 +1,27 @@1
[package]2
name = "mcp"3
edition.workspace = true4
version.workspace = true5
license.workspace = true6
publish.workspace = true7
8
[dependencies]9
axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] }10
chrono.workspace = true11
percent-encoding.workspace = true12
rand = "0.9"13
rmcp = { version = "=3.5.1", features = ["server", "macros", "transport-streamable-http-server"] }14
serde.workspace = true15
serde_json = { workspace = true, features = ["raw_value"] }16
store.workspace = true17
subtle = "2"18
thiserror.workspace = true19
toml_edit = "0.22"20
tokio.workspace = true21
tokio-util = "0.7"22
uuid.workspace = true23
24
[dev-dependencies]25
reqwest = { version = "0.13", default-features = false, features = ["rustls"] }26
rmcp = { version = "=3.5.1", features = ["client", "transport-streamable-http-client-reqwest"] }27
tempfile.workspace = true@@ -0,0 +1,155 @@
1
use axum::body::Body;
2
use axum::extract::State;
3
use axum::http::header::{AUTHORIZATION, HOST, ORIGIN};
4
use axum::http::{HeaderMap, Request, StatusCode};
5
use axum::middleware::Next;
6
use axum::response::{IntoResponse, Response};
7
use subtle::ConstantTimeEq;
8
9
pub const MAX_BODY_BYTES: usize = 1024 * 1024;
10
const LOOPBACK_HOSTS: [&str; 2] = ["127.0.0.1", "localhost"];
11
const BEARER_PREFIX: &str = "Bearer ";
12
13
#[derive(Clone)]
14
pub struct AuthState {
15
pub port: u16,
16
pub token: String,
17
}
18
19
impl AuthState {
20
pub fn allowed_hosts(&self) -> Vec<String> {
21
LOOPBACK_HOSTS
22
.iter()
23
.map(|host| format!("{host}:{}", self.port))
24
.collect()
25
}
26
27
pub fn allowed_origins(&self) -> Vec<String> {
28
self.allowed_hosts()
29
.into_iter()
30
.map(|authority| format!("http://{authority}"))
31
.collect()
32
}
33
34
fn host_allowed(&self, headers: &HeaderMap) -> bool {
35
header_text(headers, HOST)
36
.is_some_and(|host| self.allowed_hosts().iter().any(|allowed| allowed == host))
37
}
38
39
fn origin_allowed(&self, headers: &HeaderMap) -> bool {
40
match headers.get(ORIGIN) {
41
None => true,
42
Some(origin) => origin.to_str().is_ok_and(|origin| {
43
self.allowed_origins()
44
.iter()
45
.any(|allowed| allowed == origin)
46
}),
47
}
48
}
49
50
fn token_valid(&self, headers: &HeaderMap) -> bool {
51
header_text(headers, AUTHORIZATION)
52
.and_then(|value| value.strip_prefix(BEARER_PREFIX))
53
.is_some_and(|presented| presented.as_bytes().ct_eq(self.token.as_bytes()).into())
54
}
55
}
56
57
fn header_text(headers: &HeaderMap, name: axum::http::HeaderName) -> Option<&str> {
58
headers.get(name)?.to_str().ok()
59
}
60
61
pub async fn require_auth(
62
State(auth): State<AuthState>,
63
request: Request<Body>,
64
next: Next,
65
) -> Response {
66
let headers = request.headers();
67
if !auth.host_allowed(headers) || !auth.origin_allowed(headers) {
68
return StatusCode::FORBIDDEN.into_response();
69
}
70
if !auth.token_valid(headers) {
71
return StatusCode::UNAUTHORIZED.into_response();
72
}
73
next.run(request).await
74
}
75
76
pub async fn healthz() -> &'static str {
77
"ok"
78
}
79
80
#[cfg(test)]
81
mod tests {
82
use axum::http::HeaderValue;
83
84
use super::*;
85
86
fn auth() -> AuthState {
87
AuthState {
88
port: 47615,
89
token: "secret".to_owned(),
90
}
91
}
92
93
fn headers(pairs: &[(axum::http::HeaderName, &str)]) -> HeaderMap {
94
let mut map = HeaderMap::new();
95
for (name, value) in pairs {
96
map.insert(name.clone(), HeaderValue::from_str(value).unwrap());
97
}
98
map
99
}
100
101
#[test]
102
fn host_must_be_loopback_with_the_port() {
103
let cases = [
104
("127.0.0.1:47615", true),
105
("localhost:47615", true),
106
("localhost:1", false),
107
("127.0.0.1", false),
108
("evil.example:47615", false),
109
("evil.example", false),
110
];
111
for (host, allowed) in cases {
112
assert_eq!(
113
auth().host_allowed(&headers(&[(HOST, host)])),
114
allowed,
115
"{host}"
116
);
117
}
118
assert!(!auth().host_allowed(&HeaderMap::new()));
119
}
120
121
#[test]
122
fn origin_is_absent_or_loopback() {
123
let cases = [
124
(None, true),
125
(Some("http://127.0.0.1:47615"), true),
126
(Some("http://localhost:47615"), true),
127
(Some("https://localhost:47615"), false),
128
(Some("http://evil.example"), false),
129
(Some("null"), false),
130
];
131
for (origin, allowed) in cases {
132
let map = origin.map_or_else(HeaderMap::new, |value| headers(&[(ORIGIN, value)]));
133
assert_eq!(auth().origin_allowed(&map), allowed, "{origin:?}");
134
}
135
}
136
137
#[test]
138
fn token_needs_the_exact_bearer_value() {
139
let cases = [
140
("Bearer secret", true),
141
("Bearer secre", false),
142
("Bearer secrets", false),
143
("bearer secret", false),
144
("secret", false),
145
];
146
for (value, valid) in cases {
147
assert_eq!(
148
auth().token_valid(&headers(&[(AUTHORIZATION, value)])),
149
valid,
150
"{value}"
151
);
152
}
153
assert!(!auth().token_valid(&HeaderMap::new()));
154
}
155
}
@@ -0,0 +1,155 @@1
use axum::body::Body;2
use axum::extract::State;3
use axum::http::header::{AUTHORIZATION, HOST, ORIGIN};4
use axum::http::{HeaderMap, Request, StatusCode};5
use axum::middleware::Next;6
use axum::response::{IntoResponse, Response};7
use subtle::ConstantTimeEq;8
9
pub const MAX_BODY_BYTES: usize = 1024 * 1024;10
const LOOPBACK_HOSTS: [&str; 2] = ["127.0.0.1", "localhost"];11
const BEARER_PREFIX: &str = "Bearer ";12
13
#[derive(Clone)]14
pub struct AuthState {15
pub port: u16,16
pub token: String,17
}18
19
impl AuthState {20
pub fn allowed_hosts(&self) -> Vec<String> {21
LOOPBACK_HOSTS22
.iter()23
.map(|host| format!("{host}:{}", self.port))24
.collect()25
}26
27
pub fn allowed_origins(&self) -> Vec<String> {28
self.allowed_hosts()29
.into_iter()30
.map(|authority| format!("http://{authority}"))31
.collect()32
}33
34
fn host_allowed(&self, headers: &HeaderMap) -> bool {35
header_text(headers, HOST)36
.is_some_and(|host| self.allowed_hosts().iter().any(|allowed| allowed == host))37
}38
39
fn origin_allowed(&self, headers: &HeaderMap) -> bool {40
match headers.get(ORIGIN) {41
None => true,42
Some(origin) => origin.to_str().is_ok_and(|origin| {43
self.allowed_origins()44
.iter()45
.any(|allowed| allowed == origin)46
}),47
}48
}49
50
fn token_valid(&self, headers: &HeaderMap) -> bool {51
header_text(headers, AUTHORIZATION)52
.and_then(|value| value.strip_prefix(BEARER_PREFIX))53
.is_some_and(|presented| presented.as_bytes().ct_eq(self.token.as_bytes()).into())54
}55
}56
57
fn header_text(headers: &HeaderMap, name: axum::http::HeaderName) -> Option<&str> {58
headers.get(name)?.to_str().ok()59
}60
61
pub async fn require_auth(62
State(auth): State<AuthState>,63
request: Request<Body>,64
next: Next,65
) -> Response {66
let headers = request.headers();67
if !auth.host_allowed(headers) || !auth.origin_allowed(headers) {68
return StatusCode::FORBIDDEN.into_response();69
}70
if !auth.token_valid(headers) {71
return StatusCode::UNAUTHORIZED.into_response();72
}73
next.run(request).await74
}75
76
pub async fn healthz() -> &'static str {77
"ok"78
}79
80
#[cfg(test)]81
mod tests {82
use axum::http::HeaderValue;83
84
use super::*;85
86
fn auth() -> AuthState {87
AuthState {88
port: 47615,89
token: "secret".to_owned(),90
}91
}92
93
fn headers(pairs: &[(axum::http::HeaderName, &str)]) -> HeaderMap {94
let mut map = HeaderMap::new();95
for (name, value) in pairs {96
map.insert(name.clone(), HeaderValue::from_str(value).unwrap());97
}98
map99
}100
101
#[test]102
fn host_must_be_loopback_with_the_port() {103
let cases = [104
("127.0.0.1:47615", true),105
("localhost:47615", true),106
("localhost:1", false),107
("127.0.0.1", false),108
("evil.example:47615", false),109
("evil.example", false),110
];111
for (host, allowed) in cases {112
assert_eq!(113
auth().host_allowed(&headers(&[(HOST, host)])),114
allowed,115
"{host}"116
);117
}118
assert!(!auth().host_allowed(&HeaderMap::new()));119
}120
121
#[test]122
fn origin_is_absent_or_loopback() {123
let cases = [124
(None, true),125
(Some("http://127.0.0.1:47615"), true),126
(Some("http://localhost:47615"), true),127
(Some("https://localhost:47615"), false),128
(Some("http://evil.example"), false),129
(Some("null"), false),130
];131
for (origin, allowed) in cases {132
let map = origin.map_or_else(HeaderMap::new, |value| headers(&[(ORIGIN, value)]));133
assert_eq!(auth().origin_allowed(&map), allowed, "{origin:?}");134
}135
}136
137
#[test]138
fn token_needs_the_exact_bearer_value() {139
let cases = [140
("Bearer secret", true),141
("Bearer secre", false),142
("Bearer secrets", false),143
("bearer secret", false),144
("secret", false),145
];146
for (value, valid) in cases {147
assert_eq!(148
auth().token_valid(&headers(&[(AUTHORIZATION, value)])),149
valid,150
"{value}"151
);152
}153
assert!(!auth().token_valid(&HeaderMap::new()));154
}155
}@@ -0,0 +1,559 @@
1
use std::collections::{HashMap, VecDeque};
2
use std::sync::{Arc, Mutex, MutexGuard};
3
use std::time::Duration;
4
5
use chrono::{DateTime, Utc};
6
use serde::Serialize;
7
use store::{AgentProposalRecord, Store};
8
use tokio::sync::Notify;
9
use tokio::sync::mpsc::UnboundedSender;
10
11
use crate::policy::AgentPolicy;
12
13
const EVENT_CAPACITY: usize = 1000;
14
const CAPTION_CAPACITY: usize = 2000;
15
const PENDING_STATE: &str = "pending";
16
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub struct Proposal {
19
pub id: String,
20
pub conversation_id: String,
21
pub reply_to_message_id: Option<String>,
22
pub text: String,
23
pub agent: Option<String>,
24
pub session_id: Option<String>,
25
pub created_at: DateTime<Utc>,
26
}
27
28
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
29
pub struct CaptionLine {
30
#[serde(skip)]
31
pub caption_id: String,
32
pub speaker: String,
33
pub text: String,
34
pub at: DateTime<Utc>,
35
}
36
37
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
38
#[serde(rename_all = "snake_case")]
39
pub enum Outcome {
40
Sent,
41
Edited,
42
Discarded,
43
Stale,
44
Superseded,
45
}
46
47
impl Outcome {
48
fn state(self) -> &'static str {
49
match self {
50
Outcome::Sent => "sent",
51
Outcome::Edited => "edited",
52
Outcome::Discarded => "discarded",
53
Outcome::Stale => "stale",
54
Outcome::Superseded => "superseded",
55
}
56
}
57
}
58
59
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
60
#[serde(tag = "type", rename_all = "snake_case")]
61
pub enum EventKind {
62
NewMessage {
63
conversation_id: String,
64
message_id: String,
65
sender: Option<String>,
66
preview: String,
67
},
68
UserTyping {
69
conversation_id: String,
70
},
71
UserSent {
72
conversation_id: String,
73
},
74
ProposalResolved {
75
proposal_id: String,
76
conversation_id: String,
77
outcome: Outcome,
78
},
79
}
80
81
impl EventKind {
82
pub fn conversation_id(&self) -> &str {
83
match self {
84
EventKind::NewMessage {
85
conversation_id, ..
86
}
87
| EventKind::UserTyping { conversation_id }
88
| EventKind::UserSent { conversation_id }
89
| EventKind::ProposalResolved {
90
conversation_id, ..
91
} => conversation_id,
92
}
93
}
94
}
95
96
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
97
pub struct Event {
98
pub seq: u64,
99
#[serde(flatten)]
100
pub kind: EventKind,
101
}
102
103
#[derive(Debug, Clone, PartialEq, Eq)]
104
pub enum UiEvent {
105
ProposalChanged(Proposal),
106
ProposalStale(Proposal),
107
ProposalRemoved { conversation_id: String },
108
}
109
110
#[derive(Default)]
111
struct HubState {
112
policy: AgentPolicy,
113
pending: HashMap<String, Proposal>,
114
events: VecDeque<Event>,
115
last_seq: u64,
116
captions: HashMap<String, VecDeque<CaptionLine>>,
117
}
118
119
pub struct AgentHub {
120
state: Mutex<HubState>,
121
wake: Notify,
122
store: Arc<Store>,
123
ui: UnboundedSender<UiEvent>,
124
}
125
126
impl AgentHub {
127
pub fn new(store: Arc<Store>, policy: AgentPolicy, ui: UnboundedSender<UiEvent>) -> Arc<Self> {
128
Arc::new(AgentHub {
129
state: Mutex::new(HubState {
130
policy,
131
..HubState::default()
132
}),
133
wake: Notify::new(),
134
store,
135
ui,
136
})
137
}
138
139
pub fn set_policy(&self, policy: AgentPolicy) {
140
self.lock().policy = policy;
141
}
142
143
pub fn policy(&self) -> AgentPolicy {
144
self.lock().policy.clone()
145
}
146
147
pub fn pending_proposal(&self, conversation_id: &str) -> Option<Proposal> {
148
self.lock().pending.get(conversation_id).cloned()
149
}
150
151
pub fn restore_pending(&self) -> store::Result<()> {
152
let records = self.store.pending_agent_proposals()?;
153
let mut state = self.lock();
154
for record in records {
155
let proposal = proposal_from_record(record);
156
let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));
157
state
158
.pending
159
.insert(proposal.conversation_id.clone(), proposal);
160
}
161
Ok(())
162
}
163
164
pub fn add_proposal(
165
&self,
166
conversation_id: &str,
167
text: &str,
168
reply_to_message_id: Option<String>,
169
agent: Option<String>,
170
session_id: Option<String>,
171
) -> store::Result<Proposal> {
172
let proposal = Proposal {
173
id: uuid::Uuid::new_v4().to_string(),
174
conversation_id: conversation_id.to_owned(),
175
reply_to_message_id,
176
text: text.to_owned(),
177
agent,
178
session_id,
179
created_at: now_millis(),
180
};
181
self.store.insert_agent_proposal(&AgentProposalRecord {
182
id: proposal.id.clone(),
183
conversation_id: proposal.conversation_id.clone(),
184
reply_to_message_id: proposal.reply_to_message_id.clone(),
185
text: proposal.text.clone(),
186
agent: proposal.agent.clone(),
187
session_id: proposal.session_id.clone(),
188
created_at: proposal.created_at,
189
state: PENDING_STATE.to_owned(),
190
resolved_at: None,
191
})?;
192
let mut state = self.lock();
193
if let Some(previous) = state
194
.pending
195
.insert(conversation_id.to_owned(), proposal.clone())
196
{
197
self.finish(&mut state, &previous, Outcome::Superseded);
198
}
199
let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));
200
drop(state);
201
self.wake.notify_waiters();
202
Ok(proposal)
203
}
204
205
pub fn resolve(&self, proposal_id: &str, outcome: Outcome) -> bool {
206
let mut state = self.lock();
207
let Some(conversation_id) = state
208
.pending
209
.values()
210
.find(|proposal| proposal.id == proposal_id)
211
.map(|proposal| proposal.conversation_id.clone())
212
else {
213
return false;
214
};
215
let Some(proposal) = state.pending.remove(&conversation_id) else {
216
return false;
217
};
218
self.finish(&mut state, &proposal, outcome);
219
let _ = self.ui.send(UiEvent::ProposalRemoved { conversation_id });
220
drop(state);
221
self.wake.notify_waiters();
222
true
223
}
224
225
pub fn push_caption(&self, conversation_id: &str, caption_id: &str, speaker: &str, text: &str) {
226
let mut state = self.lock();
227
let lines = state
228
.captions
229
.entry(conversation_id.to_owned())
230
.or_default();
231
let line = CaptionLine {
232
caption_id: caption_id.to_owned(),
233
speaker: speaker.to_owned(),
234
text: text.to_owned(),
235
at: now_millis(),
236
};
237
match lines.back_mut() {
238
Some(last) if last.caption_id == caption_id => *last = line,
239
_ => lines.push_back(line),
240
}
241
if lines.len() > CAPTION_CAPACITY {
242
lines.pop_front();
243
}
244
}
245
246
pub fn live_captions(&self, conversation_id: &str) -> Vec<CaptionLine> {
247
self.lock()
248
.captions
249
.get(conversation_id)
250
.map(|lines| lines.iter().cloned().collect())
251
.unwrap_or_default()
252
}
253
254
pub fn clear_captions(&self, conversation_id: &str) {
255
self.lock().captions.remove(conversation_id);
256
}
257
258
pub fn user_typing(&self, conversation_id: &str) {
259
self.push(EventKind::UserTyping {
260
conversation_id: conversation_id.to_owned(),
261
});
262
}
263
264
pub fn user_sent(&self, conversation_id: &str) {
265
self.push(EventKind::UserSent {
266
conversation_id: conversation_id.to_owned(),
267
});
268
self.stale_pending(conversation_id);
269
}
270
271
pub fn message_arrived(
272
&self,
273
conversation_id: &str,
274
message_id: &str,
275
sender_is_me: bool,
276
sender: Option<String>,
277
preview: &str,
278
) {
279
if sender_is_me {
280
self.stale_pending(conversation_id);
281
return;
282
}
283
self.push(EventKind::NewMessage {
284
conversation_id: conversation_id.to_owned(),
285
message_id: message_id.to_owned(),
286
sender,
287
preview: preview.to_owned(),
288
});
289
}
290
291
pub async fn wait_events(&self, since: Option<u64>, timeout: Duration) -> (Vec<Event>, u64) {
292
let deadline = tokio::time::Instant::now() + timeout;
293
let mut cursor = since.unwrap_or_else(|| self.lock().last_seq);
294
loop {
295
let notified = self.wake.notified();
296
tokio::pin!(notified);
297
notified.as_mut().enable();
298
let (events, next) = self.events_after(cursor);
299
if !events.is_empty() {
300
return (events, next);
301
}
302
cursor = next;
303
if tokio::time::timeout_at(deadline, notified).await.is_err() {
304
return (Vec::new(), cursor);
305
}
306
}
307
}
308
309
fn events_after(&self, cursor: u64) -> (Vec<Event>, u64) {
310
let state = self.lock();
311
let events = state
312
.events
313
.iter()
314
.filter(|event| event.seq > cursor)
315
.filter(|event| state.policy.can_read_any_kind(event.kind.conversation_id()))
316
.cloned()
317
.collect();
318
(events, state.last_seq.max(cursor))
319
}
320
321
fn stale_pending(&self, conversation_id: &str) {
322
let mut state = self.lock();
323
let Some(proposal) = state.pending.remove(conversation_id) else {
324
return;
325
};
326
self.finish(&mut state, &proposal, Outcome::Stale);
327
let _ = self.ui.send(UiEvent::ProposalStale(proposal));
328
drop(state);
329
self.wake.notify_waiters();
330
}
331
332
fn finish(&self, state: &mut HubState, proposal: &Proposal, outcome: Outcome) {
333
let _ =
334
self.store
335
.set_agent_proposal_state(&proposal.id, outcome.state(), Some(now_millis()));
336
push_event(
337
state,
338
EventKind::ProposalResolved {
339
proposal_id: proposal.id.clone(),
340
conversation_id: proposal.conversation_id.clone(),
341
outcome,
342
},
343
);
344
}
345
346
fn push(&self, kind: EventKind) {
347
push_event(&mut self.lock(), kind);
348
self.wake.notify_waiters();
349
}
350
351
fn lock(&self) -> MutexGuard<'_, HubState> {
352
self.state
353
.lock()
354
.unwrap_or_else(|poisoned| poisoned.into_inner())
355
}
356
}
357
358
fn now_millis() -> DateTime<Utc> {
359
DateTime::from_timestamp_millis(Utc::now().timestamp_millis()).unwrap_or_default()
360
}
361
362
fn push_event(state: &mut HubState, kind: EventKind) {
363
state.last_seq += 1;
364
if state.events.len() == EVENT_CAPACITY {
365
state.events.pop_front();
366
}
367
state.events.push_back(Event {
368
seq: state.last_seq,
369
kind,
370
});
371
}
372
373
fn proposal_from_record(record: AgentProposalRecord) -> Proposal {
374
Proposal {
375
id: record.id,
376
conversation_id: record.conversation_id,
377
reply_to_message_id: record.reply_to_message_id,
378
text: record.text,
379
agent: record.agent,
380
session_id: record.session_id,
381
created_at: record.created_at,
382
}
383
}
384
385
#[cfg(test)]
386
mod tests {
387
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
388
389
use super::*;
390
use crate::policy::Access;
391
392
const SHORT: Duration = Duration::from_millis(50);
393
394
fn open_policy() -> AgentPolicy {
395
AgentPolicy {
396
enabled: true,
397
chats: Access::All,
398
channels: Access::All,
399
propose: true,
400
..AgentPolicy::default()
401
}
402
}
403
404
fn hub_with(policy: AgentPolicy) -> (Arc<AgentHub>, UnboundedReceiver<UiEvent>, Arc<Store>) {
405
let store = Arc::new(Store::open_in_memory().unwrap());
406
let (sender, receiver) = unbounded_channel();
407
(
408
AgentHub::new(store.clone(), policy, sender),
409
receiver,
410
store,
411
)
412
}
413
414
fn propose(hub: &AgentHub, conversation_id: &str, text: &str) -> Proposal {
415
hub.add_proposal(conversation_id, text, None, None, None)
416
.unwrap()
417
}
418
419
#[test]
420
fn a_new_proposal_supersedes_the_pending_one() {
421
let (hub, mut ui, store) = hub_with(open_policy());
422
let first = propose(&hub, "c1", "one");
423
let second = propose(&hub, "c1", "two");
424
assert_eq!(hub.pending_proposal("c1"), Some(second.clone()));
425
let pending = store.pending_agent_proposals().unwrap();
426
assert_eq!(pending.len(), 1);
427
assert_eq!(pending[0].id, second.id);
428
assert_eq!(
429
ui.try_recv().unwrap(),
430
UiEvent::ProposalChanged(first.clone())
431
);
432
assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(second));
433
let state = hub.lock();
434
assert!(matches!(
435
state.events[0].kind,
436
EventKind::ProposalResolved {
437
outcome: Outcome::Superseded,
438
..
439
}
440
));
441
}
442
443
#[test]
444
fn resolve_clears_the_proposal_and_notifies_the_ui() {
445
let (hub, mut ui, store) = hub_with(open_policy());
446
let proposal = propose(&hub, "c1", "hi");
447
ui.try_recv().unwrap();
448
assert!(hub.resolve(&proposal.id, Outcome::Sent));
449
assert!(!hub.resolve(&proposal.id, Outcome::Sent));
450
assert!(hub.pending_proposal("c1").is_none());
451
assert!(store.pending_agent_proposals().unwrap().is_empty());
452
assert_eq!(
453
ui.try_recv().unwrap(),
454
UiEvent::ProposalRemoved {
455
conversation_id: "c1".to_owned()
456
}
457
);
458
}
459
460
#[test]
461
fn user_sent_and_own_messages_make_the_proposal_stale() {
462
let (hub, mut ui, _store) = hub_with(open_policy());
463
let stale = propose(&hub, "c1", "hi");
464
ui.try_recv().unwrap();
465
hub.user_sent("c1");
466
assert!(hub.pending_proposal("c1").is_none());
467
assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalStale(stale));
468
propose(&hub, "c2", "yo");
469
hub.message_arrived("c2", "m1", false, None, "other");
470
assert!(hub.pending_proposal("c2").is_some());
471
hub.message_arrived("c2", "m2", true, None, "mine");
472
assert!(hub.pending_proposal("c2").is_none());
473
}
474
475
#[test]
476
fn restore_pending_reloads_unresolved_proposals() {
477
let (hub, _ui, store) = hub_with(open_policy());
478
let proposal = propose(&hub, "c1", "hi");
479
let (sender, mut receiver) = unbounded_channel();
480
let restored = AgentHub::new(store, open_policy(), sender);
481
restored.restore_pending().unwrap();
482
assert_eq!(restored.pending_proposal("c1"), Some(proposal.clone()));
483
assert_eq!(
484
receiver.try_recv().unwrap(),
485
UiEvent::ProposalChanged(proposal)
486
);
487
}
488
489
#[test]
490
fn captions_update_partials_and_clear() {
491
let (hub, _ui, _store) = hub_with(open_policy());
492
hub.push_caption("c1", "1", "Ana", "Hel");
493
hub.push_caption("c1", "1", "Ana", "Hello");
494
hub.push_caption("c1", "2", "Bo", "Hi");
495
let lines = hub.live_captions("c1");
496
assert_eq!(lines.len(), 2);
497
assert_eq!(lines[0].text, "Hello");
498
assert!(hub.live_captions("c2").is_empty());
499
hub.clear_captions("c1");
500
assert!(hub.live_captions("c1").is_empty());
501
}
502
503
#[tokio::test]
504
async fn waiting_without_a_cursor_only_sees_new_events() {
505
let (hub, _ui, _store) = hub_with(open_policy());
506
hub.user_typing("c1");
507
let (events, next) = hub.wait_events(None, SHORT).await;
508
assert!(events.is_empty());
509
assert_eq!(next, 1);
510
hub.user_typing("c1");
511
let (events, next) = hub.wait_events(Some(next), SHORT).await;
512
assert_eq!(events.len(), 1);
513
assert_eq!(next, 2);
514
}
515
516
#[tokio::test]
517
async fn a_waiter_wakes_when_an_event_arrives() {
518
let (hub, _ui, _store) = hub_with(open_policy());
519
let waiter = {
520
let hub = hub.clone();
521
tokio::spawn(async move { hub.wait_events(None, Duration::from_secs(5)).await })
522
};
523
tokio::time::sleep(Duration::from_millis(20)).await;
524
hub.message_arrived("c1", "m1", false, Some("Ada".to_owned()), "hello");
525
let (events, next) = waiter.await.unwrap();
526
assert_eq!(events.len(), 1);
527
assert_eq!(next, events[0].seq);
528
}
529
530
#[tokio::test]
531
async fn events_are_filtered_by_the_policy_at_read_time() {
532
let policy = AgentPolicy {
533
chats: Access::Selected(["c1".to_owned()].into()),
534
channels: Access::None,
535
..open_policy()
536
};
537
let (hub, _ui, _store) = hub_with(policy);
538
hub.user_typing("c1");
539
hub.user_typing("c2");
540
let (events, next) = hub.wait_events(Some(0), SHORT).await;
541
assert_eq!(events.len(), 1);
542
assert_eq!(events[0].kind.conversation_id(), "c1");
543
assert_eq!(next, 2);
544
hub.set_policy(AgentPolicy::default());
545
assert!(hub.wait_events(Some(0), SHORT).await.0.is_empty());
546
}
547
548
#[test]
549
fn the_ring_buffer_drops_the_oldest_events() {
550
let (hub, _ui, _store) = hub_with(open_policy());
551
for _ in 0..EVENT_CAPACITY + 5 {
552
hub.user_typing("c1");
553
}
554
let state = hub.lock();
555
assert_eq!(state.events.len(), EVENT_CAPACITY);
556
assert_eq!(state.events[0].seq, 6);
557
assert_eq!(state.last_seq, EVENT_CAPACITY as u64 + 5);
558
}
559
}
@@ -0,0 +1,559 @@1
use std::collections::{HashMap, VecDeque};2
use std::sync::{Arc, Mutex, MutexGuard};3
use std::time::Duration;4
5
use chrono::{DateTime, Utc};6
use serde::Serialize;7
use store::{AgentProposalRecord, Store};8
use tokio::sync::Notify;9
use tokio::sync::mpsc::UnboundedSender;10
11
use crate::policy::AgentPolicy;12
13
const EVENT_CAPACITY: usize = 1000;14
const CAPTION_CAPACITY: usize = 2000;15
const PENDING_STATE: &str = "pending";16
17
#[derive(Debug, Clone, PartialEq, Eq)]18
pub struct Proposal {19
pub id: String,20
pub conversation_id: String,21
pub reply_to_message_id: Option<String>,22
pub text: String,23
pub agent: Option<String>,24
pub session_id: Option<String>,25
pub created_at: DateTime<Utc>,26
}27
28
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]29
pub struct CaptionLine {30
#[serde(skip)]31
pub caption_id: String,32
pub speaker: String,33
pub text: String,34
pub at: DateTime<Utc>,35
}36
37
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]38
#[serde(rename_all = "snake_case")]39
pub enum Outcome {40
Sent,41
Edited,42
Discarded,43
Stale,44
Superseded,45
}46
47
impl Outcome {48
fn state(self) -> &'static str {49
match self {50
Outcome::Sent => "sent",51
Outcome::Edited => "edited",52
Outcome::Discarded => "discarded",53
Outcome::Stale => "stale",54
Outcome::Superseded => "superseded",55
}56
}57
}58
59
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]60
#[serde(tag = "type", rename_all = "snake_case")]61
pub enum EventKind {62
NewMessage {63
conversation_id: String,64
message_id: String,65
sender: Option<String>,66
preview: String,67
},68
UserTyping {69
conversation_id: String,70
},71
UserSent {72
conversation_id: String,73
},74
ProposalResolved {75
proposal_id: String,76
conversation_id: String,77
outcome: Outcome,78
},79
}80
81
impl EventKind {82
pub fn conversation_id(&self) -> &str {83
match self {84
EventKind::NewMessage {85
conversation_id, ..86
}87
| EventKind::UserTyping { conversation_id }88
| EventKind::UserSent { conversation_id }89
| EventKind::ProposalResolved {90
conversation_id, ..91
} => conversation_id,92
}93
}94
}95
96
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]97
pub struct Event {98
pub seq: u64,99
#[serde(flatten)]100
pub kind: EventKind,101
}102
103
#[derive(Debug, Clone, PartialEq, Eq)]104
pub enum UiEvent {105
ProposalChanged(Proposal),106
ProposalStale(Proposal),107
ProposalRemoved { conversation_id: String },108
}109
110
#[derive(Default)]111
struct HubState {112
policy: AgentPolicy,113
pending: HashMap<String, Proposal>,114
events: VecDeque<Event>,115
last_seq: u64,116
captions: HashMap<String, VecDeque<CaptionLine>>,117
}118
119
pub struct AgentHub {120
state: Mutex<HubState>,121
wake: Notify,122
store: Arc<Store>,123
ui: UnboundedSender<UiEvent>,124
}125
126
impl AgentHub {127
pub fn new(store: Arc<Store>, policy: AgentPolicy, ui: UnboundedSender<UiEvent>) -> Arc<Self> {128
Arc::new(AgentHub {129
state: Mutex::new(HubState {130
policy,131
..HubState::default()132
}),133
wake: Notify::new(),134
store,135
ui,136
})137
}138
139
pub fn set_policy(&self, policy: AgentPolicy) {140
self.lock().policy = policy;141
}142
143
pub fn policy(&self) -> AgentPolicy {144
self.lock().policy.clone()145
}146
147
pub fn pending_proposal(&self, conversation_id: &str) -> Option<Proposal> {148
self.lock().pending.get(conversation_id).cloned()149
}150
151
pub fn restore_pending(&self) -> store::Result<()> {152
let records = self.store.pending_agent_proposals()?;153
let mut state = self.lock();154
for record in records {155
let proposal = proposal_from_record(record);156
let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));157
state158
.pending159
.insert(proposal.conversation_id.clone(), proposal);160
}161
Ok(())162
}163
164
pub fn add_proposal(165
&self,166
conversation_id: &str,167
text: &str,168
reply_to_message_id: Option<String>,169
agent: Option<String>,170
session_id: Option<String>,171
) -> store::Result<Proposal> {172
let proposal = Proposal {173
id: uuid::Uuid::new_v4().to_string(),174
conversation_id: conversation_id.to_owned(),175
reply_to_message_id,176
text: text.to_owned(),177
agent,178
session_id,179
created_at: now_millis(),180
};181
self.store.insert_agent_proposal(&AgentProposalRecord {182
id: proposal.id.clone(),183
conversation_id: proposal.conversation_id.clone(),184
reply_to_message_id: proposal.reply_to_message_id.clone(),185
text: proposal.text.clone(),186
agent: proposal.agent.clone(),187
session_id: proposal.session_id.clone(),188
created_at: proposal.created_at,189
state: PENDING_STATE.to_owned(),190
resolved_at: None,191
})?;192
let mut state = self.lock();193
if let Some(previous) = state194
.pending195
.insert(conversation_id.to_owned(), proposal.clone())196
{197
self.finish(&mut state, &previous, Outcome::Superseded);198
}199
let _ = self.ui.send(UiEvent::ProposalChanged(proposal.clone()));200
drop(state);201
self.wake.notify_waiters();202
Ok(proposal)203
}204
205
pub fn resolve(&self, proposal_id: &str, outcome: Outcome) -> bool {206
let mut state = self.lock();207
let Some(conversation_id) = state208
.pending209
.values()210
.find(|proposal| proposal.id == proposal_id)211
.map(|proposal| proposal.conversation_id.clone())212
else {213
return false;214
};215
let Some(proposal) = state.pending.remove(&conversation_id) else {216
return false;217
};218
self.finish(&mut state, &proposal, outcome);219
let _ = self.ui.send(UiEvent::ProposalRemoved { conversation_id });220
drop(state);221
self.wake.notify_waiters();222
true223
}224
225
pub fn push_caption(&self, conversation_id: &str, caption_id: &str, speaker: &str, text: &str) {226
let mut state = self.lock();227
let lines = state228
.captions229
.entry(conversation_id.to_owned())230
.or_default();231
let line = CaptionLine {232
caption_id: caption_id.to_owned(),233
speaker: speaker.to_owned(),234
text: text.to_owned(),235
at: now_millis(),236
};237
match lines.back_mut() {238
Some(last) if last.caption_id == caption_id => *last = line,239
_ => lines.push_back(line),240
}241
if lines.len() > CAPTION_CAPACITY {242
lines.pop_front();243
}244
}245
246
pub fn live_captions(&self, conversation_id: &str) -> Vec<CaptionLine> {247
self.lock()248
.captions249
.get(conversation_id)250
.map(|lines| lines.iter().cloned().collect())251
.unwrap_or_default()252
}253
254
pub fn clear_captions(&self, conversation_id: &str) {255
self.lock().captions.remove(conversation_id);256
}257
258
pub fn user_typing(&self, conversation_id: &str) {259
self.push(EventKind::UserTyping {260
conversation_id: conversation_id.to_owned(),261
});262
}263
264
pub fn user_sent(&self, conversation_id: &str) {265
self.push(EventKind::UserSent {266
conversation_id: conversation_id.to_owned(),267
});268
self.stale_pending(conversation_id);269
}270
271
pub fn message_arrived(272
&self,273
conversation_id: &str,274
message_id: &str,275
sender_is_me: bool,276
sender: Option<String>,277
preview: &str,278
) {279
if sender_is_me {280
self.stale_pending(conversation_id);281
return;282
}283
self.push(EventKind::NewMessage {284
conversation_id: conversation_id.to_owned(),285
message_id: message_id.to_owned(),286
sender,287
preview: preview.to_owned(),288
});289
}290
291
pub async fn wait_events(&self, since: Option<u64>, timeout: Duration) -> (Vec<Event>, u64) {292
let deadline = tokio::time::Instant::now() + timeout;293
let mut cursor = since.unwrap_or_else(|| self.lock().last_seq);294
loop {295
let notified = self.wake.notified();296
tokio::pin!(notified);297
notified.as_mut().enable();298
let (events, next) = self.events_after(cursor);299
if !events.is_empty() {300
return (events, next);301
}302
cursor = next;303
if tokio::time::timeout_at(deadline, notified).await.is_err() {304
return (Vec::new(), cursor);305
}306
}307
}308
309
fn events_after(&self, cursor: u64) -> (Vec<Event>, u64) {310
let state = self.lock();311
let events = state312
.events313
.iter()314
.filter(|event| event.seq > cursor)315
.filter(|event| state.policy.can_read_any_kind(event.kind.conversation_id()))316
.cloned()317
.collect();318
(events, state.last_seq.max(cursor))319
}320
321
fn stale_pending(&self, conversation_id: &str) {322
let mut state = self.lock();323
let Some(proposal) = state.pending.remove(conversation_id) else {324
return;325
};326
self.finish(&mut state, &proposal, Outcome::Stale);327
let _ = self.ui.send(UiEvent::ProposalStale(proposal));328
drop(state);329
self.wake.notify_waiters();330
}331
332
fn finish(&self, state: &mut HubState, proposal: &Proposal, outcome: Outcome) {333
let _ =334
self.store335
.set_agent_proposal_state(&proposal.id, outcome.state(), Some(now_millis()));336
push_event(337
state,338
EventKind::ProposalResolved {339
proposal_id: proposal.id.clone(),340
conversation_id: proposal.conversation_id.clone(),341
outcome,342
},343
);344
}345
346
fn push(&self, kind: EventKind) {347
push_event(&mut self.lock(), kind);348
self.wake.notify_waiters();349
}350
351
fn lock(&self) -> MutexGuard<'_, HubState> {352
self.state353
.lock()354
.unwrap_or_else(|poisoned| poisoned.into_inner())355
}356
}357
358
fn now_millis() -> DateTime<Utc> {359
DateTime::from_timestamp_millis(Utc::now().timestamp_millis()).unwrap_or_default()360
}361
362
fn push_event(state: &mut HubState, kind: EventKind) {363
state.last_seq += 1;364
if state.events.len() == EVENT_CAPACITY {365
state.events.pop_front();366
}367
state.events.push_back(Event {368
seq: state.last_seq,369
kind,370
});371
}372
373
fn proposal_from_record(record: AgentProposalRecord) -> Proposal {374
Proposal {375
id: record.id,376
conversation_id: record.conversation_id,377
reply_to_message_id: record.reply_to_message_id,378
text: record.text,379
agent: record.agent,380
session_id: record.session_id,381
created_at: record.created_at,382
}383
}384
385
#[cfg(test)]386
mod tests {387
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};388
389
use super::*;390
use crate::policy::Access;391
392
const SHORT: Duration = Duration::from_millis(50);393
394
fn open_policy() -> AgentPolicy {395
AgentPolicy {396
enabled: true,397
chats: Access::All,398
channels: Access::All,399
propose: true,400
..AgentPolicy::default()401
}402
}403
404
fn hub_with(policy: AgentPolicy) -> (Arc<AgentHub>, UnboundedReceiver<UiEvent>, Arc<Store>) {405
let store = Arc::new(Store::open_in_memory().unwrap());406
let (sender, receiver) = unbounded_channel();407
(408
AgentHub::new(store.clone(), policy, sender),409
receiver,410
store,411
)412
}413
414
fn propose(hub: &AgentHub, conversation_id: &str, text: &str) -> Proposal {415
hub.add_proposal(conversation_id, text, None, None, None)416
.unwrap()417
}418
419
#[test]420
fn a_new_proposal_supersedes_the_pending_one() {421
let (hub, mut ui, store) = hub_with(open_policy());422
let first = propose(&hub, "c1", "one");423
let second = propose(&hub, "c1", "two");424
assert_eq!(hub.pending_proposal("c1"), Some(second.clone()));425
let pending = store.pending_agent_proposals().unwrap();426
assert_eq!(pending.len(), 1);427
assert_eq!(pending[0].id, second.id);428
assert_eq!(429
ui.try_recv().unwrap(),430
UiEvent::ProposalChanged(first.clone())431
);432
assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalChanged(second));433
let state = hub.lock();434
assert!(matches!(435
state.events[0].kind,436
EventKind::ProposalResolved {437
outcome: Outcome::Superseded,438
..439
}440
));441
}442
443
#[test]444
fn resolve_clears_the_proposal_and_notifies_the_ui() {445
let (hub, mut ui, store) = hub_with(open_policy());446
let proposal = propose(&hub, "c1", "hi");447
ui.try_recv().unwrap();448
assert!(hub.resolve(&proposal.id, Outcome::Sent));449
assert!(!hub.resolve(&proposal.id, Outcome::Sent));450
assert!(hub.pending_proposal("c1").is_none());451
assert!(store.pending_agent_proposals().unwrap().is_empty());452
assert_eq!(453
ui.try_recv().unwrap(),454
UiEvent::ProposalRemoved {455
conversation_id: "c1".to_owned()456
}457
);458
}459
460
#[test]461
fn user_sent_and_own_messages_make_the_proposal_stale() {462
let (hub, mut ui, _store) = hub_with(open_policy());463
let stale = propose(&hub, "c1", "hi");464
ui.try_recv().unwrap();465
hub.user_sent("c1");466
assert!(hub.pending_proposal("c1").is_none());467
assert_eq!(ui.try_recv().unwrap(), UiEvent::ProposalStale(stale));468
propose(&hub, "c2", "yo");469
hub.message_arrived("c2", "m1", false, None, "other");470
assert!(hub.pending_proposal("c2").is_some());471
hub.message_arrived("c2", "m2", true, None, "mine");472
assert!(hub.pending_proposal("c2").is_none());473
}474
475
#[test]476
fn restore_pending_reloads_unresolved_proposals() {477
let (hub, _ui, store) = hub_with(open_policy());478
let proposal = propose(&hub, "c1", "hi");479
let (sender, mut receiver) = unbounded_channel();480
let restored = AgentHub::new(store, open_policy(), sender);481
restored.restore_pending().unwrap();482
assert_eq!(restored.pending_proposal("c1"), Some(proposal.clone()));483
assert_eq!(484
receiver.try_recv().unwrap(),485
UiEvent::ProposalChanged(proposal)486
);487
}488
489
#[test]490
fn captions_update_partials_and_clear() {491
let (hub, _ui, _store) = hub_with(open_policy());492
hub.push_caption("c1", "1", "Ana", "Hel");493
hub.push_caption("c1", "1", "Ana", "Hello");494
hub.push_caption("c1", "2", "Bo", "Hi");495
let lines = hub.live_captions("c1");496
assert_eq!(lines.len(), 2);497
assert_eq!(lines[0].text, "Hello");498
assert!(hub.live_captions("c2").is_empty());499
hub.clear_captions("c1");500
assert!(hub.live_captions("c1").is_empty());501
}502
503
#[tokio::test]504
async fn waiting_without_a_cursor_only_sees_new_events() {505
let (hub, _ui, _store) = hub_with(open_policy());506
hub.user_typing("c1");507
let (events, next) = hub.wait_events(None, SHORT).await;508
assert!(events.is_empty());509
assert_eq!(next, 1);510
hub.user_typing("c1");511
let (events, next) = hub.wait_events(Some(next), SHORT).await;512
assert_eq!(events.len(), 1);513
assert_eq!(next, 2);514
}515
516
#[tokio::test]517
async fn a_waiter_wakes_when_an_event_arrives() {518
let (hub, _ui, _store) = hub_with(open_policy());519
let waiter = {520
let hub = hub.clone();521
tokio::spawn(async move { hub.wait_events(None, Duration::from_secs(5)).await })522
};523
tokio::time::sleep(Duration::from_millis(20)).await;524
hub.message_arrived("c1", "m1", false, Some("Ada".to_owned()), "hello");525
let (events, next) = waiter.await.unwrap();526
assert_eq!(events.len(), 1);527
assert_eq!(next, events[0].seq);528
}529
530
#[tokio::test]531
async fn events_are_filtered_by_the_policy_at_read_time() {532
let policy = AgentPolicy {533
chats: Access::Selected(["c1".to_owned()].into()),534
channels: Access::None,535
..open_policy()536
};537
let (hub, _ui, _store) = hub_with(policy);538
hub.user_typing("c1");539
hub.user_typing("c2");540
let (events, next) = hub.wait_events(Some(0), SHORT).await;541
assert_eq!(events.len(), 1);542
assert_eq!(events[0].kind.conversation_id(), "c1");543
assert_eq!(next, 2);544
hub.set_policy(AgentPolicy::default());545
assert!(hub.wait_events(Some(0), SHORT).await.0.is_empty());546
}547
548
#[test]549
fn the_ring_buffer_drops_the_oldest_events() {550
let (hub, _ui, _store) = hub_with(open_policy());551
for _ in 0..EVENT_CAPACITY + 5 {552
hub.user_typing("c1");553
}554
let state = hub.lock();555
assert_eq!(state.events.len(), EVENT_CAPACITY);556
assert_eq!(state.events[0].seq, 6);557
assert_eq!(state.last_seq, EVENT_CAPACITY as u64 + 5);558
}559
}@@ -0,0 +1,14 @@
1
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
2
use serde_json::Value;
3
4
use super::entry::{SERVER_NAME, ServerEntry};
5
6
pub(super) fn vscode(entry: &ServerEntry) -> String {
7
let mut config = entry.to_json(true, false);
8
config
9
.as_object_mut()
10
.expect("entry is an object")
11
.insert("name".into(), Value::from(SERVER_NAME));
12
let encoded = utf8_percent_encode(&config.to_string(), NON_ALPHANUMERIC).to_string();
13
format!("vscode:mcp/install?{encoded}")
14
}
@@ -0,0 +1,14 @@1
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};2
use serde_json::Value;3
4
use super::entry::{SERVER_NAME, ServerEntry};5
6
pub(super) fn vscode(entry: &ServerEntry) -> String {7
let mut config = entry.to_json(true, false);8
config9
.as_object_mut()10
.expect("entry is an object")11
.insert("name".into(), Value::from(SERVER_NAME));12
let encoded = utf8_percent_encode(&config.to_string(), NON_ALPHANUMERIC).to_string();13
format!("vscode:mcp/install?{encoded}")14
}@@ -0,0 +1,46 @@
1
use serde_json::{Value, json};
2
3
use crate::McpEndpoint;
4
5
pub(super) const SERVER_NAME: &str = "teams";
6
7
#[derive(Debug, Clone, PartialEq, Eq)]
8
pub(super) struct ServerEntry {
9
pub url: String,
10
pub authorization: String,
11
}
12
13
impl ServerEntry {
14
pub fn expected(endpoint: &McpEndpoint) -> Self {
15
ServerEntry {
16
url: endpoint.url.clone(),
17
authorization: format!("Bearer {}", endpoint.token),
18
}
19
}
20
21
pub fn from_json(value: &Value) -> Option<Self> {
22
Some(ServerEntry {
23
url: value.get("url")?.as_str()?.to_string(),
24
authorization: value
25
.get("headers")?
26
.get("Authorization")?
27
.as_str()?
28
.to_string(),
29
})
30
}
31
32
pub fn to_json(&self, with_type: bool, with_tools: bool) -> Value {
33
let mut value = json!({
34
"url": self.url,
35
"headers": { "Authorization": self.authorization },
36
});
37
let object = value.as_object_mut().expect("object literal");
38
if with_type {
39
object.insert("type".into(), json!("http"));
40
}
41
if with_tools {
42
object.insert("tools".into(), json!(["*"]));
43
}
44
value
45
}
46
}
@@ -0,0 +1,46 @@1
use serde_json::{Value, json};2
3
use crate::McpEndpoint;4
5
pub(super) const SERVER_NAME: &str = "teams";6
7
#[derive(Debug, Clone, PartialEq, Eq)]8
pub(super) struct ServerEntry {9
pub url: String,10
pub authorization: String,11
}12
13
impl ServerEntry {14
pub fn expected(endpoint: &McpEndpoint) -> Self {15
ServerEntry {16
url: endpoint.url.clone(),17
authorization: format!("Bearer {}", endpoint.token),18
}19
}20
21
pub fn from_json(value: &Value) -> Option<Self> {22
Some(ServerEntry {23
url: value.get("url")?.as_str()?.to_string(),24
authorization: value25
.get("headers")?26
.get("Authorization")?27
.as_str()?28
.to_string(),29
})30
}31
32
pub fn to_json(&self, with_type: bool, with_tools: bool) -> Value {33
let mut value = json!({34
"url": self.url,35
"headers": { "Authorization": self.authorization },36
});37
let object = value.as_object_mut().expect("object literal");38
if with_type {39
object.insert("type".into(), json!("http"));40
}41
if with_tools {42
object.insert("tools".into(), json!(["*"]));43
}44
value45
}46
}@@ -0,0 +1,32 @@
1
use std::path::PathBuf;
2
3
use super::Target;
4
5
#[derive(Debug, thiserror::Error)]
6
pub enum InstallError {
7
#[error("{} is not installed on this machine", .0.label())]
8
NotAvailable(Target),
9
#[error("cannot access {path}: {source}")]
10
Io {
11
path: PathBuf,
12
source: std::io::Error,
13
},
14
#[error("{path} is not valid: {message}")]
15
Malformed { path: PathBuf, message: String },
16
}
17
18
impl InstallError {
19
pub(super) fn io(path: &std::path::Path, source: std::io::Error) -> Self {
20
InstallError::Io {
21
path: path.to_path_buf(),
22
source,
23
}
24
}
25
26
pub(super) fn malformed(path: &std::path::Path, message: impl ToString) -> Self {
27
InstallError::Malformed {
28
path: path.to_path_buf(),
29
message: message.to_string(),
30
}
31
}
32
}
@@ -0,0 +1,32 @@1
use std::path::PathBuf;2
3
use super::Target;4
5
#[derive(Debug, thiserror::Error)]6
pub enum InstallError {7
#[error("{} is not installed on this machine", .0.label())]8
NotAvailable(Target),9
#[error("cannot access {path}: {source}")]10
Io {11
path: PathBuf,12
source: std::io::Error,13
},14
#[error("{path} is not valid: {message}")]15
Malformed { path: PathBuf, message: String },16
}17
18
impl InstallError {19
pub(super) fn io(path: &std::path::Path, source: std::io::Error) -> Self {20
InstallError::Io {21
path: path.to_path_buf(),22
source,23
}24
}25
26
pub(super) fn malformed(path: &std::path::Path, message: impl ToString) -> Self {27
InstallError::Malformed {28
path: path.to_path_buf(),29
message: message.to_string(),30
}31
}32
}@@ -0,0 +1,60 @@
1
use std::ffi::OsString;
2
use std::fs;
3
use std::io::Write;
4
use std::path::{Path, PathBuf};
5
6
use super::error::InstallError;
7
8
pub(super) fn read_if_exists(path: &Path) -> Result<Option<String>, InstallError> {
9
match fs::read_to_string(path) {
10
Ok(contents) => Ok(Some(contents)),
11
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
12
Err(error) => Err(InstallError::io(path, error)),
13
}
14
}
15
16
fn sibling(path: &Path, prefix: &str, suffix: &str) -> PathBuf {
17
let mut name = OsString::from(prefix);
18
name.push(path.file_name().unwrap_or_default());
19
name.push(suffix);
20
path.with_file_name(name)
21
}
22
23
pub(super) fn write_atomic(path: &Path, contents: &str) -> Result<(), InstallError> {
24
let existing = fs::metadata(path).ok();
25
if let Some(parent) = path.parent() {
26
fs::create_dir_all(parent).map_err(|error| InstallError::io(parent, error))?;
27
}
28
if existing.is_some() {
29
let backup = sibling(path, "", ".bak-rusty-teams");
30
if !backup.exists() {
31
fs::copy(path, &backup).map_err(|error| InstallError::io(&backup, error))?;
32
}
33
}
34
let temporary = sibling(path, ".", ".rusty-teams.tmp");
35
let result = write_temporary(&temporary, contents, existing.as_ref())
36
.and_then(|()| fs::rename(&temporary, path));
37
if let Err(error) = result {
38
let _ = fs::remove_file(&temporary);
39
return Err(InstallError::io(path, error));
40
}
41
Ok(())
42
}
43
44
fn write_temporary(
45
temporary: &Path,
46
contents: &str,
47
existing: Option<&fs::Metadata>,
48
) -> std::io::Result<()> {
49
let mut options = fs::OpenOptions::new();
50
options.write(true).create(true).truncate(true);
51
#[cfg(unix)]
52
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
53
let mut file = options.open(temporary)?;
54
file.write_all(contents.as_bytes())?;
55
file.sync_all()?;
56
if let Some(metadata) = existing {
57
fs::set_permissions(temporary, metadata.permissions())?;
58
}
59
Ok(())
60
}
@@ -0,0 +1,60 @@1
use std::ffi::OsString;2
use std::fs;3
use std::io::Write;4
use std::path::{Path, PathBuf};5
6
use super::error::InstallError;7
8
pub(super) fn read_if_exists(path: &Path) -> Result<Option<String>, InstallError> {9
match fs::read_to_string(path) {10
Ok(contents) => Ok(Some(contents)),11
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),12
Err(error) => Err(InstallError::io(path, error)),13
}14
}15
16
fn sibling(path: &Path, prefix: &str, suffix: &str) -> PathBuf {17
let mut name = OsString::from(prefix);18
name.push(path.file_name().unwrap_or_default());19
name.push(suffix);20
path.with_file_name(name)21
}22
23
pub(super) fn write_atomic(path: &Path, contents: &str) -> Result<(), InstallError> {24
let existing = fs::metadata(path).ok();25
if let Some(parent) = path.parent() {26
fs::create_dir_all(parent).map_err(|error| InstallError::io(parent, error))?;27
}28
if existing.is_some() {29
let backup = sibling(path, "", ".bak-rusty-teams");30
if !backup.exists() {31
fs::copy(path, &backup).map_err(|error| InstallError::io(&backup, error))?;32
}33
}34
let temporary = sibling(path, ".", ".rusty-teams.tmp");35
let result = write_temporary(&temporary, contents, existing.as_ref())36
.and_then(|()| fs::rename(&temporary, path));37
if let Err(error) = result {38
let _ = fs::remove_file(&temporary);39
return Err(InstallError::io(path, error));40
}41
Ok(())42
}43
44
fn write_temporary(45
temporary: &Path,46
contents: &str,47
existing: Option<&fs::Metadata>,48
) -> std::io::Result<()> {49
let mut options = fs::OpenOptions::new();50
options.write(true).create(true).truncate(true);51
#[cfg(unix)]52
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);53
let mut file = options.open(temporary)?;54
file.write_all(contents.as_bytes())?;55
file.sync_all()?;56
if let Some(metadata) = existing {57
fs::set_permissions(temporary, metadata.permissions())?;58
}59
Ok(())60
}@@ -0,0 +1,158 @@
1
use std::fmt;
2
use std::path::Path;
3
4
use serde::de::{Deserializer, MapAccess, Visitor};
5
use serde::{Deserialize, Serialize};
6
use serde_json::Value;
7
use serde_json::value::RawValue;
8
9
use super::entry::{SERVER_NAME, ServerEntry};
10
use super::error::InstallError;
11
use super::file;
12
13
struct OrderedObject(Vec<(String, Box<RawValue>)>);
14
15
impl<'de> Deserialize<'de> for OrderedObject {
16
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
17
struct ObjectVisitor;
18
impl<'de> Visitor<'de> for ObjectVisitor {
19
type Value = OrderedObject;
20
21
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
22
formatter.write_str("a JSON object")
23
}
24
25
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
26
let mut entries = Vec::new();
27
while let Some(entry) = map.next_entry::<String, Box<RawValue>>()? {
28
entries.push(entry);
29
}
30
Ok(OrderedObject(entries))
31
}
32
}
33
deserializer.deserialize_map(ObjectVisitor)
34
}
35
}
36
37
fn indentation(depth: usize) -> String {
38
" ".repeat(depth)
39
}
40
41
impl OrderedObject {
42
fn parse(text: &str) -> Result<Self, serde_json::Error> {
43
let trimmed = text.trim_start_matches('\u{feff}').trim();
44
if trimmed.is_empty() {
45
return Ok(OrderedObject(Vec::new()));
46
}
47
serde_json::from_str(trimmed)
48
}
49
50
fn position(&self, key: &str) -> Option<usize> {
51
self.0.iter().position(|(existing, _)| existing == key)
52
}
53
54
fn get(&self, key: &str) -> Option<&RawValue> {
55
self.position(key).map(|index| self.0[index].1.as_ref())
56
}
57
58
fn set(&mut self, key: &str, value: Box<RawValue>) {
59
match self.position(key) {
60
Some(index) => self.0[index].1 = value,
61
None => self.0.push((key.to_string(), value)),
62
}
63
}
64
65
fn remove(&mut self, key: &str) -> bool {
66
match self.position(key) {
67
Some(index) => {
68
self.0.remove(index);
69
true
70
}
71
None => false,
72
}
73
}
74
75
fn render(&self, depth: usize) -> String {
76
if self.0.is_empty() {
77
return "{}".to_string();
78
}
79
let entries: Vec<String> = self
80
.0
81
.iter()
82
.map(|(key, value)| {
83
let key = serde_json::to_string(key).expect("string serializes");
84
format!("{}{key}: {}", indentation(depth + 1), value.get())
85
})
86
.collect();
87
format!("{{\n{}\n{}}}", entries.join(",\n"), indentation(depth))
88
}
89
}
90
91
fn raw_at_depth(value: &impl Serialize, depth: usize) -> Box<RawValue> {
92
let pretty = serde_json::to_string_pretty(value).expect("value serializes");
93
let indented = pretty.replace('\n', &format!("\n{}", indentation(depth)));
94
RawValue::from_string(indented).expect("pretty json is valid")
95
}
96
97
fn load(path: &Path) -> Result<Option<OrderedObject>, InstallError> {
98
match file::read_if_exists(path)? {
99
Some(text) => OrderedObject::parse(&text)
100
.map(Some)
101
.map_err(|error| InstallError::malformed(path, error)),
102
None => Ok(None),
103
}
104
}
105
106
fn container_of(
107
root: &OrderedObject,
108
container: &str,
109
path: &Path,
110
) -> Result<OrderedObject, InstallError> {
111
match root.get(container) {
112
Some(raw) => serde_json::from_str(raw.get())
113
.map_err(|_| InstallError::malformed(path, format!("`{container}` is not an object"))),
114
None => Ok(OrderedObject(Vec::new())),
115
}
116
}
117
118
pub(super) fn read_entry(
119
path: &Path,
120
container: &str,
121
) -> Result<Option<ServerEntry>, InstallError> {
122
let Some(root) = load(path)? else {
123
return Ok(None);
124
};
125
let servers = container_of(&root, container, path)?;
126
Ok(servers
127
.get(SERVER_NAME)
128
.and_then(|raw| serde_json::from_str::<Value>(raw.get()).ok())
129
.and_then(|value| ServerEntry::from_json(&value)))
130
}
131
132
pub(super) fn upsert(path: &Path, container: &str, entry: &Value) -> Result<(), InstallError> {
133
let mut root = load(path)?.unwrap_or(OrderedObject(Vec::new()));
134
let mut servers = container_of(&root, container, path)?;
135
servers.set(SERVER_NAME, raw_at_depth(entry, 2));
136
let rendered = servers.render(1);
137
root.set(
138
container,
139
RawValue::from_string(rendered).expect("rendered object is valid json"),
140
);
141
file::write_atomic(path, &format!("{}\n", root.render(0)))
142
}
143
144
pub(super) fn remove(path: &Path, container: &str) -> Result<(), InstallError> {
145
let Some(mut root) = load(path)? else {
146
return Ok(());
147
};
148
let mut servers = container_of(&root, container, path)?;
149
if !servers.remove(SERVER_NAME) {
150
return Ok(());
151
}
152
let rendered = servers.render(1);
153
root.set(
154
container,
155
RawValue::from_string(rendered).expect("rendered object is valid json"),
156
);
157
file::write_atomic(path, &format!("{}\n", root.render(0)))
158
}
@@ -0,0 +1,158 @@1
use std::fmt;2
use std::path::Path;3
4
use serde::de::{Deserializer, MapAccess, Visitor};5
use serde::{Deserialize, Serialize};6
use serde_json::Value;7
use serde_json::value::RawValue;8
9
use super::entry::{SERVER_NAME, ServerEntry};10
use super::error::InstallError;11
use super::file;12
13
struct OrderedObject(Vec<(String, Box<RawValue>)>);14
15
impl<'de> Deserialize<'de> for OrderedObject {16
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {17
struct ObjectVisitor;18
impl<'de> Visitor<'de> for ObjectVisitor {19
type Value = OrderedObject;20
21
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {22
formatter.write_str("a JSON object")23
}24
25
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {26
let mut entries = Vec::new();27
while let Some(entry) = map.next_entry::<String, Box<RawValue>>()? {28
entries.push(entry);29
}30
Ok(OrderedObject(entries))31
}32
}33
deserializer.deserialize_map(ObjectVisitor)34
}35
}36
37
fn indentation(depth: usize) -> String {38
" ".repeat(depth)39
}40
41
impl OrderedObject {42
fn parse(text: &str) -> Result<Self, serde_json::Error> {43
let trimmed = text.trim_start_matches('\u{feff}').trim();44
if trimmed.is_empty() {45
return Ok(OrderedObject(Vec::new()));46
}47
serde_json::from_str(trimmed)48
}49
50
fn position(&self, key: &str) -> Option<usize> {51
self.0.iter().position(|(existing, _)| existing == key)52
}53
54
fn get(&self, key: &str) -> Option<&RawValue> {55
self.position(key).map(|index| self.0[index].1.as_ref())56
}57
58
fn set(&mut self, key: &str, value: Box<RawValue>) {59
match self.position(key) {60
Some(index) => self.0[index].1 = value,61
None => self.0.push((key.to_string(), value)),62
}63
}64
65
fn remove(&mut self, key: &str) -> bool {66
match self.position(key) {67
Some(index) => {68
self.0.remove(index);69
true70
}71
None => false,72
}73
}74
75
fn render(&self, depth: usize) -> String {76
if self.0.is_empty() {77
return "{}".to_string();78
}79
let entries: Vec<String> = self80
.081
.iter()82
.map(|(key, value)| {83
let key = serde_json::to_string(key).expect("string serializes");84
format!("{}{key}: {}", indentation(depth + 1), value.get())85
})86
.collect();87
format!("{{\n{}\n{}}}", entries.join(",\n"), indentation(depth))88
}89
}90
91
fn raw_at_depth(value: &impl Serialize, depth: usize) -> Box<RawValue> {92
let pretty = serde_json::to_string_pretty(value).expect("value serializes");93
let indented = pretty.replace('\n', &format!("\n{}", indentation(depth)));94
RawValue::from_string(indented).expect("pretty json is valid")95
}96
97
fn load(path: &Path) -> Result<Option<OrderedObject>, InstallError> {98
match file::read_if_exists(path)? {99
Some(text) => OrderedObject::parse(&text)100
.map(Some)101
.map_err(|error| InstallError::malformed(path, error)),102
None => Ok(None),103
}104
}105
106
fn container_of(107
root: &OrderedObject,108
container: &str,109
path: &Path,110
) -> Result<OrderedObject, InstallError> {111
match root.get(container) {112
Some(raw) => serde_json::from_str(raw.get())113
.map_err(|_| InstallError::malformed(path, format!("`{container}` is not an object"))),114
None => Ok(OrderedObject(Vec::new())),115
}116
}117
118
pub(super) fn read_entry(119
path: &Path,120
container: &str,121
) -> Result<Option<ServerEntry>, InstallError> {122
let Some(root) = load(path)? else {123
return Ok(None);124
};125
let servers = container_of(&root, container, path)?;126
Ok(servers127
.get(SERVER_NAME)128
.and_then(|raw| serde_json::from_str::<Value>(raw.get()).ok())129
.and_then(|value| ServerEntry::from_json(&value)))130
}131
132
pub(super) fn upsert(path: &Path, container: &str, entry: &Value) -> Result<(), InstallError> {133
let mut root = load(path)?.unwrap_or(OrderedObject(Vec::new()));134
let mut servers = container_of(&root, container, path)?;135
servers.set(SERVER_NAME, raw_at_depth(entry, 2));136
let rendered = servers.render(1);137
root.set(138
container,139
RawValue::from_string(rendered).expect("rendered object is valid json"),140
);141
file::write_atomic(path, &format!("{}\n", root.render(0)))142
}143
144
pub(super) fn remove(path: &Path, container: &str) -> Result<(), InstallError> {145
let Some(mut root) = load(path)? else {146
return Ok(());147
};148
let mut servers = container_of(&root, container, path)?;149
if !servers.remove(SERVER_NAME) {150
return Ok(());151
}152
let rendered = servers.render(1);153
root.set(154
container,155
RawValue::from_string(rendered).expect("rendered object is valid json"),156
);157
file::write_atomic(path, &format!("{}\n", root.render(0)))158
}@@ -0,0 +1,278 @@
1
mod deeplink;
2
mod entry;
3
mod error;
4
mod file;
5
mod json_file;
6
mod toml_file;
7
mod wsl;
8
9
#[cfg(test)]
10
mod tests;
11
12
use std::path::{Path, PathBuf};
13
14
use crate::McpEndpoint;
15
use entry::ServerEntry;
16
pub use error::InstallError;
17
18
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19
pub enum Target {
20
ClaudeCode,
21
Codex,
22
CopilotCli,
23
VsCode,
24
Cursor,
25
}
26
27
#[derive(Debug, Clone, PartialEq, Eq)]
28
pub enum Location {
29
Windows,
30
Wsl { distro: String },
31
Native,
32
}
33
34
#[derive(Debug, Clone, PartialEq, Eq)]
35
pub struct InstallState {
36
pub target: Target,
37
pub available: bool,
38
pub installed_at: Vec<Location>,
39
pub stale: bool,
40
}
41
42
#[derive(Debug, Clone, PartialEq, Eq)]
43
pub enum InstallReport {
44
Written(Vec<Location>),
45
OpenUrl(String),
46
}
47
48
#[derive(Debug, Clone, Default)]
49
pub struct Homes {
50
pub entries: Vec<(Location, PathBuf)>,
51
}
52
53
impl Homes {
54
pub fn detect() -> Homes {
55
let mut entries = Vec::new();
56
#[cfg(windows)]
57
{
58
if let Some(profile) = std::env::var_os("USERPROFILE") {
59
entries.push((Location::Windows, PathBuf::from(profile)));
60
}
61
if let Some((distro, home)) = wsl::default_home() {
62
entries.push((Location::Wsl { distro }, home));
63
}
64
}
65
#[cfg(not(windows))]
66
if let Some(home) = std::env::var_os("HOME") {
67
entries.push((Location::Native, PathBuf::from(home)));
68
}
69
Homes { entries }
70
}
71
}
72
73
#[cfg(windows)]
74
pub fn wsl_reachable(port: u16) -> Option<bool> {
75
wsl::reachable(port)
76
}
77
78
#[cfg(not(windows))]
79
pub fn wsl_reachable(_port: u16) -> Option<bool> {
80
None
81
}
82
83
enum Format {
84
Json { container: &'static str },
85
Toml,
86
}
87
88
impl Target {
89
pub const ALL: [Target; 5] = [
90
Target::ClaudeCode,
91
Target::Codex,
92
Target::CopilotCli,
93
Target::VsCode,
94
Target::Cursor,
95
];
96
97
pub fn label(self) -> &'static str {
98
match self {
99
Target::ClaudeCode => "Claude Code",
100
Target::Codex => "Codex CLI",
101
Target::CopilotCli => "Copilot CLI",
102
Target::VsCode => "VS Code",
103
Target::Cursor => "Cursor",
104
}
105
}
106
107
pub fn config_hint(self) -> &'static str {
108
match self {
109
Target::ClaudeCode => "~/.claude.json",
110
Target::Codex => "~/.codex/config.toml",
111
Target::CopilotCli => "~/.copilot/mcp-config.json",
112
Target::VsCode => "Code/User/mcp.json",
113
Target::Cursor => "~/.cursor/mcp.json",
114
}
115
}
116
117
fn format(self) -> Format {
118
match self {
119
Target::Codex => Format::Toml,
120
Target::VsCode => Format::Json {
121
container: "servers",
122
},
123
_ => Format::Json {
124
container: "mcpServers",
125
},
126
}
127
}
128
129
fn config_path(self, location: &Location, home: &Path) -> PathBuf {
130
match self {
131
Target::ClaudeCode => home.join(".claude.json"),
132
Target::Codex => home.join(".codex").join("config.toml"),
133
Target::CopilotCli => home.join(".copilot").join("mcp-config.json"),
134
Target::Cursor => home.join(".cursor").join("mcp.json"),
135
Target::VsCode => {
136
let base = match location {
137
Location::Windows => home.join("AppData").join("Roaming"),
138
_ => home.join(".config"),
139
};
140
base.join("Code").join("User").join("mcp.json")
141
}
142
}
143
}
144
145
fn marker_paths(self, location: &Location, home: &Path) -> Vec<PathBuf> {
146
let config = self.config_path(location, home);
147
let mut markers = vec![config.clone()];
148
match self {
149
Target::ClaudeCode => markers.push(home.join(".claude")),
150
_ => markers.extend(config.parent().map(Path::to_path_buf)),
151
}
152
markers
153
}
154
155
fn binary_names(self) -> &'static [&'static str] {
156
match self {
157
Target::ClaudeCode => &["claude"],
158
Target::Codex => &["codex"],
159
Target::CopilotCli => &["copilot"],
160
Target::VsCode => &["code"],
161
Target::Cursor => &["cursor"],
162
}
163
}
164
165
fn is_available_in(self, location: &Location, home: &Path) -> bool {
166
self.marker_paths(location, home)
167
.iter()
168
.any(|path| path.exists())
169
|| matches!(location, Location::Windows | Location::Native)
170
&& self.binary_names().iter().any(|name| binary_on_path(name))
171
}
172
173
fn json_entry(self, entry: &ServerEntry) -> serde_json::Value {
174
match self {
175
Target::ClaudeCode | Target::VsCode => entry.to_json(true, false),
176
Target::CopilotCli => entry.to_json(true, true),
177
_ => entry.to_json(false, false),
178
}
179
}
180
181
fn read_entry(self, path: &Path) -> Result<Option<ServerEntry>, InstallError> {
182
match self.format() {
183
Format::Json { container } => json_file::read_entry(path, container),
184
Format::Toml => toml_file::read_entry(path),
185
}
186
}
187
188
fn write_entry(self, path: &Path, entry: &ServerEntry) -> Result<(), InstallError> {
189
match self.format() {
190
Format::Json { container } => {
191
json_file::upsert(path, container, &self.json_entry(entry))
192
}
193
Format::Toml => toml_file::upsert(path, entry),
194
}
195
}
196
}
197
198
fn binary_on_path(name: &str) -> bool {
199
let Some(paths) = std::env::var_os("PATH") else {
200
return false;
201
};
202
std::env::split_paths(&paths).any(|directory| {
203
["", ".exe", ".cmd"]
204
.iter()
205
.any(|extension| directory.join(format!("{name}{extension}")).is_file())
206
})
207
}
208
209
pub fn status(target: Target, endpoint: &McpEndpoint, homes: &Homes) -> InstallState {
210
let expected = ServerEntry::expected(endpoint);
211
let mut state = InstallState {
212
target,
213
available: false,
214
installed_at: Vec::new(),
215
stale: false,
216
};
217
for (location, home) in &homes.entries {
218
state.available |= target.is_available_in(location, home);
219
let path = target.config_path(location, home);
220
if let Ok(Some(found)) = target.read_entry(&path) {
221
state.stale |= found != expected;
222
state.installed_at.push(location.clone());
223
}
224
}
225
state
226
}
227
228
pub fn install(
229
target: Target,
230
endpoint: &McpEndpoint,
231
homes: &Homes,
232
) -> Result<InstallReport, InstallError> {
233
let entry = ServerEntry::expected(endpoint);
234
if target == Target::VsCode {
235
return Ok(InstallReport::OpenUrl(deeplink::vscode(&entry)));
236
}
237
let mut written = Vec::new();
238
for (location, home) in &homes.entries {
239
if !target.is_available_in(location, home) {
240
continue;
241
}
242
target.write_entry(&target.config_path(location, home), &entry)?;
243
written.push(location.clone());
244
}
245
if written.is_empty() {
246
return Err(InstallError::NotAvailable(target));
247
}
248
Ok(InstallReport::Written(written))
249
}
250
251
pub fn uninstall(target: Target, homes: &Homes) -> Result<(), InstallError> {
252
for (location, home) in &homes.entries {
253
let path = target.config_path(location, home);
254
match target.format() {
255
Format::Json { container } => json_file::remove(&path, container)?,
256
Format::Toml => toml_file::remove(&path)?,
257
}
258
}
259
Ok(())
260
}
261
262
pub fn reinstall_all(
263
endpoint: &McpEndpoint,
264
homes: &Homes,
265
) -> Vec<(Target, Result<(), InstallError>)> {
266
let entry = ServerEntry::expected(endpoint);
267
let mut results = Vec::new();
268
for target in Target::ALL {
269
for (location, home) in &homes.entries {
270
let path = target.config_path(location, home);
271
if !matches!(target.read_entry(&path), Ok(Some(_))) {
272
continue;
273
}
274
results.push((target, target.write_entry(&path, &entry)));
275
}
276
}
277
results
278
}
@@ -0,0 +1,278 @@1
mod deeplink;2
mod entry;3
mod error;4
mod file;5
mod json_file;6
mod toml_file;7
mod wsl;8
9
#[cfg(test)]10
mod tests;11
12
use std::path::{Path, PathBuf};13
14
use crate::McpEndpoint;15
use entry::ServerEntry;16
pub use error::InstallError;17
18
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]19
pub enum Target {20
ClaudeCode,21
Codex,22
CopilotCli,23
VsCode,24
Cursor,25
}26
27
#[derive(Debug, Clone, PartialEq, Eq)]28
pub enum Location {29
Windows,30
Wsl { distro: String },31
Native,32
}33
34
#[derive(Debug, Clone, PartialEq, Eq)]35
pub struct InstallState {36
pub target: Target,37
pub available: bool,38
pub installed_at: Vec<Location>,39
pub stale: bool,40
}41
42
#[derive(Debug, Clone, PartialEq, Eq)]43
pub enum InstallReport {44
Written(Vec<Location>),45
OpenUrl(String),46
}47
48
#[derive(Debug, Clone, Default)]49
pub struct Homes {50
pub entries: Vec<(Location, PathBuf)>,51
}52
53
impl Homes {54
pub fn detect() -> Homes {55
let mut entries = Vec::new();56
#[cfg(windows)]57
{58
if let Some(profile) = std::env::var_os("USERPROFILE") {59
entries.push((Location::Windows, PathBuf::from(profile)));60
}61
if let Some((distro, home)) = wsl::default_home() {62
entries.push((Location::Wsl { distro }, home));63
}64
}65
#[cfg(not(windows))]66
if let Some(home) = std::env::var_os("HOME") {67
entries.push((Location::Native, PathBuf::from(home)));68
}69
Homes { entries }70
}71
}72
73
#[cfg(windows)]74
pub fn wsl_reachable(port: u16) -> Option<bool> {75
wsl::reachable(port)76
}77
78
#[cfg(not(windows))]79
pub fn wsl_reachable(_port: u16) -> Option<bool> {80
None81
}82
83
enum Format {84
Json { container: &'static str },85
Toml,86
}87
88
impl Target {89
pub const ALL: [Target; 5] = [90
Target::ClaudeCode,91
Target::Codex,92
Target::CopilotCli,93
Target::VsCode,94
Target::Cursor,95
];96
97
pub fn label(self) -> &'static str {98
match self {99
Target::ClaudeCode => "Claude Code",100
Target::Codex => "Codex CLI",101
Target::CopilotCli => "Copilot CLI",102
Target::VsCode => "VS Code",103
Target::Cursor => "Cursor",104
}105
}106
107
pub fn config_hint(self) -> &'static str {108
match self {109
Target::ClaudeCode => "~/.claude.json",110
Target::Codex => "~/.codex/config.toml",111
Target::CopilotCli => "~/.copilot/mcp-config.json",112
Target::VsCode => "Code/User/mcp.json",113
Target::Cursor => "~/.cursor/mcp.json",114
}115
}116
117
fn format(self) -> Format {118
match self {119
Target::Codex => Format::Toml,120
Target::VsCode => Format::Json {121
container: "servers",122
},123
_ => Format::Json {124
container: "mcpServers",125
},126
}127
}128
129
fn config_path(self, location: &Location, home: &Path) -> PathBuf {130
match self {131
Target::ClaudeCode => home.join(".claude.json"),132
Target::Codex => home.join(".codex").join("config.toml"),133
Target::CopilotCli => home.join(".copilot").join("mcp-config.json"),134
Target::Cursor => home.join(".cursor").join("mcp.json"),135
Target::VsCode => {136
let base = match location {137
Location::Windows => home.join("AppData").join("Roaming"),138
_ => home.join(".config"),139
};140
base.join("Code").join("User").join("mcp.json")141
}142
}143
}144
145
fn marker_paths(self, location: &Location, home: &Path) -> Vec<PathBuf> {146
let config = self.config_path(location, home);147
let mut markers = vec![config.clone()];148
match self {149
Target::ClaudeCode => markers.push(home.join(".claude")),150
_ => markers.extend(config.parent().map(Path::to_path_buf)),151
}152
markers153
}154
155
fn binary_names(self) -> &'static [&'static str] {156
match self {157
Target::ClaudeCode => &["claude"],158
Target::Codex => &["codex"],159
Target::CopilotCli => &["copilot"],160
Target::VsCode => &["code"],161
Target::Cursor => &["cursor"],162
}163
}164
165
fn is_available_in(self, location: &Location, home: &Path) -> bool {166
self.marker_paths(location, home)167
.iter()168
.any(|path| path.exists())169
|| matches!(location, Location::Windows | Location::Native)170
&& self.binary_names().iter().any(|name| binary_on_path(name))171
}172
173
fn json_entry(self, entry: &ServerEntry) -> serde_json::Value {174
match self {175
Target::ClaudeCode | Target::VsCode => entry.to_json(true, false),176
Target::CopilotCli => entry.to_json(true, true),177
_ => entry.to_json(false, false),178
}179
}180
181
fn read_entry(self, path: &Path) -> Result<Option<ServerEntry>, InstallError> {182
match self.format() {183
Format::Json { container } => json_file::read_entry(path, container),184
Format::Toml => toml_file::read_entry(path),185
}186
}187
188
fn write_entry(self, path: &Path, entry: &ServerEntry) -> Result<(), InstallError> {189
match self.format() {190
Format::Json { container } => {191
json_file::upsert(path, container, &self.json_entry(entry))192
}193
Format::Toml => toml_file::upsert(path, entry),194
}195
}196
}197
198
fn binary_on_path(name: &str) -> bool {199
let Some(paths) = std::env::var_os("PATH") else {200
return false;201
};202
std::env::split_paths(&paths).any(|directory| {203
["", ".exe", ".cmd"]204
.iter()205
.any(|extension| directory.join(format!("{name}{extension}")).is_file())206
})207
}208
209
pub fn status(target: Target, endpoint: &McpEndpoint, homes: &Homes) -> InstallState {210
let expected = ServerEntry::expected(endpoint);211
let mut state = InstallState {212
target,213
available: false,214
installed_at: Vec::new(),215
stale: false,216
};217
for (location, home) in &homes.entries {218
state.available |= target.is_available_in(location, home);219
let path = target.config_path(location, home);220
if let Ok(Some(found)) = target.read_entry(&path) {221
state.stale |= found != expected;222
state.installed_at.push(location.clone());223
}224
}225
state226
}227
228
pub fn install(229
target: Target,230
endpoint: &McpEndpoint,231
homes: &Homes,232
) -> Result<InstallReport, InstallError> {233
let entry = ServerEntry::expected(endpoint);234
if target == Target::VsCode {235
return Ok(InstallReport::OpenUrl(deeplink::vscode(&entry)));236
}237
let mut written = Vec::new();238
for (location, home) in &homes.entries {239
if !target.is_available_in(location, home) {240
continue;241
}242
target.write_entry(&target.config_path(location, home), &entry)?;243
written.push(location.clone());244
}245
if written.is_empty() {246
return Err(InstallError::NotAvailable(target));247
}248
Ok(InstallReport::Written(written))249
}250
251
pub fn uninstall(target: Target, homes: &Homes) -> Result<(), InstallError> {252
for (location, home) in &homes.entries {253
let path = target.config_path(location, home);254
match target.format() {255
Format::Json { container } => json_file::remove(&path, container)?,256
Format::Toml => toml_file::remove(&path)?,257
}258
}259
Ok(())260
}261
262
pub fn reinstall_all(263
endpoint: &McpEndpoint,264
homes: &Homes,265
) -> Vec<(Target, Result<(), InstallError>)> {266
let entry = ServerEntry::expected(endpoint);267
let mut results = Vec::new();268
for target in Target::ALL {269
for (location, home) in &homes.entries {270
let path = target.config_path(location, home);271
if !matches!(target.read_entry(&path), Ok(Some(_))) {272
continue;273
}274
results.push((target, target.write_entry(&path, &entry)));275
}276
}277
results278
}@@ -0,0 +1,312 @@
1
use std::fs;
2
use std::path::{Path, PathBuf};
3
4
use percent_encoding::percent_decode_str;
5
use serde_json::Value;
6
7
use super::*;
8
9
fn fixture(name: &str) -> String {
10
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
11
.join("tests/fixtures/install")
12
.join(name);
13
fs::read_to_string(path).unwrap()
14
}
15
16
fn endpoint(token: &str) -> McpEndpoint {
17
McpEndpoint {
18
url: "http://127.0.0.1:8765/mcp".to_string(),
19
token: token.to_string(),
20
}
21
}
22
23
fn homes_in(directory: &Path) -> Homes {
24
Homes {
25
entries: vec![(Location::Native, directory.to_path_buf())],
26
}
27
}
28
29
fn config(target: Target, directory: &Path) -> PathBuf {
30
target.config_path(&Location::Native, directory)
31
}
32
33
fn seed(target: Target, directory: &Path, contents: &str) -> PathBuf {
34
let path = config(target, directory);
35
fs::create_dir_all(path.parent().unwrap()).unwrap();
36
fs::write(&path, contents).unwrap();
37
path
38
}
39
40
fn backup_of(path: &Path) -> PathBuf {
41
let mut name = path.file_name().unwrap().to_os_string();
42
name.push(".bak-rusty-teams");
43
path.with_file_name(name)
44
}
45
46
#[test]
47
fn install_into_missing_file_creates_it() {
48
for target in [
49
Target::ClaudeCode,
50
Target::Codex,
51
Target::CopilotCli,
52
Target::Cursor,
53
] {
54
let directory = tempfile::tempdir().unwrap();
55
let home = directory.path();
56
fs::create_dir_all(config(target, home).parent().unwrap()).unwrap();
57
fs::create_dir_all(home.join(".claude")).unwrap();
58
let homes = homes_in(home);
59
let report = install(target, &endpoint("one"), &homes).unwrap();
60
assert_eq!(report, InstallReport::Written(vec![Location::Native]));
61
let state = status(target, &endpoint("one"), &homes);
62
assert_eq!(state.installed_at, vec![Location::Native]);
63
assert!(!state.stale);
64
}
65
}
66
67
#[test]
68
fn install_without_agent_is_not_available() {
69
let directory = tempfile::tempdir().unwrap();
70
let homes = Homes {
71
entries: vec![(
72
Location::Wsl {
73
distro: "Ubuntu".to_string(),
74
},
75
directory.path().to_path_buf(),
76
)],
77
};
78
let result = install(Target::Cursor, &endpoint("one"), &homes);
79
assert!(matches!(
80
result,
81
Err(InstallError::NotAvailable(Target::Cursor))
82
));
83
assert!(!status(Target::Cursor, &endpoint("one"), &homes).available);
84
}
85
86
#[test]
87
fn install_json_keeps_unrelated_keys_and_order() {
88
let directory = tempfile::tempdir().unwrap();
89
let path = seed(
90
Target::ClaudeCode,
91
directory.path(),
92
&fixture("claude_with_keys.json"),
93
);
94
install(
95
Target::ClaudeCode,
96
&endpoint("one"),
97
&homes_in(directory.path()),
98
)
99
.unwrap();
100
let text = fs::read_to_string(&path).unwrap();
101
let value: Value = serde_json::from_str(&text).unwrap();
102
assert_eq!(value["numStartups"], 12);
103
assert_eq!(value["mcpServers"]["other"]["command"], "npx");
104
assert_eq!(value["mcpServers"]["teams"]["type"], "http");
105
assert_eq!(
106
value["mcpServers"]["teams"]["headers"]["Authorization"],
107
"Bearer one"
108
);
109
let num_startups = text.find("numStartups").unwrap();
110
let theme = text.find("\"theme\"").unwrap();
111
let servers = text.find("mcpServers").unwrap();
112
let projects = text.find("projects").unwrap();
113
assert!(num_startups < theme && theme < servers && servers < projects);
114
assert!(text.find("\"other\"").unwrap() < text.find("\"teams\"").unwrap());
115
}
116
117
#[test]
118
fn install_toml_keeps_comments() {
119
let directory = tempfile::tempdir().unwrap();
120
let path = seed(
121
Target::Codex,
122
directory.path(),
123
&fixture("codex_with_comments.toml"),
124
);
125
install(Target::Codex, &endpoint("one"), &homes_in(directory.path())).unwrap();
126
let text = fs::read_to_string(&path).unwrap();
127
assert!(text.contains("# my codex settings"));
128
assert!(text.contains("model = \"gpt-5\" # default model"));
129
assert!(text.contains("[mcp_servers.teams]"));
130
assert!(text.contains("tool_timeout_sec = 300"));
131
assert!(text.contains("http_headers = { Authorization = \"Bearer one\" }"));
132
}
133
134
#[test]
135
fn install_twice_changes_nothing() {
136
for target in [Target::ClaudeCode, Target::Codex, Target::CopilotCli] {
137
let directory = tempfile::tempdir().unwrap();
138
let fixture_name = match target {
139
Target::Codex => "codex_with_comments.toml",
140
_ => "claude_with_keys.json",
141
};
142
let path = seed(target, directory.path(), &fixture(fixture_name));
143
let homes = homes_in(directory.path());
144
install(target, &endpoint("one"), &homes).unwrap();
145
let first = fs::read_to_string(&path).unwrap();
146
install(target, &endpoint("one"), &homes).unwrap();
147
assert_eq!(first, fs::read_to_string(&path).unwrap());
148
}
149
}
150
151
#[test]
152
fn token_change_is_stale_until_reinstall() {
153
for target in [Target::ClaudeCode, Target::Codex, Target::Cursor] {
154
let directory = tempfile::tempdir().unwrap();
155
let homes = homes_in(directory.path());
156
fs::create_dir_all(config(target, directory.path()).parent().unwrap()).unwrap();
157
install(target, &endpoint("one"), &homes).unwrap();
158
assert!(status(target, &endpoint("two"), &homes).stale);
159
let results = reinstall_all(&endpoint("two"), &homes);
160
assert!(results.iter().all(|(_, result)| result.is_ok()));
161
let state = status(target, &endpoint("two"), &homes);
162
assert!(!state.stale);
163
assert_eq!(state.installed_at, vec![Location::Native]);
164
}
165
}
166
167
#[test]
168
fn uninstall_removes_only_teams() {
169
let directory = tempfile::tempdir().unwrap();
170
let homes = homes_in(directory.path());
171
let json_path = seed(
172
Target::ClaudeCode,
173
directory.path(),
174
&fixture("claude_with_keys.json"),
175
);
176
let toml_path = seed(
177
Target::Codex,
178
directory.path(),
179
&fixture("codex_with_comments.toml"),
180
);
181
for target in [Target::ClaudeCode, Target::Codex] {
182
install(target, &endpoint("one"), &homes).unwrap();
183
uninstall(target, &homes).unwrap();
184
assert!(
185
status(target, &endpoint("one"), &homes)
186
.installed_at
187
.is_empty()
188
);
189
}
190
let value: Value = serde_json::from_str(&fs::read_to_string(&json_path).unwrap()).unwrap();
191
assert_eq!(value["mcpServers"]["other"]["command"], "npx");
192
assert!(value["mcpServers"].get("teams").is_none());
193
let toml_text = fs::read_to_string(&toml_path).unwrap();
194
assert!(toml_text.contains("[mcp_servers.other]"));
195
assert!(toml_text.contains("# my codex settings"));
196
assert!(!toml_text.contains("teams"));
197
}
198
199
#[test]
200
fn malformed_file_is_refused_and_untouched() {
201
for (target, name) in [
202
(Target::ClaudeCode, "malformed.json"),
203
(Target::Codex, "malformed.toml"),
204
] {
205
let directory = tempfile::tempdir().unwrap();
206
let original = fixture(name);
207
let path = seed(target, directory.path(), &original);
208
let homes = homes_in(directory.path());
209
let result = install(target, &endpoint("one"), &homes);
210
assert!(matches!(result, Err(InstallError::Malformed { .. })));
211
assert!(matches!(
212
uninstall(target, &homes),
213
Err(InstallError::Malformed { .. })
214
));
215
assert_eq!(fs::read_to_string(&path).unwrap(), original);
216
assert!(!backup_of(&path).exists());
217
}
218
}
219
220
#[test]
221
fn backup_is_created_once_with_original_content() {
222
let directory = tempfile::tempdir().unwrap();
223
let original = fixture("claude_with_keys.json");
224
let path = seed(Target::ClaudeCode, directory.path(), &original);
225
let homes = homes_in(directory.path());
226
install(Target::ClaudeCode, &endpoint("one"), &homes).unwrap();
227
install(Target::ClaudeCode, &endpoint("two"), &homes).unwrap();
228
assert_eq!(fs::read_to_string(backup_of(&path)).unwrap(), original);
229
}
230
231
#[test]
232
fn vscode_install_returns_deeplink_that_round_trips() {
233
let directory = tempfile::tempdir().unwrap();
234
let report = install(
235
Target::VsCode,
236
&endpoint("tok en&1"),
237
&homes_in(directory.path()),
238
)
239
.unwrap();
240
let InstallReport::OpenUrl(url) = report else {
241
panic!("expected a deeplink");
242
};
243
let encoded = url.strip_prefix("vscode:mcp/install?").unwrap();
244
assert!(!encoded.contains(['{', '"', ' ', '&']));
245
let decoded = percent_decode_str(encoded).decode_utf8().unwrap();
246
let value: Value = serde_json::from_str(&decoded).unwrap();
247
assert_eq!(value["name"], "teams");
248
assert_eq!(value["type"], "http");
249
assert_eq!(value["url"], "http://127.0.0.1:8765/mcp");
250
assert_eq!(value["headers"]["Authorization"], "Bearer tok en&1");
251
}
252
253
#[test]
254
fn vscode_status_reads_servers_key() {
255
let directory = tempfile::tempdir().unwrap();
256
seed(
257
Target::VsCode,
258
directory.path(),
259
r#"{"servers":{"teams":{"type":"http","url":"http://127.0.0.1:8765/mcp","headers":{"Authorization":"Bearer one"}}}}"#,
260
);
261
let state = status(
262
Target::VsCode,
263
&endpoint("one"),
264
&homes_in(directory.path()),
265
);
266
assert!(state.available);
267
assert_eq!(state.installed_at, vec![Location::Native]);
268
assert!(!state.stale);
269
}
270
271
#[test]
272
fn wsl_output_decodes_utf16_with_bom() {
273
let text = "Ubuntu\r\ndocker-desktop\r\n";
274
let mut bytes = vec![0xff, 0xfe];
275
bytes.extend(text.encode_utf16().flat_map(u16::to_le_bytes));
276
assert_eq!(wsl::decode_output(&bytes), text);
277
let without_bom: Vec<u8> = text.encode_utf16().flat_map(u16::to_le_bytes).collect();
278
assert_eq!(wsl::decode_output(&without_bom), text);
279
assert_eq!(wsl::decode_output(b"plain\n"), "plain\n");
280
}
281
282
#[test]
283
fn wsl_default_distro_skips_docker_and_markers() {
284
assert_eq!(
285
wsl::default_distro("docker-desktop\r\nUbuntu-24.04 (Default)\r\nDebian\r\n"),
286
Some("Ubuntu-24.04".to_string())
287
);
288
assert_eq!(
289
wsl::default_distro("Ubuntu\r\nDebian\r\n"),
290
Some("Ubuntu".to_string())
291
);
292
assert_eq!(wsl::default_distro("\r\n"), None);
293
}
294
295
#[test]
296
fn wsl_unc_home_is_built_from_distro_and_linux_home() {
297
assert_eq!(
298
wsl::unc_home("Ubuntu", "/home/daniel\n").to_string_lossy(),
299
"\\\\wsl.localhost\\Ubuntu\\home\\daniel"
300
);
301
}
302
303
#[test]
304
fn wslconfig_mirrored_mode_is_detected() {
305
assert!(wsl::wslconfig_is_mirrored(
306
"[wsl2]\nmemory=8GB\nNetworkingMode = Mirrored\n"
307
));
308
assert!(!wsl::wslconfig_is_mirrored("[wsl2]\nnetworkingMode=nat\n"));
309
assert!(!wsl::wslconfig_is_mirrored(
310
"[wsl2]\n# networkingMode=mirrored\n"
311
));
312
}
@@ -0,0 +1,312 @@1
use std::fs;2
use std::path::{Path, PathBuf};3
4
use percent_encoding::percent_decode_str;5
use serde_json::Value;6
7
use super::*;8
9
fn fixture(name: &str) -> String {10
let path = Path::new(env!("CARGO_MANIFEST_DIR"))11
.join("tests/fixtures/install")12
.join(name);13
fs::read_to_string(path).unwrap()14
}15
16
fn endpoint(token: &str) -> McpEndpoint {17
McpEndpoint {18
url: "http://127.0.0.1:8765/mcp".to_string(),19
token: token.to_string(),20
}21
}22
23
fn homes_in(directory: &Path) -> Homes {24
Homes {25
entries: vec![(Location::Native, directory.to_path_buf())],26
}27
}28
29
fn config(target: Target, directory: &Path) -> PathBuf {30
target.config_path(&Location::Native, directory)31
}32
33
fn seed(target: Target, directory: &Path, contents: &str) -> PathBuf {34
let path = config(target, directory);35
fs::create_dir_all(path.parent().unwrap()).unwrap();36
fs::write(&path, contents).unwrap();37
path38
}39
40
fn backup_of(path: &Path) -> PathBuf {41
let mut name = path.file_name().unwrap().to_os_string();42
name.push(".bak-rusty-teams");43
path.with_file_name(name)44
}45
46
#[test]47
fn install_into_missing_file_creates_it() {48
for target in [49
Target::ClaudeCode,50
Target::Codex,51
Target::CopilotCli,52
Target::Cursor,53
] {54
let directory = tempfile::tempdir().unwrap();55
let home = directory.path();56
fs::create_dir_all(config(target, home).parent().unwrap()).unwrap();57
fs::create_dir_all(home.join(".claude")).unwrap();58
let homes = homes_in(home);59
let report = install(target, &endpoint("one"), &homes).unwrap();60
assert_eq!(report, InstallReport::Written(vec![Location::Native]));61
let state = status(target, &endpoint("one"), &homes);62
assert_eq!(state.installed_at, vec![Location::Native]);63
assert!(!state.stale);64
}65
}66
67
#[test]68
fn install_without_agent_is_not_available() {69
let directory = tempfile::tempdir().unwrap();70
let homes = Homes {71
entries: vec![(72
Location::Wsl {73
distro: "Ubuntu".to_string(),74
},75
directory.path().to_path_buf(),76
)],77
};78
let result = install(Target::Cursor, &endpoint("one"), &homes);79
assert!(matches!(80
result,81
Err(InstallError::NotAvailable(Target::Cursor))82
));83
assert!(!status(Target::Cursor, &endpoint("one"), &homes).available);84
}85
86
#[test]87
fn install_json_keeps_unrelated_keys_and_order() {88
let directory = tempfile::tempdir().unwrap();89
let path = seed(90
Target::ClaudeCode,91
directory.path(),92
&fixture("claude_with_keys.json"),93
);94
install(95
Target::ClaudeCode,96
&endpoint("one"),97
&homes_in(directory.path()),98
)99
.unwrap();100
let text = fs::read_to_string(&path).unwrap();101
let value: Value = serde_json::from_str(&text).unwrap();102
assert_eq!(value["numStartups"], 12);103
assert_eq!(value["mcpServers"]["other"]["command"], "npx");104
assert_eq!(value["mcpServers"]["teams"]["type"], "http");105
assert_eq!(106
value["mcpServers"]["teams"]["headers"]["Authorization"],107
"Bearer one"108
);109
let num_startups = text.find("numStartups").unwrap();110
let theme = text.find("\"theme\"").unwrap();111
let servers = text.find("mcpServers").unwrap();112
let projects = text.find("projects").unwrap();113
assert!(num_startups < theme && theme < servers && servers < projects);114
assert!(text.find("\"other\"").unwrap() < text.find("\"teams\"").unwrap());115
}116
117
#[test]118
fn install_toml_keeps_comments() {119
let directory = tempfile::tempdir().unwrap();120
let path = seed(121
Target::Codex,122
directory.path(),123
&fixture("codex_with_comments.toml"),124
);125
install(Target::Codex, &endpoint("one"), &homes_in(directory.path())).unwrap();126
let text = fs::read_to_string(&path).unwrap();127
assert!(text.contains("# my codex settings"));128
assert!(text.contains("model = \"gpt-5\" # default model"));129
assert!(text.contains("[mcp_servers.teams]"));130
assert!(text.contains("tool_timeout_sec = 300"));131
assert!(text.contains("http_headers = { Authorization = \"Bearer one\" }"));132
}133
134
#[test]135
fn install_twice_changes_nothing() {136
for target in [Target::ClaudeCode, Target::Codex, Target::CopilotCli] {137
let directory = tempfile::tempdir().unwrap();138
let fixture_name = match target {139
Target::Codex => "codex_with_comments.toml",140
_ => "claude_with_keys.json",141
};142
let path = seed(target, directory.path(), &fixture(fixture_name));143
let homes = homes_in(directory.path());144
install(target, &endpoint("one"), &homes).unwrap();145
let first = fs::read_to_string(&path).unwrap();146
install(target, &endpoint("one"), &homes).unwrap();147
assert_eq!(first, fs::read_to_string(&path).unwrap());148
}149
}150
151
#[test]152
fn token_change_is_stale_until_reinstall() {153
for target in [Target::ClaudeCode, Target::Codex, Target::Cursor] {154
let directory = tempfile::tempdir().unwrap();155
let homes = homes_in(directory.path());156
fs::create_dir_all(config(target, directory.path()).parent().unwrap()).unwrap();157
install(target, &endpoint("one"), &homes).unwrap();158
assert!(status(target, &endpoint("two"), &homes).stale);159
let results = reinstall_all(&endpoint("two"), &homes);160
assert!(results.iter().all(|(_, result)| result.is_ok()));161
let state = status(target, &endpoint("two"), &homes);162
assert!(!state.stale);163
assert_eq!(state.installed_at, vec![Location::Native]);164
}165
}166
167
#[test]168
fn uninstall_removes_only_teams() {169
let directory = tempfile::tempdir().unwrap();170
let homes = homes_in(directory.path());171
let json_path = seed(172
Target::ClaudeCode,173
directory.path(),174
&fixture("claude_with_keys.json"),175
);176
let toml_path = seed(177
Target::Codex,178
directory.path(),179
&fixture("codex_with_comments.toml"),180
);181
for target in [Target::ClaudeCode, Target::Codex] {182
install(target, &endpoint("one"), &homes).unwrap();183
uninstall(target, &homes).unwrap();184
assert!(185
status(target, &endpoint("one"), &homes)186
.installed_at187
.is_empty()188
);189
}190
let value: Value = serde_json::from_str(&fs::read_to_string(&json_path).unwrap()).unwrap();191
assert_eq!(value["mcpServers"]["other"]["command"], "npx");192
assert!(value["mcpServers"].get("teams").is_none());193
let toml_text = fs::read_to_string(&toml_path).unwrap();194
assert!(toml_text.contains("[mcp_servers.other]"));195
assert!(toml_text.contains("# my codex settings"));196
assert!(!toml_text.contains("teams"));197
}198
199
#[test]200
fn malformed_file_is_refused_and_untouched() {201
for (target, name) in [202
(Target::ClaudeCode, "malformed.json"),203
(Target::Codex, "malformed.toml"),204
] {205
let directory = tempfile::tempdir().unwrap();206
let original = fixture(name);207
let path = seed(target, directory.path(), &original);208
let homes = homes_in(directory.path());209
let result = install(target, &endpoint("one"), &homes);210
assert!(matches!(result, Err(InstallError::Malformed { .. })));211
assert!(matches!(212
uninstall(target, &homes),213
Err(InstallError::Malformed { .. })214
));215
assert_eq!(fs::read_to_string(&path).unwrap(), original);216
assert!(!backup_of(&path).exists());217
}218
}219
220
#[test]221
fn backup_is_created_once_with_original_content() {222
let directory = tempfile::tempdir().unwrap();223
let original = fixture("claude_with_keys.json");224
let path = seed(Target::ClaudeCode, directory.path(), &original);225
let homes = homes_in(directory.path());226
install(Target::ClaudeCode, &endpoint("one"), &homes).unwrap();227
install(Target::ClaudeCode, &endpoint("two"), &homes).unwrap();228
assert_eq!(fs::read_to_string(backup_of(&path)).unwrap(), original);229
}230
231
#[test]232
fn vscode_install_returns_deeplink_that_round_trips() {233
let directory = tempfile::tempdir().unwrap();234
let report = install(235
Target::VsCode,236
&endpoint("tok en&1"),237
&homes_in(directory.path()),238
)239
.unwrap();240
let InstallReport::OpenUrl(url) = report else {241
panic!("expected a deeplink");242
};243
let encoded = url.strip_prefix("vscode:mcp/install?").unwrap();244
assert!(!encoded.contains(['{', '"', ' ', '&']));245
let decoded = percent_decode_str(encoded).decode_utf8().unwrap();246
let value: Value = serde_json::from_str(&decoded).unwrap();247
assert_eq!(value["name"], "teams");248
assert_eq!(value["type"], "http");249
assert_eq!(value["url"], "http://127.0.0.1:8765/mcp");250
assert_eq!(value["headers"]["Authorization"], "Bearer tok en&1");251
}252
253
#[test]254
fn vscode_status_reads_servers_key() {255
let directory = tempfile::tempdir().unwrap();256
seed(257
Target::VsCode,258
directory.path(),259
r#"{"servers":{"teams":{"type":"http","url":"http://127.0.0.1:8765/mcp","headers":{"Authorization":"Bearer one"}}}}"#,260
);261
let state = status(262
Target::VsCode,263
&endpoint("one"),264
&homes_in(directory.path()),265
);266
assert!(state.available);267
assert_eq!(state.installed_at, vec![Location::Native]);268
assert!(!state.stale);269
}270
271
#[test]272
fn wsl_output_decodes_utf16_with_bom() {273
let text = "Ubuntu\r\ndocker-desktop\r\n";274
let mut bytes = vec![0xff, 0xfe];275
bytes.extend(text.encode_utf16().flat_map(u16::to_le_bytes));276
assert_eq!(wsl::decode_output(&bytes), text);277
let without_bom: Vec<u8> = text.encode_utf16().flat_map(u16::to_le_bytes).collect();278
assert_eq!(wsl::decode_output(&without_bom), text);279
assert_eq!(wsl::decode_output(b"plain\n"), "plain\n");280
}281
282
#[test]283
fn wsl_default_distro_skips_docker_and_markers() {284
assert_eq!(285
wsl::default_distro("docker-desktop\r\nUbuntu-24.04 (Default)\r\nDebian\r\n"),286
Some("Ubuntu-24.04".to_string())287
);288
assert_eq!(289
wsl::default_distro("Ubuntu\r\nDebian\r\n"),290
Some("Ubuntu".to_string())291
);292
assert_eq!(wsl::default_distro("\r\n"), None);293
}294
295
#[test]296
fn wsl_unc_home_is_built_from_distro_and_linux_home() {297
assert_eq!(298
wsl::unc_home("Ubuntu", "/home/daniel\n").to_string_lossy(),299
"\\\\wsl.localhost\\Ubuntu\\home\\daniel"300
);301
}302
303
#[test]304
fn wslconfig_mirrored_mode_is_detected() {305
assert!(wsl::wslconfig_is_mirrored(306
"[wsl2]\nmemory=8GB\nNetworkingMode = Mirrored\n"307
));308
assert!(!wsl::wslconfig_is_mirrored("[wsl2]\nnetworkingMode=nat\n"));309
assert!(!wsl::wslconfig_is_mirrored(310
"[wsl2]\n# networkingMode=mirrored\n"311
));312
}@@ -0,0 +1,87 @@
1
use std::path::Path;
2
3
use toml_edit::{DocumentMut, InlineTable, Item, Table, value};
4
5
use super::entry::{SERVER_NAME, ServerEntry};
6
use super::error::InstallError;
7
use super::file;
8
9
const SERVERS_KEY: &str = "mcp_servers";
10
const TOOL_TIMEOUT_SECONDS: i64 = 300;
11
12
fn load(path: &Path) -> Result<Option<DocumentMut>, InstallError> {
13
match file::read_if_exists(path)? {
14
Some(text) => text
15
.parse::<DocumentMut>()
16
.map(Some)
17
.map_err(|error| InstallError::malformed(path, error)),
18
None => Ok(None),
19
}
20
}
21
22
fn entry_of(document: &DocumentMut) -> Option<ServerEntry> {
23
let server = document.get(SERVERS_KEY)?.get(SERVER_NAME)?;
24
Some(ServerEntry {
25
url: server.get("url")?.as_str()?.to_string(),
26
authorization: server
27
.get("http_headers")?
28
.get("Authorization")?
29
.as_str()?
30
.to_string(),
31
})
32
}
33
34
pub(super) fn read_entry(path: &Path) -> Result<Option<ServerEntry>, InstallError> {
35
Ok(load(path)?.and_then(|document| entry_of(&document)))
36
}
37
38
pub(super) fn upsert(path: &Path, entry: &ServerEntry) -> Result<(), InstallError> {
39
let mut document = load(path)?.unwrap_or_default();
40
if entry_of(&document).as_ref() != Some(entry) {
41
let server = server_table(&mut document, path)?;
42
server["url"] = value(entry.url.as_str());
43
let mut headers = InlineTable::new();
44
headers.insert("Authorization", entry.authorization.as_str().into());
45
server["http_headers"] = value(headers);
46
}
47
let server = server_table(&mut document, path)?;
48
if !server.contains_key("tool_timeout_sec") {
49
server["tool_timeout_sec"] = value(TOOL_TIMEOUT_SECONDS);
50
}
51
file::write_atomic(path, &document.to_string())
52
}
53
54
fn server_table<'document>(
55
document: &'document mut DocumentMut,
56
path: &Path,
57
) -> Result<&'document mut Table, InstallError> {
58
let servers = document
59
.entry(SERVERS_KEY)
60
.or_insert_with(|| {
61
let mut table = Table::new();
62
table.set_implicit(true);
63
Item::Table(table)
64
})
65
.as_table_mut()
66
.ok_or_else(|| InstallError::malformed(path, format!("`{SERVERS_KEY}` is not a table")))?;
67
servers
68
.entry(SERVER_NAME)
69
.or_insert_with(|| Item::Table(Table::new()))
70
.as_table_mut()
71
.ok_or_else(|| InstallError::malformed(path, format!("`{SERVER_NAME}` is not a table")))
72
}
73
74
pub(super) fn remove(path: &Path) -> Result<(), InstallError> {
75
let Some(mut document) = load(path)? else {
76
return Ok(());
77
};
78
let removed = document
79
.get_mut(SERVERS_KEY)
80
.and_then(Item::as_table_like_mut)
81
.and_then(|servers| servers.remove(SERVER_NAME))
82
.is_some();
83
if removed {
84
file::write_atomic(path, &document.to_string())?;
85
}
86
Ok(())
87
}
@@ -0,0 +1,87 @@1
use std::path::Path;2
3
use toml_edit::{DocumentMut, InlineTable, Item, Table, value};4
5
use super::entry::{SERVER_NAME, ServerEntry};6
use super::error::InstallError;7
use super::file;8
9
const SERVERS_KEY: &str = "mcp_servers";10
const TOOL_TIMEOUT_SECONDS: i64 = 300;11
12
fn load(path: &Path) -> Result<Option<DocumentMut>, InstallError> {13
match file::read_if_exists(path)? {14
Some(text) => text15
.parse::<DocumentMut>()16
.map(Some)17
.map_err(|error| InstallError::malformed(path, error)),18
None => Ok(None),19
}20
}21
22
fn entry_of(document: &DocumentMut) -> Option<ServerEntry> {23
let server = document.get(SERVERS_KEY)?.get(SERVER_NAME)?;24
Some(ServerEntry {25
url: server.get("url")?.as_str()?.to_string(),26
authorization: server27
.get("http_headers")?28
.get("Authorization")?29
.as_str()?30
.to_string(),31
})32
}33
34
pub(super) fn read_entry(path: &Path) -> Result<Option<ServerEntry>, InstallError> {35
Ok(load(path)?.and_then(|document| entry_of(&document)))36
}37
38
pub(super) fn upsert(path: &Path, entry: &ServerEntry) -> Result<(), InstallError> {39
let mut document = load(path)?.unwrap_or_default();40
if entry_of(&document).as_ref() != Some(entry) {41
let server = server_table(&mut document, path)?;42
server["url"] = value(entry.url.as_str());43
let mut headers = InlineTable::new();44
headers.insert("Authorization", entry.authorization.as_str().into());45
server["http_headers"] = value(headers);46
}47
let server = server_table(&mut document, path)?;48
if !server.contains_key("tool_timeout_sec") {49
server["tool_timeout_sec"] = value(TOOL_TIMEOUT_SECONDS);50
}51
file::write_atomic(path, &document.to_string())52
}53
54
fn server_table<'document>(55
document: &'document mut DocumentMut,56
path: &Path,57
) -> Result<&'document mut Table, InstallError> {58
let servers = document59
.entry(SERVERS_KEY)60
.or_insert_with(|| {61
let mut table = Table::new();62
table.set_implicit(true);63
Item::Table(table)64
})65
.as_table_mut()66
.ok_or_else(|| InstallError::malformed(path, format!("`{SERVERS_KEY}` is not a table")))?;67
servers68
.entry(SERVER_NAME)69
.or_insert_with(|| Item::Table(Table::new()))70
.as_table_mut()71
.ok_or_else(|| InstallError::malformed(path, format!("`{SERVER_NAME}` is not a table")))72
}73
74
pub(super) fn remove(path: &Path) -> Result<(), InstallError> {75
let Some(mut document) = load(path)? else {76
return Ok(());77
};78
let removed = document79
.get_mut(SERVERS_KEY)80
.and_then(Item::as_table_like_mut)81
.and_then(|servers| servers.remove(SERVER_NAME))82
.is_some();83
if removed {84
file::write_atomic(path, &document.to_string())?;85
}86
Ok(())87
}@@ -0,0 +1,98 @@
1
#![cfg_attr(not(windows), allow(dead_code))]
2
3
use std::path::PathBuf;
4
5
const DISTRO_SKIP_PREFIX: &str = "docker-desktop";
6
7
pub(super) fn decode_output(bytes: &[u8]) -> String {
8
let looks_utf16 = bytes.starts_with(&[0xff, 0xfe])
9
|| bytes
10
.iter()
11
.skip(1)
12
.step_by(2)
13
.take(8)
14
.all(|byte| *byte == 0)
15
&& bytes.len() >= 2;
16
let text = if looks_utf16 {
17
let units: Vec<u16> = bytes
18
.chunks_exact(2)
19
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
20
.collect();
21
String::from_utf16_lossy(&units)
22
} else {
23
String::from_utf8_lossy(bytes).into_owned()
24
};
25
text.trim_start_matches('\u{feff}').replace('\0', "")
26
}
27
28
pub(super) fn default_distro(list_output: &str) -> Option<String> {
29
list_output
30
.lines()
31
.map(|line| line.trim().trim_end_matches("(Default)").trim())
32
.find(|name| !name.is_empty() && !name.starts_with(DISTRO_SKIP_PREFIX))
33
.map(str::to_string)
34
}
35
36
pub(super) fn unc_home(distro: &str, linux_home: &str) -> PathBuf {
37
let relative = linux_home.trim().trim_matches('/').replace('/', "\\");
38
PathBuf::from(format!("\\\\wsl.localhost\\{distro}\\{relative}"))
39
}
40
41
pub(super) fn wslconfig_is_mirrored(text: &str) -> bool {
42
text.lines()
43
.filter_map(|line| line.split('#').next()?.split_once('='))
44
.any(|(key, value)| {
45
key.trim().eq_ignore_ascii_case("networkingMode")
46
&& value.trim().eq_ignore_ascii_case("mirrored")
47
})
48
}
49
50
#[cfg(windows)]
51
mod spawn {
52
use std::os::windows::process::CommandExt;
53
use std::path::PathBuf;
54
use std::process::Command;
55
56
use super::{decode_output, default_distro, unc_home, wslconfig_is_mirrored};
57
58
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
59
60
fn run(arguments: &[&str]) -> Option<String> {
61
let output = Command::new("wsl.exe")
62
.args(arguments)
63
.creation_flags(CREATE_NO_WINDOW)
64
.output()
65
.ok()?;
66
output
67
.status
68
.success()
69
.then(|| decode_output(&output.stdout))
70
}
71
72
pub fn default_home() -> Option<(String, PathBuf)> {
73
let distro = default_distro(&run(&["-l", "-q"])?)?;
74
let linux_home = run(&["-d", &distro, "--cd", "~", "-e", "pwd"])?;
75
let home = unc_home(&distro, linux_home.trim());
76
Some((distro, home))
77
}
78
79
pub fn reachable(port: u16) -> Option<bool> {
80
let probe = format!(
81
"curl -s -m 2 http://127.0.0.1:{port}/healthz || wget -qO- -T 2 http://127.0.0.1:{port}/healthz"
82
);
83
match run(&["-e", "sh", "-c", &probe]) {
84
Some(output) => Some(output.trim() == "ok"),
85
None => mirrored_networking().then_some(true),
86
}
87
}
88
89
fn mirrored_networking() -> bool {
90
std::env::var_os("USERPROFILE")
91
.map(|profile| PathBuf::from(profile).join(".wslconfig"))
92
.and_then(|path| std::fs::read_to_string(path).ok())
93
.is_some_and(|text| wslconfig_is_mirrored(&text))
94
}
95
}
96
97
#[cfg(windows)]
98
pub(super) use spawn::{default_home, reachable};
@@ -0,0 +1,98 @@1
#![cfg_attr(not(windows), allow(dead_code))]2
3
use std::path::PathBuf;4
5
const DISTRO_SKIP_PREFIX: &str = "docker-desktop";6
7
pub(super) fn decode_output(bytes: &[u8]) -> String {8
let looks_utf16 = bytes.starts_with(&[0xff, 0xfe])9
|| bytes10
.iter()11
.skip(1)12
.step_by(2)13
.take(8)14
.all(|byte| *byte == 0)15
&& bytes.len() >= 2;16
let text = if looks_utf16 {17
let units: Vec<u16> = bytes18
.chunks_exact(2)19
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))20
.collect();21
String::from_utf16_lossy(&units)22
} else {23
String::from_utf8_lossy(bytes).into_owned()24
};25
text.trim_start_matches('\u{feff}').replace('\0', "")26
}27
28
pub(super) fn default_distro(list_output: &str) -> Option<String> {29
list_output30
.lines()31
.map(|line| line.trim().trim_end_matches("(Default)").trim())32
.find(|name| !name.is_empty() && !name.starts_with(DISTRO_SKIP_PREFIX))33
.map(str::to_string)34
}35
36
pub(super) fn unc_home(distro: &str, linux_home: &str) -> PathBuf {37
let relative = linux_home.trim().trim_matches('/').replace('/', "\\");38
PathBuf::from(format!("\\\\wsl.localhost\\{distro}\\{relative}"))39
}40
41
pub(super) fn wslconfig_is_mirrored(text: &str) -> bool {42
text.lines()43
.filter_map(|line| line.split('#').next()?.split_once('='))44
.any(|(key, value)| {45
key.trim().eq_ignore_ascii_case("networkingMode")46
&& value.trim().eq_ignore_ascii_case("mirrored")47
})48
}49
50
#[cfg(windows)]51
mod spawn {52
use std::os::windows::process::CommandExt;53
use std::path::PathBuf;54
use std::process::Command;55
56
use super::{decode_output, default_distro, unc_home, wslconfig_is_mirrored};57
58
const CREATE_NO_WINDOW: u32 = 0x0800_0000;59
60
fn run(arguments: &[&str]) -> Option<String> {61
let output = Command::new("wsl.exe")62
.args(arguments)63
.creation_flags(CREATE_NO_WINDOW)64
.output()65
.ok()?;66
output67
.status68
.success()69
.then(|| decode_output(&output.stdout))70
}71
72
pub fn default_home() -> Option<(String, PathBuf)> {73
let distro = default_distro(&run(&["-l", "-q"])?)?;74
let linux_home = run(&["-d", &distro, "--cd", "~", "-e", "pwd"])?;75
let home = unc_home(&distro, linux_home.trim());76
Some((distro, home))77
}78
79
pub fn reachable(port: u16) -> Option<bool> {80
let probe = format!(81
"curl -s -m 2 http://127.0.0.1:{port}/healthz || wget -qO- -T 2 http://127.0.0.1:{port}/healthz"82
);83
match run(&["-e", "sh", "-c", &probe]) {84
Some(output) => Some(output.trim() == "ok"),85
None => mirrored_networking().then_some(true),86
}87
}88
89
fn mirrored_networking() -> bool {90
std::env::var_os("USERPROFILE")91
.map(|profile| PathBuf::from(profile).join(".wslconfig"))92
.and_then(|path| std::fs::read_to_string(path).ok())93
.is_some_and(|text| wslconfig_is_mirrored(&text))94
}95
}96
97
#[cfg(windows)]98
pub(super) use spawn::{default_home, reachable};@@ -0,0 +1,22 @@
1
mod auth;
2
mod hub;
3
pub mod install;
4
mod policy;
5
mod server;
6
mod settings;
7
mod source;
8
mod tools;
9
10
pub use hub::{AgentHub, CaptionLine, Event, EventKind, Outcome, Proposal, UiEvent};
11
pub use policy::{Access, AgentPolicy, ConversationKind, DEFAULT_PORT};
12
pub use server::{ServerError, ServerHandle, start};
13
pub use settings::{
14
load as load_policy, load_or_create_token, regenerate_token, save as save_policy,
15
};
16
pub use source::{Meeting, SourceError, SourceFuture, TeamsSource, Transcript, TranscriptTurn};
17
18
#[derive(Debug, Clone, PartialEq, Eq)]
19
pub struct McpEndpoint {
20
pub url: String,
21
pub token: String,
22
}
@@ -0,0 +1,22 @@1
mod auth;2
mod hub;3
pub mod install;4
mod policy;5
mod server;6
mod settings;7
mod source;8
mod tools;9
10
pub use hub::{AgentHub, CaptionLine, Event, EventKind, Outcome, Proposal, UiEvent};11
pub use policy::{Access, AgentPolicy, ConversationKind, DEFAULT_PORT};12
pub use server::{ServerError, ServerHandle, start};13
pub use settings::{14
load as load_policy, load_or_create_token, regenerate_token, save as save_policy,15
};16
pub use source::{Meeting, SourceError, SourceFuture, TeamsSource, Transcript, TranscriptTurn};17
18
#[derive(Debug, Clone, PartialEq, Eq)]19
pub struct McpEndpoint {20
pub url: String,21
pub token: String,22
}@@ -0,0 +1,211 @@
1
use std::collections::BTreeSet;
2
3
pub const DEFAULT_PORT: u16 = 47615;
4
5
#[derive(Debug, Clone, PartialEq, Eq, Default)]
6
pub enum Access {
7
#[default]
8
None,
9
Selected(BTreeSet<String>),
10
All,
11
}
12
13
impl Access {
14
pub fn allows(&self, conversation_id: &str) -> bool {
15
match self {
16
Access::None => false,
17
Access::Selected(ids) => ids.contains(conversation_id),
18
Access::All => true,
19
}
20
}
21
}
22
23
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24
pub enum ConversationKind {
25
Chat,
26
Meeting,
27
Channel,
28
}
29
30
#[derive(Debug, Clone, PartialEq, Eq)]
31
pub struct AgentPolicy {
32
pub enabled: bool,
33
pub port: u16,
34
pub chats: Access,
35
pub channels: Access,
36
pub propose: bool,
37
pub calendar: bool,
38
pub transcripts: bool,
39
}
40
41
impl Default for AgentPolicy {
42
fn default() -> Self {
43
AgentPolicy {
44
enabled: false,
45
port: DEFAULT_PORT,
46
chats: Access::None,
47
channels: Access::None,
48
propose: false,
49
calendar: false,
50
transcripts: false,
51
}
52
}
53
}
54
55
impl AgentPolicy {
56
pub fn access(&self, kind: ConversationKind) -> &Access {
57
match kind {
58
ConversationKind::Chat | ConversationKind::Meeting => &self.chats,
59
ConversationKind::Channel => &self.channels,
60
}
61
}
62
63
pub fn can_read(&self, kind: ConversationKind, conversation_id: &str) -> bool {
64
self.enabled && self.access(kind).allows(conversation_id)
65
}
66
67
pub fn can_propose(&self, kind: ConversationKind, conversation_id: &str) -> bool {
68
self.can_read(kind, conversation_id) && self.propose
69
}
70
71
pub fn can_read_any_kind(&self, conversation_id: &str) -> bool {
72
self.enabled
73
&& (self.chats.allows(conversation_id) || self.channels.allows(conversation_id))
74
}
75
76
pub fn readable_ids<'a>(
77
&self,
78
kind: ConversationKind,
79
conversation_ids: impl IntoIterator<Item = &'a str>,
80
) -> Vec<String> {
81
conversation_ids
82
.into_iter()
83
.filter(|conversation_id| self.can_read(kind, conversation_id))
84
.map(str::to_owned)
85
.collect()
86
}
87
}
88
89
#[cfg(test)]
90
mod tests {
91
use super::*;
92
93
fn selected(ids: &[&str]) -> Access {
94
Access::Selected(ids.iter().map(|id| (*id).to_owned()).collect())
95
}
96
97
fn policy(chats: Access, channels: Access, propose: bool) -> AgentPolicy {
98
AgentPolicy {
99
enabled: true,
100
chats,
101
channels,
102
propose,
103
..AgentPolicy::default()
104
}
105
}
106
107
#[test]
108
fn read_and_propose_follow_scope_and_flags() {
109
use ConversationKind::{Channel, Chat, Meeting};
110
let cases = [
111
(
112
policy(Access::None, Access::None, true),
113
Chat,
114
"a",
115
false,
116
false,
117
),
118
(
119
policy(Access::All, Access::None, false),
120
Chat,
121
"a",
122
true,
123
false,
124
),
125
(
126
policy(Access::All, Access::None, true),
127
Chat,
128
"a",
129
true,
130
true,
131
),
132
(
133
policy(selected(&["a"]), Access::None, true),
134
Chat,
135
"a",
136
true,
137
true,
138
),
139
(
140
policy(selected(&["a"]), Access::None, true),
141
Chat,
142
"b",
143
false,
144
false,
145
),
146
(
147
policy(selected(&["a"]), Access::None, true),
148
Meeting,
149
"a",
150
true,
151
true,
152
),
153
(
154
policy(selected(&["a"]), Access::None, true),
155
Channel,
156
"a",
157
false,
158
false,
159
),
160
(
161
policy(Access::None, Access::All, true),
162
Channel,
163
"a",
164
true,
165
true,
166
),
167
(
168
policy(Access::All, selected(&["c"]), false),
169
Channel,
170
"d",
171
false,
172
false,
173
),
174
];
175
for (policy, kind, id, read, propose) in cases {
176
assert_eq!(policy.can_read(kind, id), read, "{kind:?} {id}");
177
assert_eq!(policy.can_propose(kind, id), propose, "{kind:?} {id}");
178
}
179
}
180
181
#[test]
182
fn disabled_policy_allows_nothing() {
183
let policy = AgentPolicy {
184
enabled: false,
185
chats: Access::All,
186
channels: Access::All,
187
propose: true,
188
..AgentPolicy::default()
189
};
190
assert!(!policy.can_read(ConversationKind::Chat, "a"));
191
assert!(!policy.can_propose(ConversationKind::Channel, "a"));
192
}
193
194
#[test]
195
fn default_is_closed() {
196
let policy = AgentPolicy::default();
197
assert_eq!(policy.port, DEFAULT_PORT);
198
assert!(!policy.enabled && !policy.propose && !policy.calendar && !policy.transcripts);
199
assert_eq!(policy.chats, Access::None);
200
assert_eq!(policy.channels, Access::None);
201
}
202
203
#[test]
204
fn readable_ids_keeps_only_allowed() {
205
let policy = policy(selected(&["a", "c"]), Access::None, false);
206
assert_eq!(
207
policy.readable_ids(ConversationKind::Chat, ["a", "b", "c"]),
208
["a", "c"]
209
);
210
}
211
}
@@ -0,0 +1,211 @@1
use std::collections::BTreeSet;2
3
pub const DEFAULT_PORT: u16 = 47615;4
5
#[derive(Debug, Clone, PartialEq, Eq, Default)]6
pub enum Access {7
#[default]8
None,9
Selected(BTreeSet<String>),10
All,11
}12
13
impl Access {14
pub fn allows(&self, conversation_id: &str) -> bool {15
match self {16
Access::None => false,17
Access::Selected(ids) => ids.contains(conversation_id),18
Access::All => true,19
}20
}21
}22
23
#[derive(Debug, Clone, Copy, PartialEq, Eq)]24
pub enum ConversationKind {25
Chat,26
Meeting,27
Channel,28
}29
30
#[derive(Debug, Clone, PartialEq, Eq)]31
pub struct AgentPolicy {32
pub enabled: bool,33
pub port: u16,34
pub chats: Access,35
pub channels: Access,36
pub propose: bool,37
pub calendar: bool,38
pub transcripts: bool,39
}40
41
impl Default for AgentPolicy {42
fn default() -> Self {43
AgentPolicy {44
enabled: false,45
port: DEFAULT_PORT,46
chats: Access::None,47
channels: Access::None,48
propose: false,49
calendar: false,50
transcripts: false,51
}52
}53
}54
55
impl AgentPolicy {56
pub fn access(&self, kind: ConversationKind) -> &Access {57
match kind {58
ConversationKind::Chat | ConversationKind::Meeting => &self.chats,59
ConversationKind::Channel => &self.channels,60
}61
}62
63
pub fn can_read(&self, kind: ConversationKind, conversation_id: &str) -> bool {64
self.enabled && self.access(kind).allows(conversation_id)65
}66
67
pub fn can_propose(&self, kind: ConversationKind, conversation_id: &str) -> bool {68
self.can_read(kind, conversation_id) && self.propose69
}70
71
pub fn can_read_any_kind(&self, conversation_id: &str) -> bool {72
self.enabled73
&& (self.chats.allows(conversation_id) || self.channels.allows(conversation_id))74
}75
76
pub fn readable_ids<'a>(77
&self,78
kind: ConversationKind,79
conversation_ids: impl IntoIterator<Item = &'a str>,80
) -> Vec<String> {81
conversation_ids82
.into_iter()83
.filter(|conversation_id| self.can_read(kind, conversation_id))84
.map(str::to_owned)85
.collect()86
}87
}88
89
#[cfg(test)]90
mod tests {91
use super::*;92
93
fn selected(ids: &[&str]) -> Access {94
Access::Selected(ids.iter().map(|id| (*id).to_owned()).collect())95
}96
97
fn policy(chats: Access, channels: Access, propose: bool) -> AgentPolicy {98
AgentPolicy {99
enabled: true,100
chats,101
channels,102
propose,103
..AgentPolicy::default()104
}105
}106
107
#[test]108
fn read_and_propose_follow_scope_and_flags() {109
use ConversationKind::{Channel, Chat, Meeting};110
let cases = [111
(112
policy(Access::None, Access::None, true),113
Chat,114
"a",115
false,116
false,117
),118
(119
policy(Access::All, Access::None, false),120
Chat,121
"a",122
true,123
false,124
),125
(126
policy(Access::All, Access::None, true),127
Chat,128
"a",129
true,130
true,131
),132
(133
policy(selected(&["a"]), Access::None, true),134
Chat,135
"a",136
true,137
true,138
),139
(140
policy(selected(&["a"]), Access::None, true),141
Chat,142
"b",143
false,144
false,145
),146
(147
policy(selected(&["a"]), Access::None, true),148
Meeting,149
"a",150
true,151
true,152
),153
(154
policy(selected(&["a"]), Access::None, true),155
Channel,156
"a",157
false,158
false,159
),160
(161
policy(Access::None, Access::All, true),162
Channel,163
"a",164
true,165
true,166
),167
(168
policy(Access::All, selected(&["c"]), false),169
Channel,170
"d",171
false,172
false,173
),174
];175
for (policy, kind, id, read, propose) in cases {176
assert_eq!(policy.can_read(kind, id), read, "{kind:?} {id}");177
assert_eq!(policy.can_propose(kind, id), propose, "{kind:?} {id}");178
}179
}180
181
#[test]182
fn disabled_policy_allows_nothing() {183
let policy = AgentPolicy {184
enabled: false,185
chats: Access::All,186
channels: Access::All,187
propose: true,188
..AgentPolicy::default()189
};190
assert!(!policy.can_read(ConversationKind::Chat, "a"));191
assert!(!policy.can_propose(ConversationKind::Channel, "a"));192
}193
194
#[test]195
fn default_is_closed() {196
let policy = AgentPolicy::default();197
assert_eq!(policy.port, DEFAULT_PORT);198
assert!(!policy.enabled && !policy.propose && !policy.calendar && !policy.transcripts);199
assert_eq!(policy.chats, Access::None);200
assert_eq!(policy.channels, Access::None);201
}202
203
#[test]204
fn readable_ids_keeps_only_allowed() {205
let policy = policy(selected(&["a", "c"]), Access::None, false);206
assert_eq!(207
policy.readable_ids(ConversationKind::Chat, ["a", "b", "c"]),208
["a", "c"]209
);210
}211
}@@ -0,0 +1,85 @@
1
use std::net::SocketAddr;
2
use std::sync::Arc;
3
4
use axum::Router;
5
use axum::middleware::from_fn_with_state;
6
use axum::routing::get;
7
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
8
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
9
use tokio::net::TcpListener;
10
use tokio::task::JoinHandle;
11
use tokio_util::sync::CancellationToken;
12
13
use crate::auth::{AuthState, MAX_BODY_BYTES, healthz, require_auth};
14
use crate::hub::AgentHub;
15
use crate::source::TeamsSource;
16
use crate::tools::TeamsTools;
17
18
#[derive(Debug, thiserror::Error)]
19
pub enum ServerError {
20
#[error("port {port} is already in use, choose another port in rusty-teams Settings > MCP")]
21
PortInUse { port: u16 },
22
#[error("cannot start the MCP server on port {port}: {source}")]
23
Bind { port: u16, source: std::io::Error },
24
}
25
26
pub struct ServerHandle {
27
pub addr: SocketAddr,
28
shutdown: CancellationToken,
29
task: JoinHandle<()>,
30
}
31
32
impl ServerHandle {
33
pub async fn shutdown(self) {
34
self.shutdown.cancel();
35
let _ = self.task.await;
36
}
37
}
38
39
pub async fn start(
40
hub: Arc<AgentHub>,
41
source: Arc<dyn TeamsSource>,
42
port: u16,
43
token: String,
44
) -> Result<ServerHandle, ServerError> {
45
let listener = TcpListener::bind(("127.0.0.1", port))
46
.await
47
.map_err(|source| match source.kind() {
48
std::io::ErrorKind::AddrInUse => ServerError::PortInUse { port },
49
_ => ServerError::Bind { port, source },
50
})?;
51
let addr = listener
52
.local_addr()
53
.map_err(|source| ServerError::Bind { port, source })?;
54
let auth = AuthState {
55
port: addr.port(),
56
token,
57
};
58
let shutdown = CancellationToken::new();
59
let mut config = StreamableHttpServerConfig::default()
60
.with_allowed_hosts(auth.allowed_hosts())
61
.with_allowed_origins(auth.allowed_origins());
62
config.cancellation_token = shutdown.child_token();
63
config.max_request_body_bytes = MAX_BODY_BYTES;
64
let service: StreamableHttpService<TeamsTools, LocalSessionManager> =
65
StreamableHttpService::new(
66
move || Ok(TeamsTools::new(hub.clone(), source.clone())),
67
Default::default(),
68
config,
69
);
70
let router = Router::new()
71
.nest_service("/mcp", service)
72
.layer(from_fn_with_state(auth, require_auth))
73
.route("/healthz", get(healthz));
74
let graceful = shutdown.clone();
75
let task = tokio::spawn(async move {
76
let _ = axum::serve(listener, router)
77
.with_graceful_shutdown(async move { graceful.cancelled_owned().await })
78
.await;
79
});
80
Ok(ServerHandle {
81
addr,
82
shutdown,
83
task,
84
})
85
}
@@ -0,0 +1,85 @@1
use std::net::SocketAddr;2
use std::sync::Arc;3
4
use axum::Router;5
use axum::middleware::from_fn_with_state;6
use axum::routing::get;7
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;8
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};9
use tokio::net::TcpListener;10
use tokio::task::JoinHandle;11
use tokio_util::sync::CancellationToken;12
13
use crate::auth::{AuthState, MAX_BODY_BYTES, healthz, require_auth};14
use crate::hub::AgentHub;15
use crate::source::TeamsSource;16
use crate::tools::TeamsTools;17
18
#[derive(Debug, thiserror::Error)]19
pub enum ServerError {20
#[error("port {port} is already in use, choose another port in rusty-teams Settings > MCP")]21
PortInUse { port: u16 },22
#[error("cannot start the MCP server on port {port}: {source}")]23
Bind { port: u16, source: std::io::Error },24
}25
26
pub struct ServerHandle {27
pub addr: SocketAddr,28
shutdown: CancellationToken,29
task: JoinHandle<()>,30
}31
32
impl ServerHandle {33
pub async fn shutdown(self) {34
self.shutdown.cancel();35
let _ = self.task.await;36
}37
}38
39
pub async fn start(40
hub: Arc<AgentHub>,41
source: Arc<dyn TeamsSource>,42
port: u16,43
token: String,44
) -> Result<ServerHandle, ServerError> {45
let listener = TcpListener::bind(("127.0.0.1", port))46
.await47
.map_err(|source| match source.kind() {48
std::io::ErrorKind::AddrInUse => ServerError::PortInUse { port },49
_ => ServerError::Bind { port, source },50
})?;51
let addr = listener52
.local_addr()53
.map_err(|source| ServerError::Bind { port, source })?;54
let auth = AuthState {55
port: addr.port(),56
token,57
};58
let shutdown = CancellationToken::new();59
let mut config = StreamableHttpServerConfig::default()60
.with_allowed_hosts(auth.allowed_hosts())61
.with_allowed_origins(auth.allowed_origins());62
config.cancellation_token = shutdown.child_token();63
config.max_request_body_bytes = MAX_BODY_BYTES;64
let service: StreamableHttpService<TeamsTools, LocalSessionManager> =65
StreamableHttpService::new(66
move || Ok(TeamsTools::new(hub.clone(), source.clone())),67
Default::default(),68
config,69
);70
let router = Router::new()71
.nest_service("/mcp", service)72
.layer(from_fn_with_state(auth, require_auth))73
.route("/healthz", get(healthz));74
let graceful = shutdown.clone();75
let task = tokio::spawn(async move {76
let _ = axum::serve(listener, router)77
.with_graceful_shutdown(async move { graceful.cancelled_owned().await })78
.await;79
});80
Ok(ServerHandle {81
addr,82
shutdown,83
task,84
})85
}@@ -0,0 +1,168 @@
1
use std::collections::BTreeSet;
2
3
use rand::RngCore;
4
use store::Store;
5
6
use crate::policy::{Access, AgentPolicy, DEFAULT_PORT};
7
8
const SETTINGS_KEY: &str = "agents.settings";
9
const TOKEN_KEY: &str = "agents.token";
10
const TOKEN_BYTES: usize = 32;
11
const ALL_KEYWORD: &str = "all";
12
const SELECTED_PREFIX: &str = "selected:";
13
14
pub fn load(store: &Store) -> AgentPolicy {
15
store
16
.meta(SETTINGS_KEY)
17
.ok()
18
.flatten()
19
.map(|text| parse(&text))
20
.unwrap_or_default()
21
}
22
23
pub fn save(store: &Store, policy: &AgentPolicy) {
24
let _ = store.set_meta(SETTINGS_KEY, &serialize(policy));
25
}
26
27
pub fn load_or_create_token(store: &Store) -> store::Result<String> {
28
match store.meta(TOKEN_KEY)? {
29
Some(token) if !token.is_empty() => Ok(token),
30
_ => regenerate_token(store),
31
}
32
}
33
34
pub fn regenerate_token(store: &Store) -> store::Result<String> {
35
let mut bytes = [0_u8; TOKEN_BYTES];
36
rand::rng().fill_bytes(&mut bytes);
37
let token: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
38
store.set_meta(TOKEN_KEY, &token)?;
39
Ok(token)
40
}
41
42
fn serialize_access(access: &Access) -> String {
43
match access {
44
Access::None => String::new(),
45
Access::All => ALL_KEYWORD.to_owned(),
46
Access::Selected(ids) => format!(
47
"{SELECTED_PREFIX}{}",
48
ids.iter().cloned().collect::<Vec<_>>().join(",")
49
),
50
}
51
}
52
53
fn parse_access(value: &str) -> Access {
54
if value == ALL_KEYWORD {
55
return Access::All;
56
}
57
let Some(list) = value.strip_prefix(SELECTED_PREFIX) else {
58
return Access::None;
59
};
60
let ids: BTreeSet<String> = list
61
.split(',')
62
.filter(|id| !id.is_empty())
63
.map(str::to_owned)
64
.collect();
65
Access::Selected(ids)
66
}
67
68
fn serialize(policy: &AgentPolicy) -> String {
69
[
70
("enabled", policy.enabled.to_string()),
71
("port", policy.port.to_string()),
72
("chats", serialize_access(&policy.chats)),
73
("channels", serialize_access(&policy.channels)),
74
("propose", policy.propose.to_string()),
75
("calendar", policy.calendar.to_string()),
76
("transcripts", policy.transcripts.to_string()),
77
]
78
.iter()
79
.map(|(key, value)| format!("{key}={value}"))
80
.collect::<Vec<_>>()
81
.join("\n")
82
}
83
84
fn parse(text: &str) -> AgentPolicy {
85
let mut policy = AgentPolicy::default();
86
for line in text.lines() {
87
let Some((key, value)) = line.split_once('=') else {
88
continue;
89
};
90
let flag = value == "true";
91
match key {
92
"enabled" => policy.enabled = flag,
93
"port" => policy.port = value.parse().unwrap_or(DEFAULT_PORT),
94
"chats" => policy.chats = parse_access(value),
95
"channels" => policy.channels = parse_access(value),
96
"propose" => policy.propose = flag,
97
"calendar" => policy.calendar = flag,
98
"transcripts" => policy.transcripts = flag,
99
_ => {}
100
}
101
}
102
policy
103
}
104
105
#[cfg(test)]
106
mod tests {
107
use super::*;
108
109
#[test]
110
fn round_trips_every_field() {
111
let policy = AgentPolicy {
112
enabled: true,
113
port: 50123,
114
chats: Access::Selected(
115
["19:abc@thread.v2", "19:def@unq.gbl.spaces"]
116
.iter()
117
.map(|id| (*id).to_owned())
118
.collect(),
119
),
120
channels: Access::All,
121
propose: true,
122
calendar: true,
123
transcripts: true,
124
};
125
assert_eq!(parse(&serialize(&policy)), policy);
126
}
127
128
#[test]
129
fn empty_selection_round_trips() {
130
let policy = AgentPolicy {
131
chats: Access::Selected(BTreeSet::new()),
132
..AgentPolicy::default()
133
};
134
assert_eq!(parse(&serialize(&policy)), policy);
135
}
136
137
#[test]
138
fn garbage_falls_back_to_default() {
139
assert_eq!(parse("\u{0}\u{1}nonsense\n==\n"), AgentPolicy::default());
140
let policy = parse("port=banana\nchats=everything\nenabled=maybe");
141
assert_eq!(policy, AgentPolicy::default());
142
}
143
144
#[test]
145
fn saves_and_loads_through_the_store() {
146
let store = Store::open_in_memory().unwrap();
147
assert_eq!(load(&store), AgentPolicy::default());
148
let policy = AgentPolicy {
149
enabled: true,
150
propose: true,
151
..AgentPolicy::default()
152
};
153
save(&store, &policy);
154
assert_eq!(load(&store), policy);
155
}
156
157
#[test]
158
fn token_is_created_once_and_regenerated_on_demand() {
159
let store = Store::open_in_memory().unwrap();
160
let first = load_or_create_token(&store).unwrap();
161
assert_eq!(first.len(), TOKEN_BYTES * 2);
162
assert!(first.chars().all(|character| character.is_ascii_hexdigit()));
163
assert_eq!(load_or_create_token(&store).unwrap(), first);
164
let second = regenerate_token(&store).unwrap();
165
assert_ne!(second, first);
166
assert_eq!(load_or_create_token(&store).unwrap(), second);
167
}
168
}
@@ -0,0 +1,168 @@1
use std::collections::BTreeSet;2
3
use rand::RngCore;4
use store::Store;5
6
use crate::policy::{Access, AgentPolicy, DEFAULT_PORT};7
8
const SETTINGS_KEY: &str = "agents.settings";9
const TOKEN_KEY: &str = "agents.token";10
const TOKEN_BYTES: usize = 32;11
const ALL_KEYWORD: &str = "all";12
const SELECTED_PREFIX: &str = "selected:";13
14
pub fn load(store: &Store) -> AgentPolicy {15
store16
.meta(SETTINGS_KEY)17
.ok()18
.flatten()19
.map(|text| parse(&text))20
.unwrap_or_default()21
}22
23
pub fn save(store: &Store, policy: &AgentPolicy) {24
let _ = store.set_meta(SETTINGS_KEY, &serialize(policy));25
}26
27
pub fn load_or_create_token(store: &Store) -> store::Result<String> {28
match store.meta(TOKEN_KEY)? {29
Some(token) if !token.is_empty() => Ok(token),30
_ => regenerate_token(store),31
}32
}33
34
pub fn regenerate_token(store: &Store) -> store::Result<String> {35
let mut bytes = [0_u8; TOKEN_BYTES];36
rand::rng().fill_bytes(&mut bytes);37
let token: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();38
store.set_meta(TOKEN_KEY, &token)?;39
Ok(token)40
}41
42
fn serialize_access(access: &Access) -> String {43
match access {44
Access::None => String::new(),45
Access::All => ALL_KEYWORD.to_owned(),46
Access::Selected(ids) => format!(47
"{SELECTED_PREFIX}{}",48
ids.iter().cloned().collect::<Vec<_>>().join(",")49
),50
}51
}52
53
fn parse_access(value: &str) -> Access {54
if value == ALL_KEYWORD {55
return Access::All;56
}57
let Some(list) = value.strip_prefix(SELECTED_PREFIX) else {58
return Access::None;59
};60
let ids: BTreeSet<String> = list61
.split(',')62
.filter(|id| !id.is_empty())63
.map(str::to_owned)64
.collect();65
Access::Selected(ids)66
}67
68
fn serialize(policy: &AgentPolicy) -> String {69
[70
("enabled", policy.enabled.to_string()),71
("port", policy.port.to_string()),72
("chats", serialize_access(&policy.chats)),73
("channels", serialize_access(&policy.channels)),74
("propose", policy.propose.to_string()),75
("calendar", policy.calendar.to_string()),76
("transcripts", policy.transcripts.to_string()),77
]78
.iter()79
.map(|(key, value)| format!("{key}={value}"))80
.collect::<Vec<_>>()81
.join("\n")82
}83
84
fn parse(text: &str) -> AgentPolicy {85
let mut policy = AgentPolicy::default();86
for line in text.lines() {87
let Some((key, value)) = line.split_once('=') else {88
continue;89
};90
let flag = value == "true";91
match key {92
"enabled" => policy.enabled = flag,93
"port" => policy.port = value.parse().unwrap_or(DEFAULT_PORT),94
"chats" => policy.chats = parse_access(value),95
"channels" => policy.channels = parse_access(value),96
"propose" => policy.propose = flag,97
"calendar" => policy.calendar = flag,98
"transcripts" => policy.transcripts = flag,99
_ => {}100
}101
}102
policy103
}104
105
#[cfg(test)]106
mod tests {107
use super::*;108
109
#[test]110
fn round_trips_every_field() {111
let policy = AgentPolicy {112
enabled: true,113
port: 50123,114
chats: Access::Selected(115
["19:abc@thread.v2", "19:def@unq.gbl.spaces"]116
.iter()117
.map(|id| (*id).to_owned())118
.collect(),119
),120
channels: Access::All,121
propose: true,122
calendar: true,123
transcripts: true,124
};125
assert_eq!(parse(&serialize(&policy)), policy);126
}127
128
#[test]129
fn empty_selection_round_trips() {130
let policy = AgentPolicy {131
chats: Access::Selected(BTreeSet::new()),132
..AgentPolicy::default()133
};134
assert_eq!(parse(&serialize(&policy)), policy);135
}136
137
#[test]138
fn garbage_falls_back_to_default() {139
assert_eq!(parse("\u{0}\u{1}nonsense\n==\n"), AgentPolicy::default());140
let policy = parse("port=banana\nchats=everything\nenabled=maybe");141
assert_eq!(policy, AgentPolicy::default());142
}143
144
#[test]145
fn saves_and_loads_through_the_store() {146
let store = Store::open_in_memory().unwrap();147
assert_eq!(load(&store), AgentPolicy::default());148
let policy = AgentPolicy {149
enabled: true,150
propose: true,151
..AgentPolicy::default()152
};153
save(&store, &policy);154
assert_eq!(load(&store), policy);155
}156
157
#[test]158
fn token_is_created_once_and_regenerated_on_demand() {159
let store = Store::open_in_memory().unwrap();160
let first = load_or_create_token(&store).unwrap();161
assert_eq!(first.len(), TOKEN_BYTES * 2);162
assert!(first.chars().all(|character| character.is_ascii_hexdigit()));163
assert_eq!(load_or_create_token(&store).unwrap(), first);164
let second = regenerate_token(&store).unwrap();165
assert_ne!(second, first);166
assert_eq!(load_or_create_token(&store).unwrap(), second);167
}168
}@@ -0,0 +1,63 @@
1
use std::future::Future;
2
use std::pin::Pin;
3
use std::sync::Arc;
4
5
use chrono::{DateTime, Utc};
6
use serde::Serialize;
7
use store::Store;
8
9
pub type SourceFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, SourceError>> + Send + 'a>>;
10
11
#[derive(Debug, thiserror::Error)]
12
pub enum SourceError {
13
#[error("rusty-teams is not connected to Teams")]
14
NotConnected,
15
#[error("{0} is not supported by this build")]
16
Unsupported(&'static str),
17
#[error("{0}")]
18
Failed(String),
19
}
20
21
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
22
pub struct Meeting {
23
pub title: String,
24
pub start: DateTime<Utc>,
25
pub end: DateTime<Utc>,
26
pub all_day: bool,
27
pub organizer: Option<String>,
28
pub join_url: Option<String>,
29
pub meeting_chat_id: Option<String>,
30
}
31
32
#[derive(Debug, Clone, PartialEq, Serialize)]
33
pub struct TranscriptTurn {
34
pub speaker: String,
35
pub start_seconds: f64,
36
pub end_seconds: f64,
37
pub text: String,
38
}
39
40
#[derive(Debug, Clone, PartialEq, Serialize)]
41
pub struct Transcript {
42
pub recording_name: Option<String>,
43
pub created_at: Option<String>,
44
pub turns: Vec<TranscriptTurn>,
45
}
46
47
pub trait TeamsSource: Send + Sync + 'static {
48
fn store(&self) -> Result<Arc<Store>, SourceError>;
49
50
fn me_id(&self) -> Option<String>;
51
52
fn calendar(
53
&self,
54
_start: DateTime<Utc>,
55
_end: DateTime<Utc>,
56
) -> SourceFuture<'_, Vec<Meeting>> {
57
Box::pin(async { Err(SourceError::Unsupported("calendar")) })
58
}
59
60
fn transcript<'a>(&'a self, _meeting_chat_id: &'a str) -> SourceFuture<'a, Transcript> {
61
Box::pin(async { Err(SourceError::Unsupported("transcript")) })
62
}
63
}
@@ -0,0 +1,63 @@1
use std::future::Future;2
use std::pin::Pin;3
use std::sync::Arc;4
5
use chrono::{DateTime, Utc};6
use serde::Serialize;7
use store::Store;8
9
pub type SourceFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, SourceError>> + Send + 'a>>;10
11
#[derive(Debug, thiserror::Error)]12
pub enum SourceError {13
#[error("rusty-teams is not connected to Teams")]14
NotConnected,15
#[error("{0} is not supported by this build")]16
Unsupported(&'static str),17
#[error("{0}")]18
Failed(String),19
}20
21
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]22
pub struct Meeting {23
pub title: String,24
pub start: DateTime<Utc>,25
pub end: DateTime<Utc>,26
pub all_day: bool,27
pub organizer: Option<String>,28
pub join_url: Option<String>,29
pub meeting_chat_id: Option<String>,30
}31
32
#[derive(Debug, Clone, PartialEq, Serialize)]33
pub struct TranscriptTurn {34
pub speaker: String,35
pub start_seconds: f64,36
pub end_seconds: f64,37
pub text: String,38
}39
40
#[derive(Debug, Clone, PartialEq, Serialize)]41
pub struct Transcript {42
pub recording_name: Option<String>,43
pub created_at: Option<String>,44
pub turns: Vec<TranscriptTurn>,45
}46
47
pub trait TeamsSource: Send + Sync + 'static {48
fn store(&self) -> Result<Arc<Store>, SourceError>;49
50
fn me_id(&self) -> Option<String>;51
52
fn calendar(53
&self,54
_start: DateTime<Utc>,55
_end: DateTime<Utc>,56
) -> SourceFuture<'_, Vec<Meeting>> {57
Box::pin(async { Err(SourceError::Unsupported("calendar")) })58
}59
60
fn transcript<'a>(&'a self, _meeting_chat_id: &'a str) -> SourceFuture<'a, Transcript> {61
Box::pin(async { Err(SourceError::Unsupported("transcript")) })62
}63
}@@ -0,0 +1,481 @@
1
use std::collections::HashMap;
2
use std::sync::Arc;
3
use std::time::Duration;
4
5
use chrono::{DateTime, Utc};
6
use rmcp::handler::server::router::tool::ToolRouter;
7
use rmcp::handler::server::wrapper::Parameters;
8
use rmcp::model::{ProgressNotificationParam, RequestMetaObject};
9
use rmcp::service::Peer;
10
use rmcp::{RoleServer, ServerHandler, schemars, tool, tool_handler, tool_router};
11
use serde::{Deserialize, Serialize};
12
use serde_json::json;
13
use store::{HIGHLIGHT_END, HIGHLIGHT_START, MessageRecord, Store, plain_text};
14
15
use crate::hub::AgentHub;
16
use crate::policy::{AgentPolicy, ConversationKind};
17
use crate::source::TeamsSource;
18
19
const NOT_ALLOWED: &str =
20
"conversation not found or not allowed (allow it in rusty-teams Settings > MCP)";
21
const PROPOSE_DISABLED: &str =
22
"proposing messages is turned off (enable it in rusty-teams Settings > MCP)";
23
const DEFAULT_LIST_LIMIT: usize = 50;
24
const MAX_LIST_LIMIT: usize = 200;
25
const DEFAULT_READ_LIMIT: usize = 30;
26
const MAX_READ_LIMIT: usize = 200;
27
const DEFAULT_SEARCH_LIMIT: usize = 20;
28
const MAX_SEARCH_LIMIT: usize = 100;
29
const DEFAULT_WAIT_SECONDS: u64 = 25;
30
const MAX_WAIT_SECONDS: u64 = 50;
31
const PROGRESS_INTERVAL: Duration = Duration::from_secs(10);
32
const MAX_PROPOSAL_CHARACTERS: usize = 20_000;
33
const DEFAULT_MEETING_DAYS: i64 = 7;
34
const MAX_MEETING_DAYS: i64 = 62;
35
const CALENDAR_DISABLED: &str =
36
"calendar access is turned off (enable it in rusty-teams Settings > MCP)";
37
const TRANSCRIPTS_DISABLED: &str =
38
"meeting transcripts are turned off (enable them in rusty-teams Settings > MCP)";
39
40
#[derive(Clone)]
41
pub struct TeamsTools {
42
hub: Arc<AgentHub>,
43
source: Arc<dyn TeamsSource>,
44
tool_router: ToolRouter<Self>,
45
}
46
47
#[derive(Debug, Deserialize, schemars::JsonSchema)]
48
pub struct ListChatsParams {
49
/// Maximum number of chats to return, newest first. Default 50, max 200.
50
pub limit: Option<usize>,
51
}
52
53
#[derive(Debug, Deserialize, schemars::JsonSchema)]
54
pub struct ReadMessagesParams {
55
/// Raw conversation id as returned by list_chats or list_channels, for example "19:...@thread.v2".
56
pub conversation_id: String,
57
/// Number of messages to return. Default 30, max 200.
58
pub limit: Option<usize>,
59
/// Return only messages older than this message id, to page backwards.
60
pub before_message_id: Option<String>,
61
}
62
63
#[derive(Debug, Deserialize, schemars::JsonSchema)]
64
pub struct SearchMessagesParams {
65
/// Words to search for. Every word is a prefix match. Use "from:name" to filter by sender.
66
pub query: String,
67
/// Maximum number of hits, newest first. Default 20, max 100.
68
pub limit: Option<usize>,
69
}
70
71
#[derive(Debug, Deserialize, schemars::JsonSchema)]
72
pub struct ProposeMessageParams {
73
/// Raw conversation id as returned by list_chats or list_channels.
74
pub conversation_id: String,
75
/// Message text. Markdown is allowed.
76
pub text: String,
77
/// Id of the message this one answers (threads in channels).
78
pub reply_to_message_id: Option<String>,
79
/// Your session id, so the user can tell proposals of different sessions apart.
80
pub session_id: Option<String>,
81
/// Your name, shown to the user next to the proposal.
82
pub agent: Option<String>,
83
}
84
85
#[derive(Debug, Deserialize, schemars::JsonSchema)]
86
pub struct WaitForEventParams {
87
/// Seconds to wait for an event. Default 25, max 50.
88
pub timeout_seconds: Option<u64>,
89
/// Cursor from the previous call's "next". Omit it to only see events from now on.
90
pub since: Option<u64>,
91
}
92
93
#[derive(Debug, Deserialize, schemars::JsonSchema)]
94
pub struct ListMeetingsParams {
95
/// Start of the window, ISO 8601 with offset. Default: the start of today (UTC).
96
pub start: Option<DateTime<Utc>>,
97
/// End of the window, ISO 8601 with offset. Default: 7 days after start, max 62 days.
98
pub end: Option<DateTime<Utc>>,
99
}
100
101
#[derive(Debug, Deserialize, schemars::JsonSchema)]
102
pub struct GetTranscriptParams {
103
/// Meeting chat id as returned by list_meetings (meeting_chat_id).
104
pub meeting_chat_id: String,
105
}
106
107
#[derive(Serialize)]
108
struct MessageView {
109
message_id: String,
110
sender: Option<String>,
111
sender_id: Option<String>,
112
time: String,
113
edited_at: Option<String>,
114
text: String,
115
subject: Option<String>,
116
reply_to: Option<String>,
117
}
118
119
fn timestamp(time: DateTime<Utc>) -> String {
120
time.to_rfc3339()
121
}
122
123
fn message_view(message: MessageRecord) -> MessageView {
124
MessageView {
125
text: plain_text(&message.body_html),
126
message_id: message.message_id,
127
sender: message.sender_name,
128
sender_id: message.sender_id,
129
time: timestamp(message.created_at),
130
edited_at: message.edited_at.map(timestamp),
131
subject: message.subject,
132
reply_to: message.reply_to_id,
133
}
134
}
135
136
fn render(value: serde_json::Value) -> String {
137
value.to_string()
138
}
139
140
fn failure(error: impl std::fmt::Display) -> String {
141
error.to_string()
142
}
143
144
#[tool_router]
145
impl TeamsTools {
146
pub fn new(hub: Arc<AgentHub>, source: Arc<dyn TeamsSource>) -> Self {
147
TeamsTools {
148
hub,
149
source,
150
tool_router: Self::tool_router(),
151
}
152
}
153
154
#[tool(
155
description = "List the Teams chats (1:1, group and meeting chats) the user allowed for agents, newest activity first. Returns id, title, kind, last_message_at, unread. Use the id with read_messages and propose_message."
156
)]
157
async fn list_chats(
158
&self,
159
Parameters(params): Parameters<ListChatsParams>,
160
) -> Result<String, String> {
161
let policy = self.hub.policy();
162
let store = self.store()?;
163
let limit = params
164
.limit
165
.unwrap_or(DEFAULT_LIST_LIMIT)
166
.clamp(1, MAX_LIST_LIMIT);
167
let chats: Vec<_> = allowed_chats(&store, &policy)?
168
.into_iter()
169
.take(limit)
170
.map(|chat| {
171
json!({
172
"id": chat.id,
173
"title": chat.display_title(),
174
"kind": chat.kind,
175
"last_message_at": chat.last_message_at.map(timestamp),
176
"unread": chat.unread,
177
})
178
})
179
.collect();
180
Ok(render(json!({ "chats": chats })))
181
}
182
183
#[tool(
184
description = "List the Teams channels the user allowed for agents. Returns id, team, channel name, last_message_at, unread. Use the id with read_messages and propose_message."
185
)]
186
async fn list_channels(&self) -> Result<String, String> {
187
let policy = self.hub.policy();
188
let store = self.store()?;
189
let mut channels = Vec::new();
190
for team in store.sidebar().map_err(failure)?.teams {
191
for channel in team.channels {
192
if policy.can_read(ConversationKind::Channel, &channel.id) {
193
channels.push(json!({
194
"id": channel.id,
195
"team": team.team.name,
196
"channel": channel.name,
197
"last_message_at": channel.last_message_at.map(timestamp),
198
"unread": channel.unread,
199
}));
200
}
201
}
202
}
203
Ok(render(json!({ "channels": channels })))
204
}
205
206
#[tool(
207
description = "Read messages of one allowed chat or channel, oldest first. Returns message_id, sender, sender_id, time (RFC 3339), text (plain text), subject, reply_to. Defaults to the 30 newest messages. Pass before_message_id to page backwards."
208
)]
209
async fn read_messages(
210
&self,
211
Parameters(params): Parameters<ReadMessagesParams>,
212
) -> Result<String, String> {
213
let store = self.store()?;
214
self.readable_kind(&store, ¶ms.conversation_id)?;
215
let limit = params
216
.limit
217
.unwrap_or(DEFAULT_READ_LIMIT)
218
.clamp(1, MAX_READ_LIMIT);
219
let before = match params.before_message_id {
220
Some(message_id) => {
221
let mut found = store
222
.messages_by_id(¶ms.conversation_id, std::slice::from_ref(&message_id))
223
.map_err(failure)?;
224
let message = found
225
.remove(&message_id)
226
.ok_or_else(|| format!("unknown before_message_id {message_id}"))?;
227
Some(message.created_at)
228
}
229
None => None,
230
};
231
let messages: Vec<_> = store
232
.messages(¶ms.conversation_id, before, limit)
233
.map_err(failure)?
234
.into_iter()
235
.filter(|message| !message.deleted)
236
.map(message_view)
237
.collect();
238
Ok(render(json!({
239
"conversation_id": params.conversation_id,
240
"messages": messages,
241
})))
242
}
243
244
#[tool(
245
description = "Full-text search over the messages of all allowed chats and channels, newest first. Every word is a prefix match, \"from:name\" filters by sender. Returns conversation_id, conversation title, message_id, sender, time and a snippet."
246
)]
247
async fn search_messages(
248
&self,
249
Parameters(params): Parameters<SearchMessagesParams>,
250
) -> Result<String, String> {
251
let policy = self.hub.policy();
252
let store = self.store()?;
253
let mut titles: HashMap<String, String> = allowed_chats(&store, &policy)?
254
.into_iter()
255
.map(|chat| {
256
let title = chat.display_title();
257
(chat.id, title)
258
})
259
.collect();
260
for team in store.sidebar().map_err(failure)?.teams {
261
for channel in team.channels {
262
if policy.can_read(ConversationKind::Channel, &channel.id) {
263
titles.insert(channel.id, format!("{} / {}", team.team.name, channel.name));
264
}
265
}
266
}
267
let conversation_ids: Vec<String> = titles.keys().cloned().collect();
268
let limit = params
269
.limit
270
.unwrap_or(DEFAULT_SEARCH_LIMIT)
271
.clamp(1, MAX_SEARCH_LIMIT);
272
let hits: Vec<_> = store
273
.search_messages_in(¶ms.query, &conversation_ids, limit)
274
.map_err(failure)?
275
.into_iter()
276
.map(|hit| {
277
json!({
278
"conversation_id": hit.conversation_id,
279
"conversation": titles.get(&hit.conversation_id),
280
"message_id": hit.message_id,
281
"sender": hit.sender_name,
282
"time": timestamp(hit.created_at),
283
"snippet": hit.snippet.replace([HIGHLIGHT_START, HIGHLIGHT_END], ""),
284
})
285
})
286
.collect();
287
Ok(render(json!({ "hits": hits })))
288
}
289
290
#[tool(
291
description = "Propose a message for the user to review in rusty-teams. The message is NEVER sent automatically: the user sees it as a draft, can edit it, and sends or discards it. Only one proposal per conversation is pending, a new one replaces the old one. Returns proposal_id and state \"pending\". Use wait_for_event to learn what the user did with it."
292
)]
293
async fn propose_message(
294
&self,
295
Parameters(params): Parameters<ProposeMessageParams>,
296
) -> Result<String, String> {
297
let store = self.store()?;
298
self.readable_kind(&store, ¶ms.conversation_id)?;
299
if !self.hub.policy().propose {
300
return Err(PROPOSE_DISABLED.to_owned());
301
}
302
let text = params.text.trim();
303
if text.is_empty() || text.chars().count() > MAX_PROPOSAL_CHARACTERS {
304
return Err(format!(
305
"text must be 1 to {MAX_PROPOSAL_CHARACTERS} characters long"
306
));
307
}
308
let proposal = self
309
.hub
310
.add_proposal(
311
¶ms.conversation_id,
312
text,
313
params.reply_to_message_id,
314
params.agent,
315
params.session_id,
316
)
317
.map_err(failure)?;
318
Ok(render(
319
json!({ "proposal_id": proposal.id, "state": "pending" }),
320
))
321
}
322
323
#[tool(
324
description = "Wait up to timeout_seconds (default 25, max 50) for events in allowed conversations: new_message, user_typing, user_sent, proposal_resolved (outcome sent, edited, discarded, stale or superseded). Returns {events, next}. Call again with since set to next to continue without missing events. Without since, only events from now on are returned."
325
)]
326
async fn wait_for_event(
327
&self,
328
Parameters(params): Parameters<WaitForEventParams>,
329
meta: RequestMetaObject,
330
client: Peer<RoleServer>,
331
) -> Result<String, String> {
332
let timeout = Duration::from_secs(
333
params
334
.timeout_seconds
335
.unwrap_or(DEFAULT_WAIT_SECONDS)
336
.clamp(1, MAX_WAIT_SECONDS),
337
);
338
let progress_token = meta.get_progress_token();
339
let deadline = tokio::time::Instant::now() + timeout;
340
let mut cursor = params.since;
341
let mut elapsed_intervals = 0.0;
342
loop {
343
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
344
let (events, next) = self
345
.hub
346
.wait_events(cursor, remaining.min(PROGRESS_INTERVAL))
347
.await;
348
if !events.is_empty() || remaining <= PROGRESS_INTERVAL {
349
return Ok(render(json!({ "events": events, "next": next })));
350
}
351
cursor = Some(next);
352
elapsed_intervals += 1.0;
353
if let Some(token) = progress_token.clone() {
354
let _ = client
355
.notify_progress(
356
ProgressNotificationParam::new(token, elapsed_intervals)
357
.with_message("waiting for events"),
358
)
359
.await;
360
}
361
}
362
}
363
364
#[tool(
365
description = "List the user's calendar meetings in a time window, oldest first. Returns title, start, end (RFC 3339), all_day, organizer, join_url and meeting_chat_id (use it with get_transcript). Defaults to today and the next 7 days."
366
)]
367
async fn list_meetings(
368
&self,
369
Parameters(params): Parameters<ListMeetingsParams>,
370
) -> Result<String, String> {
371
let policy = self.hub.policy();
372
if !policy.enabled || !policy.calendar {
373
return Err(CALENDAR_DISABLED.to_owned());
374
}
375
let start = params.start.unwrap_or_else(start_of_today);
376
let end = params
377
.end
378
.unwrap_or(start + chrono::Duration::days(DEFAULT_MEETING_DAYS))
379
.min(start + chrono::Duration::days(MAX_MEETING_DAYS));
380
if end <= start {
381
return Err("end must be after start".to_owned());
382
}
383
let meetings = self.source.calendar(start, end).await.map_err(failure)?;
384
Ok(render(json!({ "meetings": meetings })))
385
}
386
387
#[tool(
388
description = "Get the spoken text of a meeting by its meeting_chat_id: the finished transcript turns (speaker, start_seconds, end_seconds, text) once the recording is processed, and live_captions while the user is in the meeting right now."
389
)]
390
async fn get_transcript(
391
&self,
392
Parameters(params): Parameters<GetTranscriptParams>,
393
) -> Result<String, String> {
394
let policy = self.hub.policy();
395
if !policy.enabled || !policy.transcripts {
396
return Err(TRANSCRIPTS_DISABLED.to_owned());
397
}
398
let live_captions = self.hub.live_captions(¶ms.meeting_chat_id);
399
match self.source.transcript(¶ms.meeting_chat_id).await {
400
Ok(transcript) => Ok(render(json!({
401
"meeting_chat_id": params.meeting_chat_id,
402
"recording_name": transcript.recording_name,
403
"created_at": transcript.created_at,
404
"turns": transcript.turns,
405
"live_captions": live_captions,
406
}))),
407
Err(_) if !live_captions.is_empty() => Ok(render(json!({
408
"meeting_chat_id": params.meeting_chat_id,
409
"turns": [],
410
"live_captions": live_captions,
411
}))),
412
Err(error) => Err(failure(error)),
413
}
414
}
415
416
fn store(&self) -> Result<Arc<Store>, String> {
417
self.source.store().map_err(failure)
418
}
419
420
fn readable_kind(
421
&self,
422
store: &Store,
423
conversation_id: &str,
424
) -> Result<ConversationKind, String> {
425
let policy = self.hub.policy();
426
let kind = conversation_kind(store, conversation_id)?;
427
match kind {
428
Some(kind) if policy.can_read(kind, conversation_id) => Ok(kind),
429
_ => Err(NOT_ALLOWED.to_owned()),
430
}
431
}
432
}
433
434
#[tool_handler(
435
router = self.tool_router,
436
name = "rusty-teams",
437
instructions = "Read-only access to the user's Teams chats and channels from their local rusty-teams app. \
438
Only conversations the user allowed in rusty-teams Settings > MCP are visible; anything else looks like it does not exist. \
439
Start with list_chats or list_channels, then read_messages or search_messages. \
440
To write, call propose_message: the user reviews the draft in the app and sends it, nothing is sent automatically. \
441
list_meetings and get_transcript only work when the user turned on calendar or transcripts access. \
442
Use wait_for_event to follow new messages and to learn what happened to a proposal."
443
)]
444
impl ServerHandler for TeamsTools {}
445
446
fn start_of_today() -> DateTime<Utc> {
447
Utc::now()
448
.date_naive()
449
.and_time(chrono::NaiveTime::MIN)
450
.and_utc()
451
}
452
453
fn conversation_kind(
454
store: &Store,
455
conversation_id: &str,
456
) -> Result<Option<ConversationKind>, String> {
457
if let Some(chat) = store.chat(conversation_id).map_err(failure)? {
458
return Ok(Some(chat_kind(&chat)));
459
}
460
Ok(store
461
.channel(conversation_id)
462
.map_err(failure)?
463
.map(|_| ConversationKind::Channel))
464
}
465
466
fn allowed_chats(store: &Store, policy: &AgentPolicy) -> Result<Vec<store::ChatRecord>, String> {
467
Ok(store
468
.recent_chats(usize::MAX >> 1)
469
.map_err(failure)?
470
.into_iter()
471
.filter(|chat| policy.can_read(chat_kind(chat), &chat.id))
472
.collect())
473
}
474
475
fn chat_kind(chat: &store::ChatRecord) -> ConversationKind {
476
if chat.kind.eq_ignore_ascii_case("meeting") {
477
ConversationKind::Meeting
478
} else {
479
ConversationKind::Chat
480
}
481
}
@@ -0,0 +1,481 @@1
use std::collections::HashMap;2
use std::sync::Arc;3
use std::time::Duration;4
5
use chrono::{DateTime, Utc};6
use rmcp::handler::server::router::tool::ToolRouter;7
use rmcp::handler::server::wrapper::Parameters;8
use rmcp::model::{ProgressNotificationParam, RequestMetaObject};9
use rmcp::service::Peer;10
use rmcp::{RoleServer, ServerHandler, schemars, tool, tool_handler, tool_router};11
use serde::{Deserialize, Serialize};12
use serde_json::json;13
use store::{HIGHLIGHT_END, HIGHLIGHT_START, MessageRecord, Store, plain_text};14
15
use crate::hub::AgentHub;16
use crate::policy::{AgentPolicy, ConversationKind};17
use crate::source::TeamsSource;18
19
const NOT_ALLOWED: &str =20
"conversation not found or not allowed (allow it in rusty-teams Settings > MCP)";21
const PROPOSE_DISABLED: &str =22
"proposing messages is turned off (enable it in rusty-teams Settings > MCP)";23
const DEFAULT_LIST_LIMIT: usize = 50;24
const MAX_LIST_LIMIT: usize = 200;25
const DEFAULT_READ_LIMIT: usize = 30;26
const MAX_READ_LIMIT: usize = 200;27
const DEFAULT_SEARCH_LIMIT: usize = 20;28
const MAX_SEARCH_LIMIT: usize = 100;29
const DEFAULT_WAIT_SECONDS: u64 = 25;30
const MAX_WAIT_SECONDS: u64 = 50;31
const PROGRESS_INTERVAL: Duration = Duration::from_secs(10);32
const MAX_PROPOSAL_CHARACTERS: usize = 20_000;33
const DEFAULT_MEETING_DAYS: i64 = 7;34
const MAX_MEETING_DAYS: i64 = 62;35
const CALENDAR_DISABLED: &str =36
"calendar access is turned off (enable it in rusty-teams Settings > MCP)";37
const TRANSCRIPTS_DISABLED: &str =38
"meeting transcripts are turned off (enable them in rusty-teams Settings > MCP)";39
40
#[derive(Clone)]41
pub struct TeamsTools {42
hub: Arc<AgentHub>,43
source: Arc<dyn TeamsSource>,44
tool_router: ToolRouter<Self>,45
}46
47
#[derive(Debug, Deserialize, schemars::JsonSchema)]48
pub struct ListChatsParams {49
/// Maximum number of chats to return, newest first. Default 50, max 200.50
pub limit: Option<usize>,51
}52
53
#[derive(Debug, Deserialize, schemars::JsonSchema)]54
pub struct ReadMessagesParams {55
/// Raw conversation id as returned by list_chats or list_channels, for example "19:...@thread.v2".56
pub conversation_id: String,57
/// Number of messages to return. Default 30, max 200.58
pub limit: Option<usize>,59
/// Return only messages older than this message id, to page backwards.60
pub before_message_id: Option<String>,61
}62
63
#[derive(Debug, Deserialize, schemars::JsonSchema)]64
pub struct SearchMessagesParams {65
/// Words to search for. Every word is a prefix match. Use "from:name" to filter by sender.66
pub query: String,67
/// Maximum number of hits, newest first. Default 20, max 100.68
pub limit: Option<usize>,69
}70
71
#[derive(Debug, Deserialize, schemars::JsonSchema)]72
pub struct ProposeMessageParams {73
/// Raw conversation id as returned by list_chats or list_channels.74
pub conversation_id: String,75
/// Message text. Markdown is allowed.76
pub text: String,77
/// Id of the message this one answers (threads in channels).78
pub reply_to_message_id: Option<String>,79
/// Your session id, so the user can tell proposals of different sessions apart.80
pub session_id: Option<String>,81
/// Your name, shown to the user next to the proposal.82
pub agent: Option<String>,83
}84
85
#[derive(Debug, Deserialize, schemars::JsonSchema)]86
pub struct WaitForEventParams {87
/// Seconds to wait for an event. Default 25, max 50.88
pub timeout_seconds: Option<u64>,89
/// Cursor from the previous call's "next". Omit it to only see events from now on.90
pub since: Option<u64>,91
}92
93
#[derive(Debug, Deserialize, schemars::JsonSchema)]94
pub struct ListMeetingsParams {95
/// Start of the window, ISO 8601 with offset. Default: the start of today (UTC).96
pub start: Option<DateTime<Utc>>,97
/// End of the window, ISO 8601 with offset. Default: 7 days after start, max 62 days.98
pub end: Option<DateTime<Utc>>,99
}100
101
#[derive(Debug, Deserialize, schemars::JsonSchema)]102
pub struct GetTranscriptParams {103
/// Meeting chat id as returned by list_meetings (meeting_chat_id).104
pub meeting_chat_id: String,105
}106
107
#[derive(Serialize)]108
struct MessageView {109
message_id: String,110
sender: Option<String>,111
sender_id: Option<String>,112
time: String,113
edited_at: Option<String>,114
text: String,115
subject: Option<String>,116
reply_to: Option<String>,117
}118
119
fn timestamp(time: DateTime<Utc>) -> String {120
time.to_rfc3339()121
}122
123
fn message_view(message: MessageRecord) -> MessageView {124
MessageView {125
text: plain_text(&message.body_html),126
message_id: message.message_id,127
sender: message.sender_name,128
sender_id: message.sender_id,129
time: timestamp(message.created_at),130
edited_at: message.edited_at.map(timestamp),131
subject: message.subject,132
reply_to: message.reply_to_id,133
}134
}135
136
fn render(value: serde_json::Value) -> String {137
value.to_string()138
}139
140
fn failure(error: impl std::fmt::Display) -> String {141
error.to_string()142
}143
144
#[tool_router]145
impl TeamsTools {146
pub fn new(hub: Arc<AgentHub>, source: Arc<dyn TeamsSource>) -> Self {147
TeamsTools {148
hub,149
source,150
tool_router: Self::tool_router(),151
}152
}153
154
#[tool(155
description = "List the Teams chats (1:1, group and meeting chats) the user allowed for agents, newest activity first. Returns id, title, kind, last_message_at, unread. Use the id with read_messages and propose_message."156
)]157
async fn list_chats(158
&self,159
Parameters(params): Parameters<ListChatsParams>,160
) -> Result<String, String> {161
let policy = self.hub.policy();162
let store = self.store()?;163
let limit = params164
.limit165
.unwrap_or(DEFAULT_LIST_LIMIT)166
.clamp(1, MAX_LIST_LIMIT);167
let chats: Vec<_> = allowed_chats(&store, &policy)?168
.into_iter()169
.take(limit)170
.map(|chat| {171
json!({172
"id": chat.id,173
"title": chat.display_title(),174
"kind": chat.kind,175
"last_message_at": chat.last_message_at.map(timestamp),176
"unread": chat.unread,177
})178
})179
.collect();180
Ok(render(json!({ "chats": chats })))181
}182
183
#[tool(184
description = "List the Teams channels the user allowed for agents. Returns id, team, channel name, last_message_at, unread. Use the id with read_messages and propose_message."185
)]186
async fn list_channels(&self) -> Result<String, String> {187
let policy = self.hub.policy();188
let store = self.store()?;189
let mut channels = Vec::new();190
for team in store.sidebar().map_err(failure)?.teams {191
for channel in team.channels {192
if policy.can_read(ConversationKind::Channel, &channel.id) {193
channels.push(json!({194
"id": channel.id,195
"team": team.team.name,196
"channel": channel.name,197
"last_message_at": channel.last_message_at.map(timestamp),198
"unread": channel.unread,199
}));200
}201
}202
}203
Ok(render(json!({ "channels": channels })))204
}205
206
#[tool(207
description = "Read messages of one allowed chat or channel, oldest first. Returns message_id, sender, sender_id, time (RFC 3339), text (plain text), subject, reply_to. Defaults to the 30 newest messages. Pass before_message_id to page backwards."208
)]209
async fn read_messages(210
&self,211
Parameters(params): Parameters<ReadMessagesParams>,212
) -> Result<String, String> {213
let store = self.store()?;214
self.readable_kind(&store, ¶ms.conversation_id)?;215
let limit = params216
.limit217
.unwrap_or(DEFAULT_READ_LIMIT)218
.clamp(1, MAX_READ_LIMIT);219
let before = match params.before_message_id {220
Some(message_id) => {221
let mut found = store222
.messages_by_id(¶ms.conversation_id, std::slice::from_ref(&message_id))223
.map_err(failure)?;224
let message = found225
.remove(&message_id)226
.ok_or_else(|| format!("unknown before_message_id {message_id}"))?;227
Some(message.created_at)228
}229
None => None,230
};231
let messages: Vec<_> = store232
.messages(¶ms.conversation_id, before, limit)233
.map_err(failure)?234
.into_iter()235
.filter(|message| !message.deleted)236
.map(message_view)237
.collect();238
Ok(render(json!({239
"conversation_id": params.conversation_id,240
"messages": messages,241
})))242
}243
244
#[tool(245
description = "Full-text search over the messages of all allowed chats and channels, newest first. Every word is a prefix match, \"from:name\" filters by sender. Returns conversation_id, conversation title, message_id, sender, time and a snippet."246
)]247
async fn search_messages(248
&self,249
Parameters(params): Parameters<SearchMessagesParams>,250
) -> Result<String, String> {251
let policy = self.hub.policy();252
let store = self.store()?;253
let mut titles: HashMap<String, String> = allowed_chats(&store, &policy)?254
.into_iter()255
.map(|chat| {256
let title = chat.display_title();257
(chat.id, title)258
})259
.collect();260
for team in store.sidebar().map_err(failure)?.teams {261
for channel in team.channels {262
if policy.can_read(ConversationKind::Channel, &channel.id) {263
titles.insert(channel.id, format!("{} / {}", team.team.name, channel.name));264
}265
}266
}267
let conversation_ids: Vec<String> = titles.keys().cloned().collect();268
let limit = params269
.limit270
.unwrap_or(DEFAULT_SEARCH_LIMIT)271
.clamp(1, MAX_SEARCH_LIMIT);272
let hits: Vec<_> = store273
.search_messages_in(¶ms.query, &conversation_ids, limit)274
.map_err(failure)?275
.into_iter()276
.map(|hit| {277
json!({278
"conversation_id": hit.conversation_id,279
"conversation": titles.get(&hit.conversation_id),280
"message_id": hit.message_id,281
"sender": hit.sender_name,282
"time": timestamp(hit.created_at),283
"snippet": hit.snippet.replace([HIGHLIGHT_START, HIGHLIGHT_END], ""),284
})285
})286
.collect();287
Ok(render(json!({ "hits": hits })))288
}289
290
#[tool(291
description = "Propose a message for the user to review in rusty-teams. The message is NEVER sent automatically: the user sees it as a draft, can edit it, and sends or discards it. Only one proposal per conversation is pending, a new one replaces the old one. Returns proposal_id and state \"pending\". Use wait_for_event to learn what the user did with it."292
)]293
async fn propose_message(294
&self,295
Parameters(params): Parameters<ProposeMessageParams>,296
) -> Result<String, String> {297
let store = self.store()?;298
self.readable_kind(&store, ¶ms.conversation_id)?;299
if !self.hub.policy().propose {300
return Err(PROPOSE_DISABLED.to_owned());301
}302
let text = params.text.trim();303
if text.is_empty() || text.chars().count() > MAX_PROPOSAL_CHARACTERS {304
return Err(format!(305
"text must be 1 to {MAX_PROPOSAL_CHARACTERS} characters long"306
));307
}308
let proposal = self309
.hub310
.add_proposal(311
¶ms.conversation_id,312
text,313
params.reply_to_message_id,314
params.agent,315
params.session_id,316
)317
.map_err(failure)?;318
Ok(render(319
json!({ "proposal_id": proposal.id, "state": "pending" }),320
))321
}322
323
#[tool(324
description = "Wait up to timeout_seconds (default 25, max 50) for events in allowed conversations: new_message, user_typing, user_sent, proposal_resolved (outcome sent, edited, discarded, stale or superseded). Returns {events, next}. Call again with since set to next to continue without missing events. Without since, only events from now on are returned."325
)]326
async fn wait_for_event(327
&self,328
Parameters(params): Parameters<WaitForEventParams>,329
meta: RequestMetaObject,330
client: Peer<RoleServer>,331
) -> Result<String, String> {332
let timeout = Duration::from_secs(333
params334
.timeout_seconds335
.unwrap_or(DEFAULT_WAIT_SECONDS)336
.clamp(1, MAX_WAIT_SECONDS),337
);338
let progress_token = meta.get_progress_token();339
let deadline = tokio::time::Instant::now() + timeout;340
let mut cursor = params.since;341
let mut elapsed_intervals = 0.0;342
loop {343
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());344
let (events, next) = self345
.hub346
.wait_events(cursor, remaining.min(PROGRESS_INTERVAL))347
.await;348
if !events.is_empty() || remaining <= PROGRESS_INTERVAL {349
return Ok(render(json!({ "events": events, "next": next })));350
}351
cursor = Some(next);352
elapsed_intervals += 1.0;353
if let Some(token) = progress_token.clone() {354
let _ = client355
.notify_progress(356
ProgressNotificationParam::new(token, elapsed_intervals)357
.with_message("waiting for events"),358
)359
.await;360
}361
}362
}363
364
#[tool(365
description = "List the user's calendar meetings in a time window, oldest first. Returns title, start, end (RFC 3339), all_day, organizer, join_url and meeting_chat_id (use it with get_transcript). Defaults to today and the next 7 days."366
)]367
async fn list_meetings(368
&self,369
Parameters(params): Parameters<ListMeetingsParams>,370
) -> Result<String, String> {371
let policy = self.hub.policy();372
if !policy.enabled || !policy.calendar {373
return Err(CALENDAR_DISABLED.to_owned());374
}375
let start = params.start.unwrap_or_else(start_of_today);376
let end = params377
.end378
.unwrap_or(start + chrono::Duration::days(DEFAULT_MEETING_DAYS))379
.min(start + chrono::Duration::days(MAX_MEETING_DAYS));380
if end <= start {381
return Err("end must be after start".to_owned());382
}383
let meetings = self.source.calendar(start, end).await.map_err(failure)?;384
Ok(render(json!({ "meetings": meetings })))385
}386
387
#[tool(388
description = "Get the spoken text of a meeting by its meeting_chat_id: the finished transcript turns (speaker, start_seconds, end_seconds, text) once the recording is processed, and live_captions while the user is in the meeting right now."389
)]390
async fn get_transcript(391
&self,392
Parameters(params): Parameters<GetTranscriptParams>,393
) -> Result<String, String> {394
let policy = self.hub.policy();395
if !policy.enabled || !policy.transcripts {396
return Err(TRANSCRIPTS_DISABLED.to_owned());397
}398
let live_captions = self.hub.live_captions(¶ms.meeting_chat_id);399
match self.source.transcript(¶ms.meeting_chat_id).await {400
Ok(transcript) => Ok(render(json!({401
"meeting_chat_id": params.meeting_chat_id,402
"recording_name": transcript.recording_name,403
"created_at": transcript.created_at,404
"turns": transcript.turns,405
"live_captions": live_captions,406
}))),407
Err(_) if !live_captions.is_empty() => Ok(render(json!({408
"meeting_chat_id": params.meeting_chat_id,409
"turns": [],410
"live_captions": live_captions,411
}))),412
Err(error) => Err(failure(error)),413
}414
}415
416
fn store(&self) -> Result<Arc<Store>, String> {417
self.source.store().map_err(failure)418
}419
420
fn readable_kind(421
&self,422
store: &Store,423
conversation_id: &str,424
) -> Result<ConversationKind, String> {425
let policy = self.hub.policy();426
let kind = conversation_kind(store, conversation_id)?;427
match kind {428
Some(kind) if policy.can_read(kind, conversation_id) => Ok(kind),429
_ => Err(NOT_ALLOWED.to_owned()),430
}431
}432
}433
434
#[tool_handler(435
router = self.tool_router,436
name = "rusty-teams",437
instructions = "Read-only access to the user's Teams chats and channels from their local rusty-teams app. \438
Only conversations the user allowed in rusty-teams Settings > MCP are visible; anything else looks like it does not exist. \439
Start with list_chats or list_channels, then read_messages or search_messages. \440
To write, call propose_message: the user reviews the draft in the app and sends it, nothing is sent automatically. \441
list_meetings and get_transcript only work when the user turned on calendar or transcripts access. \442
Use wait_for_event to follow new messages and to learn what happened to a proposal."443
)]444
impl ServerHandler for TeamsTools {}445
446
fn start_of_today() -> DateTime<Utc> {447
Utc::now()448
.date_naive()449
.and_time(chrono::NaiveTime::MIN)450
.and_utc()451
}452
453
fn conversation_kind(454
store: &Store,455
conversation_id: &str,456
) -> Result<Option<ConversationKind>, String> {457
if let Some(chat) = store.chat(conversation_id).map_err(failure)? {458
return Ok(Some(chat_kind(&chat)));459
}460
Ok(store461
.channel(conversation_id)462
.map_err(failure)?463
.map(|_| ConversationKind::Channel))464
}465
466
fn allowed_chats(store: &Store, policy: &AgentPolicy) -> Result<Vec<store::ChatRecord>, String> {467
Ok(store468
.recent_chats(usize::MAX >> 1)469
.map_err(failure)?470
.into_iter()471
.filter(|chat| policy.can_read(chat_kind(chat), &chat.id))472
.collect())473
}474
475
fn chat_kind(chat: &store::ChatRecord) -> ConversationKind {476
if chat.kind.eq_ignore_ascii_case("meeting") {477
ConversationKind::Meeting478
} else {479
ConversationKind::Chat480
}481
}@@ -0,0 +1,14 @@
1
{
2
"numStartups": 12,
3
"theme": "dark",
4
"mcpServers": {
5
"other": {
6
"type": "stdio",
7
"command": "npx",
8
"args": ["-y", "something"]
9
}
10
},
11
"projects": {
12
"/home/user/code": { "allowedTools": [] }
13
}
14
}
@@ -0,0 +1,14 @@1
{2
"numStartups": 12,3
"theme": "dark",4
"mcpServers": {5
"other": {6
"type": "stdio",7
"command": "npx",8
"args": ["-y", "something"]9
}10
},11
"projects": {12
"/home/user/code": { "allowedTools": [] }13
}14
}@@ -0,0 +1,6 @@
1
# my codex settings
2
model = "gpt-5" # default model
3
4
[mcp_servers.other]
5
command = "npx"
6
args = ["-y", "something"]
@@ -0,0 +1,6 @@1
# my codex settings2
model = "gpt-5" # default model3
4
[mcp_servers.other]5
command = "npx"6
args = ["-y", "something"]@@ -0,0 +1 @@
1
{ "mcpServers": { "other":
@@ -0,0 +1 @@1
{ "mcpServers": { "other": @@ -0,0 +1,2 @@
1
[mcp_servers
2
url =
@@ -0,0 +1,2 @@1
[mcp_servers2
url = @@ -0,0 +1,503 @@
1
use std::collections::BTreeSet;
2
use std::sync::Arc;
3
4
use chrono::{DateTime, TimeZone, Utc};
5
use mcp::{
6
Access, AgentHub, AgentPolicy, Meeting, Outcome, ServerHandle, SourceError, SourceFuture,
7
TeamsSource, Transcript, TranscriptTurn,
8
};
9
use rmcp::ServiceExt;
10
use rmcp::model::{CallToolRequestParams, ClientConfig};
11
use rmcp::service::RunningService;
12
use rmcp::transport::StreamableHttpClientTransport;
13
use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
14
use serde_json::{Value, json};
15
use store::{ChannelRecord, ChatRecord, MessageRecord, Store, TeamRecord};
16
use tokio::io::{AsyncReadExt, AsyncWriteExt};
17
use tokio::net::TcpStream;
18
19
const TOKEN: &str = "test-token";
20
const ALLOWED_CHAT: &str = "19:alpha@thread.v2";
21
const HIDDEN_CHAT: &str = "19:beta@thread.v2";
22
const CHANNEL: &str = "19:channel@thread.tacv2";
23
const MEETING_CHAT: &str = "19:meeting_abc@thread.v2";
24
25
struct FakeSource {
26
store: Arc<Store>,
27
}
28
29
impl TeamsSource for FakeSource {
30
fn store(&self) -> Result<Arc<Store>, SourceError> {
31
Ok(self.store.clone())
32
}
33
34
fn me_id(&self) -> Option<String> {
35
Some("user-me".to_owned())
36
}
37
38
fn calendar(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> SourceFuture<'_, Vec<Meeting>> {
39
let meeting = Meeting {
40
title: "Sprint review".to_owned(),
41
start: Utc.with_ymd_and_hms(2026, 10, 7, 9, 0, 0).unwrap(),
42
end: Utc.with_ymd_and_hms(2026, 10, 7, 10, 0, 0).unwrap(),
43
all_day: false,
44
organizer: Some("Ada Example".to_owned()),
45
join_url: Some("https://teams.example/join".to_owned()),
46
meeting_chat_id: Some(MEETING_CHAT.to_owned()),
47
};
48
Box::pin(async move {
49
Ok(vec![meeting]
50
.into_iter()
51
.filter(|meeting| meeting.start >= start && meeting.start < end)
52
.collect())
53
})
54
}
55
56
fn transcript<'a>(&'a self, meeting_chat_id: &'a str) -> SourceFuture<'a, Transcript> {
57
Box::pin(async move {
58
if meeting_chat_id != MEETING_CHAT {
59
return Err(SourceError::Failed(
60
"no finished recording in this meeting chat".to_owned(),
61
));
62
}
63
Ok(Transcript {
64
recording_name: Some("Sprint review".to_owned()),
65
created_at: None,
66
turns: vec![TranscriptTurn {
67
speaker: "Ada Example".to_owned(),
68
start_seconds: 1.0,
69
end_seconds: 4.5,
70
text: "Welcome everyone".to_owned(),
71
}],
72
})
73
})
74
}
75
}
76
77
struct Harness {
78
hub: Arc<AgentHub>,
79
server: ServerHandle,
80
}
81
82
impl Harness {
83
async fn start(propose: bool) -> Harness {
84
Harness::start_with(propose, false, false).await
85
}
86
87
async fn start_with(propose: bool, calendar: bool, transcripts: bool) -> Harness {
88
let store = Arc::new(Store::open_in_memory().unwrap());
89
seed(&store);
90
let policy = AgentPolicy {
91
enabled: true,
92
chats: Access::Selected(BTreeSet::from([ALLOWED_CHAT.to_owned()])),
93
channels: Access::Selected(BTreeSet::from([CHANNEL.to_owned()])),
94
propose,
95
calendar,
96
transcripts,
97
..AgentPolicy::default()
98
};
99
let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();
100
let hub = AgentHub::new(store.clone(), policy, ui);
101
let server = mcp::start(
102
hub.clone(),
103
Arc::new(FakeSource { store }),
104
0,
105
TOKEN.to_owned(),
106
)
107
.await
108
.unwrap();
109
Harness { hub, server }
110
}
111
112
fn url(&self) -> String {
113
format!("http://{}/mcp", self.server.addr)
114
}
115
116
async fn client(&self) -> RunningService<rmcp::RoleClient, ClientConfig> {
117
let transport = StreamableHttpClientTransport::from_config(
118
StreamableHttpClientTransportConfig::with_uri(self.url()).auth_header(TOKEN),
119
);
120
ClientConfig::default().serve(transport).await.unwrap()
121
}
122
}
123
124
fn seed(store: &Store) {
125
let time = |minute: u32| Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap();
126
let chat = |id: &str, title: &str| ChatRecord {
127
id: id.to_owned(),
128
kind: "group".to_owned(),
129
title: title.to_owned(),
130
last_message_at: Some(time(5)),
131
..ChatRecord::default()
132
};
133
store
134
.upsert_chats(&[chat(ALLOWED_CHAT, "Planning"), chat(HIDDEN_CHAT, "Secrets")])
135
.unwrap();
136
store
137
.upsert_teams(&[TeamRecord {
138
id: "team-1".to_owned(),
139
name: "Platform".to_owned(),
140
}])
141
.unwrap();
142
store
143
.upsert_channels(&[ChannelRecord {
144
id: CHANNEL.to_owned(),
145
team_id: "team-1".to_owned(),
146
name: "General".to_owned(),
147
membership_type: None,
148
last_message_at: Some(time(6)),
149
unread: false,
150
}])
151
.unwrap();
152
let message =
153
|conversation_id: &str, message_id: &str, minute: u32, html: &str| MessageRecord {
154
conversation_id: conversation_id.to_owned(),
155
message_id: message_id.to_owned(),
156
sender_id: Some("user-ada".to_owned()),
157
sender_name: Some("Ada Example".to_owned()),
158
created_at: time(minute),
159
body_html: html.to_owned(),
160
attachments_json: "[]".to_owned(),
161
reactions_json: "[]".to_owned(),
162
mentions_json: "[]".to_owned(),
163
links_json: "[]".to_owned(),
164
..MessageRecord::default()
165
};
166
store
167
.upsert_messages(&[
168
message(ALLOWED_CHAT, "m1", 1, "<p>budget <b>plan</b></p>"),
169
message(ALLOWED_CHAT, "m2", 2, "<p>lunch at noon</p>"),
170
message(HIDDEN_CHAT, "m3", 3, "<p>budget secrets</p>"),
171
message(CHANNEL, "m4", 4, "<p>budget channel post</p>"),
172
])
173
.unwrap();
174
}
175
176
async fn call(
177
client: &RunningService<rmcp::RoleClient, ClientConfig>,
178
tool: &'static str,
179
arguments: Value,
180
) -> (bool, String) {
181
let params = CallToolRequestParams::new(tool)
182
.with_arguments(arguments.as_object().cloned().unwrap_or_default());
183
let result = client.call_tool(params).await.unwrap();
184
let text = result
185
.content
186
.first()
187
.and_then(|content| content.as_text())
188
.map(|text| text.text.clone())
189
.unwrap_or_default();
190
(result.is_error == Some(true), text)
191
}
192
193
async fn raw_status(addr: std::net::SocketAddr, host: &str, authorization: Option<&str>) -> u16 {
194
let mut stream = TcpStream::connect(addr).await.unwrap();
195
let authorization = authorization
196
.map(|value| format!("Authorization: {value}\r\n"))
197
.unwrap_or_default();
198
let request = format!(
199
"POST /mcp HTTP/1.1\r\nHost: {host}\r\n{authorization}Content-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
200
);
201
stream.write_all(request.as_bytes()).await.unwrap();
202
let mut response = String::new();
203
stream.read_to_string(&mut response).await.unwrap();
204
response.split_whitespace().nth(1).unwrap().parse().unwrap()
205
}
206
207
#[tokio::test]
208
async fn lists_all_eight_tools() {
209
let harness = Harness::start(true).await;
210
let client = harness.client().await;
211
let mut names: Vec<String> = client
212
.list_all_tools()
213
.await
214
.unwrap()
215
.into_iter()
216
.map(|tool| tool.name.to_string())
217
.collect();
218
names.sort();
219
assert_eq!(
220
names,
221
[
222
"get_transcript",
223
"list_channels",
224
"list_chats",
225
"list_meetings",
226
"propose_message",
227
"read_messages",
228
"search_messages",
229
"wait_for_event"
230
]
231
);
232
let info = client.peer_info().unwrap();
233
assert_eq!(info.server_info.as_ref().unwrap().name, "rusty-teams");
234
}
235
236
#[tokio::test]
237
async fn rejects_missing_token_bad_host_and_serves_healthz() {
238
let harness = Harness::start(true).await;
239
let addr = harness.server.addr;
240
let own_host = addr.to_string();
241
assert_eq!(raw_status(addr, &own_host, None).await, 401);
242
assert_eq!(raw_status(addr, &own_host, Some("Bearer wrong")).await, 401);
243
assert_eq!(
244
raw_status(addr, "evil.example", Some("Bearer test-token")).await,
245
403
246
);
247
let authorized = raw_status(addr, &own_host, Some("Bearer test-token")).await;
248
assert!(authorized != 401 && authorized != 403, "{authorized}");
249
250
let mut stream = TcpStream::connect(addr).await.unwrap();
251
stream
252
.write_all(
253
format!("GET /healthz HTTP/1.1\r\nHost: {own_host}\r\nConnection: close\r\n\r\n")
254
.as_bytes(),
255
)
256
.await
257
.unwrap();
258
let mut response = String::new();
259
stream.read_to_string(&mut response).await.unwrap();
260
assert!(response.starts_with("HTTP/1.1 200"), "{response}");
261
assert!(response.ends_with("ok"), "{response}");
262
}
263
264
#[tokio::test]
265
async fn lists_only_allowed_conversations() {
266
let harness = Harness::start(true).await;
267
let client = harness.client().await;
268
let (_, chats) = call(&client, "list_chats", json!({})).await;
269
let chats: Value = serde_json::from_str(&chats).unwrap();
270
assert_eq!(chats["chats"].as_array().unwrap().len(), 1);
271
assert_eq!(chats["chats"][0]["id"], ALLOWED_CHAT);
272
let (_, channels) = call(&client, "list_channels", json!({})).await;
273
let channels: Value = serde_json::from_str(&channels).unwrap();
274
assert_eq!(channels["channels"][0]["team"], "Platform");
275
assert_eq!(channels["channels"][0]["channel"], "General");
276
}
277
278
#[tokio::test]
279
async fn read_messages_respects_scope_and_paging() {
280
let harness = Harness::start(true).await;
281
let client = harness.client().await;
282
let (is_error, text) = call(
283
&client,
284
"read_messages",
285
json!({"conversation_id": HIDDEN_CHAT}),
286
)
287
.await;
288
assert!(is_error);
289
assert!(
290
text.contains("conversation not found or not allowed"),
291
"{text}"
292
);
293
let (is_error, unknown) = call(
294
&client,
295
"read_messages",
296
json!({"conversation_id": "19:nope@thread.v2"}),
297
)
298
.await;
299
assert!(is_error);
300
assert_eq!(unknown, text);
301
302
let (is_error, body) = call(
303
&client,
304
"read_messages",
305
json!({"conversation_id": ALLOWED_CHAT}),
306
)
307
.await;
308
assert!(!is_error, "{body}");
309
let body: Value = serde_json::from_str(&body).unwrap();
310
assert_eq!(body["messages"][0]["text"], "budget plan");
311
assert_eq!(body["messages"][1]["message_id"], "m2");
312
313
let (_, older) = call(
314
&client,
315
"read_messages",
316
json!({"conversation_id": ALLOWED_CHAT, "before_message_id": "m2"}),
317
)
318
.await;
319
let older: Value = serde_json::from_str(&older).unwrap();
320
assert_eq!(older["messages"].as_array().unwrap().len(), 1);
321
assert_eq!(older["messages"][0]["message_id"], "m1");
322
}
323
324
#[tokio::test]
325
async fn search_stays_inside_the_allowed_scope() {
326
let harness = Harness::start(true).await;
327
let client = harness.client().await;
328
let (is_error, body) = call(&client, "search_messages", json!({"query": "budget"})).await;
329
assert!(!is_error, "{body}");
330
let body: Value = serde_json::from_str(&body).unwrap();
331
let mut message_ids: Vec<&str> = body["hits"]
332
.as_array()
333
.unwrap()
334
.iter()
335
.map(|hit| hit["message_id"].as_str().unwrap())
336
.collect();
337
message_ids.sort();
338
assert_eq!(message_ids, ["m1", "m4"]);
339
assert!(!body.to_string().contains('\u{1}'));
340
}
341
342
#[tokio::test]
343
async fn proposal_resolution_reaches_wait_for_event() {
344
let harness = Harness::start(true).await;
345
let client = harness.client().await;
346
let (_, start) = call(&client, "wait_for_event", json!({"timeout_seconds": 1})).await;
347
let start: Value = serde_json::from_str(&start).unwrap();
348
let cursor = start["next"].as_u64().unwrap();
349
350
let (is_error, body) = call(
351
&client,
352
"propose_message",
353
json!({"conversation_id": ALLOWED_CHAT, "text": "Sounds good", "agent": "test"}),
354
)
355
.await;
356
assert!(!is_error, "{body}");
357
let body: Value = serde_json::from_str(&body).unwrap();
358
assert_eq!(body["state"], "pending");
359
let proposal_id = body["proposal_id"].as_str().unwrap();
360
assert!(harness.hub.resolve(proposal_id, Outcome::Sent));
361
362
let (_, events) = call(
363
&client,
364
"wait_for_event",
365
json!({"timeout_seconds": 5, "since": cursor}),
366
)
367
.await;
368
let events: Value = serde_json::from_str(&events).unwrap();
369
assert_eq!(events["events"][0]["type"], "proposal_resolved");
370
assert_eq!(events["events"][0]["outcome"], "sent");
371
assert_eq!(events["events"][0]["proposal_id"], proposal_id);
372
}
373
374
#[tokio::test]
375
async fn propose_is_refused_when_turned_off_or_out_of_scope() {
376
let harness = Harness::start(false).await;
377
let client = harness.client().await;
378
let (is_error, text) = call(
379
&client,
380
"propose_message",
381
json!({"conversation_id": ALLOWED_CHAT, "text": "hi"}),
382
)
383
.await;
384
assert!(is_error);
385
assert!(text.contains("turned off"), "{text}");
386
387
let (is_error, text) = call(
388
&client,
389
"propose_message",
390
json!({"conversation_id": HIDDEN_CHAT, "text": "hi"}),
391
)
392
.await;
393
assert!(is_error);
394
assert!(text.contains("not found or not allowed"), "{text}");
395
assert!(harness.hub.pending_proposal(ALLOWED_CHAT).is_none());
396
}
397
398
#[tokio::test]
399
async fn a_second_server_on_the_same_port_reports_it_clearly() {
400
let harness = Harness::start(true).await;
401
let store = Arc::new(Store::open_in_memory().unwrap());
402
let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();
403
let hub = AgentHub::new(store.clone(), AgentPolicy::default(), ui);
404
let result = mcp::start(
405
hub,
406
Arc::new(FakeSource { store }),
407
harness.server.addr.port(),
408
TOKEN.to_owned(),
409
)
410
.await;
411
let error = result.err().expect("port is taken");
412
assert!(error.to_string().contains("already in use"), "{error}");
413
}
414
415
#[tokio::test]
416
async fn meetings_and_transcripts_need_their_switches() {
417
let harness = Harness::start(true).await;
418
let client = harness.client().await;
419
let (is_error, text) = call(&client, "list_meetings", json!({})).await;
420
assert!(is_error);
421
assert!(text.contains("calendar access is turned off"), "{text}");
422
let (is_error, text) = call(
423
&client,
424
"get_transcript",
425
json!({"meeting_chat_id": MEETING_CHAT}),
426
)
427
.await;
428
assert!(is_error);
429
assert!(text.contains("transcripts are turned off"), "{text}");
430
}
431
432
#[tokio::test]
433
async fn list_meetings_returns_the_window() {
434
let harness = Harness::start_with(true, true, false).await;
435
let client = harness.client().await;
436
let (is_error, body) = call(
437
&client,
438
"list_meetings",
439
json!({"start": "2026-10-07T00:00:00Z", "end": "2026-10-08T00:00:00Z"}),
440
)
441
.await;
442
assert!(!is_error, "{body}");
443
let body: Value = serde_json::from_str(&body).unwrap();
444
assert_eq!(body["meetings"][0]["title"], "Sprint review");
445
assert_eq!(body["meetings"][0]["meeting_chat_id"], MEETING_CHAT);
446
447
let (_, empty) = call(
448
&client,
449
"list_meetings",
450
json!({"start": "2026-10-09T00:00:00Z", "end": "2026-10-10T00:00:00Z"}),
451
)
452
.await;
453
let empty: Value = serde_json::from_str(&empty).unwrap();
454
assert!(empty["meetings"].as_array().unwrap().is_empty());
455
456
let (is_error, text) = call(
457
&client,
458
"list_meetings",
459
json!({"start": "2026-10-09T00:00:00Z", "end": "2026-10-08T00:00:00Z"}),
460
)
461
.await;
462
assert!(is_error);
463
assert!(text.contains("end must be after start"), "{text}");
464
}
465
466
#[tokio::test]
467
async fn get_transcript_returns_turns_and_live_captions() {
468
let harness = Harness::start_with(true, false, true).await;
469
let client = harness.client().await;
470
let (is_error, body) = call(
471
&client,
472
"get_transcript",
473
json!({"meeting_chat_id": MEETING_CHAT}),
474
)
475
.await;
476
assert!(!is_error, "{body}");
477
let body: Value = serde_json::from_str(&body).unwrap();
478
assert_eq!(body["turns"][0]["text"], "Welcome everyone");
479
assert!(body["live_captions"].as_array().unwrap().is_empty());
480
481
let live_chat = "19:meeting_live@thread.v2";
482
let (is_error, text) = call(
483
&client,
484
"get_transcript",
485
json!({"meeting_chat_id": live_chat}),
486
)
487
.await;
488
assert!(is_error);
489
assert!(text.contains("no finished recording"), "{text}");
490
491
harness.hub.push_caption(live_chat, "1", "Bo", "Hi all");
492
let (is_error, body) = call(
493
&client,
494
"get_transcript",
495
json!({"meeting_chat_id": live_chat}),
496
)
497
.await;
498
assert!(!is_error, "{body}");
499
let body: Value = serde_json::from_str(&body).unwrap();
500
assert!(body["turns"].as_array().unwrap().is_empty());
501
assert_eq!(body["live_captions"][0]["speaker"], "Bo");
502
assert_eq!(body["live_captions"][0]["text"], "Hi all");
503
}
@@ -0,0 +1,503 @@1
use std::collections::BTreeSet;2
use std::sync::Arc;3
4
use chrono::{DateTime, TimeZone, Utc};5
use mcp::{6
Access, AgentHub, AgentPolicy, Meeting, Outcome, ServerHandle, SourceError, SourceFuture,7
TeamsSource, Transcript, TranscriptTurn,8
};9
use rmcp::ServiceExt;10
use rmcp::model::{CallToolRequestParams, ClientConfig};11
use rmcp::service::RunningService;12
use rmcp::transport::StreamableHttpClientTransport;13
use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;14
use serde_json::{Value, json};15
use store::{ChannelRecord, ChatRecord, MessageRecord, Store, TeamRecord};16
use tokio::io::{AsyncReadExt, AsyncWriteExt};17
use tokio::net::TcpStream;18
19
const TOKEN: &str = "test-token";20
const ALLOWED_CHAT: &str = "19:alpha@thread.v2";21
const HIDDEN_CHAT: &str = "19:beta@thread.v2";22
const CHANNEL: &str = "19:channel@thread.tacv2";23
const MEETING_CHAT: &str = "19:meeting_abc@thread.v2";24
25
struct FakeSource {26
store: Arc<Store>,27
}28
29
impl TeamsSource for FakeSource {30
fn store(&self) -> Result<Arc<Store>, SourceError> {31
Ok(self.store.clone())32
}33
34
fn me_id(&self) -> Option<String> {35
Some("user-me".to_owned())36
}37
38
fn calendar(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> SourceFuture<'_, Vec<Meeting>> {39
let meeting = Meeting {40
title: "Sprint review".to_owned(),41
start: Utc.with_ymd_and_hms(2026, 10, 7, 9, 0, 0).unwrap(),42
end: Utc.with_ymd_and_hms(2026, 10, 7, 10, 0, 0).unwrap(),43
all_day: false,44
organizer: Some("Ada Example".to_owned()),45
join_url: Some("https://teams.example/join".to_owned()),46
meeting_chat_id: Some(MEETING_CHAT.to_owned()),47
};48
Box::pin(async move {49
Ok(vec![meeting]50
.into_iter()51
.filter(|meeting| meeting.start >= start && meeting.start < end)52
.collect())53
})54
}55
56
fn transcript<'a>(&'a self, meeting_chat_id: &'a str) -> SourceFuture<'a, Transcript> {57
Box::pin(async move {58
if meeting_chat_id != MEETING_CHAT {59
return Err(SourceError::Failed(60
"no finished recording in this meeting chat".to_owned(),61
));62
}63
Ok(Transcript {64
recording_name: Some("Sprint review".to_owned()),65
created_at: None,66
turns: vec![TranscriptTurn {67
speaker: "Ada Example".to_owned(),68
start_seconds: 1.0,69
end_seconds: 4.5,70
text: "Welcome everyone".to_owned(),71
}],72
})73
})74
}75
}76
77
struct Harness {78
hub: Arc<AgentHub>,79
server: ServerHandle,80
}81
82
impl Harness {83
async fn start(propose: bool) -> Harness {84
Harness::start_with(propose, false, false).await85
}86
87
async fn start_with(propose: bool, calendar: bool, transcripts: bool) -> Harness {88
let store = Arc::new(Store::open_in_memory().unwrap());89
seed(&store);90
let policy = AgentPolicy {91
enabled: true,92
chats: Access::Selected(BTreeSet::from([ALLOWED_CHAT.to_owned()])),93
channels: Access::Selected(BTreeSet::from([CHANNEL.to_owned()])),94
propose,95
calendar,96
transcripts,97
..AgentPolicy::default()98
};99
let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();100
let hub = AgentHub::new(store.clone(), policy, ui);101
let server = mcp::start(102
hub.clone(),103
Arc::new(FakeSource { store }),104
0,105
TOKEN.to_owned(),106
)107
.await108
.unwrap();109
Harness { hub, server }110
}111
112
fn url(&self) -> String {113
format!("http://{}/mcp", self.server.addr)114
}115
116
async fn client(&self) -> RunningService<rmcp::RoleClient, ClientConfig> {117
let transport = StreamableHttpClientTransport::from_config(118
StreamableHttpClientTransportConfig::with_uri(self.url()).auth_header(TOKEN),119
);120
ClientConfig::default().serve(transport).await.unwrap()121
}122
}123
124
fn seed(store: &Store) {125
let time = |minute: u32| Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap();126
let chat = |id: &str, title: &str| ChatRecord {127
id: id.to_owned(),128
kind: "group".to_owned(),129
title: title.to_owned(),130
last_message_at: Some(time(5)),131
..ChatRecord::default()132
};133
store134
.upsert_chats(&[chat(ALLOWED_CHAT, "Planning"), chat(HIDDEN_CHAT, "Secrets")])135
.unwrap();136
store137
.upsert_teams(&[TeamRecord {138
id: "team-1".to_owned(),139
name: "Platform".to_owned(),140
}])141
.unwrap();142
store143
.upsert_channels(&[ChannelRecord {144
id: CHANNEL.to_owned(),145
team_id: "team-1".to_owned(),146
name: "General".to_owned(),147
membership_type: None,148
last_message_at: Some(time(6)),149
unread: false,150
}])151
.unwrap();152
let message =153
|conversation_id: &str, message_id: &str, minute: u32, html: &str| MessageRecord {154
conversation_id: conversation_id.to_owned(),155
message_id: message_id.to_owned(),156
sender_id: Some("user-ada".to_owned()),157
sender_name: Some("Ada Example".to_owned()),158
created_at: time(minute),159
body_html: html.to_owned(),160
attachments_json: "[]".to_owned(),161
reactions_json: "[]".to_owned(),162
mentions_json: "[]".to_owned(),163
links_json: "[]".to_owned(),164
..MessageRecord::default()165
};166
store167
.upsert_messages(&[168
message(ALLOWED_CHAT, "m1", 1, "<p>budget <b>plan</b></p>"),169
message(ALLOWED_CHAT, "m2", 2, "<p>lunch at noon</p>"),170
message(HIDDEN_CHAT, "m3", 3, "<p>budget secrets</p>"),171
message(CHANNEL, "m4", 4, "<p>budget channel post</p>"),172
])173
.unwrap();174
}175
176
async fn call(177
client: &RunningService<rmcp::RoleClient, ClientConfig>,178
tool: &'static str,179
arguments: Value,180
) -> (bool, String) {181
let params = CallToolRequestParams::new(tool)182
.with_arguments(arguments.as_object().cloned().unwrap_or_default());183
let result = client.call_tool(params).await.unwrap();184
let text = result185
.content186
.first()187
.and_then(|content| content.as_text())188
.map(|text| text.text.clone())189
.unwrap_or_default();190
(result.is_error == Some(true), text)191
}192
193
async fn raw_status(addr: std::net::SocketAddr, host: &str, authorization: Option<&str>) -> u16 {194
let mut stream = TcpStream::connect(addr).await.unwrap();195
let authorization = authorization196
.map(|value| format!("Authorization: {value}\r\n"))197
.unwrap_or_default();198
let request = format!(199
"POST /mcp HTTP/1.1\r\nHost: {host}\r\n{authorization}Content-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"200
);201
stream.write_all(request.as_bytes()).await.unwrap();202
let mut response = String::new();203
stream.read_to_string(&mut response).await.unwrap();204
response.split_whitespace().nth(1).unwrap().parse().unwrap()205
}206
207
#[tokio::test]208
async fn lists_all_eight_tools() {209
let harness = Harness::start(true).await;210
let client = harness.client().await;211
let mut names: Vec<String> = client212
.list_all_tools()213
.await214
.unwrap()215
.into_iter()216
.map(|tool| tool.name.to_string())217
.collect();218
names.sort();219
assert_eq!(220
names,221
[222
"get_transcript",223
"list_channels",224
"list_chats",225
"list_meetings",226
"propose_message",227
"read_messages",228
"search_messages",229
"wait_for_event"230
]231
);232
let info = client.peer_info().unwrap();233
assert_eq!(info.server_info.as_ref().unwrap().name, "rusty-teams");234
}235
236
#[tokio::test]237
async fn rejects_missing_token_bad_host_and_serves_healthz() {238
let harness = Harness::start(true).await;239
let addr = harness.server.addr;240
let own_host = addr.to_string();241
assert_eq!(raw_status(addr, &own_host, None).await, 401);242
assert_eq!(raw_status(addr, &own_host, Some("Bearer wrong")).await, 401);243
assert_eq!(244
raw_status(addr, "evil.example", Some("Bearer test-token")).await,245
403246
);247
let authorized = raw_status(addr, &own_host, Some("Bearer test-token")).await;248
assert!(authorized != 401 && authorized != 403, "{authorized}");249
250
let mut stream = TcpStream::connect(addr).await.unwrap();251
stream252
.write_all(253
format!("GET /healthz HTTP/1.1\r\nHost: {own_host}\r\nConnection: close\r\n\r\n")254
.as_bytes(),255
)256
.await257
.unwrap();258
let mut response = String::new();259
stream.read_to_string(&mut response).await.unwrap();260
assert!(response.starts_with("HTTP/1.1 200"), "{response}");261
assert!(response.ends_with("ok"), "{response}");262
}263
264
#[tokio::test]265
async fn lists_only_allowed_conversations() {266
let harness = Harness::start(true).await;267
let client = harness.client().await;268
let (_, chats) = call(&client, "list_chats", json!({})).await;269
let chats: Value = serde_json::from_str(&chats).unwrap();270
assert_eq!(chats["chats"].as_array().unwrap().len(), 1);271
assert_eq!(chats["chats"][0]["id"], ALLOWED_CHAT);272
let (_, channels) = call(&client, "list_channels", json!({})).await;273
let channels: Value = serde_json::from_str(&channels).unwrap();274
assert_eq!(channels["channels"][0]["team"], "Platform");275
assert_eq!(channels["channels"][0]["channel"], "General");276
}277
278
#[tokio::test]279
async fn read_messages_respects_scope_and_paging() {280
let harness = Harness::start(true).await;281
let client = harness.client().await;282
let (is_error, text) = call(283
&client,284
"read_messages",285
json!({"conversation_id": HIDDEN_CHAT}),286
)287
.await;288
assert!(is_error);289
assert!(290
text.contains("conversation not found or not allowed"),291
"{text}"292
);293
let (is_error, unknown) = call(294
&client,295
"read_messages",296
json!({"conversation_id": "19:nope@thread.v2"}),297
)298
.await;299
assert!(is_error);300
assert_eq!(unknown, text);301
302
let (is_error, body) = call(303
&client,304
"read_messages",305
json!({"conversation_id": ALLOWED_CHAT}),306
)307
.await;308
assert!(!is_error, "{body}");309
let body: Value = serde_json::from_str(&body).unwrap();310
assert_eq!(body["messages"][0]["text"], "budget plan");311
assert_eq!(body["messages"][1]["message_id"], "m2");312
313
let (_, older) = call(314
&client,315
"read_messages",316
json!({"conversation_id": ALLOWED_CHAT, "before_message_id": "m2"}),317
)318
.await;319
let older: Value = serde_json::from_str(&older).unwrap();320
assert_eq!(older["messages"].as_array().unwrap().len(), 1);321
assert_eq!(older["messages"][0]["message_id"], "m1");322
}323
324
#[tokio::test]325
async fn search_stays_inside_the_allowed_scope() {326
let harness = Harness::start(true).await;327
let client = harness.client().await;328
let (is_error, body) = call(&client, "search_messages", json!({"query": "budget"})).await;329
assert!(!is_error, "{body}");330
let body: Value = serde_json::from_str(&body).unwrap();331
let mut message_ids: Vec<&str> = body["hits"]332
.as_array()333
.unwrap()334
.iter()335
.map(|hit| hit["message_id"].as_str().unwrap())336
.collect();337
message_ids.sort();338
assert_eq!(message_ids, ["m1", "m4"]);339
assert!(!body.to_string().contains('\u{1}'));340
}341
342
#[tokio::test]343
async fn proposal_resolution_reaches_wait_for_event() {344
let harness = Harness::start(true).await;345
let client = harness.client().await;346
let (_, start) = call(&client, "wait_for_event", json!({"timeout_seconds": 1})).await;347
let start: Value = serde_json::from_str(&start).unwrap();348
let cursor = start["next"].as_u64().unwrap();349
350
let (is_error, body) = call(351
&client,352
"propose_message",353
json!({"conversation_id": ALLOWED_CHAT, "text": "Sounds good", "agent": "test"}),354
)355
.await;356
assert!(!is_error, "{body}");357
let body: Value = serde_json::from_str(&body).unwrap();358
assert_eq!(body["state"], "pending");359
let proposal_id = body["proposal_id"].as_str().unwrap();360
assert!(harness.hub.resolve(proposal_id, Outcome::Sent));361
362
let (_, events) = call(363
&client,364
"wait_for_event",365
json!({"timeout_seconds": 5, "since": cursor}),366
)367
.await;368
let events: Value = serde_json::from_str(&events).unwrap();369
assert_eq!(events["events"][0]["type"], "proposal_resolved");370
assert_eq!(events["events"][0]["outcome"], "sent");371
assert_eq!(events["events"][0]["proposal_id"], proposal_id);372
}373
374
#[tokio::test]375
async fn propose_is_refused_when_turned_off_or_out_of_scope() {376
let harness = Harness::start(false).await;377
let client = harness.client().await;378
let (is_error, text) = call(379
&client,380
"propose_message",381
json!({"conversation_id": ALLOWED_CHAT, "text": "hi"}),382
)383
.await;384
assert!(is_error);385
assert!(text.contains("turned off"), "{text}");386
387
let (is_error, text) = call(388
&client,389
"propose_message",390
json!({"conversation_id": HIDDEN_CHAT, "text": "hi"}),391
)392
.await;393
assert!(is_error);394
assert!(text.contains("not found or not allowed"), "{text}");395
assert!(harness.hub.pending_proposal(ALLOWED_CHAT).is_none());396
}397
398
#[tokio::test]399
async fn a_second_server_on_the_same_port_reports_it_clearly() {400
let harness = Harness::start(true).await;401
let store = Arc::new(Store::open_in_memory().unwrap());402
let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel();403
let hub = AgentHub::new(store.clone(), AgentPolicy::default(), ui);404
let result = mcp::start(405
hub,406
Arc::new(FakeSource { store }),407
harness.server.addr.port(),408
TOKEN.to_owned(),409
)410
.await;411
let error = result.err().expect("port is taken");412
assert!(error.to_string().contains("already in use"), "{error}");413
}414
415
#[tokio::test]416
async fn meetings_and_transcripts_need_their_switches() {417
let harness = Harness::start(true).await;418
let client = harness.client().await;419
let (is_error, text) = call(&client, "list_meetings", json!({})).await;420
assert!(is_error);421
assert!(text.contains("calendar access is turned off"), "{text}");422
let (is_error, text) = call(423
&client,424
"get_transcript",425
json!({"meeting_chat_id": MEETING_CHAT}),426
)427
.await;428
assert!(is_error);429
assert!(text.contains("transcripts are turned off"), "{text}");430
}431
432
#[tokio::test]433
async fn list_meetings_returns_the_window() {434
let harness = Harness::start_with(true, true, false).await;435
let client = harness.client().await;436
let (is_error, body) = call(437
&client,438
"list_meetings",439
json!({"start": "2026-10-07T00:00:00Z", "end": "2026-10-08T00:00:00Z"}),440
)441
.await;442
assert!(!is_error, "{body}");443
let body: Value = serde_json::from_str(&body).unwrap();444
assert_eq!(body["meetings"][0]["title"], "Sprint review");445
assert_eq!(body["meetings"][0]["meeting_chat_id"], MEETING_CHAT);446
447
let (_, empty) = call(448
&client,449
"list_meetings",450
json!({"start": "2026-10-09T00:00:00Z", "end": "2026-10-10T00:00:00Z"}),451
)452
.await;453
let empty: Value = serde_json::from_str(&empty).unwrap();454
assert!(empty["meetings"].as_array().unwrap().is_empty());455
456
let (is_error, text) = call(457
&client,458
"list_meetings",459
json!({"start": "2026-10-09T00:00:00Z", "end": "2026-10-08T00:00:00Z"}),460
)461
.await;462
assert!(is_error);463
assert!(text.contains("end must be after start"), "{text}");464
}465
466
#[tokio::test]467
async fn get_transcript_returns_turns_and_live_captions() {468
let harness = Harness::start_with(true, false, true).await;469
let client = harness.client().await;470
let (is_error, body) = call(471
&client,472
"get_transcript",473
json!({"meeting_chat_id": MEETING_CHAT}),474
)475
.await;476
assert!(!is_error, "{body}");477
let body: Value = serde_json::from_str(&body).unwrap();478
assert_eq!(body["turns"][0]["text"], "Welcome everyone");479
assert!(body["live_captions"].as_array().unwrap().is_empty());480
481
let live_chat = "19:meeting_live@thread.v2";482
let (is_error, text) = call(483
&client,484
"get_transcript",485
json!({"meeting_chat_id": live_chat}),486
)487
.await;488
assert!(is_error);489
assert!(text.contains("no finished recording"), "{text}");490
491
harness.hub.push_caption(live_chat, "1", "Bo", "Hi all");492
let (is_error, body) = call(493
&client,494
"get_transcript",495
json!({"meeting_chat_id": live_chat}),496
)497
.await;498
assert!(!is_error, "{body}");499
let body: Value = serde_json::from_str(&body).unwrap();500
assert!(body["turns"].as_array().unwrap().is_empty());501
assert_eq!(body["live_captions"][0]["speaker"], "Bo");502
assert_eq!(body["live_captions"][0]["text"], "Hi all");503
}@@ -13,6 +13,7 @@ mod migrations;
13
13
mod models;
14
14
mod outbox;
15
15
mod presence;
16
mod proposals;
16
17
mod search;
17
18
mod sidebar;
18
19
mod store;
@@ -24,10 +25,11 @@ mod time;
24
25
pub use error::{Error, Result};
25
26
pub use image_files::ImageFileCache;
26
27
pub use models::{
27
ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,
28
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, ConversationHit,
29
DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord, OutboxRecord, OutboxState,
30
OutboxTarget, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
28
ActivityRecord, AgentProposalRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord,
29
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview,
30
ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
31
MessageRecord, OutboxRecord, OutboxState, OutboxTarget, SearchHit, Sidebar, SidebarTeam,
32
SyncState, TeamLayoutRecord, TeamRecord,
31
33
};
32
34
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
33
35
pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -13,6 +13,7 @@ mod migrations;13
mod models;13
mod models;14
mod outbox;14
mod outbox;15
mod presence;15
mod presence;16
mod proposals;16
mod search;17
mod search;17
mod sidebar;18
mod sidebar;18
mod store;19
mod store;@@ -24,10 +25,11 @@ mod time;24
pub use error::{Error, Result};25
pub use error::{Error, Result};25
pub use image_files::ImageFileCache;26
pub use image_files::ImageFileCache;26
pub use models::{27
pub use models::{27
ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel,28
ActivityRecord, AgentProposalRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord,28
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, ConversationHit,29
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview,29
DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord, OutboxRecord, OutboxState,30
ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,30
OutboxTarget, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,31
MessageRecord, OutboxRecord, OutboxState, OutboxTarget, SearchHit, Sidebar, SidebarTeam,32
SyncState, TeamLayoutRecord, TeamRecord,31
};33
};32
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};34
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};33
pub use store::{DATA_DIR_NAME, Store, default_database_path};35
pub use store::{DATA_DIR_NAME, Store, default_database_path};@@ -137,6 +137,28 @@ impl Store {
137
137
Ok(messages)
138
138
}
139
139
140
/// Oldest-first page of the `limit` oldest messages strictly newer than `after`.
141
pub fn messages_after(
142
&self,
143
conversation_id: &str,
144
after: DateTime<Utc>,
145
limit: usize,
146
) -> Result<Vec<MessageRecord>> {
147
let connection = self.lock()?;
148
let mut statement = connection.prepare_cached(&format!(
149
"SELECT {MESSAGE_COLUMNS} FROM messages
150
WHERE conversation_id = ?1 AND created_at > ?2
151
ORDER BY created_at ASC, message_id ASC LIMIT ?3"
152
))?;
153
let messages = statement
154
.query_map(
155
params![conversation_id, to_millis(after), limit as i64],
156
message_from_row,
157
)?
158
.collect::<rusqlite::Result<Vec<_>>>()?;
159
Ok(messages)
160
}
161
140
162
/// Oldest-first root and replies of one channel thread.
141
163
pub fn thread_messages(
142
164
&self,
@@ -137,6 +137,28 @@ impl Store {137
Ok(messages)137
Ok(messages)138
}138
}139
139
140
/// Oldest-first page of the `limit` oldest messages strictly newer than `after`.141
pub fn messages_after(142
&self,143
conversation_id: &str,144
after: DateTime<Utc>,145
limit: usize,146
) -> Result<Vec<MessageRecord>> {147
let connection = self.lock()?;148
let mut statement = connection.prepare_cached(&format!(149
"SELECT {MESSAGE_COLUMNS} FROM messages150
WHERE conversation_id = ?1 AND created_at > ?2151
ORDER BY created_at ASC, message_id ASC LIMIT ?3"152
))?;153
let messages = statement154
.query_map(155
params![conversation_id, to_millis(after), limit as i64],156
message_from_row,157
)?158
.collect::<rusqlite::Result<Vec<_>>>()?;159
Ok(messages)160
}161
140
/// Oldest-first root and replies of one channel thread.162
/// Oldest-first root and replies of one channel thread.141
pub fn thread_messages(163
pub fn thread_messages(142
&self,164
&self,@@ -73,6 +73,10 @@ const MIGRATIONS: &[Migration] = &[
73
73
script: include_str!("migrations/0016_channel_notifications.sql"),
74
74
after: None,
75
75
},
76
Migration {
77
script: include_str!("migrations/0017_agents.sql"),
78
after: None,
79
},
76
80
];
77
81
78
82
pub fn latest_version() -> i64 {
@@ -73,6 +73,10 @@ const MIGRATIONS: &[Migration] = &[73
script: include_str!("migrations/0016_channel_notifications.sql"),73
script: include_str!("migrations/0016_channel_notifications.sql"),74
after: None,74
after: None,75
},75
},76
Migration {77
script: include_str!("migrations/0017_agents.sql"),78
after: None,79
},76
];80
];77
81
78
pub fn latest_version() -> i64 {82
pub fn latest_version() -> i64 {@@ -0,0 +1,13 @@
1
CREATE TABLE agent_proposals (
2
id TEXT PRIMARY KEY,
3
conversation_id TEXT NOT NULL,
4
reply_to_message_id TEXT,
5
text TEXT NOT NULL,
6
agent TEXT,
7
session_id TEXT,
8
created_at INTEGER NOT NULL,
9
state TEXT NOT NULL,
10
resolved_at INTEGER
11
);
12
13
CREATE INDEX agent_proposals_by_conversation_state ON agent_proposals (conversation_id, state);
@@ -0,0 +1,13 @@1
CREATE TABLE agent_proposals (2
id TEXT PRIMARY KEY,3
conversation_id TEXT NOT NULL,4
reply_to_message_id TEXT,5
text TEXT NOT NULL,6
agent TEXT,7
session_id TEXT,8
created_at INTEGER NOT NULL,9
state TEXT NOT NULL,10
resolved_at INTEGER11
);12
13
CREATE INDEX agent_proposals_by_conversation_state ON agent_proposals (conversation_id, state);@@ -26,6 +26,18 @@ pub struct ChatRecord {
26
26
pub last_event_system: bool,
27
27
}
28
28
29
impl ChatRecord {
30
pub fn display_title(&self) -> String {
31
if !self.title.trim().is_empty() {
32
self.title.clone()
33
} else if !self.member_summary.trim().is_empty() {
34
self.member_summary.clone()
35
} else {
36
"Chat".to_owned()
37
}
38
}
39
}
40
29
41
#[derive(Debug, Clone, PartialEq)]
30
42
pub struct AvatarRecord {
31
43
pub user_id: String,
@@ -312,3 +324,16 @@ pub struct DraftRecord {
312
324
pub images: Vec<AttachmentImage>,
313
325
pub updated_at: DateTime<Utc>,
314
326
}
327
328
#[derive(Debug, Clone, PartialEq, Eq)]
329
pub struct AgentProposalRecord {
330
pub id: String,
331
pub conversation_id: String,
332
pub reply_to_message_id: Option<String>,
333
pub text: String,
334
pub agent: Option<String>,
335
pub session_id: Option<String>,
336
pub created_at: DateTime<Utc>,
337
pub state: String,
338
pub resolved_at: Option<DateTime<Utc>>,
339
}
@@ -26,6 +26,18 @@ pub struct ChatRecord {26
pub last_event_system: bool,26
pub last_event_system: bool,27
}27
}28
28
29
impl ChatRecord {30
pub fn display_title(&self) -> String {31
if !self.title.trim().is_empty() {32
self.title.clone()33
} else if !self.member_summary.trim().is_empty() {34
self.member_summary.clone()35
} else {36
"Chat".to_owned()37
}38
}39
}40
29
#[derive(Debug, Clone, PartialEq)]41
#[derive(Debug, Clone, PartialEq)]30
pub struct AvatarRecord {42
pub struct AvatarRecord {31
pub user_id: String,43
pub user_id: String,@@ -312,3 +324,16 @@ pub struct DraftRecord {312
pub images: Vec<AttachmentImage>,324
pub images: Vec<AttachmentImage>,313
pub updated_at: DateTime<Utc>,325
pub updated_at: DateTime<Utc>,314
}326
}327
328
#[derive(Debug, Clone, PartialEq, Eq)]329
pub struct AgentProposalRecord {330
pub id: String,331
pub conversation_id: String,332
pub reply_to_message_id: Option<String>,333
pub text: String,334
pub agent: Option<String>,335
pub session_id: Option<String>,336
pub created_at: DateTime<Utc>,337
pub state: String,338
pub resolved_at: Option<DateTime<Utc>>,339
}@@ -0,0 +1,75 @@
1
use chrono::{DateTime, Utc};
2
use rusqlite::{Row, params};
3
4
use crate::error::Result;
5
use crate::models::AgentProposalRecord;
6
use crate::store::Store;
7
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
8
9
const PENDING_STATE: &str = "pending";
10
11
const PROPOSAL_COLUMNS: &str = "id, conversation_id, reply_to_message_id, text, agent, session_id, created_at, state, resolved_at";
12
13
impl Store {
14
pub fn insert_agent_proposal(&self, proposal: &AgentProposalRecord) -> Result<()> {
15
let connection = self.lock()?;
16
connection.execute(
17
&format!(
18
"INSERT INTO agent_proposals ({PROPOSAL_COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)"
19
),
20
params![
21
proposal.id,
22
proposal.conversation_id,
23
proposal.reply_to_message_id,
24
proposal.text,
25
proposal.agent,
26
proposal.session_id,
27
to_millis(proposal.created_at),
28
proposal.state,
29
optional_to_millis(proposal.resolved_at),
30
],
31
)?;
32
Ok(())
33
}
34
35
pub fn set_agent_proposal_state(
36
&self,
37
proposal_id: &str,
38
state: &str,
39
resolved_at: Option<DateTime<Utc>>,
40
) -> Result<bool> {
41
let connection = self.lock()?;
42
let changed = connection.execute(
43
"UPDATE agent_proposals SET state = ?2, resolved_at = ?3 WHERE id = ?1",
44
params![proposal_id, state, optional_to_millis(resolved_at)],
45
)?;
46
Ok(changed > 0)
47
}
48
49
/// Oldest first.
50
pub fn pending_agent_proposals(&self) -> Result<Vec<AgentProposalRecord>> {
51
let connection = self.lock()?;
52
let mut statement = connection.prepare_cached(&format!(
53
"SELECT {PROPOSAL_COLUMNS} FROM agent_proposals WHERE state = ?1
54
ORDER BY created_at ASC, id ASC"
55
))?;
56
let proposals = statement
57
.query_map([PENDING_STATE], proposal_from_row)?
58
.collect::<rusqlite::Result<_>>()?;
59
Ok(proposals)
60
}
61
}
62
63
fn proposal_from_row(row: &Row<'_>) -> rusqlite::Result<AgentProposalRecord> {
64
Ok(AgentProposalRecord {
65
id: row.get(0)?,
66
conversation_id: row.get(1)?,
67
reply_to_message_id: row.get(2)?,
68
text: row.get(3)?,
69
agent: row.get(4)?,
70
session_id: row.get(5)?,
71
created_at: from_millis(row.get(6)?),
72
state: row.get(7)?,
73
resolved_at: optional_from_millis(row.get(8)?),
74
})
75
}
@@ -0,0 +1,75 @@1
use chrono::{DateTime, Utc};2
use rusqlite::{Row, params};3
4
use crate::error::Result;5
use crate::models::AgentProposalRecord;6
use crate::store::Store;7
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};8
9
const PENDING_STATE: &str = "pending";10
11
const PROPOSAL_COLUMNS: &str = "id, conversation_id, reply_to_message_id, text, agent, session_id, created_at, state, resolved_at";12
13
impl Store {14
pub fn insert_agent_proposal(&self, proposal: &AgentProposalRecord) -> Result<()> {15
let connection = self.lock()?;16
connection.execute(17
&format!(18
"INSERT INTO agent_proposals ({PROPOSAL_COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)"19
),20
params![21
proposal.id,22
proposal.conversation_id,23
proposal.reply_to_message_id,24
proposal.text,25
proposal.agent,26
proposal.session_id,27
to_millis(proposal.created_at),28
proposal.state,29
optional_to_millis(proposal.resolved_at),30
],31
)?;32
Ok(())33
}34
35
pub fn set_agent_proposal_state(36
&self,37
proposal_id: &str,38
state: &str,39
resolved_at: Option<DateTime<Utc>>,40
) -> Result<bool> {41
let connection = self.lock()?;42
let changed = connection.execute(43
"UPDATE agent_proposals SET state = ?2, resolved_at = ?3 WHERE id = ?1",44
params![proposal_id, state, optional_to_millis(resolved_at)],45
)?;46
Ok(changed > 0)47
}48
49
/// Oldest first.50
pub fn pending_agent_proposals(&self) -> Result<Vec<AgentProposalRecord>> {51
let connection = self.lock()?;52
let mut statement = connection.prepare_cached(&format!(53
"SELECT {PROPOSAL_COLUMNS} FROM agent_proposals WHERE state = ?154
ORDER BY created_at ASC, id ASC"55
))?;56
let proposals = statement57
.query_map([PENDING_STATE], proposal_from_row)?58
.collect::<rusqlite::Result<_>>()?;59
Ok(proposals)60
}61
}62
63
fn proposal_from_row(row: &Row<'_>) -> rusqlite::Result<AgentProposalRecord> {64
Ok(AgentProposalRecord {65
id: row.get(0)?,66
conversation_id: row.get(1)?,67
reply_to_message_id: row.get(2)?,68
text: row.get(3)?,69
agent: row.get(4)?,70
session_id: row.get(5)?,71
created_at: from_millis(row.get(6)?),72
state: row.get(7)?,73
resolved_at: optional_from_millis(row.get(8)?),74
})75
}@@ -2,7 +2,7 @@ use rusqlite::{Connection, OptionalExtension, Transaction, params};
2
2
3
3
use crate::error::Result;
4
4
use crate::models::{ConversationHit, MessageRecord, SearchHit};
5
use crate::store::Store;
5
use crate::store::{Store, json_ids};
6
6
use crate::text::plain_text;
7
7
use crate::time::from_millis;
8
8
@@ -126,6 +126,45 @@ impl Store {
126
126
Ok(hits)
127
127
}
128
128
129
/// Like `search_messages`, restricted to `conversation_ids` before the limit applies.
130
pub fn search_messages_in(
131
&self,
132
query: &str,
133
conversation_ids: &[String],
134
limit: usize,
135
) -> Result<Vec<SearchHit>> {
136
let Some(expression) = match_expression(query) else {
137
return Ok(Vec::new());
138
};
139
let connection = self.lock()?;
140
let mut statement = connection.prepare_cached(&format!(
141
"SELECT k.conversation_id, k.message_id, m.sender_name, m.created_at,
142
snippet(message_search, 0, char({}), char({}), '...', {SNIPPET_TOKENS})
143
FROM message_search
144
JOIN search_keys k ON k.id = message_search.rowid
145
JOIN messages m ON m.conversation_id = k.conversation_id AND m.message_id = k.message_id
146
WHERE message_search MATCH ?1
147
AND k.conversation_id IN (SELECT value FROM json_each(?2))
148
ORDER BY m.created_at DESC LIMIT ?3",
149
HIGHLIGHT_START as u32, HIGHLIGHT_END as u32
150
))?;
151
let hits = statement
152
.query_map(
153
params![expression, json_ids(conversation_ids), limit as i64],
154
|row| {
155
Ok(SearchHit {
156
conversation_id: row.get(0)?,
157
message_id: row.get(1)?,
158
sender_name: row.get(2)?,
159
created_at: from_millis(row.get(3)?),
160
snippet: row.get(4)?,
161
})
162
},
163
)?
164
.collect::<rusqlite::Result<_>>()?;
165
Ok(hits)
166
}
167
129
168
pub fn search_conversations(&self, query: &str, limit: usize) -> Result<Vec<ConversationHit>> {
130
169
let Some(expression) = match_expression(query).filter(|_| !query.contains(SENDER_FILTER))
131
170
else {
@@ -2,7 +2,7 @@ use rusqlite::{Connection, OptionalExtension, Transaction, params};2
2
3
use crate::error::Result;3
use crate::error::Result;4
use crate::models::{ConversationHit, MessageRecord, SearchHit};4
use crate::models::{ConversationHit, MessageRecord, SearchHit};5
use crate::store::Store;5
use crate::store::{Store, json_ids};6
use crate::text::plain_text;6
use crate::text::plain_text;7
use crate::time::from_millis;7
use crate::time::from_millis;8
8
@@ -126,6 +126,45 @@ impl Store {126
Ok(hits)126
Ok(hits)127
}127
}128
128
129
/// Like `search_messages`, restricted to `conversation_ids` before the limit applies.130
pub fn search_messages_in(131
&self,132
query: &str,133
conversation_ids: &[String],134
limit: usize,135
) -> Result<Vec<SearchHit>> {136
let Some(expression) = match_expression(query) else {137
return Ok(Vec::new());138
};139
let connection = self.lock()?;140
let mut statement = connection.prepare_cached(&format!(141
"SELECT k.conversation_id, k.message_id, m.sender_name, m.created_at,142
snippet(message_search, 0, char({}), char({}), '...', {SNIPPET_TOKENS})143
FROM message_search144
JOIN search_keys k ON k.id = message_search.rowid145
JOIN messages m ON m.conversation_id = k.conversation_id AND m.message_id = k.message_id146
WHERE message_search MATCH ?1147
AND k.conversation_id IN (SELECT value FROM json_each(?2))148
ORDER BY m.created_at DESC LIMIT ?3",149
HIGHLIGHT_START as u32, HIGHLIGHT_END as u32150
))?;151
let hits = statement152
.query_map(153
params![expression, json_ids(conversation_ids), limit as i64],154
|row| {155
Ok(SearchHit {156
conversation_id: row.get(0)?,157
message_id: row.get(1)?,158
sender_name: row.get(2)?,159
created_at: from_millis(row.get(3)?),160
snippet: row.get(4)?,161
})162
},163
)?164
.collect::<rusqlite::Result<_>>()?;165
Ok(hits)166
}167
129
pub fn search_conversations(&self, query: &str, limit: usize) -> Result<Vec<ConversationHit>> {168
pub fn search_conversations(&self, query: &str, limit: usize) -> Result<Vec<ConversationHit>> {130
let Some(expression) = match_expression(query).filter(|_| !query.contains(SENDER_FILTER))169
let Some(expression) = match_expression(query).filter(|_| !query.contains(SENDER_FILTER))131
else {170
else {@@ -0,0 +1,110 @@
1
use chrono::{DateTime, TimeZone, Utc};
2
use store::{AgentProposalRecord, MessageRecord, Store};
3
4
fn at(minute: u32) -> DateTime<Utc> {
5
Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()
6
}
7
8
fn message(conversation_id: &str, message_id: &str, minute: u32, html: &str) -> MessageRecord {
9
MessageRecord {
10
conversation_id: conversation_id.to_owned(),
11
message_id: message_id.to_owned(),
12
sender_id: Some("user-ada".to_owned()),
13
sender_name: Some("Ada Example".to_owned()),
14
created_at: at(minute),
15
body_html: html.to_owned(),
16
attachments_json: "[]".to_owned(),
17
reactions_json: "[]".to_owned(),
18
mentions_json: "[]".to_owned(),
19
links_json: "[]".to_owned(),
20
..MessageRecord::default()
21
}
22
}
23
24
fn proposal(id: &str, conversation_id: &str, minute: u32) -> AgentProposalRecord {
25
AgentProposalRecord {
26
id: id.to_owned(),
27
conversation_id: conversation_id.to_owned(),
28
reply_to_message_id: None,
29
text: format!("text {id}"),
30
agent: Some("claude".to_owned()),
31
session_id: None,
32
created_at: at(minute),
33
state: "pending".to_owned(),
34
resolved_at: None,
35
}
36
}
37
38
#[test]
39
fn search_in_filters_before_the_limit_applies() {
40
let store = Store::open_in_memory().unwrap();
41
store
42
.upsert_messages(&[
43
message("c1", "m1", 1, "<p>budget one</p>"),
44
message("c2", "m2", 2, "<p>budget two</p>"),
45
message("c2", "m3", 3, "<p>budget three</p>"),
46
])
47
.unwrap();
48
let hits = store
49
.search_messages_in("budget", &["c1".to_owned()], 1)
50
.unwrap();
51
assert_eq!(hits.len(), 1);
52
assert_eq!(hits[0].message_id, "m1");
53
assert!(
54
store
55
.search_messages_in("budget", &[], 10)
56
.unwrap()
57
.is_empty()
58
);
59
}
60
61
#[test]
62
fn messages_after_pages_forward_oldest_first() {
63
let store = Store::open_in_memory().unwrap();
64
store
65
.upsert_messages(&[
66
message("c1", "m1", 1, "<p>a</p>"),
67
message("c1", "m2", 2, "<p>b</p>"),
68
message("c1", "m3", 3, "<p>c</p>"),
69
message("c2", "m4", 4, "<p>d</p>"),
70
])
71
.unwrap();
72
let page = store.messages_after("c1", at(1), 1).unwrap();
73
assert_eq!(page.len(), 1);
74
assert_eq!(page[0].message_id, "m2");
75
assert_eq!(store.messages_after("c1", at(1), 10).unwrap().len(), 2);
76
}
77
78
#[test]
79
fn proposals_persist_and_only_pending_ones_are_listed() {
80
let store = Store::open_in_memory().unwrap();
81
store
82
.insert_agent_proposal(&proposal("p2", "c1", 2))
83
.unwrap();
84
store
85
.insert_agent_proposal(&proposal("p1", "c2", 1))
86
.unwrap();
87
let pending = store.pending_agent_proposals().unwrap();
88
assert_eq!(
89
pending
90
.iter()
91
.map(|record| record.id.as_str())
92
.collect::<Vec<_>>(),
93
["p1", "p2"]
94
);
95
assert_eq!(pending[0], proposal("p1", "c2", 1));
96
97
assert!(
98
store
99
.set_agent_proposal_state("p1", "sent", Some(at(5)))
100
.unwrap()
101
);
102
assert!(
103
!store
104
.set_agent_proposal_state("nope", "sent", None)
105
.unwrap()
106
);
107
let pending = store.pending_agent_proposals().unwrap();
108
assert_eq!(pending.len(), 1);
109
assert_eq!(pending[0].id, "p2");
110
}
@@ -0,0 +1,110 @@1
use chrono::{DateTime, TimeZone, Utc};2
use store::{AgentProposalRecord, MessageRecord, Store};3
4
fn at(minute: u32) -> DateTime<Utc> {5
Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()6
}7
8
fn message(conversation_id: &str, message_id: &str, minute: u32, html: &str) -> MessageRecord {9
MessageRecord {10
conversation_id: conversation_id.to_owned(),11
message_id: message_id.to_owned(),12
sender_id: Some("user-ada".to_owned()),13
sender_name: Some("Ada Example".to_owned()),14
created_at: at(minute),15
body_html: html.to_owned(),16
attachments_json: "[]".to_owned(),17
reactions_json: "[]".to_owned(),18
mentions_json: "[]".to_owned(),19
links_json: "[]".to_owned(),20
..MessageRecord::default()21
}22
}23
24
fn proposal(id: &str, conversation_id: &str, minute: u32) -> AgentProposalRecord {25
AgentProposalRecord {26
id: id.to_owned(),27
conversation_id: conversation_id.to_owned(),28
reply_to_message_id: None,29
text: format!("text {id}"),30
agent: Some("claude".to_owned()),31
session_id: None,32
created_at: at(minute),33
state: "pending".to_owned(),34
resolved_at: None,35
}36
}37
38
#[test]39
fn search_in_filters_before_the_limit_applies() {40
let store = Store::open_in_memory().unwrap();41
store42
.upsert_messages(&[43
message("c1", "m1", 1, "<p>budget one</p>"),44
message("c2", "m2", 2, "<p>budget two</p>"),45
message("c2", "m3", 3, "<p>budget three</p>"),46
])47
.unwrap();48
let hits = store49
.search_messages_in("budget", &["c1".to_owned()], 1)50
.unwrap();51
assert_eq!(hits.len(), 1);52
assert_eq!(hits[0].message_id, "m1");53
assert!(54
store55
.search_messages_in("budget", &[], 10)56
.unwrap()57
.is_empty()58
);59
}60
61
#[test]62
fn messages_after_pages_forward_oldest_first() {63
let store = Store::open_in_memory().unwrap();64
store65
.upsert_messages(&[66
message("c1", "m1", 1, "<p>a</p>"),67
message("c1", "m2", 2, "<p>b</p>"),68
message("c1", "m3", 3, "<p>c</p>"),69
message("c2", "m4", 4, "<p>d</p>"),70
])71
.unwrap();72
let page = store.messages_after("c1", at(1), 1).unwrap();73
assert_eq!(page.len(), 1);74
assert_eq!(page[0].message_id, "m2");75
assert_eq!(store.messages_after("c1", at(1), 10).unwrap().len(), 2);76
}77
78
#[test]79
fn proposals_persist_and_only_pending_ones_are_listed() {80
let store = Store::open_in_memory().unwrap();81
store82
.insert_agent_proposal(&proposal("p2", "c1", 2))83
.unwrap();84
store85
.insert_agent_proposal(&proposal("p1", "c2", 1))86
.unwrap();87
let pending = store.pending_agent_proposals().unwrap();88
assert_eq!(89
pending90
.iter()91
.map(|record| record.id.as_str())92
.collect::<Vec<_>>(),93
["p1", "p2"]94
);95
assert_eq!(pending[0], proposal("p1", "c2", 1));96
97
assert!(98
store99
.set_agent_proposal_state("p1", "sent", Some(at(5)))100
.unwrap()101
);102
assert!(103
!store104
.set_agent_proposal_state("nope", "sent", None)105
.unwrap()106
);107
let pending = store.pending_agent_proposals().unwrap();108
assert_eq!(pending.len(), 1);109
assert_eq!(pending[0].id, "p2");110
}@@ -470,11 +470,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
470
470
let path = directory.path().join("nested").join("cache.sqlite3");
471
471
{
472
472
let store = Store::open(&path).unwrap();
473
assert_eq!(store.schema_version().unwrap(), 16);
473
assert_eq!(store.schema_version().unwrap(), 17);
474
474
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
475
475
}
476
476
let reopened = Store::open(&path).unwrap();
477
assert_eq!(reopened.schema_version().unwrap(), 16);
477
assert_eq!(reopened.schema_version().unwrap(), 17);
478
478
assert_eq!(reopened.message_count("c").unwrap(), 1);
479
479
drop(reopened);
480
480
let mode: String = rusqlite_open(&path)
@@ -503,10 +503,10 @@ fn old_schema_is_upgraded_in_place() {
503
503
let path = directory.path().join("cache.sqlite3");
504
504
drop(Store::open(&path).unwrap());
505
505
let connection = rusqlite_open(&path);
506
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
506
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
507
507
drop(connection);
508
508
let store = Store::open(&path).unwrap();
509
assert_eq!(store.schema_version().unwrap(), 16);
509
assert_eq!(store.schema_version().unwrap(), 17);
510
510
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
511
511
}
512
512
@@ -572,7 +572,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
572
572
let store = Store::open(&path).unwrap();
573
573
let state = store.sync_state("c").unwrap().unwrap();
574
574
assert_eq!(state.delta_link, None);
575
assert_eq!(store.schema_version().unwrap(), 16);
575
assert_eq!(store.schema_version().unwrap(), 17);
576
576
}
577
577
578
578
#[test]
@@ -591,6 +591,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {
591
591
ALTER TABLE messages DROP COLUMN subject;
592
592
ALTER TABLE folders DROP COLUMN expanded;
593
593
DROP TABLE channel_tabs;
594
DROP TABLE agent_proposals;
594
595
ALTER TABLE channel_layout DROP COLUMN notification_level;
595
596
ALTER TABLE channel_layout DROP COLUMN include_replies;
596
597
PRAGMA user_version = 12",
@@ -841,7 +842,7 @@ fn migration_indexes_rows_that_predate_search() {
841
842
"DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
842
843
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
843
844
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
844
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;
845
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_proposals;
845
846
DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
846
847
ALTER TABLE messages DROP COLUMN sender_application_id;
847
848
ALTER TABLE messages DROP COLUMN links_json;
@@ -470,11 +470,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {470
let path = directory.path().join("nested").join("cache.sqlite3");470
let path = directory.path().join("nested").join("cache.sqlite3");471
{471
{472
let store = Store::open(&path).unwrap();472
let store = Store::open(&path).unwrap();473
assert_eq!(store.schema_version().unwrap(), 16);473
assert_eq!(store.schema_version().unwrap(), 17);474
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();474
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();475
}475
}476
let reopened = Store::open(&path).unwrap();476
let reopened = Store::open(&path).unwrap();477
assert_eq!(reopened.schema_version().unwrap(), 16);477
assert_eq!(reopened.schema_version().unwrap(), 17);478
assert_eq!(reopened.message_count("c").unwrap(), 1);478
assert_eq!(reopened.message_count("c").unwrap(), 1);479
drop(reopened);479
drop(reopened);480
let mode: String = rusqlite_open(&path)480
let mode: String = rusqlite_open(&path)@@ -503,10 +503,10 @@ fn old_schema_is_upgraded_in_place() {503
let path = directory.path().join("cache.sqlite3");503
let path = directory.path().join("cache.sqlite3");504
drop(Store::open(&path).unwrap());504
drop(Store::open(&path).unwrap());505
let connection = rusqlite_open(&path);505
let connection = rusqlite_open(&path);506
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();506
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();507
drop(connection);507
drop(connection);508
let store = Store::open(&path).unwrap();508
let store = Store::open(&path).unwrap();509
assert_eq!(store.schema_version().unwrap(), 16);509
assert_eq!(store.schema_version().unwrap(), 17);510
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();510
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();511
}511
}512
512
@@ -572,7 +572,7 @@ fn migration_to_v2_keeps_existing_sync_state() {572
let store = Store::open(&path).unwrap();572
let store = Store::open(&path).unwrap();573
let state = store.sync_state("c").unwrap().unwrap();573
let state = store.sync_state("c").unwrap().unwrap();574
assert_eq!(state.delta_link, None);574
assert_eq!(state.delta_link, None);575
assert_eq!(store.schema_version().unwrap(), 16);575
assert_eq!(store.schema_version().unwrap(), 17);576
}576
}577
577
578
#[test]578
#[test]@@ -591,6 +591,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {591
ALTER TABLE messages DROP COLUMN subject;591
ALTER TABLE messages DROP COLUMN subject;592
ALTER TABLE folders DROP COLUMN expanded;592
ALTER TABLE folders DROP COLUMN expanded;593
DROP TABLE channel_tabs;593
DROP TABLE channel_tabs;594
DROP TABLE agent_proposals;594
ALTER TABLE channel_layout DROP COLUMN notification_level;595
ALTER TABLE channel_layout DROP COLUMN notification_level;595
ALTER TABLE channel_layout DROP COLUMN include_replies;596
ALTER TABLE channel_layout DROP COLUMN include_replies;596
PRAGMA user_version = 12",597
PRAGMA user_version = 12",@@ -841,7 +842,7 @@ fn migration_indexes_rows_that_predate_search() {841
"DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;842
"DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;842
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;843
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;843
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;844
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;844
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;845
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_proposals;845
DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;846
DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;846
ALTER TABLE messages DROP COLUMN sender_application_id;847
ALTER TABLE messages DROP COLUMN sender_application_id;847
ALTER TABLE messages DROP COLUMN links_json;848
ALTER TABLE messages DROP COLUMN links_json;