BlueGit

ict rusty-teams

feat(agents): provider catalog, chat runs, and fork workflow docs

Extends agent settings and MCP/chat runs on the fork product line, and records the fork-vs-upstream remote rules for ongoing development.

metis Joachim Mild · pushed by metis

Authored 2026-11-11 · 2 weeks ago

Hash
870a0301ae898a808c221a21e0ca1d651022dd81
Parent
b07109fc
156 files changed +5676 −2379
.cursor/rules/fork-workflow.mdc added +38 −0
@@ -0,0 +1,38 @@
1 ---
2 description: Fork vs Upstream — wo entwickeln, PRs und eigene Releases
3 alwaysApply: true
4 ---
5
6 # Fork-Workflow (rusty-teams)
7
8 Dieses Repo ist Joes Fork-Arbeitskopie. Remotes und Rollen:
9
10 | Remote | Repo | Rolle |
11 |---|---|---|
12 | `fork` | `d0dg3r/rusty-teams` | Produktlinie — entwickeln, pushen, eigene Releases |
13 | `origin` | `danieldaeschle/rusty-teams` | Upstream — nur lesen + gezielt PRs |
14
15 ## Immer
16
17 - Alltagskomits und Feature-Branches nach **`fork`** pushen (`git push -u fork HEAD`), nie nach `origin`.
18 - Dauerhafte SoT auf dem Fork: Branch `main` (bzw. der aktuelle Integrationsbranch) auf `fork`.
19 - Upstream mitnehmen: `git fetch origin`, dann `merge`/`rebase` von `origin/main` in den Fork-Branch — Konflikte hier lösen.
20
21 ## PRs an Upstream
22
23 - Nur **kleine, thematische Scheiben**, abgezweigt vom aktuellen `origin/main`.
24 - Nicht den ganzen Fork-Stand (Agent-Providers, lokale Experimente, …) als einen PR schicken.
25 - PR-Quelle: Branch auf `fork` → Ziel `danieldaeschle/rusty-teams`.
26
27 ## Eigene Releases
28
29 - Tags und GitHub Releases auf **`fork`** (`d0dg3r/rusty-teams`).
30 - Tag-Namespace nicht mit Upstream kollidieren: `v0.3.0-joe.1` (oder klar eigener Major), nicht denselben `vX.Y.Z`-Inhalt wie Upstream vortäuschen.
31 - CI: Tag `v*` → `.github/workflows/build.yml` baut Assets und veröffentlicht das Release am Fork.
32 - Lokale Installation: Release-Binary → `/usr/local/bin/rusty-teams` (`teams` ist Symlink).
33
34 ## Nicht tun
35
36 - Alltagskomits auf `origin` pushen
37 - Riesen-PR mit vermischten Fork-Features an Daniel
38 - Upstream-Tag-Namen für abweichenden Fork-Inhalt wiederverwenden
@@ -0,0 +1,38 @@
1---
2description: Fork vs Upstream — wo entwickeln, PRs und eigene Releases
3alwaysApply: true
4---
5
6# Fork-Workflow (rusty-teams)
7
8Dieses Repo ist Joes Fork-Arbeitskopie. Remotes und Rollen:
9
10| Remote | Repo | Rolle |
11|---|---|---|
12| `fork` | `d0dg3r/rusty-teams` | Produktlinie — entwickeln, pushen, eigene Releases |
13| `origin` | `danieldaeschle/rusty-teams` | Upstream — nur lesen + gezielt PRs |
14
15## Immer
16
17- Alltagskomits und Feature-Branches nach **`fork`** pushen (`git push -u fork HEAD`), nie nach `origin`.
18- Dauerhafte SoT auf dem Fork: Branch `main` (bzw. der aktuelle Integrationsbranch) auf `fork`.
19- Upstream mitnehmen: `git fetch origin`, dann `merge`/`rebase` von `origin/main` in den Fork-Branch — Konflikte hier lösen.
20
21## PRs an Upstream
22
23- Nur **kleine, thematische Scheiben**, abgezweigt vom aktuellen `origin/main`.
24- Nicht den ganzen Fork-Stand (Agent-Providers, lokale Experimente, …) als einen PR schicken.
25- PR-Quelle: Branch auf `fork` → Ziel `danieldaeschle/rusty-teams`.
26
27## Eigene Releases
28
29- Tags und GitHub Releases auf **`fork`** (`d0dg3r/rusty-teams`).
30- Tag-Namespace nicht mit Upstream kollidieren: `v0.3.0-joe.1` (oder klar eigener Major), nicht denselben `vX.Y.Z`-Inhalt wie Upstream vortäuschen.
31- CI: Tag `v*` → `.github/workflows/build.yml` baut Assets und veröffentlicht das Release am Fork.
32- Lokale Installation: Release-Binary → `/usr/local/bin/rusty-teams` (`teams` ist Symlink).
33
34## Nicht tun
35
36- Alltagskomits auf `origin` pushen
37- Riesen-PR mit vermischten Fork-Features an Daniel
38- Upstream-Tag-Namen für abweichenden Fork-Inhalt wiederverwenden
AGENTS.md added +11 −0
@@ -0,0 +1,11 @@
1 # Agent notes — rusty-teams
2
3 ## Fork vs Upstream
4
5 Pflicht-Workflow (Cursor Rule `.cursor/rules/fork-workflow.mdc`, `alwaysApply`):
6
7 - **`fork`** (`d0dg3r/rusty-teams`) = entwickeln, pushen, eigene Releases
8 - **`origin`** (`danieldaeschle/rusty-teams`) = Upstream; nur fetch + gezielte kleine PRs
9 - Nie Alltagskomits nach `origin` pushen
10 - Upstream-PRs: frischer Branch von `origin/main`, eine Scheibe Thema
11 - Fork-Releases: Tags wie `v0.3.0-joe.1` auf `fork`, nicht Upstream-`vX.Y.Z` spiegeln wenn der Inhalt abweicht
@@ -0,0 +1,11 @@
1# Agent notes — rusty-teams
2
3## Fork vs Upstream
4
5Pflicht-Workflow (Cursor Rule `.cursor/rules/fork-workflow.mdc`, `alwaysApply`):
6
7- **`fork`** (`d0dg3r/rusty-teams`) = entwickeln, pushen, eigene Releases
8- **`origin`** (`danieldaeschle/rusty-teams`) = Upstream; nur fetch + gezielte kleine PRs
9- Nie Alltagskomits nach `origin` pushen
10- Upstream-PRs: frischer Branch von `origin/main`, eine Scheibe Thema
11- Fork-Releases: Tags wie `v0.3.0-joe.1` auf `fork`, nicht Upstream-`vX.Y.Z` spiegeln wenn der Inhalt abweicht
Cargo.lock +31 −18
@@ -111,8 +111,9 @@ dependencies = [
111 111
112 112 [[package]]
113 113 name = "agents"
114 version = "0.1.0"
114 version = "0.2.0"
115 115 dependencies = [
116 "reqwest 0.13.5",
116 117 "serde",
117 118 "serde_json",
118 119 "tempfile",
@@ -273,7 +274,7 @@ checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
273 274
274 275 [[package]]
275 276 name = "app"
276 version = "0.1.0"
277 version = "0.2.0"
277 278 dependencies = [
278 279 "agents",
279 280 "app-base",
@@ -305,7 +306,7 @@ dependencies = [
305 306
306 307 [[package]]
307 308 name = "app-base"
308 version = "0.1.0"
309 version = "0.2.0"
309 310 dependencies = [
310 311 "agents",
311 312 "calling",
@@ -327,6 +328,7 @@ dependencies = [
327 328 "session",
328 329 "sha2 0.10.9",
329 330 "store",
331 "sys-locale",
330 332 "teams-core",
331 333 "tempfile",
332 334 "tokio",
@@ -337,7 +339,7 @@ dependencies = [
337 339
338 340 [[package]]
339 341 name = "app-call-model"
340 version = "0.1.0"
342 version = "0.2.0"
341 343 dependencies = [
342 344 "agents",
343 345 "app-base",
@@ -363,7 +365,7 @@ dependencies = [
363 365
364 366 [[package]]
365 367 name = "app-state"
366 version = "0.1.0"
368 version = "0.2.0"
367 369 dependencies = [
368 370 "agents",
369 371 "app-base",
@@ -392,7 +394,7 @@ dependencies = [
392 394
393 395 [[package]]
394 396 name = "app-ui-kit"
395 version = "0.1.0"
397 version = "0.2.0"
396 398 dependencies = [
397 399 "app-base",
398 400 "gpui-kit",
@@ -1086,7 +1088,7 @@ dependencies = [
1086 1088
1087 1089 [[package]]
1088 1090 name = "browser"
1089 version = "0.1.0"
1091 version = "0.2.0"
1090 1092 dependencies = [
1091 1093 "directories",
1092 1094 "futures-util",
@@ -1195,7 +1197,7 @@ dependencies = [
1195 1197
1196 1198 [[package]]
1197 1199 name = "calling"
1198 version = "0.1.0"
1200 version = "0.2.0"
1199 1201 dependencies = [
1200 1202 "base64 0.22.1",
1201 1203 "chatsvc",
@@ -1361,12 +1363,13 @@ dependencies = [
1361 1363
1362 1364 [[package]]
1363 1365 name = "chatsvc"
1364 version = "0.1.0"
1366 version = "0.2.0"
1365 1367 dependencies = [
1366 1368 "base64 0.22.1",
1367 1369 "chrono",
1368 1370 "futures-util",
1369 1371 "percent-encoding",
1372 "reqwest 0.12.28",
1370 1373 "serde",
1371 1374 "serde_json",
1372 1375 "session",
@@ -1454,7 +1457,7 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
1454 1457
1455 1458 [[package]]
1456 1459 name = "cli"
1457 version = "0.1.0"
1460 version = "0.2.0"
1458 1461 dependencies = [
1459 1462 "chrono",
1460 1463 "clap",
@@ -4147,7 +4150,7 @@ dependencies = [
4147 4150
4148 4151 [[package]]
4149 4152 name = "graph"
4150 version = "0.1.0"
4153 version = "0.2.0"
4151 4154 dependencies = [
4152 4155 "base64 0.22.1",
4153 4156 "chrono",
@@ -4489,6 +4492,7 @@ dependencies = [
4489 4492 "tokio",
4490 4493 "tokio-rustls",
4491 4494 "tower-service",
4495 "webpki-roots",
4492 4496 ]
4493 4497
4494 4498 [[package]]
@@ -5188,8 +5192,6 @@ dependencies = [
5188 5192 [[package]]
5189 5193 name = "libwebrtc"
5190 5194 version = "0.3.51"
5191 source = "registry+https://github.com/rust-lang/crates.io-index"
5192 checksum = "14f9145a63a8439508a9b5b51dffa4b1c12f812f49fcc4310ebae3d467f639ab"
5193 5195 dependencies = [
5194 5196 "cxx",
5195 5197 "glib 0.21.5",
@@ -5493,7 +5495,7 @@ dependencies = [
5493 5495
5494 5496 [[package]]
5495 5497 name = "mcp"
5496 version = "0.1.0"
5498 version = "0.2.0"
5497 5499 dependencies = [
5498 5500 "axum",
5499 5501 "base64 0.22.1",
@@ -7674,6 +7676,7 @@ dependencies = [
7674 7676 "wasm-bindgen",
7675 7677 "wasm-bindgen-futures",
7676 7678 "web-sys",
7679 "webpki-roots",
7677 7680 ]
7678 7681
7679 7682 [[package]]
@@ -8474,9 +8477,12 @@ dependencies = [
8474 8477
8475 8478 [[package]]
8476 8479 name = "session"
8477 version = "0.1.0"
8480 version = "0.2.0"
8478 8481 dependencies = [
8482 "base64 0.22.1",
8479 8483 "futures-util",
8484 "reqwest 0.13.5",
8485 "rustls",
8480 8486 "serde",
8481 8487 "serde_json",
8482 8488 "thiserror 2.0.21",
@@ -8741,7 +8747,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
8741 8747
8742 8748 [[package]]
8743 8749 name = "store"
8744 version = "0.1.0"
8750 version = "0.2.0"
8745 8751 dependencies = [
8746 8752 "chrono",
8747 8753 "directories",
@@ -9188,12 +9194,13 @@ dependencies = [
9188 9194
9189 9195 [[package]]
9190 9196 name = "teams-core"
9191 version = "0.1.0"
9197 version = "0.2.0"
9192 9198 dependencies = [
9193 9199 "chatsvc",
9194 9200 "chrono",
9195 9201 "futures-util",
9196 9202 "graph",
9203 "iana-time-zone",
9197 9204 "percent-encoding",
9198 9205 "regex",
9199 9206 "scraper",
@@ -9442,7 +9449,11 @@ checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"
9442 9449 dependencies = [
9443 9450 "futures-util",
9444 9451 "log",
9452 "rustls",
9453 "rustls-native-certs",
9454 "rustls-pki-types",
9445 9455 "tokio",
9456 "tokio-rustls",
9446 9457 "tungstenite",
9447 9458 ]
9448 9459
@@ -9940,6 +9951,8 @@ dependencies = [
9940 9951 "httparse",
9941 9952 "log",
9942 9953 "rand 0.9.5",
9954 "rustls",
9955 "rustls-pki-types",
9943 9956 "sha1",
9944 9957 "thiserror 2.0.21",
9945 9958 "utf-8",
@@ -10576,7 +10589,7 @@ dependencies = [
10576 10589
10577 10590 [[package]]
10578 10591 name = "webview"
10579 version = "0.1.0"
10592 version = "0.2.0"
10580 10593 dependencies = [
10581 10594 "serde_json",
10582 10595 "session",
@@ -111,8 +111,9 @@ dependencies = [
111
111
112[[package]]
112[[package]]
113name = "agents"
113name = "agents"
114version = "0.1.0"
114version = "0.2.0"
115dependencies = [
115dependencies = [
116 "reqwest 0.13.5",
116 "serde",
117 "serde",
117 "serde_json",
118 "serde_json",
118 "tempfile",
119 "tempfile",
@@ -273,7 +274,7 @@ checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
273
274
274[[package]]
275[[package]]
275name = "app"
276name = "app"
276version = "0.1.0"
277version = "0.2.0"
277dependencies = [
278dependencies = [
278 "agents",
279 "agents",
279 "app-base",
280 "app-base",
@@ -305,7 +306,7 @@ dependencies = [
305
306
306[[package]]
307[[package]]
307name = "app-base"
308name = "app-base"
308version = "0.1.0"
309version = "0.2.0"
309dependencies = [
310dependencies = [
310 "agents",
311 "agents",
311 "calling",
312 "calling",
@@ -327,6 +328,7 @@ dependencies = [
327 "session",
328 "session",
328 "sha2 0.10.9",
329 "sha2 0.10.9",
329 "store",
330 "store",
331 "sys-locale",
330 "teams-core",
332 "teams-core",
331 "tempfile",
333 "tempfile",
332 "tokio",
334 "tokio",
@@ -337,7 +339,7 @@ dependencies = [
337
339
338[[package]]
340[[package]]
339name = "app-call-model"
341name = "app-call-model"
340version = "0.1.0"
342version = "0.2.0"
341dependencies = [
343dependencies = [
342 "agents",
344 "agents",
343 "app-base",
345 "app-base",
@@ -363,7 +365,7 @@ dependencies = [
363
365
364[[package]]
366[[package]]
365name = "app-state"
367name = "app-state"
366version = "0.1.0"
368version = "0.2.0"
367dependencies = [
369dependencies = [
368 "agents",
370 "agents",
369 "app-base",
371 "app-base",
@@ -392,7 +394,7 @@ dependencies = [
392
394
393[[package]]
395[[package]]
394name = "app-ui-kit"
396name = "app-ui-kit"
395version = "0.1.0"
397version = "0.2.0"
396dependencies = [
398dependencies = [
397 "app-base",
399 "app-base",
398 "gpui-kit",
400 "gpui-kit",
@@ -1086,7 +1088,7 @@ dependencies = [
1086
1088
1087[[package]]
1089[[package]]
1088name = "browser"
1090name = "browser"
1089version = "0.1.0"
1091version = "0.2.0"
1090dependencies = [
1092dependencies = [
1091 "directories",
1093 "directories",
1092 "futures-util",
1094 "futures-util",
@@ -1195,7 +1197,7 @@ dependencies = [
1195
1197
1196[[package]]
1198[[package]]
1197name = "calling"
1199name = "calling"
1198version = "0.1.0"
1200version = "0.2.0"
1199dependencies = [
1201dependencies = [
1200 "base64 0.22.1",
1202 "base64 0.22.1",
1201 "chatsvc",
1203 "chatsvc",
@@ -1361,12 +1363,13 @@ dependencies = [
1361
1363
1362[[package]]
1364[[package]]
1363name = "chatsvc"
1365name = "chatsvc"
1364version = "0.1.0"
1366version = "0.2.0"
1365dependencies = [
1367dependencies = [
1366 "base64 0.22.1",
1368 "base64 0.22.1",
1367 "chrono",
1369 "chrono",
1368 "futures-util",
1370 "futures-util",
1369 "percent-encoding",
1371 "percent-encoding",
1372 "reqwest 0.12.28",
1370 "serde",
1373 "serde",
1371 "serde_json",
1374 "serde_json",
1372 "session",
1375 "session",
@@ -1454,7 +1457,7 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
1454
1457
1455[[package]]
1458[[package]]
1456name = "cli"
1459name = "cli"
1457version = "0.1.0"
1460version = "0.2.0"
1458dependencies = [
1461dependencies = [
1459 "chrono",
1462 "chrono",
1460 "clap",
1463 "clap",
@@ -4147,7 +4150,7 @@ dependencies = [
4147
4150
4148[[package]]
4151[[package]]
4149name = "graph"
4152name = "graph"
4150version = "0.1.0"
4153version = "0.2.0"
4151dependencies = [
4154dependencies = [
4152 "base64 0.22.1",
4155 "base64 0.22.1",
4153 "chrono",
4156 "chrono",
@@ -4489,6 +4492,7 @@ dependencies = [
4489 "tokio",
4492 "tokio",
4490 "tokio-rustls",
4493 "tokio-rustls",
4491 "tower-service",
4494 "tower-service",
4495 "webpki-roots",
4492]
4496]
4493
4497
4494[[package]]
4498[[package]]
@@ -5188,8 +5192,6 @@ dependencies = [
5188[[package]]
5192[[package]]
5189name = "libwebrtc"
5193name = "libwebrtc"
5190version = "0.3.51"
5194version = "0.3.51"
5191source = "registry+https://github.com/rust-lang/crates.io-index"
5192checksum = "14f9145a63a8439508a9b5b51dffa4b1c12f812f49fcc4310ebae3d467f639ab"
5193dependencies = [
5195dependencies = [
5194 "cxx",
5196 "cxx",
5195 "glib 0.21.5",
5197 "glib 0.21.5",
@@ -5493,7 +5495,7 @@ dependencies = [
5493
5495
5494[[package]]
5496[[package]]
5495name = "mcp"
5497name = "mcp"
5496version = "0.1.0"
5498version = "0.2.0"
5497dependencies = [
5499dependencies = [
5498 "axum",
5500 "axum",
5499 "base64 0.22.1",
5501 "base64 0.22.1",
@@ -7674,6 +7676,7 @@ dependencies = [
7674 "wasm-bindgen",
7676 "wasm-bindgen",
7675 "wasm-bindgen-futures",
7677 "wasm-bindgen-futures",
7676 "web-sys",
7678 "web-sys",
7679 "webpki-roots",
7677]
7680]
7678
7681
7679[[package]]
7682[[package]]
@@ -8474,9 +8477,12 @@ dependencies = [
8474
8477
8475[[package]]
8478[[package]]
8476name = "session"
8479name = "session"
8477version = "0.1.0"
8480version = "0.2.0"
8478dependencies = [
8481dependencies = [
8482 "base64 0.22.1",
8479 "futures-util",
8483 "futures-util",
8484 "reqwest 0.13.5",
8485 "rustls",
8480 "serde",
8486 "serde",
8481 "serde_json",
8487 "serde_json",
8482 "thiserror 2.0.21",
8488 "thiserror 2.0.21",
@@ -8741,7 +8747,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
8741
8747
8742[[package]]
8748[[package]]
8743name = "store"
8749name = "store"
8744version = "0.1.0"
8750version = "0.2.0"
8745dependencies = [
8751dependencies = [
8746 "chrono",
8752 "chrono",
8747 "directories",
8753 "directories",
@@ -9188,12 +9194,13 @@ dependencies = [
9188
9194
9189[[package]]
9195[[package]]
9190name = "teams-core"
9196name = "teams-core"
9191version = "0.1.0"
9197version = "0.2.0"
9192dependencies = [
9198dependencies = [
9193 "chatsvc",
9199 "chatsvc",
9194 "chrono",
9200 "chrono",
9195 "futures-util",
9201 "futures-util",
9196 "graph",
9202 "graph",
9203 "iana-time-zone",
9197 "percent-encoding",
9204 "percent-encoding",
9198 "regex",
9205 "regex",
9199 "scraper",
9206 "scraper",
@@ -9442,7 +9449,11 @@ checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"
9442dependencies = [
9449dependencies = [
9443 "futures-util",
9450 "futures-util",
9444 "log",
9451 "log",
9452 "rustls",
9453 "rustls-native-certs",
9454 "rustls-pki-types",
9445 "tokio",
9455 "tokio",
9456 "tokio-rustls",
9446 "tungstenite",
9457 "tungstenite",
9447]
9458]
9448
9459
@@ -9940,6 +9951,8 @@ dependencies = [
9940 "httparse",
9951 "httparse",
9941 "log",
9952 "log",
9942 "rand 0.9.5",
9953 "rand 0.9.5",
9954 "rustls",
9955 "rustls-pki-types",
9943 "sha1",
9956 "sha1",
9944 "thiserror 2.0.21",
9957 "thiserror 2.0.21",
9945 "utf-8",
9958 "utf-8",
@@ -10576,7 +10589,7 @@ dependencies = [
10576
10589
10577[[package]]
10590[[package]]
10578name = "webview"
10591name = "webview"
10579version = "0.1.0"
10592version = "0.2.0"
10580dependencies = [
10593dependencies = [
10581 "serde_json",
10594 "serde_json",
10582 "session",
10595 "session",
crates/agents/Cargo.toml +1 −0
@@ -11,6 +11,7 @@ serde_json.workspace = true
11 11 thiserror.workspace = true
12 12 tokio.workspace = true
13 13 uuid.workspace = true
14 reqwest = { version = "0.13", default-features = false, features = ["rustls", "json"] }
14 15
15 16 [dev-dependencies]
16 17 tempfile.workspace = true
@@ -11,6 +11,7 @@ serde_json.workspace = true
11thiserror.workspace = true
11thiserror.workspace = true
12tokio.workspace = true
12tokio.workspace = true
13uuid.workspace = true
13uuid.workspace = true
14reqwest = { version = "0.13", default-features = false, features = ["rustls", "json"] }
14
15
15[dev-dependencies]
16[dev-dependencies]
16tempfile.workspace = true
17tempfile.workspace = true
crates/agents/src/catalog.rs added +171 −0
@@ -0,0 +1,171 @@
1 use std::path::{Path, PathBuf};
2
3 use crate::profile::{AgentProfile, Environment};
4
5 #[derive(Clone, Debug, PartialEq, Eq)]
6 pub struct CliHit {
7 pub profile: AgentProfile,
8 pub binary: PathBuf,
9 }
10
11 struct Template {
12 names: &'static [&'static str],
13 build: fn() -> AgentProfile,
14 cursor: bool,
15 }
16
17 pub fn scan_clis() -> Vec<CliHit> {
18 let templates = [
19 Template {
20 names: &["claude"],
21 build: AgentProfile::claude_host,
22 cursor: false,
23 },
24 Template {
25 names: &["copilot"],
26 build: AgentProfile::copilot_host,
27 cursor: false,
28 },
29 Template {
30 names: &["codex"],
31 build: AgentProfile::codex_host,
32 cursor: false,
33 },
34 Template {
35 names: &["cursor-agent", "agent"],
36 build: AgentProfile::cursor_host,
37 cursor: true,
38 },
39 Template {
40 names: &["agy"],
41 build: AgentProfile::agy_host,
42 cursor: false,
43 },
44 ];
45 templates
46 .into_iter()
47 .filter_map(|template| {
48 let binary = find_binary(template.names, template.cursor)?;
49 let program = binary
50 .file_name()
51 .and_then(|name| name.to_str())
52 .unwrap_or(template.names[0]);
53 let mut profile = with_program((template.build)(), program);
54 if !cfg!(windows) {
55 profile.open_session_command.clear();
56 }
57 profile.environment = Environment::Host;
58 Some(CliHit { profile, binary })
59 })
60 .collect()
61 }
62
63 /// A bare program name is looked up on `PATH` and in `~/.local/bin`.
64 /// A desktop session often omits the user bin directory, so `claude` and
65 /// `cursor-agent` exist for the shell but not for the app.
66 pub fn resolve_program(program: &str) -> Option<PathBuf> {
67 let path = Path::new(program);
68 if path.is_absolute() || program.contains('/') || program.contains('\\') {
69 return path.is_file().then(|| path.to_path_buf());
70 }
71 for directory in candidate_dirs() {
72 if let Some(found) = executable(&directory, program) {
73 return Some(found);
74 }
75 }
76 None
77 }
78
79 pub fn already_installed(existing: &[AgentProfile], hit: &AgentProfile) -> bool {
80 let program = hit.command_program();
81 existing.iter().any(|agent| {
82 agent.is_command()
83 && agent.environment == hit.environment
84 && agent.command_program() == program
85 })
86 }
87
88 fn with_program(mut profile: AgentProfile, program: &str) -> AgentProfile {
89 let rest = profile.command.split_once(' ').map(|(_, rest)| rest);
90 profile.command = match rest {
91 Some(rest) => format!("{program} {rest}"),
92 None => program.to_owned(),
93 };
94 profile
95 }
96
97 fn candidate_dirs() -> Vec<PathBuf> {
98 let mut dirs = Vec::new();
99 if let Some(path) = std::env::var_os("PATH") {
100 dirs.extend(std::env::split_paths(&path));
101 }
102 if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
103 let home = PathBuf::from(home);
104 dirs.push(home.join(".local").join("bin"));
105 }
106 dirs
107 }
108
109 fn find_binary(names: &[&str], cursor: bool) -> Option<PathBuf> {
110 for directory in candidate_dirs() {
111 for name in names {
112 if let Some(path) = executable(&directory, name) {
113 if cursor && *name == "agent" && !looks_like_cursor(&path) {
114 continue;
115 }
116 return Some(path);
117 }
118 }
119 }
120 None
121 }
122
123 fn executable(directory: &Path, name: &str) -> Option<PathBuf> {
124 ["", ".exe", ".cmd"].into_iter().find_map(|extension| {
125 let path = directory.join(format!("{name}{extension}"));
126 path.is_file().then_some(path)
127 })
128 }
129
130 fn looks_like_cursor(path: &Path) -> bool {
131 let linked = std::fs::read_link(path).unwrap_or_else(|_| path.to_path_buf());
132 let text = format!("{} {}", path.display(), linked.display());
133 text.contains("cursor-agent")
134 }
135
136 #[cfg(test)]
137 mod tests {
138 use super::*;
139
140 #[test]
141 fn a_wsl_claude_does_not_hide_the_host_binary() {
142 let wsl = AgentProfile::claude_wsl();
143 let host = AgentProfile::claude_host();
144 assert!(!already_installed(&[wsl], &host));
145 assert!(already_installed(&[host.clone()], &host));
146 }
147
148 #[test]
149 fn an_absolute_program_is_used_and_a_missing_name_is_not() {
150 let directory = std::env::temp_dir().join(format!("agents-resolve-{}", std::process::id()));
151 let _ = std::fs::remove_dir_all(&directory);
152 std::fs::create_dir_all(&directory).unwrap();
153 let binary = directory.join("claude");
154 std::fs::write(&binary, b"").unwrap();
155 assert_eq!(
156 resolve_program(binary.to_str().unwrap()).as_deref(),
157 Some(binary.as_path())
158 );
159 assert!(resolve_program("definitely-not-a-real-program").is_none());
160 let _ = std::fs::remove_dir_all(&directory);
161 }
162
163 #[test]
164 fn the_program_token_is_replaced_and_the_rest_stays() {
165 let profile = with_program(AgentProfile::cursor_host(), "cursor-agent");
166 assert_eq!(
167 profile.command,
168 "cursor-agent -p --trust --approve-mcps {prompt}"
169 );
170 }
171 }
@@ -0,0 +1,171 @@
1use std::path::{Path, PathBuf};
2
3use crate::profile::{AgentProfile, Environment};
4
5#[derive(Clone, Debug, PartialEq, Eq)]
6pub struct CliHit {
7 pub profile: AgentProfile,
8 pub binary: PathBuf,
9}
10
11struct Template {
12 names: &'static [&'static str],
13 build: fn() -> AgentProfile,
14 cursor: bool,
15}
16
17pub fn scan_clis() -> Vec<CliHit> {
18 let templates = [
19 Template {
20 names: &["claude"],
21 build: AgentProfile::claude_host,
22 cursor: false,
23 },
24 Template {
25 names: &["copilot"],
26 build: AgentProfile::copilot_host,
27 cursor: false,
28 },
29 Template {
30 names: &["codex"],
31 build: AgentProfile::codex_host,
32 cursor: false,
33 },
34 Template {
35 names: &["cursor-agent", "agent"],
36 build: AgentProfile::cursor_host,
37 cursor: true,
38 },
39 Template {
40 names: &["agy"],
41 build: AgentProfile::agy_host,
42 cursor: false,
43 },
44 ];
45 templates
46 .into_iter()
47 .filter_map(|template| {
48 let binary = find_binary(template.names, template.cursor)?;
49 let program = binary
50 .file_name()
51 .and_then(|name| name.to_str())
52 .unwrap_or(template.names[0]);
53 let mut profile = with_program((template.build)(), program);
54 if !cfg!(windows) {
55 profile.open_session_command.clear();
56 }
57 profile.environment = Environment::Host;
58 Some(CliHit { profile, binary })
59 })
60 .collect()
61}
62
63/// A bare program name is looked up on `PATH` and in `~/.local/bin`.
64/// A desktop session often omits the user bin directory, so `claude` and
65/// `cursor-agent` exist for the shell but not for the app.
66pub fn resolve_program(program: &str) -> Option<PathBuf> {
67 let path = Path::new(program);
68 if path.is_absolute() || program.contains('/') || program.contains('\\') {
69 return path.is_file().then(|| path.to_path_buf());
70 }
71 for directory in candidate_dirs() {
72 if let Some(found) = executable(&directory, program) {
73 return Some(found);
74 }
75 }
76 None
77}
78
79pub fn already_installed(existing: &[AgentProfile], hit: &AgentProfile) -> bool {
80 let program = hit.command_program();
81 existing.iter().any(|agent| {
82 agent.is_command()
83 && agent.environment == hit.environment
84 && agent.command_program() == program
85 })
86}
87
88fn with_program(mut profile: AgentProfile, program: &str) -> AgentProfile {
89 let rest = profile.command.split_once(' ').map(|(_, rest)| rest);
90 profile.command = match rest {
91 Some(rest) => format!("{program} {rest}"),
92 None => program.to_owned(),
93 };
94 profile
95}
96
97fn candidate_dirs() -> Vec<PathBuf> {
98 let mut dirs = Vec::new();
99 if let Some(path) = std::env::var_os("PATH") {
100 dirs.extend(std::env::split_paths(&path));
101 }
102 if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
103 let home = PathBuf::from(home);
104 dirs.push(home.join(".local").join("bin"));
105 }
106 dirs
107}
108
109fn find_binary(names: &[&str], cursor: bool) -> Option<PathBuf> {
110 for directory in candidate_dirs() {
111 for name in names {
112 if let Some(path) = executable(&directory, name) {
113 if cursor && *name == "agent" && !looks_like_cursor(&path) {
114 continue;
115 }
116 return Some(path);
117 }
118 }
119 }
120 None
121}
122
123fn executable(directory: &Path, name: &str) -> Option<PathBuf> {
124 ["", ".exe", ".cmd"].into_iter().find_map(|extension| {
125 let path = directory.join(format!("{name}{extension}"));
126 path.is_file().then_some(path)
127 })
128}
129
130fn looks_like_cursor(path: &Path) -> bool {
131 let linked = std::fs::read_link(path).unwrap_or_else(|_| path.to_path_buf());
132 let text = format!("{} {}", path.display(), linked.display());
133 text.contains("cursor-agent")
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139
140 #[test]
141 fn a_wsl_claude_does_not_hide_the_host_binary() {
142 let wsl = AgentProfile::claude_wsl();
143 let host = AgentProfile::claude_host();
144 assert!(!already_installed(&[wsl], &host));
145 assert!(already_installed(&[host.clone()], &host));
146 }
147
148 #[test]
149 fn an_absolute_program_is_used_and_a_missing_name_is_not() {
150 let directory = std::env::temp_dir().join(format!("agents-resolve-{}", std::process::id()));
151 let _ = std::fs::remove_dir_all(&directory);
152 std::fs::create_dir_all(&directory).unwrap();
153 let binary = directory.join("claude");
154 std::fs::write(&binary, b"").unwrap();
155 assert_eq!(
156 resolve_program(binary.to_str().unwrap()).as_deref(),
157 Some(binary.as_path())
158 );
159 assert!(resolve_program("definitely-not-a-real-program").is_none());
160 let _ = std::fs::remove_dir_all(&directory);
161 }
162
163 #[test]
164 fn the_program_token_is_replaced_and_the_rest_stays() {
165 let profile = with_program(AgentProfile::cursor_host(), "cursor-agent");
166 assert_eq!(
167 profile.command,
168 "cursor-agent -p --trust --approve-mcps {prompt}"
169 );
170 }
171}
crates/agents/src/chat.rs added +568 −0
@@ -0,0 +1,568 @@
1 use serde_json::{Value, json};
2
3 use crate::profile::{AgentBackend, AgentProfile};
4
5 const TURN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
6 const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
7 const ANTHROPIC_VERSION: &str = "2023-06-01";
8 const ANTHROPIC_URL: &str = "https://api.anthropic.com/v1/messages";
9 const MAX_TOKENS: u32 = 4096;
10
11 #[derive(Clone, Debug, PartialEq, Eq)]
12 pub struct ToolSpec {
13 pub name: String,
14 pub description: String,
15 pub parameters: Value,
16 }
17
18 #[derive(Clone, Debug, PartialEq, Eq)]
19 pub struct ToolCall {
20 pub id: String,
21 pub name: String,
22 pub arguments: String,
23 }
24
25 #[derive(Clone, Debug, PartialEq, Eq)]
26 pub enum ChatRole {
27 User,
28 Assistant,
29 Tool,
30 }
31
32 #[derive(Clone, Debug, PartialEq, Eq)]
33 pub struct ChatMessage {
34 pub role: ChatRole,
35 pub text: String,
36 pub tool_calls: Vec<ToolCall>,
37 pub tool_call_id: String,
38 }
39
40 impl ChatMessage {
41 pub fn user(text: impl Into<String>) -> Self {
42 Self {
43 role: ChatRole::User,
44 text: text.into(),
45 tool_calls: Vec::new(),
46 tool_call_id: String::new(),
47 }
48 }
49
50 pub fn assistant(text: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
51 Self {
52 role: ChatRole::Assistant,
53 text: text.into(),
54 tool_calls,
55 tool_call_id: String::new(),
56 }
57 }
58
59 pub fn tool(id: impl Into<String>, text: impl Into<String>) -> Self {
60 Self {
61 role: ChatRole::Tool,
62 text: text.into(),
63 tool_calls: Vec::new(),
64 tool_call_id: id.into(),
65 }
66 }
67 }
68
69 #[derive(Clone, Debug, PartialEq, Eq)]
70 pub enum ChatReply {
71 Text(String),
72 Tools { text: String, calls: Vec<ToolCall> },
73 }
74
75 pub async fn complete_text(
76 profile: &AgentProfile,
77 system: &str,
78 user: &str,
79 ) -> Result<String, String> {
80 match next_turn(profile, system, &[ChatMessage::user(user)], &[]).await? {
81 ChatReply::Text(text) => Ok(text),
82 ChatReply::Tools { text, .. } => Ok(text),
83 }
84 }
85
86 pub async fn next_turn(
87 profile: &AgentProfile,
88 system: &str,
89 messages: &[ChatMessage],
90 tools: &[ToolSpec],
91 ) -> Result<ChatReply, String> {
92 let body = match &profile.backend {
93 AgentBackend::OpenAi { .. } => openai_body(system, messages, tools),
94 AgentBackend::Anthropic { .. } => anthropic_body(profile, system, messages, tools)?,
95 AgentBackend::Command => return Err("this agent is a command, not a chat API".to_owned()),
96 };
97 let value = post(profile, &body).await?;
98 match &profile.backend {
99 AgentBackend::OpenAi { .. } => parse_openai(&value),
100 AgentBackend::Anthropic { .. } => parse_anthropic(&value),
101 AgentBackend::Command => unreachable!(),
102 }
103 }
104
105 const MODEL_LIST_LIMIT: usize = 400;
106
107 pub async fn list_models(profile: &AgentProfile) -> Result<Vec<String>, String> {
108 let (url, key, anthropic) = models_endpoint(profile)?;
109 let value = get(&key, &url, anthropic).await?;
110 let mut names = model_names(&value);
111 names.sort_by(|left, right| left.to_ascii_lowercase().cmp(&right.to_ascii_lowercase()));
112 names.dedup();
113 names.truncate(MODEL_LIST_LIMIT);
114 if names.is_empty() {
115 return Err("the endpoint listed no models".to_owned());
116 }
117 Ok(names)
118 }
119
120 pub async fn probe_backend(profile: &AgentProfile) -> Result<String, String> {
121 let names = list_models(profile).await?;
122 Ok(match names.len() {
123 1 => names[0].clone(),
124 2..=4 => names.join(", "),
125 count => format!("{count} models"),
126 })
127 }
128
129 fn models_endpoint(profile: &AgentProfile) -> Result<(String, String, bool), String> {
130 match &profile.backend {
131 AgentBackend::OpenAi {
132 base_url, api_key, ..
133 } => Ok((models_url(base_url), api_key.clone(), false)),
134 AgentBackend::Anthropic { api_key, .. } => {
135 if api_key.trim().is_empty() {
136 return Err("the Anthropic key is empty".to_owned());
137 }
138 Ok((
139 "https://api.anthropic.com/v1/models".to_owned(),
140 api_key.clone(),
141 true,
142 ))
143 }
144 AgentBackend::Command => Err("this agent is a command".to_owned()),
145 }
146 }
147
148 fn openai_body(system: &str, messages: &[ChatMessage], tools: &[ToolSpec]) -> Value {
149 let mut chat = Vec::new();
150 if !system.is_empty() {
151 chat.push(json!({"role": "system", "content": system}));
152 }
153 for message in messages {
154 match message.role {
155 ChatRole::User => chat.push(json!({"role": "user", "content": message.text})),
156 ChatRole::Tool => chat.push(json!({
157 "role": "tool",
158 "tool_call_id": message.tool_call_id,
159 "content": message.text,
160 })),
161 ChatRole::Assistant => {
162 let mut row = json!({"role": "assistant", "content": message.text});
163 if !message.tool_calls.is_empty() {
164 row["tool_calls"] = Value::Array(
165 message
166 .tool_calls
167 .iter()
168 .map(|call| {
169 json!({
170 "id": call.id,
171 "type": "function",
172 "function": { "name": call.name, "arguments": call.arguments },
173 })
174 })
175 .collect(),
176 );
177 }
178 chat.push(row);
179 }
180 }
181 }
182 let mut body = json!({"messages": chat, "stream": false});
183 if !tools.is_empty() {
184 body["tools"] = Value::Array(
185 tools
186 .iter()
187 .map(|tool| {
188 json!({
189 "type": "function",
190 "function": {
191 "name": tool.name,
192 "description": tool.description,
193 "parameters": tool.parameters,
194 }
195 })
196 })
197 .collect(),
198 );
199 }
200 body
201 }
202
203 fn anthropic_body(
204 profile: &AgentProfile,
205 system: &str,
206 messages: &[ChatMessage],
207 tools: &[ToolSpec],
208 ) -> Result<Value, String> {
209 let AgentBackend::Anthropic { model, .. } = &profile.backend else {
210 return Err("not an Anthropic profile".to_owned());
211 };
212 let mut chat = Vec::new();
213 for message in messages {
214 match message.role {
215 ChatRole::User => chat.push(json!({"role": "user", "content": message.text})),
216 ChatRole::Tool => chat.push(json!({
217 "role": "user",
218 "content": [{
219 "type": "tool_result",
220 "tool_use_id": message.tool_call_id,
221 "content": message.text,
222 }]
223 })),
224 ChatRole::Assistant => {
225 let mut content = Vec::new();
226 if !message.text.is_empty() {
227 content.push(json!({"type": "text", "text": message.text}));
228 }
229 for call in &message.tool_calls {
230 let input = serde_json::from_str::<Value>(&call.arguments)
231 .unwrap_or(Value::Object(Default::default()));
232 content.push(json!({
233 "type": "tool_use",
234 "id": call.id,
235 "name": call.name,
236 "input": input,
237 }));
238 }
239 chat.push(json!({"role": "assistant", "content": content}));
240 }
241 }
242 }
243 let mut body = json!({
244 "model": model,
245 "max_tokens": MAX_TOKENS,
246 "messages": chat,
247 });
248 if !system.is_empty() {
249 body["system"] = Value::String(system.to_owned());
250 }
251 if !tools.is_empty() {
252 body["tools"] = Value::Array(
253 tools
254 .iter()
255 .map(|tool| {
256 json!({
257 "name": tool.name,
258 "description": tool.description,
259 "input_schema": tool.parameters,
260 })
261 })
262 .collect(),
263 );
264 }
265 Ok(body)
266 }
267
268 fn chat_url(base_url: &str) -> String {
269 let base = base_url.trim().trim_end_matches('/');
270 if base.ends_with("/chat/completions") {
271 return base.to_owned();
272 }
273 // Ollama answers the OpenAI route only under /v1. The model list also
274 // accepts the bare port, so a base without /v1 still has to land there.
275 if base.contains(":11434") {
276 let origin = base.strip_suffix("/v1").unwrap_or(base);
277 return format!("{origin}/v1/chat/completions");
278 }
279 format!("{base}/chat/completions")
280 }
281
282 fn models_url(base_url: &str) -> String {
283 let base = base_url.trim().trim_end_matches('/');
284 if base.contains(":11434") {
285 let origin = base.trim_end_matches("/v1");
286 format!("{origin}/api/tags")
287 } else {
288 format!("{base}/models")
289 }
290 }
291
292 async fn post(profile: &AgentProfile, body: &Value) -> Result<Value, String> {
293 let (url, key, anthropic, model) = endpoint(profile)?;
294 let mut payload = body.clone();
295 if !anthropic {
296 payload["model"] = Value::String(model);
297 }
298 let client = client(TURN_TIMEOUT)?;
299 let mut request = client.post(url).json(&payload);
300 request = authorize(request, &key, anthropic);
301 read_json(request).await
302 }
303
304 async fn get(key: &str, url: &str, anthropic: bool) -> Result<Value, String> {
305 let client = client(PROBE_TIMEOUT)?;
306 let request = authorize(client.get(url), key, anthropic);
307 read_json(request).await
308 }
309
310 fn endpoint(profile: &AgentProfile) -> Result<(String, String, bool, String), String> {
311 match &profile.backend {
312 AgentBackend::OpenAi {
313 base_url,
314 model,
315 api_key,
316 } => {
317 if model.trim().is_empty() {
318 return Err("choose a model first".to_owned());
319 }
320 Ok((chat_url(base_url), api_key.clone(), false, model.clone()))
321 }
322 AgentBackend::Anthropic { model, api_key } => {
323 if api_key.trim().is_empty() {
324 return Err("the Anthropic key is empty".to_owned());
325 }
326 if model.trim().is_empty() {
327 return Err("choose a model first".to_owned());
328 }
329 Ok((
330 ANTHROPIC_URL.to_owned(),
331 api_key.clone(),
332 true,
333 model.clone(),
334 ))
335 }
336 AgentBackend::Command => Err("this agent is a command".to_owned()),
337 }
338 }
339
340 fn client(timeout: std::time::Duration) -> Result<reqwest::Client, String> {
341 reqwest::Client::builder()
342 .timeout(timeout)
343 .build()
344 .map_err(|error| error.to_string())
345 }
346
347 fn authorize(
348 request: reqwest::RequestBuilder,
349 key: &str,
350 anthropic: bool,
351 ) -> reqwest::RequestBuilder {
352 if anthropic {
353 return request
354 .header("x-api-key", key)
355 .header("anthropic-version", ANTHROPIC_VERSION);
356 }
357 if key.trim().is_empty() {
358 request
359 } else {
360 request.bearer_auth(key)
361 }
362 }
363
364 async fn read_json(request: reqwest::RequestBuilder) -> Result<Value, String> {
365 let response = request.send().await.map_err(|error| error.to_string())?;
366 let status = response.status();
367 let bytes = response.bytes().await.map_err(|error| error.to_string())?;
368 let value: Value = serde_json::from_slice(&bytes).map_err(|_| {
369 let body = String::from_utf8_lossy(&bytes);
370 let snippet: String = body.trim().chars().take(180).collect();
371 if snippet.is_empty() {
372 format!("HTTP {status} with an empty body")
373 } else {
374 format!("HTTP {status}: {snippet}")
375 }
376 })?;
377 if !status.is_success() {
378 return Err(api_error(&value).unwrap_or_else(|| format!("HTTP {status}")));
379 }
380 Ok(value)
381 }
382
383 fn api_error(value: &Value) -> Option<String> {
384 value["error"]["message"]
385 .as_str()
386 .or_else(|| value["error"].as_str())
387 .map(str::to_owned)
388 }
389
390 pub(crate) fn parse_openai(value: &Value) -> Result<ChatReply, String> {
391 if let Some(message) = api_error(value) {
392 return Err(message);
393 }
394 let message = &value["choices"][0]["message"];
395 let text = message["content"].as_str().unwrap_or("").trim().to_owned();
396 let calls = message["tool_calls"]
397 .as_array()
398 .map(|calls| {
399 calls
400 .iter()
401 .filter_map(|call| {
402 let name = call["function"]["name"].as_str()?;
403 let arguments = call["function"]["arguments"].as_str().unwrap_or("{}");
404 Some(ToolCall {
405 id: call["id"].as_str().unwrap_or(name).to_owned(),
406 name: name.to_owned(),
407 arguments: arguments.to_owned(),
408 })
409 })
410 .collect::<Vec<_>>()
411 })
412 .unwrap_or_default();
413 if calls.is_empty() {
414 if text.is_empty() {
415 return Err("the model returned an empty answer".to_owned());
416 }
417 Ok(ChatReply::Text(text))
418 } else {
419 Ok(ChatReply::Tools { text, calls })
420 }
421 }
422
423 pub(crate) fn parse_anthropic(value: &Value) -> Result<ChatReply, String> {
424 if let Some(message) = api_error(value) {
425 return Err(message);
426 }
427 let mut text = String::new();
428 let mut calls = Vec::new();
429 for block in value["content"].as_array().into_iter().flatten() {
430 match block["type"].as_str() {
431 Some("text") => {
432 if !text.is_empty() {
433 text.push('\n');
434 }
435 text.push_str(block["text"].as_str().unwrap_or(""));
436 }
437 Some("tool_use") => {
438 let name = block["name"].as_str().unwrap_or("");
439 if name.is_empty() {
440 continue;
441 }
442 let input = &block["input"];
443 calls.push(ToolCall {
444 id: block["id"].as_str().unwrap_or(name).to_owned(),
445 name: name.to_owned(),
446 arguments: input.to_string(),
447 });
448 }
449 _ => {}
450 }
451 }
452 let text = text.trim().to_owned();
453 if calls.is_empty() {
454 if text.is_empty() {
455 return Err("the model returned an empty answer".to_owned());
456 }
457 Ok(ChatReply::Text(text))
458 } else {
459 Ok(ChatReply::Tools { text, calls })
460 }
461 }
462
463 fn model_names(value: &Value) -> Vec<String> {
464 let list = value["models"]
465 .as_array()
466 .or_else(|| value["data"].as_array());
467 list.map(|models| {
468 models
469 .iter()
470 .filter_map(|model| {
471 model["name"]
472 .as_str()
473 .or_else(|| model["id"].as_str())
474 .map(str::to_owned)
475 })
476 .collect()
477 })
478 .unwrap_or_default()
479 }
480
481 #[cfg(test)]
482 mod tests {
483 use super::*;
484
485 #[test]
486 fn openai_text_and_tool_calls_parse() {
487 let text = parse_openai(&json!({
488 "choices": [{"message": {"content": " hello "}}]
489 }))
490 .unwrap();
491 assert_eq!(text, ChatReply::Text("hello".to_owned()));
492 let tools = parse_openai(&json!({
493 "choices": [{"message": {
494 "content": "",
495 "tool_calls": [{
496 "id": "c1",
497 "function": {"name": "propose_message", "arguments": "{\"text\":\"hi\"}"}
498 }]
499 }}]
500 }))
501 .unwrap();
502 assert_eq!(
503 tools,
504 ChatReply::Tools {
505 text: String::new(),
506 calls: vec![ToolCall {
507 id: "c1".to_owned(),
508 name: "propose_message".to_owned(),
509 arguments: "{\"text\":\"hi\"}".to_owned(),
510 }],
511 }
512 );
513 }
514
515 #[test]
516 fn anthropic_text_and_tool_use_parse() {
517 let text = parse_anthropic(&json!({
518 "content": [{"type": "text", "text": "done"}]
519 }))
520 .unwrap();
521 assert_eq!(text, ChatReply::Text("done".to_owned()));
522 let tools = parse_anthropic(&json!({
523 "content": [
524 {"type": "text", "text": "looking"},
525 {"type": "tool_use", "id": "t1", "name": "list_chats", "input": {"limit": 1}}
526 ]
527 }))
528 .unwrap();
529 match tools {
530 ChatReply::Tools { text, calls } => {
531 assert_eq!(text, "looking");
532 assert_eq!(calls[0].name, "list_chats");
533 assert_eq!(calls[0].arguments, "{\"limit\":1}");
534 }
535 other => panic!("{other:?}"),
536 }
537 }
538
539 #[test]
540 fn model_lists_keep_ollama_names_and_openai_ids() {
541 let ollama = model_names(&json!({
542 "models": [{"name": "llama3.2:latest"}, {"name": "qwen2.5:7b"}]
543 }));
544 assert_eq!(ollama, ["llama3.2:latest", "qwen2.5:7b"]);
545 let openai = model_names(&json!({"data": [{"id": "gpt-4o"}, {"id": "gpt-4o-mini"}]}));
546 assert_eq!(openai, ["gpt-4o", "gpt-4o-mini"]);
547 let many = model_names(&json!({
548 "data": (0..12).map(|index| json!({"id": format!("m{index}")})).collect::<Vec<_>>()
549 }));
550 assert_eq!(many.len(), 12);
551 }
552
553 #[test]
554 fn ollama_models_use_the_native_tags_path() {
555 assert_eq!(
556 models_url("http://127.0.0.1:11434/v1"),
557 "http://127.0.0.1:11434/api/tags"
558 );
559 assert_eq!(
560 chat_url("http://127.0.0.1:11434/v1"),
561 "http://127.0.0.1:11434/v1/chat/completions"
562 );
563 assert_eq!(
564 chat_url("http://mac-01.lan:11434"),
565 "http://mac-01.lan:11434/v1/chat/completions"
566 );
567 }
568 }
@@ -0,0 +1,568 @@
1use serde_json::{Value, json};
2
3use crate::profile::{AgentBackend, AgentProfile};
4
5const TURN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
6const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
7const ANTHROPIC_VERSION: &str = "2023-06-01";
8const ANTHROPIC_URL: &str = "https://api.anthropic.com/v1/messages";
9const MAX_TOKENS: u32 = 4096;
10
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct ToolSpec {
13 pub name: String,
14 pub description: String,
15 pub parameters: Value,
16}
17
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct ToolCall {
20 pub id: String,
21 pub name: String,
22 pub arguments: String,
23}
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum ChatRole {
27 User,
28 Assistant,
29 Tool,
30}
31
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct ChatMessage {
34 pub role: ChatRole,
35 pub text: String,
36 pub tool_calls: Vec<ToolCall>,
37 pub tool_call_id: String,
38}
39
40impl ChatMessage {
41 pub fn user(text: impl Into<String>) -> Self {
42 Self {
43 role: ChatRole::User,
44 text: text.into(),
45 tool_calls: Vec::new(),
46 tool_call_id: String::new(),
47 }
48 }
49
50 pub fn assistant(text: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
51 Self {
52 role: ChatRole::Assistant,
53 text: text.into(),
54 tool_calls,
55 tool_call_id: String::new(),
56 }
57 }
58
59 pub fn tool(id: impl Into<String>, text: impl Into<String>) -> Self {
60 Self {
61 role: ChatRole::Tool,
62 text: text.into(),
63 tool_calls: Vec::new(),
64 tool_call_id: id.into(),
65 }
66 }
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub enum ChatReply {
71 Text(String),
72 Tools { text: String, calls: Vec<ToolCall> },
73}
74
75pub async fn complete_text(
76 profile: &AgentProfile,
77 system: &str,
78 user: &str,
79) -> Result<String, String> {
80 match next_turn(profile, system, &[ChatMessage::user(user)], &[]).await? {
81 ChatReply::Text(text) => Ok(text),
82 ChatReply::Tools { text, .. } => Ok(text),
83 }
84}
85
86pub async fn next_turn(
87 profile: &AgentProfile,
88 system: &str,
89 messages: &[ChatMessage],
90 tools: &[ToolSpec],
91) -> Result<ChatReply, String> {
92 let body = match &profile.backend {
93 AgentBackend::OpenAi { .. } => openai_body(system, messages, tools),
94 AgentBackend::Anthropic { .. } => anthropic_body(profile, system, messages, tools)?,
95 AgentBackend::Command => return Err("this agent is a command, not a chat API".to_owned()),
96 };
97 let value = post(profile, &body).await?;
98 match &profile.backend {
99 AgentBackend::OpenAi { .. } => parse_openai(&value),
100 AgentBackend::Anthropic { .. } => parse_anthropic(&value),
101 AgentBackend::Command => unreachable!(),
102 }
103}
104
105const MODEL_LIST_LIMIT: usize = 400;
106
107pub async fn list_models(profile: &AgentProfile) -> Result<Vec<String>, String> {
108 let (url, key, anthropic) = models_endpoint(profile)?;
109 let value = get(&key, &url, anthropic).await?;
110 let mut names = model_names(&value);
111 names.sort_by(|left, right| left.to_ascii_lowercase().cmp(&right.to_ascii_lowercase()));
112 names.dedup();
113 names.truncate(MODEL_LIST_LIMIT);
114 if names.is_empty() {
115 return Err("the endpoint listed no models".to_owned());
116 }
117 Ok(names)
118}
119
120pub async fn probe_backend(profile: &AgentProfile) -> Result<String, String> {
121 let names = list_models(profile).await?;
122 Ok(match names.len() {
123 1 => names[0].clone(),
124 2..=4 => names.join(", "),
125 count => format!("{count} models"),
126 })
127}
128
129fn models_endpoint(profile: &AgentProfile) -> Result<(String, String, bool), String> {
130 match &profile.backend {
131 AgentBackend::OpenAi {
132 base_url, api_key, ..
133 } => Ok((models_url(base_url), api_key.clone(), false)),
134 AgentBackend::Anthropic { api_key, .. } => {
135 if api_key.trim().is_empty() {
136 return Err("the Anthropic key is empty".to_owned());
137 }
138 Ok((
139 "https://api.anthropic.com/v1/models".to_owned(),
140 api_key.clone(),
141 true,
142 ))
143 }
144 AgentBackend::Command => Err("this agent is a command".to_owned()),
145 }
146}
147
148fn openai_body(system: &str, messages: &[ChatMessage], tools: &[ToolSpec]) -> Value {
149 let mut chat = Vec::new();
150 if !system.is_empty() {
151 chat.push(json!({"role": "system", "content": system}));
152 }
153 for message in messages {
154 match message.role {
155 ChatRole::User => chat.push(json!({"role": "user", "content": message.text})),
156 ChatRole::Tool => chat.push(json!({
157 "role": "tool",
158 "tool_call_id": message.tool_call_id,
159 "content": message.text,
160 })),
161 ChatRole::Assistant => {
162 let mut row = json!({"role": "assistant", "content": message.text});
163 if !message.tool_calls.is_empty() {
164 row["tool_calls"] = Value::Array(
165 message
166 .tool_calls
167 .iter()
168 .map(|call| {
169 json!({
170 "id": call.id,
171 "type": "function",
172 "function": { "name": call.name, "arguments": call.arguments },
173 })
174 })
175 .collect(),
176 );
177 }
178 chat.push(row);
179 }
180 }
181 }
182 let mut body = json!({"messages": chat, "stream": false});
183 if !tools.is_empty() {
184 body["tools"] = Value::Array(
185 tools
186 .iter()
187 .map(|tool| {
188 json!({
189 "type": "function",
190 "function": {
191 "name": tool.name,
192 "description": tool.description,
193 "parameters": tool.parameters,
194 }
195 })
196 })
197 .collect(),
198 );
199 }
200 body
201}
202
203fn anthropic_body(
204 profile: &AgentProfile,
205 system: &str,
206 messages: &[ChatMessage],
207 tools: &[ToolSpec],
208) -> Result<Value, String> {
209 let AgentBackend::Anthropic { model, .. } = &profile.backend else {
210 return Err("not an Anthropic profile".to_owned());
211 };
212 let mut chat = Vec::new();
213 for message in messages {
214 match message.role {
215 ChatRole::User => chat.push(json!({"role": "user", "content": message.text})),
216 ChatRole::Tool => chat.push(json!({
217 "role": "user",
218 "content": [{
219 "type": "tool_result",
220 "tool_use_id": message.tool_call_id,
221 "content": message.text,
222 }]
223 })),
224 ChatRole::Assistant => {
225 let mut content = Vec::new();
226 if !message.text.is_empty() {
227 content.push(json!({"type": "text", "text": message.text}));
228 }
229 for call in &message.tool_calls {
230 let input = serde_json::from_str::<Value>(&call.arguments)
231 .unwrap_or(Value::Object(Default::default()));
232 content.push(json!({
233 "type": "tool_use",
234 "id": call.id,
235 "name": call.name,
236 "input": input,
237 }));
238 }
239 chat.push(json!({"role": "assistant", "content": content}));
240 }
241 }
242 }
243 let mut body = json!({
244 "model": model,
245 "max_tokens": MAX_TOKENS,
246 "messages": chat,
247 });
248 if !system.is_empty() {
249 body["system"] = Value::String(system.to_owned());
250 }
251 if !tools.is_empty() {
252 body["tools"] = Value::Array(
253 tools
254 .iter()
255 .map(|tool| {
256 json!({
257 "name": tool.name,
258 "description": tool.description,
259 "input_schema": tool.parameters,
260 })
261 })
262 .collect(),
263 );
264 }
265 Ok(body)
266}
267
268fn chat_url(base_url: &str) -> String {
269 let base = base_url.trim().trim_end_matches('/');
270 if base.ends_with("/chat/completions") {
271 return base.to_owned();
272 }
273 // Ollama answers the OpenAI route only under /v1. The model list also
274 // accepts the bare port, so a base without /v1 still has to land there.
275 if base.contains(":11434") {
276 let origin = base.strip_suffix("/v1").unwrap_or(base);
277 return format!("{origin}/v1/chat/completions");
278 }
279 format!("{base}/chat/completions")
280}
281
282fn models_url(base_url: &str) -> String {
283 let base = base_url.trim().trim_end_matches('/');
284 if base.contains(":11434") {
285 let origin = base.trim_end_matches("/v1");
286 format!("{origin}/api/tags")
287 } else {
288 format!("{base}/models")
289 }
290}
291
292async fn post(profile: &AgentProfile, body: &Value) -> Result<Value, String> {
293 let (url, key, anthropic, model) = endpoint(profile)?;
294 let mut payload = body.clone();
295 if !anthropic {
296 payload["model"] = Value::String(model);
297 }
298 let client = client(TURN_TIMEOUT)?;
299 let mut request = client.post(url).json(&payload);
300 request = authorize(request, &key, anthropic);
301 read_json(request).await
302}
303
304async fn get(key: &str, url: &str, anthropic: bool) -> Result<Value, String> {
305 let client = client(PROBE_TIMEOUT)?;
306 let request = authorize(client.get(url), key, anthropic);
307 read_json(request).await
308}
309
310fn endpoint(profile: &AgentProfile) -> Result<(String, String, bool, String), String> {
311 match &profile.backend {
312 AgentBackend::OpenAi {
313 base_url,
314 model,
315 api_key,
316 } => {
317 if model.trim().is_empty() {
318 return Err("choose a model first".to_owned());
319 }
320 Ok((chat_url(base_url), api_key.clone(), false, model.clone()))
321 }
322 AgentBackend::Anthropic { model, api_key } => {
323 if api_key.trim().is_empty() {
324 return Err("the Anthropic key is empty".to_owned());
325 }
326 if model.trim().is_empty() {
327 return Err("choose a model first".to_owned());
328 }
329 Ok((
330 ANTHROPIC_URL.to_owned(),
331 api_key.clone(),
332 true,
333 model.clone(),
334 ))
335 }
336 AgentBackend::Command => Err("this agent is a command".to_owned()),
337 }
338}
339
340fn client(timeout: std::time::Duration) -> Result<reqwest::Client, String> {
341 reqwest::Client::builder()
342 .timeout(timeout)
343 .build()
344 .map_err(|error| error.to_string())
345}
346
347fn authorize(
348 request: reqwest::RequestBuilder,
349 key: &str,
350 anthropic: bool,
351) -> reqwest::RequestBuilder {
352 if anthropic {
353 return request
354 .header("x-api-key", key)
355 .header("anthropic-version", ANTHROPIC_VERSION);
356 }
357 if key.trim().is_empty() {
358 request
359 } else {
360 request.bearer_auth(key)
361 }
362}
363
364async fn read_json(request: reqwest::RequestBuilder) -> Result<Value, String> {
365 let response = request.send().await.map_err(|error| error.to_string())?;
366 let status = response.status();
367 let bytes = response.bytes().await.map_err(|error| error.to_string())?;
368 let value: Value = serde_json::from_slice(&bytes).map_err(|_| {
369 let body = String::from_utf8_lossy(&bytes);
370 let snippet: String = body.trim().chars().take(180).collect();
371 if snippet.is_empty() {
372 format!("HTTP {status} with an empty body")
373 } else {
374 format!("HTTP {status}: {snippet}")
375 }
376 })?;
377 if !status.is_success() {
378 return Err(api_error(&value).unwrap_or_else(|| format!("HTTP {status}")));
379 }
380 Ok(value)
381}
382
383fn api_error(value: &Value) -> Option<String> {
384 value["error"]["message"]
385 .as_str()
386 .or_else(|| value["error"].as_str())
387 .map(str::to_owned)
388}
389
390pub(crate) fn parse_openai(value: &Value) -> Result<ChatReply, String> {
391 if let Some(message) = api_error(value) {
392 return Err(message);
393 }
394 let message = &value["choices"][0]["message"];
395 let text = message["content"].as_str().unwrap_or("").trim().to_owned();
396 let calls = message["tool_calls"]
397 .as_array()
398 .map(|calls| {
399 calls
400 .iter()
401 .filter_map(|call| {
402 let name = call["function"]["name"].as_str()?;
403 let arguments = call["function"]["arguments"].as_str().unwrap_or("{}");
404 Some(ToolCall {
405 id: call["id"].as_str().unwrap_or(name).to_owned(),
406 name: name.to_owned(),
407 arguments: arguments.to_owned(),
408 })
409 })
410 .collect::<Vec<_>>()
411 })
412 .unwrap_or_default();
413 if calls.is_empty() {
414 if text.is_empty() {
415 return Err("the model returned an empty answer".to_owned());
416 }
417 Ok(ChatReply::Text(text))
418 } else {
419 Ok(ChatReply::Tools { text, calls })
420 }
421}
422
423pub(crate) fn parse_anthropic(value: &Value) -> Result<ChatReply, String> {
424 if let Some(message) = api_error(value) {
425 return Err(message);
426 }
427 let mut text = String::new();
428 let mut calls = Vec::new();
429 for block in value["content"].as_array().into_iter().flatten() {
430 match block["type"].as_str() {
431 Some("text") => {
432 if !text.is_empty() {
433 text.push('\n');
434 }
435 text.push_str(block["text"].as_str().unwrap_or(""));
436 }
437 Some("tool_use") => {
438 let name = block["name"].as_str().unwrap_or("");
439 if name.is_empty() {
440 continue;
441 }
442 let input = &block["input"];
443 calls.push(ToolCall {
444 id: block["id"].as_str().unwrap_or(name).to_owned(),
445 name: name.to_owned(),
446 arguments: input.to_string(),
447 });
448 }
449 _ => {}
450 }
451 }
452 let text = text.trim().to_owned();
453 if calls.is_empty() {
454 if text.is_empty() {
455 return Err("the model returned an empty answer".to_owned());
456 }
457 Ok(ChatReply::Text(text))
458 } else {
459 Ok(ChatReply::Tools { text, calls })
460 }
461}
462
463fn model_names(value: &Value) -> Vec<String> {
464 let list = value["models"]
465 .as_array()
466 .or_else(|| value["data"].as_array());
467 list.map(|models| {
468 models
469 .iter()
470 .filter_map(|model| {
471 model["name"]
472 .as_str()
473 .or_else(|| model["id"].as_str())
474 .map(str::to_owned)
475 })
476 .collect()
477 })
478 .unwrap_or_default()
479}
480
481#[cfg(test)]
482mod tests {
483 use super::*;
484
485 #[test]
486 fn openai_text_and_tool_calls_parse() {
487 let text = parse_openai(&json!({
488 "choices": [{"message": {"content": " hello "}}]
489 }))
490 .unwrap();
491 assert_eq!(text, ChatReply::Text("hello".to_owned()));
492 let tools = parse_openai(&json!({
493 "choices": [{"message": {
494 "content": "",
495 "tool_calls": [{
496 "id": "c1",
497 "function": {"name": "propose_message", "arguments": "{\"text\":\"hi\"}"}
498 }]
499 }}]
500 }))
501 .unwrap();
502 assert_eq!(
503 tools,
504 ChatReply::Tools {
505 text: String::new(),
506 calls: vec![ToolCall {
507 id: "c1".to_owned(),
508 name: "propose_message".to_owned(),
509 arguments: "{\"text\":\"hi\"}".to_owned(),
510 }],
511 }
512 );
513 }
514
515 #[test]
516 fn anthropic_text_and_tool_use_parse() {
517 let text = parse_anthropic(&json!({
518 "content": [{"type": "text", "text": "done"}]
519 }))
520 .unwrap();
521 assert_eq!(text, ChatReply::Text("done".to_owned()));
522 let tools = parse_anthropic(&json!({
523 "content": [
524 {"type": "text", "text": "looking"},
525 {"type": "tool_use", "id": "t1", "name": "list_chats", "input": {"limit": 1}}
526 ]
527 }))
528 .unwrap();
529 match tools {
530 ChatReply::Tools { text, calls } => {
531 assert_eq!(text, "looking");
532 assert_eq!(calls[0].name, "list_chats");
533 assert_eq!(calls[0].arguments, "{\"limit\":1}");
534 }
535 other => panic!("{other:?}"),
536 }
537 }
538
539 #[test]
540 fn model_lists_keep_ollama_names_and_openai_ids() {
541 let ollama = model_names(&json!({
542 "models": [{"name": "llama3.2:latest"}, {"name": "qwen2.5:7b"}]
543 }));
544 assert_eq!(ollama, ["llama3.2:latest", "qwen2.5:7b"]);
545 let openai = model_names(&json!({"data": [{"id": "gpt-4o"}, {"id": "gpt-4o-mini"}]}));
546 assert_eq!(openai, ["gpt-4o", "gpt-4o-mini"]);
547 let many = model_names(&json!({
548 "data": (0..12).map(|index| json!({"id": format!("m{index}")})).collect::<Vec<_>>()
549 }));
550 assert_eq!(many.len(), 12);
551 }
552
553 #[test]
554 fn ollama_models_use_the_native_tags_path() {
555 assert_eq!(
556 models_url("http://127.0.0.1:11434/v1"),
557 "http://127.0.0.1:11434/api/tags"
558 );
559 assert_eq!(
560 chat_url("http://127.0.0.1:11434/v1"),
561 "http://127.0.0.1:11434/v1/chat/completions"
562 );
563 assert_eq!(
564 chat_url("http://mac-01.lan:11434"),
565 "http://mac-01.lan:11434/v1/chat/completions"
566 );
567 }
568}
crates/agents/src/invocation.rs +1 −1
@@ -287,7 +287,7 @@ pub fn kill_process_invocation(process_id: u32, session_id: &str) -> Option<Invo
287 287 }
288 288
289 289 pub fn supports_resume(profile: &AgentProfile) -> bool {
290 profile.command.contains(SESSION_FLAG)
290 profile.is_command() && profile.command.contains(SESSION_FLAG)
291 291 }
292 292
293 293 pub fn resume_invocation(
@@ -287,7 +287,7 @@ pub fn kill_process_invocation(process_id: u32, session_id: &str) -> Option<Invo
287}
287}
288
288
289pub fn supports_resume(profile: &AgentProfile) -> bool {
289pub fn supports_resume(profile: &AgentProfile) -> bool {
290 profile.command.contains(SESSION_FLAG)
290 profile.is_command() && profile.command.contains(SESSION_FLAG)
291}
291}
292
292
293pub fn resume_invocation(
293pub fn resume_invocation(
crates/agents/src/lib.rs +8 −1
@@ -1,4 +1,6 @@
1 1 mod action;
2 mod catalog;
3 mod chat;
2 4 mod context;
3 5 mod desktop_sessions;
4 6 mod inbox;
@@ -11,6 +13,11 @@ mod settings;
11 13 mod template;
12 14
13 15 pub use action::AgentAction;
16 pub use catalog::{CliHit, already_installed, resolve_program, scan_clis};
17 pub use chat::{
18 ChatMessage, ChatReply, ToolCall, ToolSpec, complete_text, list_models, next_turn,
19 probe_backend,
20 };
14 21 pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};
15 22 pub use desktop_sessions::{DesktopSession, desktop_sessions};
16 23 pub use inbox::{DeliveryError, deliver, inbox_frame};
@@ -20,7 +27,7 @@ pub use invocation::{
20 27 version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,
21 28 };
22 29 pub use parse::{OutputParser, RunEvent, parse_line};
23 pub use profile::{AgentProfile, Environment, OutputFormat};
30 pub use profile::{AgentBackend, AgentProfile, Environment, OutputFormat};
24 31 pub use runner::{
25 32 RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,
26 33 };
@@ -1,4 +1,6 @@
1mod action;
1mod action;
2mod catalog;
3mod chat;
2mod context;
4mod context;
3mod desktop_sessions;
5mod desktop_sessions;
4mod inbox;
6mod inbox;
@@ -11,6 +13,11 @@ mod settings;
11mod template;
13mod template;
12
14
13pub use action::AgentAction;
15pub use action::AgentAction;
16pub use catalog::{CliHit, already_installed, resolve_program, scan_clis};
17pub use chat::{
18 ChatMessage, ChatReply, ToolCall, ToolSpec, complete_text, list_models, next_turn,
19 probe_backend,
20};
14pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};
21pub use context::{MessageContext, ThreadMessage, build_prompt, build_session_prompt};
15pub use desktop_sessions::{DesktopSession, desktop_sessions};
22pub use desktop_sessions::{DesktopSession, desktop_sessions};
16pub use inbox::{DeliveryError, deliver, inbox_frame};
23pub use inbox::{DeliveryError, deliver, inbox_frame};
@@ -20,7 +27,7 @@ pub use invocation::{
20 version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,
27 version_check_invocation, wsl_path, wsl_stop_invocation, wsl_unc_distro,
21};
28};
22pub use parse::{OutputParser, RunEvent, parse_line};
29pub use parse::{OutputParser, RunEvent, parse_line};
23pub use profile::{AgentProfile, Environment, OutputFormat};
30pub use profile::{AgentBackend, AgentProfile, Environment, OutputFormat};
24pub use runner::{
31pub use runner::{
25 RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,
32 RunOutcome, RunStatus, RunUpdate, probe, run, run_stop_invocation, run_stop_invocation_within,
26};
33};
crates/agents/src/profile.rs +156 −0
@@ -29,6 +29,25 @@ pub enum OutputFormat {
29 29 Text,
30 30 }
31 31
32 /// Where a run is answered. Missing JSON stays a command, so older settings keep working.
33 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
34 #[serde(tag = "type", rename_all = "snake_case")]
35 pub enum AgentBackend {
36 #[default]
37 Command,
38 OpenAi {
39 base_url: String,
40 model: String,
41 #[serde(default)]
42 api_key: String,
43 },
44 Anthropic {
45 model: String,
46 #[serde(default)]
47 api_key: String,
48 },
49 }
50
32 51 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
33 52 #[serde(default)]
34 53 pub struct AgentProfile {
@@ -39,9 +58,38 @@ pub struct AgentProfile {
39 58 pub output: OutputFormat,
40 59 pub open_session_command: String,
41 60 pub mcp_config_flag: String,
61 pub backend: AgentBackend,
42 62 }
43 63
44 64 impl AgentProfile {
65 pub fn is_command(&self) -> bool {
66 matches!(self.backend, AgentBackend::Command)
67 }
68
69 pub fn is_chat(&self) -> bool {
70 !self.is_command()
71 }
72
73 pub fn backend_label(&self) -> String {
74 match &self.backend {
75 AgentBackend::Command => String::new(),
76 AgentBackend::OpenAi {
77 base_url, model, ..
78 } => {
79 let model = if model.is_empty() { "no model" } else { model };
80 format!("{model} · {base_url}")
81 }
82 AgentBackend::Anthropic { model, .. } => {
83 let model = if model.is_empty() { "no model" } else { model };
84 format!("Anthropic · {model}")
85 }
86 }
87 }
88
89 pub fn command_program(&self) -> &str {
90 self.command.split_whitespace().next().unwrap_or("")
91 }
92
45 93 pub(crate) fn migrate_open_session_command(&mut self) {
46 94 let replacement = match self.open_session_command.as_str() {
47 95 LEGACY_CLAUDE_WSL_OPEN_SESSION => CLAUDE_WSL_OPEN_SESSION,
@@ -60,6 +108,7 @@ impl AgentProfile {
60 108 output: OutputFormat::ClaudeStreamJson,
61 109 open_session_command: CLAUDE_WSL_OPEN_SESSION.to_string(),
62 110 mcp_config_flag: "--mcp-config".to_string(),
111 backend: AgentBackend::Command,
63 112 }
64 113 }
65 114
@@ -72,6 +121,112 @@ impl AgentProfile {
72 121 output: OutputFormat::ClaudeStreamJson,
73 122 open_session_command: "wt.exe -d {cwd} claude --resume {session_id}".to_string(),
74 123 mcp_config_flag: "--mcp-config".to_string(),
124 backend: AgentBackend::Command,
125 }
126 }
127
128 pub fn copilot_host() -> Self {
129 Self {
130 id: "copilot-host".to_string(),
131 name: "Copilot CLI".to_string(),
132 environment: Environment::Host,
133 command: COPILOT_COMMAND.to_string(),
134 output: OutputFormat::CopilotJsonl,
135 open_session_command: "wt.exe -d {cwd} copilot --resume {session_id}".to_string(),
136 mcp_config_flag: "--additional-mcp-config".to_string(),
137 backend: AgentBackend::Command,
138 }
139 }
140
141 pub fn codex_host() -> Self {
142 Self {
143 id: "codex".to_string(),
144 name: "Codex CLI".to_string(),
145 environment: Environment::Host,
146 command: "codex exec --skip-git-repo-check {prompt}".to_string(),
147 output: OutputFormat::Text,
148 ..Self::default()
149 }
150 }
151
152 pub fn cursor_host() -> Self {
153 Self {
154 id: "cursor".to_string(),
155 name: "Cursor CLI".to_string(),
156 environment: Environment::Host,
157 command: "agent -p --trust --approve-mcps {prompt}".to_string(),
158 output: OutputFormat::Text,
159 ..Self::default()
160 }
161 }
162
163 pub fn agy_host() -> Self {
164 Self {
165 id: "agy".to_string(),
166 name: "Antigravity CLI".to_string(),
167 environment: Environment::Host,
168 command: "agy -p {prompt}".to_string(),
169 output: OutputFormat::Text,
170 ..Self::default()
171 }
172 }
173
174 pub fn ollama() -> Self {
175 Self::open_ai("ollama", "Ollama", "http://127.0.0.1:11434/v1", "", "")
176 }
177
178 pub fn openai() -> Self {
179 Self::open_ai(
180 "openai",
181 "OpenAI",
182 "https://api.openai.com/v1",
183 "gpt-4o",
184 "",
185 )
186 }
187
188 pub fn openrouter() -> Self {
189 Self::open_ai(
190 "openrouter",
191 "OpenRouter",
192 "https://openrouter.ai/api/v1",
193 "openrouter/auto",
194 "",
195 )
196 }
197
198 pub fn openai_compatible() -> Self {
199 Self::open_ai(
200 "openai-compatible",
201 "OpenAI-compatible",
202 "http://127.0.0.1:8080/v1",
203 "",
204 "",
205 )
206 }
207
208 pub fn anthropic() -> Self {
209 Self {
210 id: "anthropic".to_string(),
211 name: "Anthropic".to_string(),
212 backend: AgentBackend::Anthropic {
213 model: "claude-sonnet-4-5".to_string(),
214 api_key: String::new(),
215 },
216 ..Self::default()
217 }
218 }
219
220 fn open_ai(id: &str, name: &str, base_url: &str, model: &str, api_key: &str) -> Self {
221 Self {
222 id: id.to_string(),
223 name: name.to_string(),
224 backend: AgentBackend::OpenAi {
225 base_url: base_url.to_string(),
226 model: model.to_string(),
227 api_key: api_key.to_string(),
228 },
229 ..Self::default()
75 230 }
76 231 }
77 232
@@ -84,6 +239,7 @@ impl AgentProfile {
84 239 output: OutputFormat::CopilotJsonl,
85 240 open_session_command: COPILOT_WSL_OPEN_SESSION.to_string(),
86 241 mcp_config_flag: "--additional-mcp-config".to_string(),
242 backend: AgentBackend::Command,
87 243 }
88 244 }
89 245 }
@@ -29,6 +29,25 @@ pub enum OutputFormat {
29 Text,
29 Text,
30}
30}
31
31
32/// Where a run is answered. Missing JSON stays a command, so older settings keep working.
33#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(tag = "type", rename_all = "snake_case")]
35pub enum AgentBackend {
36 #[default]
37 Command,
38 OpenAi {
39 base_url: String,
40 model: String,
41 #[serde(default)]
42 api_key: String,
43 },
44 Anthropic {
45 model: String,
46 #[serde(default)]
47 api_key: String,
48 },
49}
50
32#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
51#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(default)]
52#[serde(default)]
34pub struct AgentProfile {
53pub struct AgentProfile {
@@ -39,9 +58,38 @@ pub struct AgentProfile {
39 pub output: OutputFormat,
58 pub output: OutputFormat,
40 pub open_session_command: String,
59 pub open_session_command: String,
41 pub mcp_config_flag: String,
60 pub mcp_config_flag: String,
61 pub backend: AgentBackend,
42}
62}
43
63
44impl AgentProfile {
64impl AgentProfile {
65 pub fn is_command(&self) -> bool {
66 matches!(self.backend, AgentBackend::Command)
67 }
68
69 pub fn is_chat(&self) -> bool {
70 !self.is_command()
71 }
72
73 pub fn backend_label(&self) -> String {
74 match &self.backend {
75 AgentBackend::Command => String::new(),
76 AgentBackend::OpenAi {
77 base_url, model, ..
78 } => {
79 let model = if model.is_empty() { "no model" } else { model };
80 format!("{model} · {base_url}")
81 }
82 AgentBackend::Anthropic { model, .. } => {
83 let model = if model.is_empty() { "no model" } else { model };
84 format!("Anthropic · {model}")
85 }
86 }
87 }
88
89 pub fn command_program(&self) -> &str {
90 self.command.split_whitespace().next().unwrap_or("")
91 }
92
45 pub(crate) fn migrate_open_session_command(&mut self) {
93 pub(crate) fn migrate_open_session_command(&mut self) {
46 let replacement = match self.open_session_command.as_str() {
94 let replacement = match self.open_session_command.as_str() {
47 LEGACY_CLAUDE_WSL_OPEN_SESSION => CLAUDE_WSL_OPEN_SESSION,
95 LEGACY_CLAUDE_WSL_OPEN_SESSION => CLAUDE_WSL_OPEN_SESSION,
@@ -60,6 +108,7 @@ impl AgentProfile {
60 output: OutputFormat::ClaudeStreamJson,
108 output: OutputFormat::ClaudeStreamJson,
61 open_session_command: CLAUDE_WSL_OPEN_SESSION.to_string(),
109 open_session_command: CLAUDE_WSL_OPEN_SESSION.to_string(),
62 mcp_config_flag: "--mcp-config".to_string(),
110 mcp_config_flag: "--mcp-config".to_string(),
111 backend: AgentBackend::Command,
63 }
112 }
64 }
113 }
65
114
@@ -72,6 +121,112 @@ impl AgentProfile {
72 output: OutputFormat::ClaudeStreamJson,
121 output: OutputFormat::ClaudeStreamJson,
73 open_session_command: "wt.exe -d {cwd} claude --resume {session_id}".to_string(),
122 open_session_command: "wt.exe -d {cwd} claude --resume {session_id}".to_string(),
74 mcp_config_flag: "--mcp-config".to_string(),
123 mcp_config_flag: "--mcp-config".to_string(),
124 backend: AgentBackend::Command,
125 }
126 }
127
128 pub fn copilot_host() -> Self {
129 Self {
130 id: "copilot-host".to_string(),
131 name: "Copilot CLI".to_string(),
132 environment: Environment::Host,
133 command: COPILOT_COMMAND.to_string(),
134 output: OutputFormat::CopilotJsonl,
135 open_session_command: "wt.exe -d {cwd} copilot --resume {session_id}".to_string(),
136 mcp_config_flag: "--additional-mcp-config".to_string(),
137 backend: AgentBackend::Command,
138 }
139 }
140
141 pub fn codex_host() -> Self {
142 Self {
143 id: "codex".to_string(),
144 name: "Codex CLI".to_string(),
145 environment: Environment::Host,
146 command: "codex exec --skip-git-repo-check {prompt}".to_string(),
147 output: OutputFormat::Text,
148 ..Self::default()
149 }
150 }
151
152 pub fn cursor_host() -> Self {
153 Self {
154 id: "cursor".to_string(),
155 name: "Cursor CLI".to_string(),
156 environment: Environment::Host,
157 command: "agent -p --trust --approve-mcps {prompt}".to_string(),
158 output: OutputFormat::Text,
159 ..Self::default()
160 }
161 }
162
163 pub fn agy_host() -> Self {
164 Self {
165 id: "agy".to_string(),
166 name: "Antigravity CLI".to_string(),
167 environment: Environment::Host,
168 command: "agy -p {prompt}".to_string(),
169 output: OutputFormat::Text,
170 ..Self::default()
171 }
172 }
173
174 pub fn ollama() -> Self {
175 Self::open_ai("ollama", "Ollama", "http://127.0.0.1:11434/v1", "", "")
176 }
177
178 pub fn openai() -> Self {
179 Self::open_ai(
180 "openai",
181 "OpenAI",
182 "https://api.openai.com/v1",
183 "gpt-4o",
184 "",
185 )
186 }
187
188 pub fn openrouter() -> Self {
189 Self::open_ai(
190 "openrouter",
191 "OpenRouter",
192 "https://openrouter.ai/api/v1",
193 "openrouter/auto",
194 "",
195 )
196 }
197
198 pub fn openai_compatible() -> Self {
199 Self::open_ai(
200 "openai-compatible",
201 "OpenAI-compatible",
202 "http://127.0.0.1:8080/v1",
203 "",
204 "",
205 )
206 }
207
208 pub fn anthropic() -> Self {
209 Self {
210 id: "anthropic".to_string(),
211 name: "Anthropic".to_string(),
212 backend: AgentBackend::Anthropic {
213 model: "claude-sonnet-4-5".to_string(),
214 api_key: String::new(),
215 },
216 ..Self::default()
217 }
218 }
219
220 fn open_ai(id: &str, name: &str, base_url: &str, model: &str, api_key: &str) -> Self {
221 Self {
222 id: id.to_string(),
223 name: name.to_string(),
224 backend: AgentBackend::OpenAi {
225 base_url: base_url.to_string(),
226 model: model.to_string(),
227 api_key: api_key.to_string(),
228 },
229 ..Self::default()
75 }
230 }
76 }
231 }
77
232
@@ -84,6 +239,7 @@ impl AgentProfile {
84 output: OutputFormat::CopilotJsonl,
239 output: OutputFormat::CopilotJsonl,
85 open_session_command: COPILOT_WSL_OPEN_SESSION.to_string(),
240 open_session_command: COPILOT_WSL_OPEN_SESSION.to_string(),
86 mcp_config_flag: "--additional-mcp-config".to_string(),
241 mcp_config_flag: "--additional-mcp-config".to_string(),
242 backend: AgentBackend::Command,
87 }
243 }
88 }
244 }
89}
245}
crates/agents/src/runner.rs +22 −1
@@ -1,4 +1,5 @@
1 1 use std::collections::VecDeque;
2 use std::path::PathBuf;
2 3 use std::process::Stdio;
3 4 use std::sync::{Arc, Mutex};
4 5
@@ -40,17 +41,37 @@ pub struct RunOutcome {
40 41 }
41 42
42 43 fn command_for(invocation: &Invocation) -> Command {
43 let mut command = Command::new(&invocation.program);
44 let program = crate::catalog::resolve_program(&invocation.program)
45 .unwrap_or_else(|| PathBuf::from(&invocation.program));
46 let mut command = Command::new(program);
44 47 command.args(&invocation.args);
45 48 if let Some(cwd) = &invocation.cwd {
46 49 command.current_dir(cwd);
47 50 }
51 prepend_user_bin(&mut command);
48 52 command.kill_on_drop(true);
49 53 #[cfg(windows)]
50 54 command.creation_flags(0x0800_0000);
51 55 command
52 56 }
53 57
58 fn prepend_user_bin(command: &mut Command) {
59 let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) else {
60 return;
61 };
62 let bin = PathBuf::from(home).join(".local").join("bin");
63 if !bin.is_dir() {
64 return;
65 }
66 let mut paths = vec![bin];
67 if let Some(path) = std::env::var_os("PATH") {
68 paths.extend(std::env::split_paths(&path));
69 }
70 if let Ok(joined) = std::env::join_paths(paths) {
71 command.env("PATH", joined);
72 }
73 }
74
54 75 #[cfg(windows)]
55 76 fn taskkill_tree(process_id: u32) -> Invocation {
56 77 Invocation {
@@ -1,4 +1,5 @@
1use std::collections::VecDeque;
1use std::collections::VecDeque;
2use std::path::PathBuf;
2use std::process::Stdio;
3use std::process::Stdio;
3use std::sync::{Arc, Mutex};
4use std::sync::{Arc, Mutex};
4
5
@@ -40,17 +41,37 @@ pub struct RunOutcome {
40}
41}
41
42
42fn command_for(invocation: &Invocation) -> Command {
43fn command_for(invocation: &Invocation) -> Command {
43 let mut command = Command::new(&invocation.program);
44 let program = crate::catalog::resolve_program(&invocation.program)
45 .unwrap_or_else(|| PathBuf::from(&invocation.program));
46 let mut command = Command::new(program);
44 command.args(&invocation.args);
47 command.args(&invocation.args);
45 if let Some(cwd) = &invocation.cwd {
48 if let Some(cwd) = &invocation.cwd {
46 command.current_dir(cwd);
49 command.current_dir(cwd);
47 }
50 }
51 prepend_user_bin(&mut command);
48 command.kill_on_drop(true);
52 command.kill_on_drop(true);
49 #[cfg(windows)]
53 #[cfg(windows)]
50 command.creation_flags(0x0800_0000);
54 command.creation_flags(0x0800_0000);
51 command
55 command
52}
56}
53
57
58fn prepend_user_bin(command: &mut Command) {
59 let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) else {
60 return;
61 };
62 let bin = PathBuf::from(home).join(".local").join("bin");
63 if !bin.is_dir() {
64 return;
65 }
66 let mut paths = vec![bin];
67 if let Some(path) = std::env::var_os("PATH") {
68 paths.extend(std::env::split_paths(&path));
69 }
70 if let Ok(joined) = std::env::join_paths(paths) {
71 command.env("PATH", joined);
72 }
73}
74
54#[cfg(windows)]
75#[cfg(windows)]
55fn taskkill_tree(process_id: u32) -> Invocation {
76fn taskkill_tree(process_id: u32) -> Invocation {
56 Invocation {
77 Invocation {
crates/agents/src/settings.rs +46 −2
@@ -3,7 +3,7 @@ use std::collections::HashMap;
3 3 use serde::{Deserialize, Serialize};
4 4
5 5 use crate::action::AgentAction;
6 use crate::profile::AgentProfile;
6 use crate::profile::{AgentBackend, AgentProfile};
7 7 use crate::template::{is_known_placeholder, placeholders_in};
8 8
9 9 pub const SETTINGS_KEY: &str = "agents.settings";
@@ -20,6 +20,8 @@ pub enum SettingsProblem {
20 20 item_id: String,
21 21 placeholder: String,
22 22 },
23 #[error("agent {agent_id} has an empty model")]
24 EmptyModel { agent_id: String },
23 25 }
24 26
25 27 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -29,6 +31,8 @@ pub struct AgentSettings {
29 31 pub actions: Vec<AgentAction>,
30 32 pub resume_interrupted_runs: bool,
31 33 pub recent_working_dirs: HashMap<String, Vec<String>>,
34 /// Empty means Microsoft Copilot. Otherwise the id of a chat profile.
35 pub write_with: String,
32 36 }
33 37
34 38 impl Default for AgentSettings {
@@ -41,6 +45,7 @@ impl Default for AgentSettings {
41 45 ],
42 46 resume_interrupted_runs: true,
43 47 recent_working_dirs: HashMap::new(),
48 write_with: String::new(),
44 49 }
45 50 }
46 51 }
@@ -90,11 +95,22 @@ impl AgentSettings {
90 95 pub fn validate(&self) -> Vec<SettingsProblem> {
91 96 let mut problems = Vec::new();
92 97 for agent in &self.agents {
93 if agent.command.trim().is_empty() {
98 if agent.is_command() && agent.command.trim().is_empty() {
94 99 problems.push(SettingsProblem::EmptyCommand {
95 100 agent_id: agent.id.clone(),
96 101 });
97 102 }
103 let model = match &agent.backend {
104 AgentBackend::OpenAi { model, .. } | AgentBackend::Anthropic { model, .. } => {
105 model.as_str()
106 }
107 AgentBackend::Command => "",
108 };
109 if agent.is_chat() && model.trim().is_empty() {
110 problems.push(SettingsProblem::EmptyModel {
111 agent_id: agent.id.clone(),
112 });
113 }
98 114 check_placeholders(
99 115 &agent.id,
100 116 &[&agent.command, &agent.open_session_command],
@@ -235,4 +251,32 @@ mod tests {
235 251 placeholder: "nope".to_string(),
236 252 }));
237 253 }
254
255 #[test]
256 fn a_profile_without_backend_stays_a_command() {
257 let loaded = AgentSettings::from_json(
258 r#"{"agents":[{"id":"legacy","name":"Legacy","command":"claude -p"}]}"#,
259 )
260 .unwrap();
261 assert!(loaded.agents[0].is_command());
262 assert!(loaded.write_with.is_empty());
263 }
264
265 #[test]
266 fn chat_profiles_need_a_model_and_write_with_round_trips() {
267 let mut settings = AgentSettings::default();
268 settings.agents.push(AgentProfile::ollama());
269 assert!(settings.validate().contains(&SettingsProblem::EmptyModel {
270 agent_id: "ollama".to_string(),
271 }));
272 settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi {
273 base_url: "http://127.0.0.1:11434/v1".to_owned(),
274 model: "qwen3.5:9b".to_owned(),
275 api_key: String::new(),
276 };
277 settings.write_with = "ollama".to_owned();
278 let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
279 assert_eq!(loaded.write_with, "ollama");
280 assert!(loaded.validate().is_empty());
281 }
238 282 }
@@ -3,7 +3,7 @@ use std::collections::HashMap;
3use serde::{Deserialize, Serialize};
3use serde::{Deserialize, Serialize};
4
4
5use crate::action::AgentAction;
5use crate::action::AgentAction;
6use crate::profile::AgentProfile;
6use crate::profile::{AgentBackend, AgentProfile};
7use crate::template::{is_known_placeholder, placeholders_in};
7use crate::template::{is_known_placeholder, placeholders_in};
8
8
9pub const SETTINGS_KEY: &str = "agents.settings";
9pub const SETTINGS_KEY: &str = "agents.settings";
@@ -20,6 +20,8 @@ pub enum SettingsProblem {
20 item_id: String,
20 item_id: String,
21 placeholder: String,
21 placeholder: String,
22 },
22 },
23 #[error("agent {agent_id} has an empty model")]
24 EmptyModel { agent_id: String },
23}
25}
24
26
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
27#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -29,6 +31,8 @@ pub struct AgentSettings {
29 pub actions: Vec<AgentAction>,
31 pub actions: Vec<AgentAction>,
30 pub resume_interrupted_runs: bool,
32 pub resume_interrupted_runs: bool,
31 pub recent_working_dirs: HashMap<String, Vec<String>>,
33 pub recent_working_dirs: HashMap<String, Vec<String>>,
34 /// Empty means Microsoft Copilot. Otherwise the id of a chat profile.
35 pub write_with: String,
32}
36}
33
37
34impl Default for AgentSettings {
38impl Default for AgentSettings {
@@ -41,6 +45,7 @@ impl Default for AgentSettings {
41 ],
45 ],
42 resume_interrupted_runs: true,
46 resume_interrupted_runs: true,
43 recent_working_dirs: HashMap::new(),
47 recent_working_dirs: HashMap::new(),
48 write_with: String::new(),
44 }
49 }
45 }
50 }
46}
51}
@@ -90,11 +95,22 @@ impl AgentSettings {
90 pub fn validate(&self) -> Vec<SettingsProblem> {
95 pub fn validate(&self) -> Vec<SettingsProblem> {
91 let mut problems = Vec::new();
96 let mut problems = Vec::new();
92 for agent in &self.agents {
97 for agent in &self.agents {
93 if agent.command.trim().is_empty() {
98 if agent.is_command() && agent.command.trim().is_empty() {
94 problems.push(SettingsProblem::EmptyCommand {
99 problems.push(SettingsProblem::EmptyCommand {
95 agent_id: agent.id.clone(),
100 agent_id: agent.id.clone(),
96 });
101 });
97 }
102 }
103 let model = match &agent.backend {
104 AgentBackend::OpenAi { model, .. } | AgentBackend::Anthropic { model, .. } => {
105 model.as_str()
106 }
107 AgentBackend::Command => "",
108 };
109 if agent.is_chat() && model.trim().is_empty() {
110 problems.push(SettingsProblem::EmptyModel {
111 agent_id: agent.id.clone(),
112 });
113 }
98 check_placeholders(
114 check_placeholders(
99 &agent.id,
115 &agent.id,
100 &[&agent.command, &agent.open_session_command],
116 &[&agent.command, &agent.open_session_command],
@@ -235,4 +251,32 @@ mod tests {
235 placeholder: "nope".to_string(),
251 placeholder: "nope".to_string(),
236 }));
252 }));
237 }
253 }
254
255 #[test]
256 fn a_profile_without_backend_stays_a_command() {
257 let loaded = AgentSettings::from_json(
258 r#"{"agents":[{"id":"legacy","name":"Legacy","command":"claude -p"}]}"#,
259 )
260 .unwrap();
261 assert!(loaded.agents[0].is_command());
262 assert!(loaded.write_with.is_empty());
263 }
264
265 #[test]
266 fn chat_profiles_need_a_model_and_write_with_round_trips() {
267 let mut settings = AgentSettings::default();
268 settings.agents.push(AgentProfile::ollama());
269 assert!(settings.validate().contains(&SettingsProblem::EmptyModel {
270 agent_id: "ollama".to_string(),
271 }));
272 settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi {
273 base_url: "http://127.0.0.1:11434/v1".to_owned(),
274 model: "qwen3.5:9b".to_owned(),
275 api_key: String::new(),
276 };
277 settings.write_with = "ollama".to_owned();
278 let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
279 assert_eq!(loaded.write_with, "ollama");
280 assert!(loaded.validate().is_empty());
281 }
238}
282}
crates/app-state/src/activity/feed.rs +14 −5
@@ -231,9 +231,8 @@ impl Feed {
231 231 .iter()
232 232 .filter(|entry| filter.admits(entry))
233 233 .collect();
234 admitted.sort_by(|left, right| {
235 (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id))
236 });
234 admitted
235 .sort_by(|left, right| (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id)));
237 236 let mut sections: Vec<Section<'_>> = Vec::new();
238 237 for entry in admitted {
239 238 let bucket = Bucket::of(entry.updated_at, today, offset);
@@ -294,7 +293,11 @@ mod tests {
294 293 .map(|section| {
295 294 (
296 295 section.bucket,
297 section.entries.iter().map(|entry| entry.id.as_str()).collect(),
296 section
297 .entries
298 .iter()
299 .map(|entry| entry.id.as_str())
300 .collect(),
298 301 )
299 302 })
300 303 .collect();
@@ -309,7 +312,13 @@ mod tests {
309 312 let mentions = feed.sections(Filter::Mentions, today, offset);
310 313 assert_eq!(mentions[0].entries.len(), 2);
311 314 let unread = feed.sections(Filter::Unread, today, offset);
312 assert_eq!(unread.iter().map(|section| section.entries.len()).sum::<usize>(), 2);
315 assert_eq!(
316 unread
317 .iter()
318 .map(|section| section.entries.len())
319 .sum::<usize>(),
320 2
321 );
313 322 assert_eq!(feed.unread_count(), 2);
314 323 assert_eq!(feed.bell_count(), 2);
315 324 }
@@ -231,9 +231,8 @@ impl Feed {
231 .iter()
231 .iter()
232 .filter(|entry| filter.admits(entry))
232 .filter(|entry| filter.admits(entry))
233 .collect();
233 .collect();
234 admitted.sort_by(|left, right| {
234 admitted
235 (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id))
235 .sort_by(|left, right| (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id)));
236 });
237 let mut sections: Vec<Section<'_>> = Vec::new();
236 let mut sections: Vec<Section<'_>> = Vec::new();
238 for entry in admitted {
237 for entry in admitted {
239 let bucket = Bucket::of(entry.updated_at, today, offset);
238 let bucket = Bucket::of(entry.updated_at, today, offset);
@@ -294,7 +293,11 @@ mod tests {
294 .map(|section| {
293 .map(|section| {
295 (
294 (
296 section.bucket,
295 section.bucket,
297 section.entries.iter().map(|entry| entry.id.as_str()).collect(),
296 section
297 .entries
298 .iter()
299 .map(|entry| entry.id.as_str())
300 .collect(),
298 )
301 )
299 })
302 })
300 .collect();
303 .collect();
@@ -309,7 +312,13 @@ mod tests {
309 let mentions = feed.sections(Filter::Mentions, today, offset);
312 let mentions = feed.sections(Filter::Mentions, today, offset);
310 assert_eq!(mentions[0].entries.len(), 2);
313 assert_eq!(mentions[0].entries.len(), 2);
311 let unread = feed.sections(Filter::Unread, today, offset);
314 let unread = feed.sections(Filter::Unread, today, offset);
312 assert_eq!(unread.iter().map(|section| section.entries.len()).sum::<usize>(), 2);
315 assert_eq!(
316 unread
317 .iter()
318 .map(|section| section.entries.len())
319 .sum::<usize>(),
320 2
321 );
313 assert_eq!(feed.unread_count(), 2);
322 assert_eq!(feed.unread_count(), 2);
314 assert_eq!(feed.bell_count(), 2);
323 assert_eq!(feed.bell_count(), 2);
315 }
324 }
crates/app-state/src/activity/server.rs +50 −11
@@ -10,7 +10,10 @@ const APP_TEMPLATES: [(&str, &str); 4] = [
10 10 ("recapIsReady", "Meeting recap is ready"),
11 11 ("recapIsReadyForFollowedMeetings", "Meeting recap is ready"),
12 12 ("recapIsReadyV2", "Recap ready: {subject}"),
13 ("recapIsReadyForFollowedMeetingsV2", "Recap ready: {subject}"),
13 (
14 "recapIsReadyForFollowedMeetingsV2",
15 "Recap ready: {subject}",
16 ),
14 17 ];
15 18
16 19 pub fn feed_of(snapshot: &ActivitySnapshot, seen_locally_ms: i64) -> Feed {
@@ -63,7 +66,10 @@ fn entry_of(item: &ActivityItem) -> Entry {
63 66 updated_at: DateTime::from_timestamp_millis(item.timestamp_ms).unwrap_or_else(Utc::now),
64 67 read: false,
65 68 counts_for_bell: false,
66 source_label: item.source_app_name.clone().or_else(|| item.thread_topic.clone()),
69 source_label: item
70 .source_app_name
71 .clone()
72 .or_else(|| item.thread_topic.clone()),
67 73 link: item.tap_url.clone(),
68 74 reply_id: channel_reply(item, kind),
69 75 title: app_title(item),
@@ -97,12 +103,19 @@ fn app_title(item: &ActivityItem) -> Option<String> {
97 103
98 104 pub fn kind_of(item: &ActivityItem) -> Kind {
99 105 match item.activity_type.as_str() {
100 "mention" | "mentionInChat" | "mentionInCommunity" | "mentionInSubCommunity"
106 "mention"
107 | "mentionInChat"
108 | "mentionInCommunity"
109 | "mentionInSubCommunity"
101 110 | "communityMention" => Kind::Mention,
102 111 "reply" | "replyToReply" | "replyInChat" | "communityReply" | "communityReplyToReply" => {
103 112 Kind::Reply
104 113 }
105 "reaction" | "reactionInChat" | "like" | "likeInChat" | "reactionInCommunity"
114 "reaction"
115 | "reactionInChat"
116 | "like"
117 | "likeInChat"
118 | "reactionInCommunity"
106 119 | "reactionInSubCommunity" => Kind::Reaction,
107 120 "call" if item.activity_subtype == "missedCall" => Kind::MissedCall,
108 121 "call" | "voicemail" | "callOrMeetup" => Kind::Call,
@@ -144,7 +157,13 @@ fn preview_of(item: &ActivityItem) -> String {
144 157 "forwardedMessage" => "Forwarded message",
145 158 "isMeeting" => "Teams Meeting",
146 159 "replyWithQuote" if item.preview.is_empty() => "Replied with quote",
147 _ => return item.preview.split_whitespace().collect::<Vec<_>>().join(" "),
160 _ => {
161 return item
162 .preview
163 .split_whitespace()
164 .collect::<Vec<_>>()
165 .join(" ");
166 }
148 167 };
149 168 fixed.to_owned()
150 169 }
@@ -178,8 +197,14 @@ mod tests {
178 197
179 198 #[test]
180 199 fn a_preview_with_line_breaks_becomes_one_line() {
181 let multiline = ActivityItem { preview: "Menu 09.11.-13.11. -\nPlease order\r\n until 9:30".into(), ..item("mention", "person") };
182 assert_eq!(preview_of(&multiline), "Menu 09.11.-13.11. - Please order until 9:30");
200 let multiline = ActivityItem {
201 preview: "Menu 09.11.-13.11. -\nPlease order\r\n until 9:30".into(),
202 ..item("mention", "person")
203 };
204 assert_eq!(
205 preview_of(&multiline),
206 "Menu 09.11.-13.11. - Please order until 9:30"
207 );
183 208 }
184 209
185 210 #[test]
@@ -191,7 +216,10 @@ mod tests {
191 216 recap.event_start_ms = Some(1793865600000);
192 217 recap.event_end_ms = Some(1793869200000);
193 218 let entry = entry_of(&recap);
194 assert_eq!(entry.title.as_deref(), Some("Recap ready: Following: Sprint {Demo}"));
219 assert_eq!(
220 entry.title.as_deref(),
221 Some("Recap ready: Following: Sprint {Demo}")
222 );
195 223 let (start, end) = entry.event_range.unwrap();
196 224 assert_eq!((end - start).num_minutes(), 60);
197 225 assert_eq!(entry_of(&item("msGraph", "recapIsReadyV2")).title, None);
@@ -213,7 +241,11 @@ mod tests {
213 241 ("unknownType", "", Kind::Other),
214 242 ];
215 243 for (activity_type, subtype, kind) in cases {
216 assert_eq!(kind_of(&item(activity_type, subtype)), kind, "{activity_type}");
244 assert_eq!(
245 kind_of(&item(activity_type, subtype)),
246 kind,
247 "{activity_type}"
248 );
217 249 }
218 250 }
219 251
@@ -242,7 +274,10 @@ mod tests {
242 274 });
243 275 assert_eq!(recap.conversation_id, "19:meeting_Zm9v@thread.v2");
244 276 assert_eq!(recap.message_id, "");
245 assert_eq!(recap.link.as_deref(), Some("https://teams.microsoft.com/l/entity/x"));
277 assert_eq!(
278 recap.link.as_deref(),
279 Some("https://teams.microsoft.com/l/entity/x")
280 );
246 281 }
247 282
248 283 #[test]
@@ -305,7 +340,11 @@ mod tests {
305 340 .collect();
306 341 assert_eq!(
307 342 read,
308 [("old", true, false), ("new", false, true), ("flagged", true, false)]
343 [
344 ("old", true, false),
345 ("new", false, true),
346 ("flagged", true, false)
347 ]
309 348 );
310 349 assert_eq!(feed_of(&snapshot, 300).bell_count(), 0);
311 350 }
@@ -10,7 +10,10 @@ const APP_TEMPLATES: [(&str, &str); 4] = [
10 ("recapIsReady", "Meeting recap is ready"),
10 ("recapIsReady", "Meeting recap is ready"),
11 ("recapIsReadyForFollowedMeetings", "Meeting recap is ready"),
11 ("recapIsReadyForFollowedMeetings", "Meeting recap is ready"),
12 ("recapIsReadyV2", "Recap ready: {subject}"),
12 ("recapIsReadyV2", "Recap ready: {subject}"),
13 ("recapIsReadyForFollowedMeetingsV2", "Recap ready: {subject}"),
13 (
14 "recapIsReadyForFollowedMeetingsV2",
15 "Recap ready: {subject}",
16 ),
14];
17];
15
18
16pub fn feed_of(snapshot: &ActivitySnapshot, seen_locally_ms: i64) -> Feed {
19pub fn feed_of(snapshot: &ActivitySnapshot, seen_locally_ms: i64) -> Feed {
@@ -63,7 +66,10 @@ fn entry_of(item: &ActivityItem) -> Entry {
63 updated_at: DateTime::from_timestamp_millis(item.timestamp_ms).unwrap_or_else(Utc::now),
66 updated_at: DateTime::from_timestamp_millis(item.timestamp_ms).unwrap_or_else(Utc::now),
64 read: false,
67 read: false,
65 counts_for_bell: false,
68 counts_for_bell: false,
66 source_label: item.source_app_name.clone().or_else(|| item.thread_topic.clone()),
69 source_label: item
70 .source_app_name
71 .clone()
72 .or_else(|| item.thread_topic.clone()),
67 link: item.tap_url.clone(),
73 link: item.tap_url.clone(),
68 reply_id: channel_reply(item, kind),
74 reply_id: channel_reply(item, kind),
69 title: app_title(item),
75 title: app_title(item),
@@ -97,12 +103,19 @@ fn app_title(item: &ActivityItem) -> Option<String> {
97
103
98pub fn kind_of(item: &ActivityItem) -> Kind {
104pub fn kind_of(item: &ActivityItem) -> Kind {
99 match item.activity_type.as_str() {
105 match item.activity_type.as_str() {
100 "mention" | "mentionInChat" | "mentionInCommunity" | "mentionInSubCommunity"
106 "mention"
107 | "mentionInChat"
108 | "mentionInCommunity"
109 | "mentionInSubCommunity"
101 | "communityMention" => Kind::Mention,
110 | "communityMention" => Kind::Mention,
102 "reply" | "replyToReply" | "replyInChat" | "communityReply" | "communityReplyToReply" => {
111 "reply" | "replyToReply" | "replyInChat" | "communityReply" | "communityReplyToReply" => {
103 Kind::Reply
112 Kind::Reply
104 }
113 }
105 "reaction" | "reactionInChat" | "like" | "likeInChat" | "reactionInCommunity"
114 "reaction"
115 | "reactionInChat"
116 | "like"
117 | "likeInChat"
118 | "reactionInCommunity"
106 | "reactionInSubCommunity" => Kind::Reaction,
119 | "reactionInSubCommunity" => Kind::Reaction,
107 "call" if item.activity_subtype == "missedCall" => Kind::MissedCall,
120 "call" if item.activity_subtype == "missedCall" => Kind::MissedCall,
108 "call" | "voicemail" | "callOrMeetup" => Kind::Call,
121 "call" | "voicemail" | "callOrMeetup" => Kind::Call,
@@ -144,7 +157,13 @@ fn preview_of(item: &ActivityItem) -> String {
144 "forwardedMessage" => "Forwarded message",
157 "forwardedMessage" => "Forwarded message",
145 "isMeeting" => "Teams Meeting",
158 "isMeeting" => "Teams Meeting",
146 "replyWithQuote" if item.preview.is_empty() => "Replied with quote",
159 "replyWithQuote" if item.preview.is_empty() => "Replied with quote",
147 _ => return item.preview.split_whitespace().collect::<Vec<_>>().join(" "),
160 _ => {
161 return item
162 .preview
163 .split_whitespace()
164 .collect::<Vec<_>>()
165 .join(" ");
166 }
148 };
167 };
149 fixed.to_owned()
168 fixed.to_owned()
150}
169}
@@ -178,8 +197,14 @@ mod tests {
178
197
179 #[test]
198 #[test]
180 fn a_preview_with_line_breaks_becomes_one_line() {
199 fn a_preview_with_line_breaks_becomes_one_line() {
181 let multiline = ActivityItem { preview: "Menu 09.11.-13.11. -\nPlease order\r\n until 9:30".into(), ..item("mention", "person") };
200 let multiline = ActivityItem {
182 assert_eq!(preview_of(&multiline), "Menu 09.11.-13.11. - Please order until 9:30");
201 preview: "Menu 09.11.-13.11. -\nPlease order\r\n until 9:30".into(),
202 ..item("mention", "person")
203 };
204 assert_eq!(
205 preview_of(&multiline),
206 "Menu 09.11.-13.11. - Please order until 9:30"
207 );
183 }
208 }
184
209
185 #[test]
210 #[test]
@@ -191,7 +216,10 @@ mod tests {
191 recap.event_start_ms = Some(1793865600000);
216 recap.event_start_ms = Some(1793865600000);
192 recap.event_end_ms = Some(1793869200000);
217 recap.event_end_ms = Some(1793869200000);
193 let entry = entry_of(&recap);
218 let entry = entry_of(&recap);
194 assert_eq!(entry.title.as_deref(), Some("Recap ready: Following: Sprint {Demo}"));
219 assert_eq!(
220 entry.title.as_deref(),
221 Some("Recap ready: Following: Sprint {Demo}")
222 );
195 let (start, end) = entry.event_range.unwrap();
223 let (start, end) = entry.event_range.unwrap();
196 assert_eq!((end - start).num_minutes(), 60);
224 assert_eq!((end - start).num_minutes(), 60);
197 assert_eq!(entry_of(&item("msGraph", "recapIsReadyV2")).title, None);
225 assert_eq!(entry_of(&item("msGraph", "recapIsReadyV2")).title, None);
@@ -213,7 +241,11 @@ mod tests {
213 ("unknownType", "", Kind::Other),
241 ("unknownType", "", Kind::Other),
214 ];
242 ];
215 for (activity_type, subtype, kind) in cases {
243 for (activity_type, subtype, kind) in cases {
216 assert_eq!(kind_of(&item(activity_type, subtype)), kind, "{activity_type}");
244 assert_eq!(
245 kind_of(&item(activity_type, subtype)),
246 kind,
247 "{activity_type}"
248 );
217 }
249 }
218 }
250 }
219
251
@@ -242,7 +274,10 @@ mod tests {
242 });
274 });
243 assert_eq!(recap.conversation_id, "19:meeting_Zm9v@thread.v2");
275 assert_eq!(recap.conversation_id, "19:meeting_Zm9v@thread.v2");
244 assert_eq!(recap.message_id, "");
276 assert_eq!(recap.message_id, "");
245 assert_eq!(recap.link.as_deref(), Some("https://teams.microsoft.com/l/entity/x"));
277 assert_eq!(
278 recap.link.as_deref(),
279 Some("https://teams.microsoft.com/l/entity/x")
280 );
246 }
281 }
247
282
248 #[test]
283 #[test]
@@ -305,7 +340,11 @@ mod tests {
305 .collect();
340 .collect();
306 assert_eq!(
341 assert_eq!(
307 read,
342 read,
308 [("old", true, false), ("new", false, true), ("flagged", true, false)]
343 [
344 ("old", true, false),
345 ("new", false, true),
346 ("flagged", true, false)
347 ]
309 );
348 );
310 assert_eq!(feed_of(&snapshot, 300).bell_count(), 0);
349 assert_eq!(feed_of(&snapshot, 300).bell_count(), 0);
311 }
350 }
crates/app-state/src/agent_api/bridge.rs +9 −3
@@ -1,5 +1,5 @@
1 use std::collections::{HashMap, HashSet};
2 1 use std::collections::hash_map::DefaultHasher;
2 use std::collections::{HashMap, HashSet};
3 3 use std::hash::{Hash, Hasher};
4 4 use std::sync::atomic::{AtomicBool, Ordering};
5 5 use std::sync::{Arc, Mutex};
@@ -474,8 +474,14 @@ pub fn spawn_message_bridge(engine: Arc<Engine>, hub: Arc<AgentHub>, source: Arc
474 474 loop {
475 475 let conversation_id = match receiver.recv().await {
476 476 Ok(CoreEvent::MessagesChanged { conversation_id }) => conversation_id,
477 Ok(CoreEvent::MessagesStoredLate { conversation_id, message_ids }) => {
478 stored_late.entry(conversation_id).or_default().extend(message_ids);
477 Ok(CoreEvent::MessagesStoredLate {
478 conversation_id,
479 message_ids,
480 }) => {
481 stored_late
482 .entry(conversation_id)
483 .or_default()
484 .extend(message_ids);
479 485 continue;
480 486 }
481 487 Ok(_) => continue,
@@ -1,5 +1,5 @@
1use std::collections::{HashMap, HashSet};
2use std::collections::hash_map::DefaultHasher;
1use std::collections::hash_map::DefaultHasher;
2use std::collections::{HashMap, HashSet};
3use std::hash::{Hash, Hasher};
3use std::hash::{Hash, Hasher};
4use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex};
5use std::sync::{Arc, Mutex};
@@ -474,8 +474,14 @@ pub fn spawn_message_bridge(engine: Arc<Engine>, hub: Arc<AgentHub>, source: Arc
474 loop {
474 loop {
475 let conversation_id = match receiver.recv().await {
475 let conversation_id = match receiver.recv().await {
476 Ok(CoreEvent::MessagesChanged { conversation_id }) => conversation_id,
476 Ok(CoreEvent::MessagesChanged { conversation_id }) => conversation_id,
477 Ok(CoreEvent::MessagesStoredLate { conversation_id, message_ids }) => {
477 Ok(CoreEvent::MessagesStoredLate {
478 stored_late.entry(conversation_id).or_default().extend(message_ids);
478 conversation_id,
479 message_ids,
480 }) => {
481 stored_late
482 .entry(conversation_id)
483 .or_default()
484 .extend(message_ids);
479 continue;
485 continue;
480 }
486 }
481 Ok(_) => continue,
487 Ok(_) => continue,
crates/app-state/src/agent_api/mod.rs +7 −111
@@ -1,12 +1,12 @@
1 pub mod bridge;
2 1 pub mod body;
3 pub mod meetings;
2 pub mod bridge;
4 3 pub mod pending;
5 4 pub mod source;
6 5
7 6 use std::collections::{BTreeSet, HashMap, HashSet};
8 7 use std::sync::Arc;
9 8
9 use app_base::agent_api::{extras, image_scale};
10 10 use chrono::{DateTime, Local};
11 11 use gpui_kit::*;
12 12 use mcp::install::{Homes, Location};
@@ -15,7 +15,6 @@ use mcp::{
15 15 ReactionProposal, ServerHandle,
16 16 };
17 17 use store::Store;
18 use app_base::agent_api::{extras, image_scale};
19 18
20 19 use crate::backend::Engine;
21 20 use crate::runtime;
@@ -74,7 +73,6 @@ pub struct AgentApi {
74 73 generation: u64,
75 74 reinstall_note: Option<String>,
76 75 demo: bool,
77 announced_meetings: HashSet<String>,
78 76 }
79 77
80 78 struct AgentApiHandle(Entity<AgentApi>);
@@ -150,14 +148,10 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
150 148 generation: 0,
151 149 reinstall_note: None,
152 150 demo,
153 announced_meetings: HashSet::new(),
154 151 });
155 152 bridge::drain_ui_events(receiver, api.downgrade(), cx);
156 153 api.update(cx, |api, cx| {
157 154 let _ = api.hub.restore_pending();
158 if demo && api.hub.pending_meetings().is_empty() {
159 let _ = api.hub.propose_meeting(crate::demo::agent_meeting_draft(), Some("claude".to_owned()), None);
160 }
161 155 api.reconcile(cx);
162 156 });
163 157 cx.set_global(AgentApiHandle(api));
@@ -209,7 +203,7 @@ pub fn chat_allowed(conversation_id: &str, cx: &App) -> bool {
209 203 };
210 204 let api = api.read(cx);
211 205 let policy = api.hub.policy();
212 policy.write && policy.can_read_any_kind(conversation_id)
206 policy.propose && policy.can_read_any_kind(conversation_id)
213 207 }
214 208
215 209 pub fn allow_chat(conversation_id: &str, cx: &mut App) {
@@ -222,7 +216,7 @@ pub fn allow_chat(conversation_id: &str, cx: &mut App) {
222 216 api.update_policy(
223 217 move |policy| {
224 218 policy.enabled = true;
225 policy.write = true;
219 policy.propose = true;
226 220 let access = if is_channel {
227 221 &mut policy.channels
228 222 } else {
@@ -248,96 +242,7 @@ pub fn update_policy(cx: &mut App, change: impl FnOnce(&mut AgentPolicy)) {
248 242 }
249 243
250 244 pub fn proposal(conversation_id: &str, cx: &App) -> Option<ProposalEntry> {
251 handle(cx)?
252 .read(cx)
253 .proposals
254 .get(conversation_id)
255 .filter(|entry| !entry.proposal.direct)
256 .cloned()
257 }
258
259 pub fn free_writing(conversation_id: &str, cx: &App) -> Option<mcp::FreeWriting> {
260 handle(cx)?.read(cx).hub.free_writing(conversation_id)
261 }
262
263 pub fn allow_free_writing(conversation_id: &str, minutes: u32, agent: Option<String>, cx: &mut App) {
264 let Some(api) = handle(cx) else {
265 return;
266 };
267 let lasting = std::time::Duration::from_secs(u64::from(minutes) * 60);
268 let until = chrono::Utc::now() + chrono::Duration::minutes(i64::from(minutes));
269 api.update(cx, |api, cx| {
270 api.hub.grant_free_writing(conversation_id, until, agent);
271 cx.notify();
272 let conversation_id = conversation_id.to_owned();
273 cx.spawn(async move |this, cx| {
274 cx.background_executor().timer(lasting).await;
275 this.update(cx, |api, cx| {
276 if api.hub.free_writing(&conversation_id).is_none() {
277 api.hub.stop_free_writing(&conversation_id);
278 }
279 cx.notify();
280 })
281 .ok();
282 })
283 .detach();
284 });
285 }
286
287 pub fn stop_free_writing(conversation_id: &str, cx: &mut App) {
288 if let Some(api) = handle(cx) {
289 api.update(cx, |api, cx| {
290 api.hub.stop_free_writing(conversation_id);
291 cx.notify();
292 });
293 }
294 }
295
296 pub fn direct_messages(cx: &App) -> Vec<ProposalEntry> {
297 let Some(api) = handle(cx) else {
298 return Vec::new();
299 };
300 api.read(cx)
301 .proposals
302 .values()
303 .filter(|entry| entry.proposal.direct && entry.status == ProposalStatus::Pending)
304 .cloned()
305 .collect()
306 }
307
308 pub fn direct_reactions(cx: &App) -> Vec<ReactionProposal> {
309 let Some(api) = handle(cx) else {
310 return Vec::new();
311 };
312 api.read(cx)
313 .reactions
314 .values()
315 .filter(|reaction| reaction.direct)
316 .cloned()
317 .collect()
318 }
319
320 pub fn hold_for_review(conversation_id: &str, cx: &mut App) {
321 if let Some(api) = handle(cx) {
322 api.update(cx, |api, cx| {
323 if let Some(entry) = api.proposals.get_mut(conversation_id) {
324 entry.proposal.direct = false;
325 cx.notify();
326 }
327 });
328 }
329 }
330
331 pub fn hold_reaction_for_review(conversation_id: &str, message_id: &str, cx: &mut App) {
332 if let Some(api) = handle(cx) {
333 api.update(cx, |api, cx| {
334 let key = (conversation_id.to_owned(), message_id.to_owned());
335 if let Some(reaction) = api.reactions.get_mut(&key) {
336 reaction.direct = false;
337 cx.notify();
338 }
339 });
340 }
245 handle(cx)?.read(cx).proposals.get(conversation_id).cloned()
341 246 }
342 247
343 248 pub fn reaction_proposals(conversation_id: &str, cx: &App) -> HashMap<String, ReactionProposal> {
@@ -347,7 +252,7 @@ pub fn reaction_proposals(conversation_id: &str, cx: &App) -> HashMap<String, Re
347 252 api.read(cx)
348 253 .reactions
349 254 .values()
350 .filter(|reaction| reaction.conversation_id == conversation_id && !reaction.direct)
255 .filter(|reaction| reaction.conversation_id == conversation_id)
351 256 .map(|reaction| (reaction.message_id.clone(), reaction.clone()))
352 257 .collect()
353 258 }
@@ -373,9 +278,7 @@ pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
373 278 api.read(cx)
374 279 .proposals
375 280 .iter()
376 .filter(|(_, entry)| {
377 !entry.proposal.direct && !matches!(entry.status, ProposalStatus::Stale { .. })
378 })
281 .filter(|(_, entry)| !matches!(entry.status, ProposalStatus::Stale { .. }))
379 282 .map(|(conversation_id, entry)| {
380 283 (
381 284 conversation_id.clone(),
@@ -563,13 +466,6 @@ impl AgentApi {
563 466 pictures: Vec<ProposalPicture>,
564 467 cx: &mut Context<Self>,
565 468 ) {
566 if matches!(event, mcp::UiEvent::MeetingProposalsChanged) {
567 let pending = self.hub.pending_meetings();
568 for proposal in meetings::unannounced(&self.announced_meetings, &pending) {
569 meetings::announce(proposal, cx);
570 }
571 self.announced_meetings = pending.into_iter().map(|proposal| proposal.id).collect();
572 }
573 469 if let mcp::UiEvent::ReactionProposalChanged(reaction) = &event
574 470 && let Some(excerpt) = pending::reacted_excerpt(
575 471 &self.store,
@@ -1,12 +1,12 @@
1pub mod bridge;
2pub mod body;
1pub mod body;
3pub mod meetings;
2pub mod bridge;
4pub mod pending;
3pub mod pending;
5pub mod source;
4pub mod source;
6
5
7use std::collections::{BTreeSet, HashMap, HashSet};
6use std::collections::{BTreeSet, HashMap, HashSet};
8use std::sync::Arc;
7use std::sync::Arc;
9
8
9use app_base::agent_api::{extras, image_scale};
10use chrono::{DateTime, Local};
10use chrono::{DateTime, Local};
11use gpui_kit::*;
11use gpui_kit::*;
12use mcp::install::{Homes, Location};
12use mcp::install::{Homes, Location};
@@ -15,7 +15,6 @@ use mcp::{
15 ReactionProposal, ServerHandle,
15 ReactionProposal, ServerHandle,
16};
16};
17use store::Store;
17use store::Store;
18use app_base::agent_api::{extras, image_scale};
19
18
20use crate::backend::Engine;
19use crate::backend::Engine;
21use crate::runtime;
20use crate::runtime;
@@ -74,7 +73,6 @@ pub struct AgentApi {
74 generation: u64,
73 generation: u64,
75 reinstall_note: Option<String>,
74 reinstall_note: Option<String>,
76 demo: bool,
75 demo: bool,
77 announced_meetings: HashSet<String>,
78}
76}
79
77
80struct AgentApiHandle(Entity<AgentApi>);
78struct AgentApiHandle(Entity<AgentApi>);
@@ -150,14 +148,10 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
150 generation: 0,
148 generation: 0,
151 reinstall_note: None,
149 reinstall_note: None,
152 demo,
150 demo,
153 announced_meetings: HashSet::new(),
154 });
151 });
155 bridge::drain_ui_events(receiver, api.downgrade(), cx);
152 bridge::drain_ui_events(receiver, api.downgrade(), cx);
156 api.update(cx, |api, cx| {
153 api.update(cx, |api, cx| {
157 let _ = api.hub.restore_pending();
154 let _ = api.hub.restore_pending();
158 if demo && api.hub.pending_meetings().is_empty() {
159 let _ = api.hub.propose_meeting(crate::demo::agent_meeting_draft(), Some("claude".to_owned()), None);
160 }
161 api.reconcile(cx);
155 api.reconcile(cx);
162 });
156 });
163 cx.set_global(AgentApiHandle(api));
157 cx.set_global(AgentApiHandle(api));
@@ -209,7 +203,7 @@ pub fn chat_allowed(conversation_id: &str, cx: &App) -> bool {
209 };
203 };
210 let api = api.read(cx);
204 let api = api.read(cx);
211 let policy = api.hub.policy();
205 let policy = api.hub.policy();
212 policy.write && policy.can_read_any_kind(conversation_id)
206 policy.propose && policy.can_read_any_kind(conversation_id)
213}
207}
214
208
215pub fn allow_chat(conversation_id: &str, cx: &mut App) {
209pub fn allow_chat(conversation_id: &str, cx: &mut App) {
@@ -222,7 +216,7 @@ pub fn allow_chat(conversation_id: &str, cx: &mut App) {
222 api.update_policy(
216 api.update_policy(
223 move |policy| {
217 move |policy| {
224 policy.enabled = true;
218 policy.enabled = true;
225 policy.write = true;
219 policy.propose = true;
226 let access = if is_channel {
220 let access = if is_channel {
227 &mut policy.channels
221 &mut policy.channels
228 } else {
222 } else {
@@ -248,96 +242,7 @@ pub fn update_policy(cx: &mut App, change: impl FnOnce(&mut AgentPolicy)) {
248}
242}
249
243
250pub fn proposal(conversation_id: &str, cx: &App) -> Option<ProposalEntry> {
244pub fn proposal(conversation_id: &str, cx: &App) -> Option<ProposalEntry> {
251 handle(cx)?
245 handle(cx)?.read(cx).proposals.get(conversation_id).cloned()
252 .read(cx)
253 .proposals
254 .get(conversation_id)
255 .filter(|entry| !entry.proposal.direct)
256 .cloned()
257}
258
259pub fn free_writing(conversation_id: &str, cx: &App) -> Option<mcp::FreeWriting> {
260 handle(cx)?.read(cx).hub.free_writing(conversation_id)
261}
262
263pub fn allow_free_writing(conversation_id: &str, minutes: u32, agent: Option<String>, cx: &mut App) {
264 let Some(api) = handle(cx) else {
265 return;
266 };
267 let lasting = std::time::Duration::from_secs(u64::from(minutes) * 60);
268 let until = chrono::Utc::now() + chrono::Duration::minutes(i64::from(minutes));
269 api.update(cx, |api, cx| {
270 api.hub.grant_free_writing(conversation_id, until, agent);
271 cx.notify();
272 let conversation_id = conversation_id.to_owned();
273 cx.spawn(async move |this, cx| {
274 cx.background_executor().timer(lasting).await;
275 this.update(cx, |api, cx| {
276 if api.hub.free_writing(&conversation_id).is_none() {
277 api.hub.stop_free_writing(&conversation_id);
278 }
279 cx.notify();
280 })
281 .ok();
282 })
283 .detach();
284 });
285}
286
287pub fn stop_free_writing(conversation_id: &str, cx: &mut App) {
288 if let Some(api) = handle(cx) {
289 api.update(cx, |api, cx| {
290 api.hub.stop_free_writing(conversation_id);
291 cx.notify();
292 });
293 }
294}
295
296pub fn direct_messages(cx: &App) -> Vec<ProposalEntry> {
297 let Some(api) = handle(cx) else {
298 return Vec::new();
299 };
300 api.read(cx)
301 .proposals
302 .values()
303 .filter(|entry| entry.proposal.direct && entry.status == ProposalStatus::Pending)
304 .cloned()
305 .collect()
306}
307
308pub fn direct_reactions(cx: &App) -> Vec<ReactionProposal> {
309 let Some(api) = handle(cx) else {
310 return Vec::new();
311 };
312 api.read(cx)
313 .reactions
314 .values()
315 .filter(|reaction| reaction.direct)
316 .cloned()
317 .collect()
318}
319
320pub fn hold_for_review(conversation_id: &str, cx: &mut App) {
321 if let Some(api) = handle(cx) {
322 api.update(cx, |api, cx| {
323 if let Some(entry) = api.proposals.get_mut(conversation_id) {
324 entry.proposal.direct = false;
325 cx.notify();
326 }
327 });
328 }
329}
330
331pub fn hold_reaction_for_review(conversation_id: &str, message_id: &str, cx: &mut App) {
332 if let Some(api) = handle(cx) {
333 api.update(cx, |api, cx| {
334 let key = (conversation_id.to_owned(), message_id.to_owned());
335 if let Some(reaction) = api.reactions.get_mut(&key) {
336 reaction.direct = false;
337 cx.notify();
338 }
339 });
340 }
341}
246}
342
247
343pub fn reaction_proposals(conversation_id: &str, cx: &App) -> HashMap<String, ReactionProposal> {
248pub fn reaction_proposals(conversation_id: &str, cx: &App) -> HashMap<String, ReactionProposal> {
@@ -347,7 +252,7 @@ pub fn reaction_proposals(conversation_id: &str, cx: &App) -> HashMap<String, Re
347 api.read(cx)
252 api.read(cx)
348 .reactions
253 .reactions
349 .values()
254 .values()
350 .filter(|reaction| reaction.conversation_id == conversation_id && !reaction.direct)
255 .filter(|reaction| reaction.conversation_id == conversation_id)
351 .map(|reaction| (reaction.message_id.clone(), reaction.clone()))
256 .map(|reaction| (reaction.message_id.clone(), reaction.clone()))
352 .collect()
257 .collect()
353}
258}
@@ -373,9 +278,7 @@ pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
373 api.read(cx)
278 api.read(cx)
374 .proposals
279 .proposals
375 .iter()
280 .iter()
376 .filter(|(_, entry)| {
281 .filter(|(_, entry)| !matches!(entry.status, ProposalStatus::Stale { .. }))
377 !entry.proposal.direct && !matches!(entry.status, ProposalStatus::Stale { .. })
378 })
379 .map(|(conversation_id, entry)| {
282 .map(|(conversation_id, entry)| {
380 (
283 (
381 conversation_id.clone(),
284 conversation_id.clone(),
@@ -563,13 +466,6 @@ impl AgentApi {
563 pictures: Vec<ProposalPicture>,
466 pictures: Vec<ProposalPicture>,
564 cx: &mut Context<Self>,
467 cx: &mut Context<Self>,
565 ) {
468 ) {
566 if matches!(event, mcp::UiEvent::MeetingProposalsChanged) {
567 let pending = self.hub.pending_meetings();
568 for proposal in meetings::unannounced(&self.announced_meetings, &pending) {
569 meetings::announce(proposal, cx);
570 }
571 self.announced_meetings = pending.into_iter().map(|proposal| proposal.id).collect();
572 }
573 if let mcp::UiEvent::ReactionProposalChanged(reaction) = &event
469 if let mcp::UiEvent::ReactionProposalChanged(reaction) = &event
574 && let Some(excerpt) = pending::reacted_excerpt(
470 && let Some(excerpt) = pending::reacted_excerpt(
575 &self.store,
471 &self.store,
crates/app-state/src/agents/chat_run.rs added +106 −0
@@ -0,0 +1,106 @@
1 use agents::{
2 ChatMessage, ChatReply, McpEndpoint, RunEvent, RunOutcome, RunStatus, RunUpdate, ToolSpec,
3 next_turn,
4 };
5 use tokio::sync::{mpsc, oneshot};
6
7 use mcp::{ListedTool, ToolSession};
8
9 const SYSTEM: &str = "You help with one Teams message. Use the tools to read what you need and to propose a reply or a reaction. You never send anything yourself.";
10 const ROUNDS: usize = 8;
11
12 pub async fn run_chat(
13 profile: agents::AgentProfile,
14 prompt: String,
15 endpoint: Option<McpEndpoint>,
16 events: mpsc::UnboundedSender<RunUpdate>,
17 mut stop: oneshot::Receiver<()>,
18 ) -> RunOutcome {
19 let session = match endpoint {
20 Some(endpoint) => {
21 match ToolSession::connect(&mcp::McpEndpoint {
22 url: endpoint.url,
23 token: endpoint.token,
24 })
25 .await
26 {
27 Ok(session) => Some(session),
28 Err(error) => {
29 let _ = events.send(RunUpdate::Event(RunEvent::Step(format!(
30 "MCP tools unavailable: {error}"
31 ))));
32 None
33 }
34 }
35 }
36 None => None,
37 };
38 let specs = match &session {
39 Some(session) => session
40 .tools()
41 .await
42 .unwrap_or_default()
43 .into_iter()
44 .map(spec)
45 .collect(),
46 None => Vec::new(),
47 };
48 let mut messages = vec![ChatMessage::user(prompt)];
49 let mut stop_armed = true;
50 for _ in 0..ROUNDS {
51 let turn = tokio::select! {
52 biased;
53 result = &mut stop, if stop_armed => {
54 if result.is_ok() {
55 return RunOutcome { status: RunStatus::Stopped, exit_code: None };
56 }
57 stop_armed = false;
58 continue;
59 }
60 turn = next_turn(&profile, SYSTEM, &messages, &specs) => turn,
61 };
62 match turn {
63 Err(message) => return failed(message),
64 Ok(ChatReply::Text(text)) => {
65 let _ = events.send(RunUpdate::Event(RunEvent::Text(text.clone())));
66 return RunOutcome {
67 status: RunStatus::Completed { final_text: text },
68 exit_code: None,
69 };
70 }
71 Ok(ChatReply::Tools { text, calls }) => {
72 messages.push(ChatMessage::assistant(text, calls.clone()));
73 for call in calls {
74 let _ = events.send(RunUpdate::Event(RunEvent::Step(call.name.clone())));
75 let result = match &session {
76 Some(session) => session
77 .call(&call.name, &call.arguments)
78 .await
79 .unwrap_or_else(|error| error),
80 None => "tools are not available".to_owned(),
81 };
82 messages.push(ChatMessage::tool(call.id, result));
83 }
84 }
85 }
86 }
87 failed("stopped after too many tool calls".to_owned())
88 }
89
90 fn spec(tool: ListedTool) -> ToolSpec {
91 ToolSpec {
92 name: tool.name,
93 description: tool.description,
94 parameters: tool.parameters,
95 }
96 }
97
98 fn failed(message: String) -> RunOutcome {
99 RunOutcome {
100 status: RunStatus::Failed {
101 message,
102 stderr_tail: Vec::new(),
103 },
104 exit_code: None,
105 }
106 }
@@ -0,0 +1,106 @@
1use agents::{
2 ChatMessage, ChatReply, McpEndpoint, RunEvent, RunOutcome, RunStatus, RunUpdate, ToolSpec,
3 next_turn,
4};
5use tokio::sync::{mpsc, oneshot};
6
7use mcp::{ListedTool, ToolSession};
8
9const SYSTEM: &str = "You help with one Teams message. Use the tools to read what you need and to propose a reply or a reaction. You never send anything yourself.";
10const ROUNDS: usize = 8;
11
12pub async fn run_chat(
13 profile: agents::AgentProfile,
14 prompt: String,
15 endpoint: Option<McpEndpoint>,
16 events: mpsc::UnboundedSender<RunUpdate>,
17 mut stop: oneshot::Receiver<()>,
18) -> RunOutcome {
19 let session = match endpoint {
20 Some(endpoint) => {
21 match ToolSession::connect(&mcp::McpEndpoint {
22 url: endpoint.url,
23 token: endpoint.token,
24 })
25 .await
26 {
27 Ok(session) => Some(session),
28 Err(error) => {
29 let _ = events.send(RunUpdate::Event(RunEvent::Step(format!(
30 "MCP tools unavailable: {error}"
31 ))));
32 None
33 }
34 }
35 }
36 None => None,
37 };
38 let specs = match &session {
39 Some(session) => session
40 .tools()
41 .await
42 .unwrap_or_default()
43 .into_iter()
44 .map(spec)
45 .collect(),
46 None => Vec::new(),
47 };
48 let mut messages = vec![ChatMessage::user(prompt)];
49 let mut stop_armed = true;
50 for _ in 0..ROUNDS {
51 let turn = tokio::select! {
52 biased;
53 result = &mut stop, if stop_armed => {
54 if result.is_ok() {
55 return RunOutcome { status: RunStatus::Stopped, exit_code: None };
56 }
57 stop_armed = false;
58 continue;
59 }
60 turn = next_turn(&profile, SYSTEM, &messages, &specs) => turn,
61 };
62 match turn {
63 Err(message) => return failed(message),
64 Ok(ChatReply::Text(text)) => {
65 let _ = events.send(RunUpdate::Event(RunEvent::Text(text.clone())));
66 return RunOutcome {
67 status: RunStatus::Completed { final_text: text },
68 exit_code: None,
69 };
70 }
71 Ok(ChatReply::Tools { text, calls }) => {
72 messages.push(ChatMessage::assistant(text, calls.clone()));
73 for call in calls {
74 let _ = events.send(RunUpdate::Event(RunEvent::Step(call.name.clone())));
75 let result = match &session {
76 Some(session) => session
77 .call(&call.name, &call.arguments)
78 .await
79 .unwrap_or_else(|error| error),
80 None => "tools are not available".to_owned(),
81 };
82 messages.push(ChatMessage::tool(call.id, result));
83 }
84 }
85 }
86 }
87 failed("stopped after too many tool calls".to_owned())
88}
89
90fn spec(tool: ListedTool) -> ToolSpec {
91 ToolSpec {
92 name: tool.name,
93 description: tool.description,
94 parameters: tool.parameters,
95 }
96}
97
98fn failed(message: String) -> RunOutcome {
99 RunOutcome {
100 status: RunStatus::Failed {
101 message,
102 stderr_tail: Vec::new(),
103 },
104 exit_code: None,
105 }
106}
crates/app-state/src/agents/mod.rs +11 −3
@@ -1,3 +1,4 @@
1 mod chat_run;
1 2 pub mod demo;
2 3 #[cfg(any(test, feature = "test-support"))]
3 4 pub mod fixtures;
@@ -11,14 +12,15 @@ pub mod store;
11 12 use std::path::PathBuf;
12 13 use std::time::Duration;
13 14
15 use agents::{AgentAction, Environment};
14 16 pub use app_base::agents::{lanes, settings_problems};
15 17 pub use app_ui_kit::{settings_controls, spinner};
16 use agents::{AgentAction, Environment};
17 18 use directories::ProjectDirs;
18 19 use gpui_kit::*;
19 20
20 21 pub use runs::{
21 AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions, StartRequest, needs_dialog,
22 AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions, StartRequest,
23 needs_dialog,
22 24 };
23 25
24 26 use crate::app_state::{AppHandle, AppState};
@@ -202,7 +204,13 @@ fn open_run_session(run: &AgentRun, cx: &mut App) {
202 204
203 205 pub fn environment_label(environment: &Environment) -> String {
204 206 match environment {
205 Environment::Host => "Windows".to_owned(),
207 Environment::Host => {
208 if cfg!(windows) {
209 "Windows".to_owned()
210 } else {
211 "This computer".to_owned()
212 }
213 }
206 214 Environment::Wsl { distro: None } => "WSL".to_owned(),
207 215 Environment::Wsl {
208 216 distro: Some(distro),
@@ -1,3 +1,4 @@
1mod chat_run;
1pub mod demo;
2pub mod demo;
2#[cfg(any(test, feature = "test-support"))]
3#[cfg(any(test, feature = "test-support"))]
3pub mod fixtures;
4pub mod fixtures;
@@ -11,14 +12,15 @@ pub mod store;
11use std::path::PathBuf;
12use std::path::PathBuf;
12use std::time::Duration;
13use std::time::Duration;
13
14
15use agents::{AgentAction, Environment};
14pub use app_base::agents::{lanes, settings_problems};
16pub use app_base::agents::{lanes, settings_problems};
15pub use app_ui_kit::{settings_controls, spinner};
17pub use app_ui_kit::{settings_controls, spinner};
16use agents::{AgentAction, Environment};
17use directories::ProjectDirs;
18use directories::ProjectDirs;
18use gpui_kit::*;
19use gpui_kit::*;
19
20
20pub use runs::{
21pub use runs::{
21 AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions, StartRequest, needs_dialog,
22 AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions, StartRequest,
23 needs_dialog,
22};
24};
23
25
24use crate::app_state::{AppHandle, AppState};
26use crate::app_state::{AppHandle, AppState};
@@ -202,7 +204,13 @@ fn open_run_session(run: &AgentRun, cx: &mut App) {
202
204
203pub fn environment_label(environment: &Environment) -> String {
205pub fn environment_label(environment: &Environment) -> String {
204 match environment {
206 match environment {
205 Environment::Host => "Windows".to_owned(),
207 Environment::Host => {
208 if cfg!(windows) {
209 "Windows".to_owned()
210 } else {
211 "This computer".to_owned()
212 }
213 }
206 Environment::Wsl { distro: None } => "WSL".to_owned(),
214 Environment::Wsl { distro: None } => "WSL".to_owned(),
207 Environment::Wsl {
215 Environment::Wsl {
208 distro: Some(distro),
216 distro: Some(distro),
crates/app-state/src/agents/runs.rs +65 −12
@@ -838,14 +838,22 @@ impl AgentRuns {
838 838 return;
839 839 };
840 840 let prompt = run.pending_prompt.clone().unwrap_or_default();
841 let planned = self.launch_plan(&run, &prompt, cx);
842 if let Some(run) = self.run_mut(run_id) {
843 run.pending_prompt = None;
844 if run.current_step == QUEUED_STEP {
845 run.started_at = Utc::now();
846 run.push_step("Starting".to_owned());
847 }
841 if let Some(profile) = self
842 .settings
843 .agents
844 .iter()
845 .find(|agent| agent.id == run.agent_id)
846 .cloned()
847 .filter(|profile| profile.is_chat())
848 {
849 self.mark_launching(run_id);
850 let endpoint = mcp_bridge::endpoint(cx);
851 self.spawn_chat(run_id, profile, prompt, endpoint, cx);
852 self.persist(cx);
853 return;
848 854 }
855 let planned = self.launch_plan(&run, &prompt, cx);
856 self.mark_launching(run_id);
849 857 match planned {
850 858 Ok((plan, format)) => self.spawn(run_id, plan, format, cx),
851 859 Err(message) => self.finish(
@@ -898,6 +906,54 @@ impl AgentRuns {
898 906 .map_err(|error| error.to_string())
899 907 }
900 908
909 fn mark_launching(&mut self, run_id: u64) {
910 if let Some(run) = self.run_mut(run_id) {
911 run.pending_prompt = None;
912 if run.current_step == QUEUED_STEP {
913 run.started_at = Utc::now();
914 run.push_step("Starting".to_owned());
915 }
916 }
917 }
918
919 fn spawn_chat(
920 &mut self,
921 run_id: u64,
922 profile: AgentProfile,
923 prompt: String,
924 endpoint: Option<McpEndpoint>,
925 cx: &mut Context<Self>,
926 ) {
927 let (updates_sender, mut updates) = mpsc::unbounded_channel();
928 let (stop_sender, stop_receiver) = oneshot::channel();
929 self.stops.insert(run_id, stop_sender);
930 if let Some(run) = self.run_mut(run_id) {
931 run.launch_session_id = Some(run.session_id.clone());
932 run.launched = true;
933 }
934 let outcome = runtime::spawn(super::chat_run::run_chat(
935 profile,
936 prompt,
937 endpoint,
938 updates_sender,
939 stop_receiver,
940 ));
941 cx.spawn(async move |this, cx| {
942 while let Some(update) = updates.recv().await {
943 if this
944 .update(cx, |runs, cx| runs.apply_update(run_id, update, cx))
945 .is_err()
946 {
947 return;
948 }
949 }
950 let outcome = outcome.await.ok();
951 this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))
952 .ok();
953 })
954 .detach();
955 }
956
901 957 fn spawn(
902 958 &mut self,
903 959 run_id: u64,
@@ -1211,7 +1267,7 @@ pub(super) mod tests {
1211 1267 use std::sync::Arc;
1212 1268 use std::time::Duration;
1213 1269
1214 use agents::{AgentAction, AgentProfile, AgentSettings, Environment, OutputFormat};
1270 use agents::{AgentAction, AgentProfile, AgentSettings};
1215 1271 use chrono::TimeZone;
1216 1272 use store::{MessageRecord, Store};
1217 1273
@@ -1237,11 +1293,8 @@ pub(super) mod tests {
1237 1293 let profile = AgentProfile {
1238 1294 id: "fake".to_owned(),
1239 1295 name: "Fake".to_owned(),
1240 environment: Environment::Host,
1241 1296 command: command.to_owned(),
1242 output: OutputFormat::ClaudeStreamJson,
1243 open_session_command: String::new(),
1244 mcp_config_flag: String::new(),
1297 ..AgentProfile::default()
1245 1298 };
1246 1299 let action = AgentAction {
1247 1300 id: "ask".to_owned(),
@@ -838,14 +838,22 @@ impl AgentRuns {
838 return;
838 return;
839 };
839 };
840 let prompt = run.pending_prompt.clone().unwrap_or_default();
840 let prompt = run.pending_prompt.clone().unwrap_or_default();
841 let planned = self.launch_plan(&run, &prompt, cx);
841 if let Some(profile) = self
842 if let Some(run) = self.run_mut(run_id) {
842 .settings
843 run.pending_prompt = None;
843 .agents
844 if run.current_step == QUEUED_STEP {
844 .iter()
845 run.started_at = Utc::now();
845 .find(|agent| agent.id == run.agent_id)
846 run.push_step("Starting".to_owned());
846 .cloned()
847 }
847 .filter(|profile| profile.is_chat())
848 {
849 self.mark_launching(run_id);
850 let endpoint = mcp_bridge::endpoint(cx);
851 self.spawn_chat(run_id, profile, prompt, endpoint, cx);
852 self.persist(cx);
853 return;
848 }
854 }
855 let planned = self.launch_plan(&run, &prompt, cx);
856 self.mark_launching(run_id);
849 match planned {
857 match planned {
850 Ok((plan, format)) => self.spawn(run_id, plan, format, cx),
858 Ok((plan, format)) => self.spawn(run_id, plan, format, cx),
851 Err(message) => self.finish(
859 Err(message) => self.finish(
@@ -898,6 +906,54 @@ impl AgentRuns {
898 .map_err(|error| error.to_string())
906 .map_err(|error| error.to_string())
899 }
907 }
900
908
909 fn mark_launching(&mut self, run_id: u64) {
910 if let Some(run) = self.run_mut(run_id) {
911 run.pending_prompt = None;
912 if run.current_step == QUEUED_STEP {
913 run.started_at = Utc::now();
914 run.push_step("Starting".to_owned());
915 }
916 }
917 }
918
919 fn spawn_chat(
920 &mut self,
921 run_id: u64,
922 profile: AgentProfile,
923 prompt: String,
924 endpoint: Option<McpEndpoint>,
925 cx: &mut Context<Self>,
926 ) {
927 let (updates_sender, mut updates) = mpsc::unbounded_channel();
928 let (stop_sender, stop_receiver) = oneshot::channel();
929 self.stops.insert(run_id, stop_sender);
930 if let Some(run) = self.run_mut(run_id) {
931 run.launch_session_id = Some(run.session_id.clone());
932 run.launched = true;
933 }
934 let outcome = runtime::spawn(super::chat_run::run_chat(
935 profile,
936 prompt,
937 endpoint,
938 updates_sender,
939 stop_receiver,
940 ));
941 cx.spawn(async move |this, cx| {
942 while let Some(update) = updates.recv().await {
943 if this
944 .update(cx, |runs, cx| runs.apply_update(run_id, update, cx))
945 .is_err()
946 {
947 return;
948 }
949 }
950 let outcome = outcome.await.ok();
951 this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))
952 .ok();
953 })
954 .detach();
955 }
956
901 fn spawn(
957 fn spawn(
902 &mut self,
958 &mut self,
903 run_id: u64,
959 run_id: u64,
@@ -1211,7 +1267,7 @@ pub(super) mod tests {
1211 use std::sync::Arc;
1267 use std::sync::Arc;
1212 use std::time::Duration;
1268 use std::time::Duration;
1213
1269
1214 use agents::{AgentAction, AgentProfile, AgentSettings, Environment, OutputFormat};
1270 use agents::{AgentAction, AgentProfile, AgentSettings};
1215 use chrono::TimeZone;
1271 use chrono::TimeZone;
1216 use store::{MessageRecord, Store};
1272 use store::{MessageRecord, Store};
1217
1273
@@ -1237,11 +1293,8 @@ pub(super) mod tests {
1237 let profile = AgentProfile {
1293 let profile = AgentProfile {
1238 id: "fake".to_owned(),
1294 id: "fake".to_owned(),
1239 name: "Fake".to_owned(),
1295 name: "Fake".to_owned(),
1240 environment: Environment::Host,
1241 command: command.to_owned(),
1296 command: command.to_owned(),
1242 output: OutputFormat::ClaudeStreamJson,
1297 ..AgentProfile::default()
1243 open_session_command: String::new(),
1244 mcp_config_flag: String::new(),
1245 };
1298 };
1246 let action = AgentAction {
1299 let action = AgentAction {
1247 id: "ask".to_owned(),
1300 id: "ask".to_owned(),
crates/app-state/src/app_state.rs +11 −7
@@ -102,10 +102,7 @@ pub enum AppEvent {
102 102 CallTone(chatsvc::sounds::CallTone),
103 103 SoundSettings,
104 104 ChatSettings,
105 FollowedStatus {
106 user_id: String,
107 text: &'static str,
108 },
105 FollowedStatus { user_id: String, text: &'static str },
109 106 }
110 107
111 108 #[derive(Debug, Clone, Copy, Default)]
@@ -386,8 +383,10 @@ impl AppState {
386 383 state.followed_presence = crate::presence_follow::load_followed(&state.store);
387 384 state.collapsed = state.load_collapsed();
388 385 state.call_share_sound = crate::call::load_share_sound(&state.store);
389 state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
390 state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
386 state.call_share_motion =
387 crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
388 state.call_share_standout =
389 crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
391 390 state.call_report_enabled = crate::call::load_report_enabled(&state.store);
392 391 state.call_view = crate::call::ViewSettings::load(&state.store);
393 392 state.call_background = crate::call::load_background(&state.store);
@@ -686,7 +685,12 @@ impl AppState {
686 685 Err(_) => Some("cancelled".to_owned()),
687 686 };
688 687 if let Some(failure) = failure {
689 let host = image.url.split("://").nth(1).and_then(|rest| rest.split('/').next()).unwrap_or_default();
688 let host = image
689 .url
690 .split("://")
691 .nth(1)
692 .and_then(|rest| rest.split('/').next())
693 .unwrap_or_default();
690 694 log::warn!("image from {host} not loaded: {failure}");
691 695 this.update(cx, |state, cx| {
692 696 state.directory.mark_image_failed(&image.url);
@@ -102,10 +102,7 @@ pub enum AppEvent {
102 CallTone(chatsvc::sounds::CallTone),
102 CallTone(chatsvc::sounds::CallTone),
103 SoundSettings,
103 SoundSettings,
104 ChatSettings,
104 ChatSettings,
105 FollowedStatus {
105 FollowedStatus { user_id: String, text: &'static str },
106 user_id: String,
107 text: &'static str,
108 },
109}
106}
110
107
111#[derive(Debug, Clone, Copy, Default)]
108#[derive(Debug, Clone, Copy, Default)]
@@ -386,8 +383,10 @@ impl AppState {
386 state.followed_presence = crate::presence_follow::load_followed(&state.store);
383 state.followed_presence = crate::presence_follow::load_followed(&state.store);
387 state.collapsed = state.load_collapsed();
384 state.collapsed = state.load_collapsed();
388 state.call_share_sound = crate::call::load_share_sound(&state.store);
385 state.call_share_sound = crate::call::load_share_sound(&state.store);
389 state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
386 state.call_share_motion =
390 state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
387 crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
388 state.call_share_standout =
389 crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
391 state.call_report_enabled = crate::call::load_report_enabled(&state.store);
390 state.call_report_enabled = crate::call::load_report_enabled(&state.store);
392 state.call_view = crate::call::ViewSettings::load(&state.store);
391 state.call_view = crate::call::ViewSettings::load(&state.store);
393 state.call_background = crate::call::load_background(&state.store);
392 state.call_background = crate::call::load_background(&state.store);
@@ -686,7 +685,12 @@ impl AppState {
686 Err(_) => Some("cancelled".to_owned()),
685 Err(_) => Some("cancelled".to_owned()),
687 };
686 };
688 if let Some(failure) = failure {
687 if let Some(failure) = failure {
689 let host = image.url.split("://").nth(1).and_then(|rest| rest.split('/').next()).unwrap_or_default();
688 let host = image
689 .url
690 .split("://")
691 .nth(1)
692 .and_then(|rest| rest.split('/').next())
693 .unwrap_or_default();
690 log::warn!("image from {host} not loaded: {failure}");
694 log::warn!("image from {host} not loaded: {failure}");
691 this.update(cx, |state, cx| {
695 this.update(cx, |state, cx| {
692 state.directory.mark_image_failed(&image.url);
696 state.directory.mark_image_failed(&image.url);
crates/app-state/src/backend.rs +5 −2
@@ -305,9 +305,12 @@ async fn realtime_loop(
305 305 let receipt_engine = engine.clone();
306 306 let receipt_event = message.clone();
307 307 engine.handle_pin_event(&message);
308 if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID) {
308 if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID)
309 {
309 310 let activity_engine = engine.clone();
310 tokio::spawn(async move { activity_engine.refresh_activity().await });
311 tokio::spawn(
312 async move { activity_engine.refresh_activity().await },
313 );
311 314 }
312 315 tokio::spawn(async move {
313 316 receipt_engine.handle_receipt_event(&receipt_event).await
@@ -305,9 +305,12 @@ async fn realtime_loop(
305 let receipt_engine = engine.clone();
305 let receipt_engine = engine.clone();
306 let receipt_event = message.clone();
306 let receipt_event = message.clone();
307 engine.handle_pin_event(&message);
307 engine.handle_pin_event(&message);
308 if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID) {
308 if message.conversation_id.as_deref() == Some(chatsvc::ACTIVITY_FEED_ID)
309 {
309 let activity_engine = engine.clone();
310 let activity_engine = engine.clone();
310 tokio::spawn(async move { activity_engine.refresh_activity().await });
311 tokio::spawn(
312 async move { activity_engine.refresh_activity().await },
313 );
311 }
314 }
312 tokio::spawn(async move {
315 tokio::spawn(async move {
313 receipt_engine.handle_receipt_event(&receipt_event).await
316 receipt_engine.handle_receipt_event(&receipt_event).await
crates/app-state/src/banner_image.rs +4 −2
@@ -12,11 +12,13 @@ const ABANDONED_AFTER: Duration = Duration::from_secs(30 * 24 * 60 * 60);
12 12
13 13 /// The centered box with the banner's aspect ratio: `(x, y, width, height)`.
14 14 pub fn crop_box(width: u32, height: u32) -> (u32, u32, u32, u32) {
15 let wanted_height = (u64::from(width) * u64::from(BANNER_IMAGE_HEIGHT) / u64::from(BANNER_IMAGE_WIDTH)) as u32;
15 let wanted_height =
16 (u64::from(width) * u64::from(BANNER_IMAGE_HEIGHT) / u64::from(BANNER_IMAGE_WIDTH)) as u32;
16 17 if wanted_height <= height {
17 18 (0, (height - wanted_height) / 2, width, wanted_height.max(1))
18 19 } else {
19 let wanted_width = (u64::from(height) * u64::from(BANNER_IMAGE_WIDTH) / u64::from(BANNER_IMAGE_HEIGHT)) as u32;
20 let wanted_width = (u64::from(height) * u64::from(BANNER_IMAGE_WIDTH)
21 / u64::from(BANNER_IMAGE_HEIGHT)) as u32;
20 22 ((width - wanted_width) / 2, 0, wanted_width.max(1), height)
21 23 }
22 24 }
@@ -12,11 +12,13 @@ const ABANDONED_AFTER: Duration = Duration::from_secs(30 * 24 * 60 * 60);
12
12
13/// The centered box with the banner's aspect ratio: `(x, y, width, height)`.
13/// The centered box with the banner's aspect ratio: `(x, y, width, height)`.
14pub fn crop_box(width: u32, height: u32) -> (u32, u32, u32, u32) {
14pub fn crop_box(width: u32, height: u32) -> (u32, u32, u32, u32) {
15 let wanted_height = (u64::from(width) * u64::from(BANNER_IMAGE_HEIGHT) / u64::from(BANNER_IMAGE_WIDTH)) as u32;
15 let wanted_height =
16 (u64::from(width) * u64::from(BANNER_IMAGE_HEIGHT) / u64::from(BANNER_IMAGE_WIDTH)) as u32;
16 if wanted_height <= height {
17 if wanted_height <= height {
17 (0, (height - wanted_height) / 2, width, wanted_height.max(1))
18 (0, (height - wanted_height) / 2, width, wanted_height.max(1))
18 } else {
19 } else {
19 let wanted_width = (u64::from(height) * u64::from(BANNER_IMAGE_WIDTH) / u64::from(BANNER_IMAGE_HEIGHT)) as u32;
20 let wanted_width = (u64::from(height) * u64::from(BANNER_IMAGE_WIDTH)
21 / u64::from(BANNER_IMAGE_HEIGHT)) as u32;
20 ((width - wanted_width) / 2, 0, wanted_width.max(1), height)
22 ((width - wanted_width) / 2, 0, wanted_width.max(1), height)
21 }
23 }
22}
24}
crates/app-state/src/call/actions.rs +165 −47
@@ -3,7 +3,8 @@ use std::time::{Duration, Instant};
3 3 use calling::meeting::LiveMeeting;
4 4 use calling::{
5 5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal,
7 ShareSource, VideoKey,
7 8 };
8 9 use gpui_kit::*;
9 10
@@ -14,14 +15,15 @@ use super::demo::{
14 15 DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call,
15 16 start_demo_scene_call,
16 17 };
18 use super::end_screen::{CallEndScreen, end_tone};
17 19 use super::features::{TransferCandidate, room_closed_move};
18 20 use super::media::CallMedia;
19 21 use super::mic::save_mic;
20 use super::end_screen::{CallEndScreen, end_tone};
21 22 use super::model::{ActiveCall, CallKind, CallModel, ConsultTransfer, ended_notice};
22 23 use super::prejoin::{DemoMeeting, MeetingJoin};
23 24 use super::report::{
24 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report, shared,
25 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report,
26 shared,
25 27 };
26 28 use super::ring::{MissedCall, RingOutcome};
27 29 use super::target::{is_echo_chat, is_organizer, plan_for_chat};
@@ -143,12 +145,20 @@ impl AppState {
143 145 self.show_call(true, cx);
144 146 return;
145 147 }
146 let chat = self.sidebar.chats.iter().find(|chat| chat.id == conversation_id);
148 let chat = self
149 .sidebar
150 .chats
151 .iter()
152 .find(|chat| chat.id == conversation_id);
147 153 if chat.is_some_and(is_echo_chat) {
148 154 self.start_test_call(cx);
149 155 return;
150 156 }
151 let chat = self.sidebar.chats.iter().find(|chat| chat.id == conversation_id);
157 let chat = self
158 .sidebar
159 .chats
160 .iter()
161 .find(|chat| chat.id == conversation_id);
152 162 let plan = chat.and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
153 163 let Some(plan) = plan else {
154 164 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
@@ -301,7 +311,10 @@ impl AppState {
301 311 if let Some(call) = self.call.as_mut() {
302 312 call.report.clone_from(&report);
303 313 }
304 let rights_conversation = self.call.as_ref().and_then(|call| call.conversation_id.clone());
314 let rights_conversation = self
315 .call
316 .as_ref()
317 .and_then(|call| call.conversation_id.clone());
305 318 self.apply_recording_rights(rights_conversation.as_deref(), cx);
306 319 self.follow_call(call_id, updates, report, cx);
307 320 cx.emit(AppEvent::Call);
@@ -345,8 +358,15 @@ impl AppState {
345 358 let action = NoticeAction::new("Open folder", move |_, _| {
346 359 crate::downloads::reveal_in_file_manager(&path)
347 360 });
348 let text = match self.notice.as_ref().filter(|notice| notice.action.is_none()) {
349 Some(ended) => format!("{}. {REPORT_SAVED_NOTICE}", ended.text.trim_end_matches('.')),
361 let text = match self
362 .notice
363 .as_ref()
364 .filter(|notice| notice.action.is_none())
365 {
366 Some(ended) => format!(
367 "{}. {REPORT_SAVED_NOTICE}",
368 ended.text.trim_end_matches('.')
369 ),
350 370 None => REPORT_SAVED_NOTICE.to_owned(),
351 371 };
352 372 self.raise_notice(text, Some(action), cx);
@@ -354,7 +374,9 @@ impl AppState {
354 374
355 375 pub fn set_call_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
356 376 self.call_report_enabled = on;
357 let _ = self.store.set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
377 let _ = self
378 .store
379 .set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
358 380 cx.notify();
359 381 }
360 382
@@ -381,7 +403,9 @@ impl AppState {
381 403 return;
382 404 };
383 405 let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
384 report.borrow_mut().observe(&CallUpdate::State(CallState::Ended { reason }));
406 report
407 .borrow_mut()
408 .observe(&CallUpdate::State(CallState::Ended { reason }));
385 409 let recorder = report.borrow().clone();
386 410 let saved = cx
387 411 .background_executor()
@@ -436,7 +460,8 @@ impl AppState {
436 460 CallUpdate::Roster(entries) => entries,
437 461 other => return other,
438 462 };
439 let user_id = |entry: &calling::RosterEntry| entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
463 let user_id =
464 |entry: &calling::RosterEntry| entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
440 465 let missing: Vec<String> = entries
441 466 .iter()
442 467 .filter(|entry| entry.display_name.is_empty())
@@ -444,7 +469,10 @@ impl AppState {
444 469 .collect();
445 470 if !missing.is_empty() {
446 471 let names = crate::people::resolve_names(self, &missing);
447 for entry in entries.iter_mut().filter(|entry| entry.display_name.is_empty()) {
472 for entry in entries
473 .iter_mut()
474 .filter(|entry| entry.display_name.is_empty())
475 {
448 476 if let Some(name) = user_id(entry).and_then(|id| names.get(&id)) {
449 477 entry.display_name = name.clone();
450 478 }
@@ -515,7 +543,11 @@ impl AppState {
515 543 return;
516 544 }
517 545 CallUpdate::MeetingOptionsSaved(result) => {
518 if call.options_dialog.as_mut().is_some_and(|dialog| dialog.saved(result)) {
546 if call
547 .options_dialog
548 .as_mut()
549 .is_some_and(|dialog| dialog.saved(result))
550 {
519 551 call.options_dialog = None;
520 552 }
521 553 cx.notify();
@@ -540,13 +572,17 @@ impl AppState {
540 572 .is_none_or(|played_at| played_at.elapsed() >= LOBBY_TONE_THROTTLE)
541 573 {
542 574 call.lobby_tone_at = Some(Instant::now());
543 cx.emit(AppEvent::CallTone(chatsvc::sounds::CallTone::MeetingReminder));
575 cx.emit(AppEvent::CallTone(
576 chatsvc::sounds::CallTone::MeetingReminder,
577 ));
544 578 }
545 579 if call.model.screen_sharer != sharer_before {
546 580 call.pictures.forget(&VideoKey::Screen, cx);
547 581 }
548 582 if let Some(language) = call.model.take_ready_caption_language() {
549 let _ = call.commands.send(CallCommand::SetCaptionLanguage(language));
583 let _ = call
584 .commands
585 .send(CallCommand::SetCaptionLanguage(language));
550 586 }
551 587 if call.model.screen_sharer.is_none() {
552 588 call.stage_fullscreen = false;
@@ -823,7 +859,8 @@ impl AppState {
823 859 return;
824 860 };
825 861 if let Some(own_mri) = call.model.own_mri.clone() {
826 call.model.note_reaction(own_mri, reaction.clone(), Instant::now());
862 call.model
863 .note_reaction(own_mri, reaction.clone(), Instant::now());
827 864 }
828 865 self.send_call_command(CallCommand::SendReaction(reaction));
829 866 cx.emit(AppEvent::Call);
@@ -1414,12 +1451,12 @@ mod tests {
1414 1451 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1415 1452 use crate::call::TransferCandidate;
1416 1453 use crate::call::background::BackgroundPick;
1417 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1418 1454 use crate::call::demo::demo_ring;
1419 use chatsvc::sounds::CallTone;
1420 1455 use crate::call::features::room_closed_move;
1421 1456 use crate::call::model::BreakoutState;
1457 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1422 1458 use crate::data::Person;
1459 use chatsvc::sounds::CallTone;
1423 1460
1424 1461 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
1425 1462 cx.update(gpui_kit::init);
@@ -1522,7 +1559,15 @@ mod tests {
1522 1559 let app = app_with_call(cx);
1523 1560 let key = calling::VideoKey::Person("8:orgid:peer".into());
1524 1561 let shown = |app: &Entity<AppState>, cx: &mut TestAppContext| {
1525 cx.update(|cx| app.read(cx).call.as_ref().unwrap().pictures.live(&key, Instant::now()).is_some())
1562 cx.update(|cx| {
1563 app.read(cx)
1564 .call
1565 .as_ref()
1566 .unwrap()
1567 .pictures
1568 .live(&key, Instant::now())
1569 .is_some()
1570 })
1526 1571 };
1527 1572 cx.update(|cx| {
1528 1573 app.update(cx, |state, cx| {
@@ -1568,11 +1613,16 @@ mod tests {
1568 1613 state.select_call_output(DeviceChoice::Device("headset".into()), cx);
1569 1614 })
1570 1615 });
1571 assert_eq!(load_input(&store), DeviceChoice::Device("headset-mic".into()));
1616 assert_eq!(
1617 load_input(&store),
1618 DeviceChoice::Device("headset-mic".into())
1619 );
1572 1620 assert_eq!(load_output(&store), DeviceChoice::Device("headset".into()));
1573 1621 assert_eq!(
1574 1622 control.try_recv_command(),
1575 Some(CallCommand::SelectInput(DeviceChoice::Device("headset-mic".into())))
1623 Some(CallCommand::SelectInput(DeviceChoice::Device(
1624 "headset-mic".into()
1625 )))
1576 1626 );
1577 1627 cx.update(|cx| {
1578 1628 app.update(cx, |state, cx| {
@@ -1610,12 +1660,16 @@ mod tests {
1610 1660 while let Some(command) = control.try_recv_command() {
1611 1661 commands.push(command);
1612 1662 }
1613 assert!(commands.contains(&CallCommand::SelectInput(DeviceChoice::Device(
1614 "unplugged-mic".into()
1615 ))));
1616 assert!(commands.contains(&CallCommand::SelectOutput(DeviceChoice::Device(
1617 "headset".into()
1618 ))));
1663 assert!(
1664 commands.contains(&CallCommand::SelectInput(DeviceChoice::Device(
1665 "unplugged-mic".into()
1666 )))
1667 );
1668 assert!(
1669 commands.contains(&CallCommand::SelectOutput(DeviceChoice::Device(
1670 "headset".into()
1671 )))
1672 );
1619 1673 assert_eq!(
1620 1674 load_input(&store),
1621 1675 DeviceChoice::Device("unplugged-mic".into())
@@ -1981,16 +2035,39 @@ mod tests {
1981 2035 cx.update(|cx| {
1982 2036 organizer.update(cx, |state, cx| {
1983 2037 state.run_call_record_action(RecordAction::Start(RecordingKind::AudioOnly), cx);
1984 state.run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
2038 state
2039 .run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
1985 2040 state.run_call_record_action(RecordAction::Stop(StopScope::RecordingOnly), cx);
1986 2041 state.run_call_record_action(RecordAction::Stop(StopScope::TranscriptionOnly), cx);
1987 2042 })
1988 2043 });
1989 2044 let title = "Standup".to_owned();
1990 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::AudioOnly, title: title.clone() }));
1991 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::TranscriptOnly, title }));
1992 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::RecordingOnly }));
1993 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::TranscriptionOnly }));
2045 assert_eq!(
2046 control.try_recv_command(),
2047 Some(CallCommand::StartRecording {
2048 kind: RecordingKind::AudioOnly,
2049 title: title.clone()
2050 })
2051 );
2052 assert_eq!(
2053 control.try_recv_command(),
2054 Some(CallCommand::StartRecording {
2055 kind: RecordingKind::TranscriptOnly,
2056 title
2057 })
2058 );
2059 assert_eq!(
2060 control.try_recv_command(),
2061 Some(CallCommand::StopRecording {
2062 scope: StopScope::RecordingOnly
2063 })
2064 );
2065 assert_eq!(
2066 control.try_recv_command(),
2067 Some(CallCommand::StopRecording {
2068 scope: StopScope::TranscriptionOnly
2069 })
2070 );
1994 2071 assert_eq!(control.try_recv_command(), None);
1995 2072 }
1996 2073
@@ -1999,7 +2076,11 @@ mod tests {
1999 2076 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2000 2077 cx.update(|cx| {
2001 2078 app.update(cx, |state, cx| {
2002 state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
2079 state.apply_call_update(
2080 7,
2081 CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),
2082 cx,
2083 );
2003 2084 state.toggle_call_chat(cx);
2004 2085 state.show_call_transcript(cx);
2005 2086 })
@@ -2009,7 +2090,10 @@ mod tests {
2009 2090 (call.chat_open, call.transcript_open)
2010 2091 });
2011 2092 assert!(!chat_open && transcript_open);
2012 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
2093 assert_eq!(
2094 control.try_recv_command(),
2095 Some(CallCommand::SetCaptions(true))
2096 );
2013 2097 cx.update(|cx| {
2014 2098 app.update(cx, |state, cx| {
2015 2099 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
@@ -2026,15 +2110,24 @@ mod tests {
2026 2110 }
2027 2111
2028 2112 #[gpui_kit::test]
2029 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(cx: &mut TestAppContext) {
2113 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(
2114 cx: &mut TestAppContext,
2115 ) {
2030 2116 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2031 2117 cx.update(|cx| {
2032 2118 app.update(cx, |state, cx| {
2033 2119 state.choose_call_caption_language("de-DE", cx);
2034 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::Starting), cx);
2120 state.apply_call_update(
2121 7,
2122 CallUpdate::Captions(calling::CaptionState::Starting),
2123 cx,
2124 );
2035 2125 })
2036 2126 });
2037 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
2127 assert_eq!(
2128 control.try_recv_command(),
2129 Some(CallCommand::SetCaptions(true))
2130 );
2038 2131 assert_eq!(control.try_recv_command(), None);
2039 2132 cx.update(|cx| {
2040 2133 app.update(cx, |state, cx| {
@@ -2042,8 +2135,14 @@ mod tests {
2042 2135 state.choose_call_caption_language("fr-FR", cx);
2043 2136 })
2044 2137 });
2045 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("de-DE".into())));
2046 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("fr-FR".into())));
2138 assert_eq!(
2139 control.try_recv_command(),
2140 Some(CallCommand::SetCaptionLanguage("de-DE".into()))
2141 );
2142 assert_eq!(
2143 control.try_recv_command(),
2144 Some(CallCommand::SetCaptionLanguage("fr-FR".into()))
2145 );
2047 2146 assert_eq!(control.try_recv_command(), None);
2048 2147 }
2049 2148
@@ -2058,10 +2157,19 @@ mod tests {
2058 2157 });
2059 2158 let (view, stored) = cx.update(|cx| {
2060 2159 let state = app.read(cx);
2061 (state.call.as_ref().unwrap().model.view, ViewSettings::load(&state.store))
2160 (
2161 state.call.as_ref().unwrap().model.view,
2162 ViewSettings::load(&state.store),
2163 )
2062 2164 });
2063 assert_eq!((view.caption_size, view.caption_position), (CaptionSize::Large, CaptionPosition::Top));
2064 assert_eq!((stored.caption_size, stored.caption_position), (CaptionSize::Large, CaptionPosition::Top));
2165 assert_eq!(
2166 (view.caption_size, view.caption_position),
2167 (CaptionSize::Large, CaptionPosition::Top)
2168 );
2169 assert_eq!(
2170 (stored.caption_size, stored.caption_position),
2171 (CaptionSize::Large, CaptionPosition::Top)
2172 );
2065 2173 }
2066 2174
2067 2175 fn live_one_to_one() -> CallModel {
@@ -2102,9 +2210,7 @@ mod tests {
2102 2210 }
2103 2211
2104 2212 #[gpui_kit::test]
2105 fn a_blind_transfer_names_the_target(
2106 cx: &mut TestAppContext,
2107 ) {
2213 fn a_blind_transfer_names_the_target(cx: &mut TestAppContext) {
2108 2214 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
2109 2215 cx.update(|cx| {
2110 2216 app.update(cx, |state, cx| {
@@ -2435,7 +2541,13 @@ mod tests {
2435 2541 })
2436 2542 .detach();
2437 2543 app.update(cx, |state, cx| {
2438 state.apply_call_update(7, CallUpdate::State(CallState::Ended { reason: EndReason::Dropped }), cx);
2544 state.apply_call_update(
2545 7,
2546 CallUpdate::State(CallState::Ended {
2547 reason: EndReason::Dropped,
2548 }),
2549 cx,
2550 );
2439 2551 assert!(state.call.is_none());
2440 2552 assert!(state.notice.is_none());
2441 2553 let screen = state.call_end.as_ref().expect("end screen");
@@ -2453,7 +2565,13 @@ mod tests {
2453 2565 let app = app_with_call(cx);
2454 2566 cx.update(|cx| {
2455 2567 app.update(cx, |state, cx| {
2456 state.apply_call_update(7, CallUpdate::State(CallState::Ended { reason: EndReason::Remote(EndKind::Removed) }), cx);
2568 state.apply_call_update(
2569 7,
2570 CallUpdate::State(CallState::Ended {
2571 reason: EndReason::Remote(EndKind::Removed),
2572 }),
2573 cx,
2574 );
2457 2575 assert!(state.call_end.is_none());
2458 2576 assert!(state.notice.is_some());
2459 2577 })
@@ -3,7 +3,8 @@ use std::time::{Duration, Instant};
3use calling::meeting::LiveMeeting;
3use calling::meeting::LiveMeeting;
4use calling::{
4use calling::{
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal,
7 ShareSource, VideoKey,
7};
8};
8use gpui_kit::*;
9use gpui_kit::*;
9
10
@@ -14,14 +15,15 @@ use super::demo::{
14 DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call,
15 DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call,
15 start_demo_scene_call,
16 start_demo_scene_call,
16};
17};
18use super::end_screen::{CallEndScreen, end_tone};
17use super::features::{TransferCandidate, room_closed_move};
19use super::features::{TransferCandidate, room_closed_move};
18use super::media::CallMedia;
20use super::media::CallMedia;
19use super::mic::save_mic;
21use super::mic::save_mic;
20use super::end_screen::{CallEndScreen, end_tone};
21use super::model::{ActiveCall, CallKind, CallModel, ConsultTransfer, ended_notice};
22use super::model::{ActiveCall, CallKind, CallModel, ConsultTransfer, ended_notice};
22use super::prejoin::{DemoMeeting, MeetingJoin};
23use super::prejoin::{DemoMeeting, MeetingJoin};
23use super::report::{
24use super::report::{
24 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report, shared,
25 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report,
26 shared,
25};
27};
26use super::ring::{MissedCall, RingOutcome};
28use super::ring::{MissedCall, RingOutcome};
27use super::target::{is_echo_chat, is_organizer, plan_for_chat};
29use super::target::{is_echo_chat, is_organizer, plan_for_chat};
@@ -143,12 +145,20 @@ impl AppState {
143 self.show_call(true, cx);
145 self.show_call(true, cx);
144 return;
146 return;
145 }
147 }
146 let chat = self.sidebar.chats.iter().find(|chat| chat.id == conversation_id);
148 let chat = self
149 .sidebar
150 .chats
151 .iter()
152 .find(|chat| chat.id == conversation_id);
147 if chat.is_some_and(is_echo_chat) {
153 if chat.is_some_and(is_echo_chat) {
148 self.start_test_call(cx);
154 self.start_test_call(cx);
149 return;
155 return;
150 }
156 }
151 let chat = self.sidebar.chats.iter().find(|chat| chat.id == conversation_id);
157 let chat = self
158 .sidebar
159 .chats
160 .iter()
161 .find(|chat| chat.id == conversation_id);
152 let plan = chat.and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
162 let plan = chat.and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
153 let Some(plan) = plan else {
163 let Some(plan) = plan else {
154 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
164 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
@@ -301,7 +311,10 @@ impl AppState {
301 if let Some(call) = self.call.as_mut() {
311 if let Some(call) = self.call.as_mut() {
302 call.report.clone_from(&report);
312 call.report.clone_from(&report);
303 }
313 }
304 let rights_conversation = self.call.as_ref().and_then(|call| call.conversation_id.clone());
314 let rights_conversation = self
315 .call
316 .as_ref()
317 .and_then(|call| call.conversation_id.clone());
305 self.apply_recording_rights(rights_conversation.as_deref(), cx);
318 self.apply_recording_rights(rights_conversation.as_deref(), cx);
306 self.follow_call(call_id, updates, report, cx);
319 self.follow_call(call_id, updates, report, cx);
307 cx.emit(AppEvent::Call);
320 cx.emit(AppEvent::Call);
@@ -345,8 +358,15 @@ impl AppState {
345 let action = NoticeAction::new("Open folder", move |_, _| {
358 let action = NoticeAction::new("Open folder", move |_, _| {
346 crate::downloads::reveal_in_file_manager(&path)
359 crate::downloads::reveal_in_file_manager(&path)
347 });
360 });
348 let text = match self.notice.as_ref().filter(|notice| notice.action.is_none()) {
361 let text = match self
349 Some(ended) => format!("{}. {REPORT_SAVED_NOTICE}", ended.text.trim_end_matches('.')),
362 .notice
363 .as_ref()
364 .filter(|notice| notice.action.is_none())
365 {
366 Some(ended) => format!(
367 "{}. {REPORT_SAVED_NOTICE}",
368 ended.text.trim_end_matches('.')
369 ),
350 None => REPORT_SAVED_NOTICE.to_owned(),
370 None => REPORT_SAVED_NOTICE.to_owned(),
351 };
371 };
352 self.raise_notice(text, Some(action), cx);
372 self.raise_notice(text, Some(action), cx);
@@ -354,7 +374,9 @@ impl AppState {
354
374
355 pub fn set_call_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
375 pub fn set_call_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
356 self.call_report_enabled = on;
376 self.call_report_enabled = on;
357 let _ = self.store.set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
377 let _ = self
378 .store
379 .set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
358 cx.notify();
380 cx.notify();
359 }
381 }
360
382
@@ -381,7 +403,9 @@ impl AppState {
381 return;
403 return;
382 };
404 };
383 let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
405 let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
384 report.borrow_mut().observe(&CallUpdate::State(CallState::Ended { reason }));
406 report
407 .borrow_mut()
408 .observe(&CallUpdate::State(CallState::Ended { reason }));
385 let recorder = report.borrow().clone();
409 let recorder = report.borrow().clone();
386 let saved = cx
410 let saved = cx
387 .background_executor()
411 .background_executor()
@@ -436,7 +460,8 @@ impl AppState {
436 CallUpdate::Roster(entries) => entries,
460 CallUpdate::Roster(entries) => entries,
437 other => return other,
461 other => return other,
438 };
462 };
439 let user_id = |entry: &calling::RosterEntry| entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
463 let user_id =
464 |entry: &calling::RosterEntry| entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
440 let missing: Vec<String> = entries
465 let missing: Vec<String> = entries
441 .iter()
466 .iter()
442 .filter(|entry| entry.display_name.is_empty())
467 .filter(|entry| entry.display_name.is_empty())
@@ -444,7 +469,10 @@ impl AppState {
444 .collect();
469 .collect();
445 if !missing.is_empty() {
470 if !missing.is_empty() {
446 let names = crate::people::resolve_names(self, &missing);
471 let names = crate::people::resolve_names(self, &missing);
447 for entry in entries.iter_mut().filter(|entry| entry.display_name.is_empty()) {
472 for entry in entries
473 .iter_mut()
474 .filter(|entry| entry.display_name.is_empty())
475 {
448 if let Some(name) = user_id(entry).and_then(|id| names.get(&id)) {
476 if let Some(name) = user_id(entry).and_then(|id| names.get(&id)) {
449 entry.display_name = name.clone();
477 entry.display_name = name.clone();
450 }
478 }
@@ -515,7 +543,11 @@ impl AppState {
515 return;
543 return;
516 }
544 }
517 CallUpdate::MeetingOptionsSaved(result) => {
545 CallUpdate::MeetingOptionsSaved(result) => {
518 if call.options_dialog.as_mut().is_some_and(|dialog| dialog.saved(result)) {
546 if call
547 .options_dialog
548 .as_mut()
549 .is_some_and(|dialog| dialog.saved(result))
550 {
519 call.options_dialog = None;
551 call.options_dialog = None;
520 }
552 }
521 cx.notify();
553 cx.notify();
@@ -540,13 +572,17 @@ impl AppState {
540 .is_none_or(|played_at| played_at.elapsed() >= LOBBY_TONE_THROTTLE)
572 .is_none_or(|played_at| played_at.elapsed() >= LOBBY_TONE_THROTTLE)
541 {
573 {
542 call.lobby_tone_at = Some(Instant::now());
574 call.lobby_tone_at = Some(Instant::now());
543 cx.emit(AppEvent::CallTone(chatsvc::sounds::CallTone::MeetingReminder));
575 cx.emit(AppEvent::CallTone(
576 chatsvc::sounds::CallTone::MeetingReminder,
577 ));
544 }
578 }
545 if call.model.screen_sharer != sharer_before {
579 if call.model.screen_sharer != sharer_before {
546 call.pictures.forget(&VideoKey::Screen, cx);
580 call.pictures.forget(&VideoKey::Screen, cx);
547 }
581 }
548 if let Some(language) = call.model.take_ready_caption_language() {
582 if let Some(language) = call.model.take_ready_caption_language() {
549 let _ = call.commands.send(CallCommand::SetCaptionLanguage(language));
583 let _ = call
584 .commands
585 .send(CallCommand::SetCaptionLanguage(language));
550 }
586 }
551 if call.model.screen_sharer.is_none() {
587 if call.model.screen_sharer.is_none() {
552 call.stage_fullscreen = false;
588 call.stage_fullscreen = false;
@@ -823,7 +859,8 @@ impl AppState {
823 return;
859 return;
824 };
860 };
825 if let Some(own_mri) = call.model.own_mri.clone() {
861 if let Some(own_mri) = call.model.own_mri.clone() {
826 call.model.note_reaction(own_mri, reaction.clone(), Instant::now());
862 call.model
863 .note_reaction(own_mri, reaction.clone(), Instant::now());
827 }
864 }
828 self.send_call_command(CallCommand::SendReaction(reaction));
865 self.send_call_command(CallCommand::SendReaction(reaction));
829 cx.emit(AppEvent::Call);
866 cx.emit(AppEvent::Call);
@@ -1414,12 +1451,12 @@ mod tests {
1414 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1451 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1415 use crate::call::TransferCandidate;
1452 use crate::call::TransferCandidate;
1416 use crate::call::background::BackgroundPick;
1453 use crate::call::background::BackgroundPick;
1417 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1418 use crate::call::demo::demo_ring;
1454 use crate::call::demo::demo_ring;
1419 use chatsvc::sounds::CallTone;
1420 use crate::call::features::room_closed_move;
1455 use crate::call::features::room_closed_move;
1421 use crate::call::model::BreakoutState;
1456 use crate::call::model::BreakoutState;
1457 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1422 use crate::data::Person;
1458 use crate::data::Person;
1459 use chatsvc::sounds::CallTone;
1423
1460
1424 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
1461 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
1425 cx.update(gpui_kit::init);
1462 cx.update(gpui_kit::init);
@@ -1522,7 +1559,15 @@ mod tests {
1522 let app = app_with_call(cx);
1559 let app = app_with_call(cx);
1523 let key = calling::VideoKey::Person("8:orgid:peer".into());
1560 let key = calling::VideoKey::Person("8:orgid:peer".into());
1524 let shown = |app: &Entity<AppState>, cx: &mut TestAppContext| {
1561 let shown = |app: &Entity<AppState>, cx: &mut TestAppContext| {
1525 cx.update(|cx| app.read(cx).call.as_ref().unwrap().pictures.live(&key, Instant::now()).is_some())
1562 cx.update(|cx| {
1563 app.read(cx)
1564 .call
1565 .as_ref()
1566 .unwrap()
1567 .pictures
1568 .live(&key, Instant::now())
1569 .is_some()
1570 })
1526 };
1571 };
1527 cx.update(|cx| {
1572 cx.update(|cx| {
1528 app.update(cx, |state, cx| {
1573 app.update(cx, |state, cx| {
@@ -1568,11 +1613,16 @@ mod tests {
1568 state.select_call_output(DeviceChoice::Device("headset".into()), cx);
1613 state.select_call_output(DeviceChoice::Device("headset".into()), cx);
1569 })
1614 })
1570 });
1615 });
1571 assert_eq!(load_input(&store), DeviceChoice::Device("headset-mic".into()));
1616 assert_eq!(
1617 load_input(&store),
1618 DeviceChoice::Device("headset-mic".into())
1619 );
1572 assert_eq!(load_output(&store), DeviceChoice::Device("headset".into()));
1620 assert_eq!(load_output(&store), DeviceChoice::Device("headset".into()));
1573 assert_eq!(
1621 assert_eq!(
1574 control.try_recv_command(),
1622 control.try_recv_command(),
1575 Some(CallCommand::SelectInput(DeviceChoice::Device("headset-mic".into())))
1623 Some(CallCommand::SelectInput(DeviceChoice::Device(
1624 "headset-mic".into()
1625 )))
1576 );
1626 );
1577 cx.update(|cx| {
1627 cx.update(|cx| {
1578 app.update(cx, |state, cx| {
1628 app.update(cx, |state, cx| {
@@ -1610,12 +1660,16 @@ mod tests {
1610 while let Some(command) = control.try_recv_command() {
1660 while let Some(command) = control.try_recv_command() {
1611 commands.push(command);
1661 commands.push(command);
1612 }
1662 }
1613 assert!(commands.contains(&CallCommand::SelectInput(DeviceChoice::Device(
1663 assert!(
1614 "unplugged-mic".into()
1664 commands.contains(&CallCommand::SelectInput(DeviceChoice::Device(
1615 ))));
1665 "unplugged-mic".into()
1616 assert!(commands.contains(&CallCommand::SelectOutput(DeviceChoice::Device(
1666 )))
1617 "headset".into()
1667 );
1618 ))));
1668 assert!(
1669 commands.contains(&CallCommand::SelectOutput(DeviceChoice::Device(
1670 "headset".into()
1671 )))
1672 );
1619 assert_eq!(
1673 assert_eq!(
1620 load_input(&store),
1674 load_input(&store),
1621 DeviceChoice::Device("unplugged-mic".into())
1675 DeviceChoice::Device("unplugged-mic".into())
@@ -1981,16 +2035,39 @@ mod tests {
1981 cx.update(|cx| {
2035 cx.update(|cx| {
1982 organizer.update(cx, |state, cx| {
2036 organizer.update(cx, |state, cx| {
1983 state.run_call_record_action(RecordAction::Start(RecordingKind::AudioOnly), cx);
2037 state.run_call_record_action(RecordAction::Start(RecordingKind::AudioOnly), cx);
1984 state.run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
2038 state
2039 .run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
1985 state.run_call_record_action(RecordAction::Stop(StopScope::RecordingOnly), cx);
2040 state.run_call_record_action(RecordAction::Stop(StopScope::RecordingOnly), cx);
1986 state.run_call_record_action(RecordAction::Stop(StopScope::TranscriptionOnly), cx);
2041 state.run_call_record_action(RecordAction::Stop(StopScope::TranscriptionOnly), cx);
1987 })
2042 })
1988 });
2043 });
1989 let title = "Standup".to_owned();
2044 let title = "Standup".to_owned();
1990 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::AudioOnly, title: title.clone() }));
2045 assert_eq!(
1991 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::TranscriptOnly, title }));
2046 control.try_recv_command(),
1992 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::RecordingOnly }));
2047 Some(CallCommand::StartRecording {
1993 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::TranscriptionOnly }));
2048 kind: RecordingKind::AudioOnly,
2049 title: title.clone()
2050 })
2051 );
2052 assert_eq!(
2053 control.try_recv_command(),
2054 Some(CallCommand::StartRecording {
2055 kind: RecordingKind::TranscriptOnly,
2056 title
2057 })
2058 );
2059 assert_eq!(
2060 control.try_recv_command(),
2061 Some(CallCommand::StopRecording {
2062 scope: StopScope::RecordingOnly
2063 })
2064 );
2065 assert_eq!(
2066 control.try_recv_command(),
2067 Some(CallCommand::StopRecording {
2068 scope: StopScope::TranscriptionOnly
2069 })
2070 );
1994 assert_eq!(control.try_recv_command(), None);
2071 assert_eq!(control.try_recv_command(), None);
1995 }
2072 }
1996
2073
@@ -1999,7 +2076,11 @@ mod tests {
1999 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2076 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2000 cx.update(|cx| {
2077 cx.update(|cx| {
2001 app.update(cx, |state, cx| {
2078 app.update(cx, |state, cx| {
2002 state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
2079 state.apply_call_update(
2080 7,
2081 CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),
2082 cx,
2083 );
2003 state.toggle_call_chat(cx);
2084 state.toggle_call_chat(cx);
2004 state.show_call_transcript(cx);
2085 state.show_call_transcript(cx);
2005 })
2086 })
@@ -2009,7 +2090,10 @@ mod tests {
2009 (call.chat_open, call.transcript_open)
2090 (call.chat_open, call.transcript_open)
2010 });
2091 });
2011 assert!(!chat_open && transcript_open);
2092 assert!(!chat_open && transcript_open);
2012 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
2093 assert_eq!(
2094 control.try_recv_command(),
2095 Some(CallCommand::SetCaptions(true))
2096 );
2013 cx.update(|cx| {
2097 cx.update(|cx| {
2014 app.update(cx, |state, cx| {
2098 app.update(cx, |state, cx| {
2015 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
2099 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
@@ -2026,15 +2110,24 @@ mod tests {
2026 }
2110 }
2027
2111
2028 #[gpui_kit::test]
2112 #[gpui_kit::test]
2029 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(cx: &mut TestAppContext) {
2113 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(
2114 cx: &mut TestAppContext,
2115 ) {
2030 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2116 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2031 cx.update(|cx| {
2117 cx.update(|cx| {
2032 app.update(cx, |state, cx| {
2118 app.update(cx, |state, cx| {
2033 state.choose_call_caption_language("de-DE", cx);
2119 state.choose_call_caption_language("de-DE", cx);
2034 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::Starting), cx);
2120 state.apply_call_update(
2121 7,
2122 CallUpdate::Captions(calling::CaptionState::Starting),
2123 cx,
2124 );
2035 })
2125 })
2036 });
2126 });
2037 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
2127 assert_eq!(
2128 control.try_recv_command(),
2129 Some(CallCommand::SetCaptions(true))
2130 );
2038 assert_eq!(control.try_recv_command(), None);
2131 assert_eq!(control.try_recv_command(), None);
2039 cx.update(|cx| {
2132 cx.update(|cx| {
2040 app.update(cx, |state, cx| {
2133 app.update(cx, |state, cx| {
@@ -2042,8 +2135,14 @@ mod tests {
2042 state.choose_call_caption_language("fr-FR", cx);
2135 state.choose_call_caption_language("fr-FR", cx);
2043 })
2136 })
2044 });
2137 });
2045 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("de-DE".into())));
2138 assert_eq!(
2046 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("fr-FR".into())));
2139 control.try_recv_command(),
2140 Some(CallCommand::SetCaptionLanguage("de-DE".into()))
2141 );
2142 assert_eq!(
2143 control.try_recv_command(),
2144 Some(CallCommand::SetCaptionLanguage("fr-FR".into()))
2145 );
2047 assert_eq!(control.try_recv_command(), None);
2146 assert_eq!(control.try_recv_command(), None);
2048 }
2147 }
2049
2148
@@ -2058,10 +2157,19 @@ mod tests {
2058 });
2157 });
2059 let (view, stored) = cx.update(|cx| {
2158 let (view, stored) = cx.update(|cx| {
2060 let state = app.read(cx);
2159 let state = app.read(cx);
2061 (state.call.as_ref().unwrap().model.view, ViewSettings::load(&state.store))
2160 (
2161 state.call.as_ref().unwrap().model.view,
2162 ViewSettings::load(&state.store),
2163 )
2062 });
2164 });
2063 assert_eq!((view.caption_size, view.caption_position), (CaptionSize::Large, CaptionPosition::Top));
2165 assert_eq!(
2064 assert_eq!((stored.caption_size, stored.caption_position), (CaptionSize::Large, CaptionPosition::Top));
2166 (view.caption_size, view.caption_position),
2167 (CaptionSize::Large, CaptionPosition::Top)
2168 );
2169 assert_eq!(
2170 (stored.caption_size, stored.caption_position),
2171 (CaptionSize::Large, CaptionPosition::Top)
2172 );
2065 }
2173 }
2066
2174
2067 fn live_one_to_one() -> CallModel {
2175 fn live_one_to_one() -> CallModel {
@@ -2102,9 +2210,7 @@ mod tests {
2102 }
2210 }
2103
2211
2104 #[gpui_kit::test]
2212 #[gpui_kit::test]
2105 fn a_blind_transfer_names_the_target(
2213 fn a_blind_transfer_names_the_target(cx: &mut TestAppContext) {
2106 cx: &mut TestAppContext,
2107 ) {
2108 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
2214 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
2109 cx.update(|cx| {
2215 cx.update(|cx| {
2110 app.update(cx, |state, cx| {
2216 app.update(cx, |state, cx| {
@@ -2435,7 +2541,13 @@ mod tests {
2435 })
2541 })
2436 .detach();
2542 .detach();
2437 app.update(cx, |state, cx| {
2543 app.update(cx, |state, cx| {
2438 state.apply_call_update(7, CallUpdate::State(CallState::Ended { reason: EndReason::Dropped }), cx);
2544 state.apply_call_update(
2545 7,
2546 CallUpdate::State(CallState::Ended {
2547 reason: EndReason::Dropped,
2548 }),
2549 cx,
2550 );
2439 assert!(state.call.is_none());
2551 assert!(state.call.is_none());
2440 assert!(state.notice.is_none());
2552 assert!(state.notice.is_none());
2441 let screen = state.call_end.as_ref().expect("end screen");
2553 let screen = state.call_end.as_ref().expect("end screen");
@@ -2453,7 +2565,13 @@ mod tests {
2453 let app = app_with_call(cx);
2565 let app = app_with_call(cx);
2454 cx.update(|cx| {
2566 cx.update(|cx| {
2455 app.update(cx, |state, cx| {
2567 app.update(cx, |state, cx| {
2456 state.apply_call_update(7, CallUpdate::State(CallState::Ended { reason: EndReason::Remote(EndKind::Removed) }), cx);
2568 state.apply_call_update(
2569 7,
2570 CallUpdate::State(CallState::Ended {
2571 reason: EndReason::Remote(EndKind::Removed),
2572 }),
2573 cx,
2574 );
2457 assert!(state.call_end.is_none());
2575 assert!(state.call_end.is_none());
2458 assert!(state.notice.is_some());
2576 assert!(state.notice.is_some());
2459 })
2577 })
crates/app-state/src/call/calendar.rs +2 −6
@@ -39,12 +39,8 @@ impl AppState {
39 39 pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {
40 40 let now = Utc::now();
41 41 let offset = Local::now().offset().fix();
42 self.calls_list.rebuild(
43 &self.call_history,
44 &self.sidebar.chats,
45 now,
46 offset,
47 );
42 self.calls_list
43 .rebuild(&self.call_history, &self.sidebar.chats, now, offset);
48 44 cx.emit(AppEvent::CallHistory);
49 45 cx.notify();
50 46 }
@@ -39,12 +39,8 @@ impl AppState {
39 pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {
39 pub fn rebuild_calls_list(&mut self, cx: &mut Context<Self>) {
40 let now = Utc::now();
40 let now = Utc::now();
41 let offset = Local::now().offset().fix();
41 let offset = Local::now().offset().fix();
42 self.calls_list.rebuild(
42 self.calls_list
43 &self.call_history,
43 .rebuild(&self.call_history, &self.sidebar.chats, now, offset);
44 &self.sidebar.chats,
45 now,
46 offset,
47 );
48 cx.emit(AppEvent::CallHistory);
44 cx.emit(AppEvent::CallHistory);
49 cx.notify();
45 cx.notify();
50 }
46 }
crates/app-state/src/call/consult.rs +64 −15
@@ -44,7 +44,12 @@ impl AppState {
44 44 self.begin_consult(target, handle, cx);
45 45 }
46 46
47 fn begin_consult(&mut self, target: TransferCandidate, handle: CallHandle, cx: &mut Context<Self>) {
47 fn begin_consult(
48 &mut self,
49 target: TransferCandidate,
50 handle: CallHandle,
51 cx: &mut Context<Self>,
52 ) {
48 53 let callee = (target.mri.clone(), target.name.clone());
49 54 self.note_call_feature("consult", format!("start with {}", target.mri));
50 55 self.send_call_command(CallCommand::Hold(true));
@@ -101,7 +106,9 @@ impl AppState {
101 106 }
102 107
103 108 pub(super) fn is_held_call(&self, call_id: u64) -> bool {
104 self.held_call.as_ref().is_some_and(|held| held.id == call_id)
109 self.held_call
110 .as_ref()
111 .is_some_and(|held| held.id == call_id)
105 112 }
106 113
107 114 pub(super) fn apply_held_call_update(&mut self, update: CallUpdate, cx: &mut Context<Self>) {
@@ -137,7 +144,11 @@ impl AppState {
137 144 .consult
138 145 .as_ref()
139 146 .is_some_and(|consult| consult.transfer == ConsultTransfer::Done);
140 if transferred { None } else { call.consult.take() }
147 if transferred {
148 None
149 } else {
150 call.consult.take()
151 }
141 152 });
142 153 if let Some(consult) = consult {
143 154 self.raise_notice(format!("{} hung up", consult.held_name), None, cx);
@@ -265,10 +276,16 @@ mod tests {
265 276 let call = state.call.as_ref().unwrap();
266 277 assert_ne!(call.id, HELD_ID);
267 278 assert_eq!(call.model.peer_name, "Ana");
268 assert_eq!(call.consult.as_ref().unwrap().banner_text(), "Chris is on hold");
279 assert_eq!(
280 call.consult.as_ref().unwrap().banner_text(),
281 "Chris is on hold"
282 );
269 283 })
270 284 });
271 assert_eq!(held_control.try_recv_command(), Some(CallCommand::Hold(true)));
285 assert_eq!(
286 held_control.try_recv_command(),
287 Some(CallCommand::Hold(true))
288 );
272 289 }
273 290
274 291 #[gpui_kit::test]
@@ -305,20 +322,40 @@ mod tests {
305 322 app.update(cx, |state, cx| {
306 323 state.apply_call_update(CONSULT_ID, CallUpdate::ReplacementLink(leg()), cx);
307 324 state.transfer_consulted(cx);
308 state.apply_call_update(HELD_ID, CallUpdate::TransferResult { succeeded: false }, cx);
325 state.apply_call_update(
326 HELD_ID,
327 CallUpdate::TransferResult { succeeded: false },
328 cx,
329 );
309 330 state.transfer_consulted(cx);
310 state.apply_call_update(HELD_ID, CallUpdate::TransferResult { succeeded: true }, cx);
331 state.apply_call_update(
332 HELD_ID,
333 CallUpdate::TransferResult { succeeded: true },
334 cx,
335 );
311 336 state.apply_call_update(HELD_ID, ended(), cx);
312 337 assert!(state.held_call.is_none());
313 338 assert!(state.call.as_ref().unwrap().consult.is_some());
314 339 state.apply_call_update(CONSULT_ID, ended(), cx);
315 340 assert!(state.call.is_none());
316 assert_eq!(state.notice.as_ref().unwrap().text, "Call transferred to Ana");
341 assert_eq!(
342 state.notice.as_ref().unwrap().text,
343 "Call transferred to Ana"
344 );
317 345 })
318 346 });
319 assert!(matches!(held_control.try_recv_command(), Some(CallCommand::Transfer { .. })));
320 assert!(matches!(held_control.try_recv_command(), Some(CallCommand::Transfer { .. })));
321 assert_eq!(consult_control.try_recv_command(), Some(CallCommand::Hangup));
347 assert!(matches!(
348 held_control.try_recv_command(),
349 Some(CallCommand::Transfer { .. })
350 ));
351 assert!(matches!(
352 held_control.try_recv_command(),
353 Some(CallCommand::Transfer { .. })
354 ));
355 assert_eq!(
356 consult_control.try_recv_command(),
357 Some(CallCommand::Hangup)
358 );
322 359 }
323 360
324 361 #[gpui_kit::test]
@@ -350,11 +387,20 @@ mod tests {
350 387 let call = state.call.as_ref().expect("held call is back");
351 388 assert_eq!(call.id, HELD_ID);
352 389 assert!(state.held_call.is_none());
353 assert_eq!(state.notice.as_ref().unwrap().text, "The consultation ended");
390 assert_eq!(
391 state.notice.as_ref().unwrap().text,
392 "The consultation ended"
393 );
354 394 })
355 395 });
356 assert_eq!(held_control.try_recv_command(), Some(CallCommand::Hold(false)));
357 assert_eq!(consult_control.try_recv_command(), Some(CallCommand::Hangup));
396 assert_eq!(
397 held_control.try_recv_command(),
398 Some(CallCommand::Hold(false))
399 );
400 assert_eq!(
401 consult_control.try_recv_command(),
402 Some(CallCommand::Hangup)
403 );
358 404 }
359 405
360 406 #[gpui_kit::test]
@@ -363,7 +409,10 @@ mod tests {
363 409 cx.update(|cx| {
364 410 app.update(cx, |state, cx| {
365 411 state.apply_call_update(HELD_ID, CallUpdate::Hold(HoldState::Active), cx);
366 assert_eq!(state.held_call.as_ref().unwrap().model.hold, HoldState::Active);
412 assert_eq!(
413 state.held_call.as_ref().unwrap().model.hold,
414 HoldState::Active
415 );
367 416 assert_eq!(state.call.as_ref().unwrap().model.hold, HoldState::Active);
368 417 assert_eq!(state.call.as_ref().unwrap().model.peer_name, "Ana");
369 418 assert!(!state.can_transfer_call());
@@ -44,7 +44,12 @@ impl AppState {
44 self.begin_consult(target, handle, cx);
44 self.begin_consult(target, handle, cx);
45 }
45 }
46
46
47 fn begin_consult(&mut self, target: TransferCandidate, handle: CallHandle, cx: &mut Context<Self>) {
47 fn begin_consult(
48 &mut self,
49 target: TransferCandidate,
50 handle: CallHandle,
51 cx: &mut Context<Self>,
52 ) {
48 let callee = (target.mri.clone(), target.name.clone());
53 let callee = (target.mri.clone(), target.name.clone());
49 self.note_call_feature("consult", format!("start with {}", target.mri));
54 self.note_call_feature("consult", format!("start with {}", target.mri));
50 self.send_call_command(CallCommand::Hold(true));
55 self.send_call_command(CallCommand::Hold(true));
@@ -101,7 +106,9 @@ impl AppState {
101 }
106 }
102
107
103 pub(super) fn is_held_call(&self, call_id: u64) -> bool {
108 pub(super) fn is_held_call(&self, call_id: u64) -> bool {
104 self.held_call.as_ref().is_some_and(|held| held.id == call_id)
109 self.held_call
110 .as_ref()
111 .is_some_and(|held| held.id == call_id)
105 }
112 }
106
113
107 pub(super) fn apply_held_call_update(&mut self, update: CallUpdate, cx: &mut Context<Self>) {
114 pub(super) fn apply_held_call_update(&mut self, update: CallUpdate, cx: &mut Context<Self>) {
@@ -137,7 +144,11 @@ impl AppState {
137 .consult
144 .consult
138 .as_ref()
145 .as_ref()
139 .is_some_and(|consult| consult.transfer == ConsultTransfer::Done);
146 .is_some_and(|consult| consult.transfer == ConsultTransfer::Done);
140 if transferred { None } else { call.consult.take() }
147 if transferred {
148 None
149 } else {
150 call.consult.take()
151 }
141 });
152 });
142 if let Some(consult) = consult {
153 if let Some(consult) = consult {
143 self.raise_notice(format!("{} hung up", consult.held_name), None, cx);
154 self.raise_notice(format!("{} hung up", consult.held_name), None, cx);
@@ -265,10 +276,16 @@ mod tests {
265 let call = state.call.as_ref().unwrap();
276 let call = state.call.as_ref().unwrap();
266 assert_ne!(call.id, HELD_ID);
277 assert_ne!(call.id, HELD_ID);
267 assert_eq!(call.model.peer_name, "Ana");
278 assert_eq!(call.model.peer_name, "Ana");
268 assert_eq!(call.consult.as_ref().unwrap().banner_text(), "Chris is on hold");
279 assert_eq!(
280 call.consult.as_ref().unwrap().banner_text(),
281 "Chris is on hold"
282 );
269 })
283 })
270 });
284 });
271 assert_eq!(held_control.try_recv_command(), Some(CallCommand::Hold(true)));
285 assert_eq!(
286 held_control.try_recv_command(),
287 Some(CallCommand::Hold(true))
288 );
272 }
289 }
273
290
274 #[gpui_kit::test]
291 #[gpui_kit::test]
@@ -305,20 +322,40 @@ mod tests {
305 app.update(cx, |state, cx| {
322 app.update(cx, |state, cx| {
306 state.apply_call_update(CONSULT_ID, CallUpdate::ReplacementLink(leg()), cx);
323 state.apply_call_update(CONSULT_ID, CallUpdate::ReplacementLink(leg()), cx);
307 state.transfer_consulted(cx);
324 state.transfer_consulted(cx);
308 state.apply_call_update(HELD_ID, CallUpdate::TransferResult { succeeded: false }, cx);
325 state.apply_call_update(
326 HELD_ID,
327 CallUpdate::TransferResult { succeeded: false },
328 cx,
329 );
309 state.transfer_consulted(cx);
330 state.transfer_consulted(cx);
310 state.apply_call_update(HELD_ID, CallUpdate::TransferResult { succeeded: true }, cx);
331 state.apply_call_update(
332 HELD_ID,
333 CallUpdate::TransferResult { succeeded: true },
334 cx,
335 );
311 state.apply_call_update(HELD_ID, ended(), cx);
336 state.apply_call_update(HELD_ID, ended(), cx);
312 assert!(state.held_call.is_none());
337 assert!(state.held_call.is_none());
313 assert!(state.call.as_ref().unwrap().consult.is_some());
338 assert!(state.call.as_ref().unwrap().consult.is_some());
314 state.apply_call_update(CONSULT_ID, ended(), cx);
339 state.apply_call_update(CONSULT_ID, ended(), cx);
315 assert!(state.call.is_none());
340 assert!(state.call.is_none());
316 assert_eq!(state.notice.as_ref().unwrap().text, "Call transferred to Ana");
341 assert_eq!(
342 state.notice.as_ref().unwrap().text,
343 "Call transferred to Ana"
344 );
317 })
345 })
318 });
346 });
319 assert!(matches!(held_control.try_recv_command(), Some(CallCommand::Transfer { .. })));
347 assert!(matches!(
320 assert!(matches!(held_control.try_recv_command(), Some(CallCommand::Transfer { .. })));
348 held_control.try_recv_command(),
321 assert_eq!(consult_control.try_recv_command(), Some(CallCommand::Hangup));
349 Some(CallCommand::Transfer { .. })
350 ));
351 assert!(matches!(
352 held_control.try_recv_command(),
353 Some(CallCommand::Transfer { .. })
354 ));
355 assert_eq!(
356 consult_control.try_recv_command(),
357 Some(CallCommand::Hangup)
358 );
322 }
359 }
323
360
324 #[gpui_kit::test]
361 #[gpui_kit::test]
@@ -350,11 +387,20 @@ mod tests {
350 let call = state.call.as_ref().expect("held call is back");
387 let call = state.call.as_ref().expect("held call is back");
351 assert_eq!(call.id, HELD_ID);
388 assert_eq!(call.id, HELD_ID);
352 assert!(state.held_call.is_none());
389 assert!(state.held_call.is_none());
353 assert_eq!(state.notice.as_ref().unwrap().text, "The consultation ended");
390 assert_eq!(
391 state.notice.as_ref().unwrap().text,
392 "The consultation ended"
393 );
354 })
394 })
355 });
395 });
356 assert_eq!(held_control.try_recv_command(), Some(CallCommand::Hold(false)));
396 assert_eq!(
357 assert_eq!(consult_control.try_recv_command(), Some(CallCommand::Hangup));
397 held_control.try_recv_command(),
398 Some(CallCommand::Hold(false))
399 );
400 assert_eq!(
401 consult_control.try_recv_command(),
402 Some(CallCommand::Hangup)
403 );
358 }
404 }
359
405
360 #[gpui_kit::test]
406 #[gpui_kit::test]
@@ -363,7 +409,10 @@ mod tests {
363 cx.update(|cx| {
409 cx.update(|cx| {
364 app.update(cx, |state, cx| {
410 app.update(cx, |state, cx| {
365 state.apply_call_update(HELD_ID, CallUpdate::Hold(HoldState::Active), cx);
411 state.apply_call_update(HELD_ID, CallUpdate::Hold(HoldState::Active), cx);
366 assert_eq!(state.held_call.as_ref().unwrap().model.hold, HoldState::Active);
412 assert_eq!(
413 state.held_call.as_ref().unwrap().model.hold,
414 HoldState::Active
415 );
367 assert_eq!(state.call.as_ref().unwrap().model.hold, HoldState::Active);
416 assert_eq!(state.call.as_ref().unwrap().model.hold, HoldState::Active);
368 assert_eq!(state.call.as_ref().unwrap().model.peer_name, "Ana");
417 assert_eq!(state.call.as_ref().unwrap().model.peer_name, "Ana");
369 assert!(!state.can_transfer_call());
418 assert!(!state.can_transfer_call());
crates/app-state/src/call/features.rs +3 −13
@@ -1,6 +1,4 @@
1 use calling::{
2 CallCommand, CallSpec, Callee, EndKind, EndReason, HoldState,
3 };
1 use calling::{CallCommand, CallSpec, Callee, EndKind, EndReason, HoldState};
4 2 use gpui_kit::*;
5 3
6 4 use super::background::BackgroundPick;
@@ -57,11 +55,7 @@ impl AppState {
57 55 self.send_call_command(command);
58 56 }
59 57
60 pub fn open_call_transcript(
61 &mut self,
62 panel: AnyView,
63 cx: &mut Context<Self>,
64 ) {
58 pub fn open_call_transcript(&mut self, panel: AnyView, cx: &mut Context<Self>) {
65 59 self.transcript_panel = Some(panel);
66 60 self.show_call_transcript(cx);
67 61 }
@@ -212,11 +206,7 @@ impl AppState {
212 206 && self.held_call.is_none()
213 207 }
214 208
215 pub fn open_transfer_picker(
216 &mut self,
217 picker: AnyView,
218 cx: &mut Context<Self>,
219 ) {
209 pub fn open_transfer_picker(&mut self, picker: AnyView, cx: &mut Context<Self>) {
220 210 if self.can_transfer_call() {
221 211 self.transfer_picker = Some(picker);
222 212 cx.notify();
@@ -1,6 +1,4 @@
1use calling::{
1use calling::{CallCommand, CallSpec, Callee, EndKind, EndReason, HoldState};
2 CallCommand, CallSpec, Callee, EndKind, EndReason, HoldState,
3};
4use gpui_kit::*;
2use gpui_kit::*;
5
3
6use super::background::BackgroundPick;
4use super::background::BackgroundPick;
@@ -57,11 +55,7 @@ impl AppState {
57 self.send_call_command(command);
55 self.send_call_command(command);
58 }
56 }
59
57
60 pub fn open_call_transcript(
58 pub fn open_call_transcript(&mut self, panel: AnyView, cx: &mut Context<Self>) {
61 &mut self,
62 panel: AnyView,
63 cx: &mut Context<Self>,
64 ) {
65 self.transcript_panel = Some(panel);
59 self.transcript_panel = Some(panel);
66 self.show_call_transcript(cx);
60 self.show_call_transcript(cx);
67 }
61 }
@@ -212,11 +206,7 @@ impl AppState {
212 && self.held_call.is_none()
206 && self.held_call.is_none()
213 }
207 }
214
208
215 pub fn open_transfer_picker(
209 pub fn open_transfer_picker(&mut self, picker: AnyView, cx: &mut Context<Self>) {
216 &mut self,
217 picker: AnyView,
218 cx: &mut Context<Self>,
219 ) {
220 if self.can_transfer_call() {
210 if self.can_transfer_call() {
221 self.transfer_picker = Some(picker);
211 self.transfer_picker = Some(picker);
222 cx.notify();
212 cx.notify();
crates/app-state/src/call/launcher.rs +34 −10
@@ -1,14 +1,14 @@
1 1 use std::future::Future;
2 2 use std::sync::{Arc, Mutex};
3 3
4 use tokio::sync::watch;
5 4 use std::time::Duration;
5 use tokio::sync::watch;
6 6
7 7 use calling::meeting::{LiveMeeting, fetch_live_meeting};
8 8 use calling::{
9 AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,
10 DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent, MeetingTarget,
11 call_channel,
9 AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState,
10 CallUpdate, DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent,
11 MeetingTarget, call_channel,
12 12 };
13 13 use session::{Session, SessionConfig, Transport};
14 14
@@ -423,24 +423,39 @@ mod tests {
423 423 #[tokio::test]
424 424 async fn waiting_gives_up_after_the_timeout() {
425 425 let (_sender, receiver) = watch::channel(None::<u32>);
426 assert_eq!(wait_until_ready(receiver, Duration::from_millis(20)).await, None);
426 assert_eq!(
427 wait_until_ready(receiver, Duration::from_millis(20)).await,
428 None
429 );
427 430 }
428 431
429 432 #[tokio::test]
430 433 async fn waiting_gives_up_when_the_launcher_is_gone() {
431 434 let (sender, receiver) = watch::channel(None::<u32>);
432 435 drop(sender);
433 assert_eq!(wait_until_ready(receiver, Duration::from_secs(5)).await, None);
436 assert_eq!(
437 wait_until_ready(receiver, Duration::from_secs(5)).await,
438 None
439 );
434 440 }
435 441
436 442 #[tokio::test]
437 443 async fn queued_call_fails_with_notice_after_the_timeout() {
438 444 let (_sender, receiver) = watch::channel(None);
439 445 let (mut handle, control) = call_channel();
440 queue_outgoing(receiver, Duration::from_millis(20), CallSpec::Echo, OutgoingKind::Audio, control).await;
446 queue_outgoing(
447 receiver,
448 Duration::from_millis(20),
449 CallSpec::Echo,
450 OutgoingKind::Audio,
451 control,
452 )
453 .await;
441 454 assert_eq!(
442 455 handle.updates.recv().await,
443 Some(CallUpdate::State(CallState::Ended { reason: EndReason::Failed(NOT_READY.to_owned()) }))
456 Some(CallUpdate::State(CallState::Ended {
457 reason: EndReason::Failed(NOT_READY.to_owned())
458 }))
444 459 );
445 460 }
446 461
@@ -449,10 +464,19 @@ mod tests {
449 464 let (_sender, receiver) = watch::channel(None);
450 465 let (mut handle, control) = call_channel();
451 466 handle.commands.send(CallCommand::Hangup).unwrap();
452 queue_outgoing(receiver, Duration::from_secs(30), CallSpec::Echo, OutgoingKind::Video, control).await;
467 queue_outgoing(
468 receiver,
469 Duration::from_secs(30),
470 CallSpec::Echo,
471 OutgoingKind::Video,
472 control,
473 )
474 .await;
453 475 assert_eq!(
454 476 handle.updates.recv().await,
455 Some(CallUpdate::State(CallState::Ended { reason: EndReason::Cancelled }))
477 Some(CallUpdate::State(CallState::Ended {
478 reason: EndReason::Cancelled
479 }))
456 480 );
457 481 }
458 482 }
@@ -1,14 +1,14 @@
1use std::future::Future;
1use std::future::Future;
2use std::sync::{Arc, Mutex};
2use std::sync::{Arc, Mutex};
3
3
4use tokio::sync::watch;
5use std::time::Duration;
4use std::time::Duration;
5use tokio::sync::watch;
6
6
7use calling::meeting::{LiveMeeting, fetch_live_meeting};
7use calling::meeting::{LiveMeeting, fetch_live_meeting};
8use calling::{
8use calling::{
9 AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,
9 AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState,
10 DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent, MeetingTarget,
10 CallUpdate, DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent,
11 call_channel,
11 MeetingTarget, call_channel,
12};
12};
13use session::{Session, SessionConfig, Transport};
13use session::{Session, SessionConfig, Transport};
14
14
@@ -423,24 +423,39 @@ mod tests {
423 #[tokio::test]
423 #[tokio::test]
424 async fn waiting_gives_up_after_the_timeout() {
424 async fn waiting_gives_up_after_the_timeout() {
425 let (_sender, receiver) = watch::channel(None::<u32>);
425 let (_sender, receiver) = watch::channel(None::<u32>);
426 assert_eq!(wait_until_ready(receiver, Duration::from_millis(20)).await, None);
426 assert_eq!(
427 wait_until_ready(receiver, Duration::from_millis(20)).await,
428 None
429 );
427 }
430 }
428
431
429 #[tokio::test]
432 #[tokio::test]
430 async fn waiting_gives_up_when_the_launcher_is_gone() {
433 async fn waiting_gives_up_when_the_launcher_is_gone() {
431 let (sender, receiver) = watch::channel(None::<u32>);
434 let (sender, receiver) = watch::channel(None::<u32>);
432 drop(sender);
435 drop(sender);
433 assert_eq!(wait_until_ready(receiver, Duration::from_secs(5)).await, None);
436 assert_eq!(
437 wait_until_ready(receiver, Duration::from_secs(5)).await,
438 None
439 );
434 }
440 }
435
441
436 #[tokio::test]
442 #[tokio::test]
437 async fn queued_call_fails_with_notice_after_the_timeout() {
443 async fn queued_call_fails_with_notice_after_the_timeout() {
438 let (_sender, receiver) = watch::channel(None);
444 let (_sender, receiver) = watch::channel(None);
439 let (mut handle, control) = call_channel();
445 let (mut handle, control) = call_channel();
440 queue_outgoing(receiver, Duration::from_millis(20), CallSpec::Echo, OutgoingKind::Audio, control).await;
446 queue_outgoing(
447 receiver,
448 Duration::from_millis(20),
449 CallSpec::Echo,
450 OutgoingKind::Audio,
451 control,
452 )
453 .await;
441 assert_eq!(
454 assert_eq!(
442 handle.updates.recv().await,
455 handle.updates.recv().await,
443 Some(CallUpdate::State(CallState::Ended { reason: EndReason::Failed(NOT_READY.to_owned()) }))
456 Some(CallUpdate::State(CallState::Ended {
457 reason: EndReason::Failed(NOT_READY.to_owned())
458 }))
444 );
459 );
445 }
460 }
446
461
@@ -449,10 +464,19 @@ mod tests {
449 let (_sender, receiver) = watch::channel(None);
464 let (_sender, receiver) = watch::channel(None);
450 let (mut handle, control) = call_channel();
465 let (mut handle, control) = call_channel();
451 handle.commands.send(CallCommand::Hangup).unwrap();
466 handle.commands.send(CallCommand::Hangup).unwrap();
452 queue_outgoing(receiver, Duration::from_secs(30), CallSpec::Echo, OutgoingKind::Video, control).await;
467 queue_outgoing(
468 receiver,
469 Duration::from_secs(30),
470 CallSpec::Echo,
471 OutgoingKind::Video,
472 control,
473 )
474 .await;
453 assert_eq!(
475 assert_eq!(
454 handle.updates.recv().await,
476 handle.updates.recv().await,
455 Some(CallUpdate::State(CallState::Ended { reason: EndReason::Cancelled }))
477 Some(CallUpdate::State(CallState::Ended {
478 reason: EndReason::Cancelled
479 }))
456 );
480 );
457 }
481 }
458}
482}
crates/app-state/src/call/list.rs +7 −2
@@ -50,7 +50,9 @@ impl HistoryFilter {
50 50 match self {
51 51 HistoryFilter::All => true,
52 52 HistoryFilter::Missed => entry.missed(),
53 HistoryFilter::Incoming => entry.direction == CallDirection::Incoming && !entry.missed(),
53 HistoryFilter::Incoming => {
54 entry.direction == CallDirection::Incoming && !entry.missed()
55 }
54 56 HistoryFilter::Outgoing => entry.direction == CallDirection::Outgoing,
55 57 }
56 58 }
@@ -253,7 +255,10 @@ mod tests {
253 255 let mut list = CallsList::default();
254 256 list.set_filter(HistoryFilter::Missed);
255 257 list.rebuild(&[call("outgoing")], &[], now(), zero());
256 assert_eq!(list.entries().last(), Some(&ListEntry::Empty("No missed calls")));
258 assert_eq!(
259 list.entries().last(),
260 Some(&ListEntry::Empty("No missed calls"))
261 );
257 262 }
258 263
259 264 #[test]
@@ -50,7 +50,9 @@ impl HistoryFilter {
50 match self {
50 match self {
51 HistoryFilter::All => true,
51 HistoryFilter::All => true,
52 HistoryFilter::Missed => entry.missed(),
52 HistoryFilter::Missed => entry.missed(),
53 HistoryFilter::Incoming => entry.direction == CallDirection::Incoming && !entry.missed(),
53 HistoryFilter::Incoming => {
54 entry.direction == CallDirection::Incoming && !entry.missed()
55 }
54 HistoryFilter::Outgoing => entry.direction == CallDirection::Outgoing,
56 HistoryFilter::Outgoing => entry.direction == CallDirection::Outgoing,
55 }
57 }
56 }
58 }
@@ -253,7 +255,10 @@ mod tests {
253 let mut list = CallsList::default();
255 let mut list = CallsList::default();
254 list.set_filter(HistoryFilter::Missed);
256 list.set_filter(HistoryFilter::Missed);
255 list.rebuild(&[call("outgoing")], &[], now(), zero());
257 list.rebuild(&[call("outgoing")], &[], now(), zero());
256 assert_eq!(list.entries().last(), Some(&ListEntry::Empty("No missed calls")));
258 assert_eq!(
259 list.entries().last(),
260 Some(&ListEntry::Empty("No missed calls"))
261 );
257 }
262 }
258
263
259 #[test]
264 #[test]
crates/app-state/src/call/mod.rs +21 −19
@@ -12,34 +12,32 @@ pub mod overlay_layout;
12 12 pub mod people_actions;
13 13 pub mod prejoin;
14 14 pub mod record_load;
15 pub mod remote_command;
16 15 pub mod reminder;
16 pub mod remote_command;
17 pub mod schedule;
17 18 pub mod share_actions;
18 19 pub mod share_overlay;
19 20 pub mod speed_dial;
20 pub mod schedule;
21 21 pub mod target;
22 22 pub mod view_actions;
23 23 pub mod week;
24 24
25 25 pub use app_call_model::{
26 26 agenda, background, bubbles, caption_style, demo, end_screen, fullscreen, health, media, mic,
27 model, options_dialog, people, preview, record_rights,
28 recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,
29 week_grid,
27 model, options_dialog, people, preview, record_rights, recording_menu, report, ring,
28 share_view, stage_layout, stage_split, transcript, view_settings, week_grid,
30 29 };
31 30
32 31 pub use actions::{
33 32 apply_sound_output, load_camera, load_camera_effects, load_input, load_output, load_share_sound,
34 33 };
35 pub use mic::load_mic;
36 34 pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
37 pub use caption_style::{CaptionPosition, CaptionSize};
38 35 pub use background::{
39 36 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
40 37 load_custom_backgrounds,
41 38 };
42 39 pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};
40 pub use caption_style::{CaptionPosition, CaptionSize};
43 41 pub use demo::DemoScene;
44 42 pub use features::TransferCandidate;
45 43 pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};
@@ -47,29 +45,33 @@ pub use history::CallRow;
47 45 pub use launcher::CallLauncher;
48 46 pub use list::{CALL_ROW_HEIGHT, CallsList, EMPTY_HEIGHT, HistoryFilter, ListEntry};
49 47 pub use media::CallMedia;
48 pub use mic::load_mic;
49 pub use model::ConsultCall;
50 50 pub use model::{
51 51 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
52 52 TileState,
53 53 };
54 pub use model::ConsultCall;
55 54 pub use options_dialog::OptionsDialog;
56 pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
57 55 pub use people::{PeopleSections, PersonRow, people_sections};
58 pub use share_actions::ZoomStep;
59 pub use speed_dial::SpeedDialEntry;
60 pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, ShareStage, load_flag};
56 pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
61 57 pub use preview::{CameraPreview, preview_backgrounds};
58 pub use record_rights::{RecordBlock, RecordFeature};
59 pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
62 60 pub use reminder::{MeetingToasts, ReminderPhase, subtitle as meeting_subtitle};
61 pub use report::load_enabled as load_report_enabled;
63 62 pub use ring::{MissedCall, RingEntry, Rings};
64 pub use stage_split::{
65 GRID_PADDING, STRIP_GAP, GalleryPage, SpeakerSplit, StripSplit, TILE_GAP, gallery_page,
66 measured_stage, speaker_split, strip_split, video_wants,
63 pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
64 pub use share_actions::ZoomStep;
65 pub use share_view::{
66 SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, ShareStage, load_flag,
67 load_strip_width,
67 68 };
69 pub use speed_dial::SpeedDialEntry;
68 70 pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};
69 pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
70 pub use record_rights::{RecordBlock, RecordFeature};
71 pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
72 pub use report::load_enabled as load_report_enabled;
71 pub use stage_split::{
72 GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP, gallery_split, measured_stage,
73 speaker_split, strip_split, video_wants,
74 };
73 75 pub use target::{is_echo_chat, plan_for_chat};
74 76 pub use transcript::clock_label;
75 77 pub use view_settings::{CallLayout, ViewSettings};
@@ -12,34 +12,32 @@ pub mod overlay_layout;
12pub mod people_actions;
12pub mod people_actions;
13pub mod prejoin;
13pub mod prejoin;
14pub mod record_load;
14pub mod record_load;
15pub mod remote_command;
16pub mod reminder;
15pub mod reminder;
16pub mod remote_command;
17pub mod schedule;
17pub mod share_actions;
18pub mod share_actions;
18pub mod share_overlay;
19pub mod share_overlay;
19pub mod speed_dial;
20pub mod speed_dial;
20pub mod schedule;
21pub mod target;
21pub mod target;
22pub mod view_actions;
22pub mod view_actions;
23pub mod week;
23pub mod week;
24
24
25pub use app_call_model::{
25pub use app_call_model::{
26 agenda, background, bubbles, caption_style, demo, end_screen, fullscreen, health, media, mic,
26 agenda, background, bubbles, caption_style, demo, end_screen, fullscreen, health, media, mic,
27 model, options_dialog, people, preview, record_rights,
27 model, options_dialog, people, preview, record_rights, recording_menu, report, ring,
28 recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,
28 share_view, stage_layout, stage_split, transcript, view_settings, week_grid,
29 week_grid,
30};
29};
31
30
32pub use actions::{
31pub use actions::{
33 apply_sound_output, load_camera, load_camera_effects, load_input, load_output, load_share_sound,
32 apply_sound_output, load_camera, load_camera_effects, load_input, load_output, load_share_sound,
34};
33};
35pub use mic::load_mic;
36pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
34pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
37pub use caption_style::{CaptionPosition, CaptionSize};
38pub use background::{
35pub use background::{
39 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
36 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
40 load_custom_backgrounds,
37 load_custom_backgrounds,
41};
38};
42pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};
39pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};
40pub use caption_style::{CaptionPosition, CaptionSize};
43pub use demo::DemoScene;
41pub use demo::DemoScene;
44pub use features::TransferCandidate;
42pub use features::TransferCandidate;
45pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};
43pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};
@@ -47,29 +45,33 @@ pub use history::CallRow;
47pub use launcher::CallLauncher;
45pub use launcher::CallLauncher;
48pub use list::{CALL_ROW_HEIGHT, CallsList, EMPTY_HEIGHT, HistoryFilter, ListEntry};
46pub use list::{CALL_ROW_HEIGHT, CallsList, EMPTY_HEIGHT, HistoryFilter, ListEntry};
49pub use media::CallMedia;
47pub use media::CallMedia;
48pub use mic::load_mic;
49pub use model::ConsultCall;
50pub use model::{
50pub use model::{
51 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
51 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
52 TileState,
52 TileState,
53};
53};
54pub use model::ConsultCall;
55pub use options_dialog::OptionsDialog;
54pub use options_dialog::OptionsDialog;
56pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
57pub use people::{PeopleSections, PersonRow, people_sections};
55pub use people::{PeopleSections, PersonRow, people_sections};
58pub use share_actions::ZoomStep;
56pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
59pub use speed_dial::SpeedDialEntry;
60pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, ShareStage, load_flag};
61pub use preview::{CameraPreview, preview_backgrounds};
57pub use preview::{CameraPreview, preview_backgrounds};
58pub use record_rights::{RecordBlock, RecordFeature};
59pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
62pub use reminder::{MeetingToasts, ReminderPhase, subtitle as meeting_subtitle};
60pub use reminder::{MeetingToasts, ReminderPhase, subtitle as meeting_subtitle};
61pub use report::load_enabled as load_report_enabled;
63pub use ring::{MissedCall, RingEntry, Rings};
62pub use ring::{MissedCall, RingEntry, Rings};
64pub use stage_split::{
63pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
65 GRID_PADDING, STRIP_GAP, GalleryPage, SpeakerSplit, StripSplit, TILE_GAP, gallery_page,
64pub use share_actions::ZoomStep;
66 measured_stage, speaker_split, strip_split, video_wants,
65pub use share_view::{
66 SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, ShareStage, load_flag,
67 load_strip_width,
67};
68};
69pub use speed_dial::SpeedDialEntry;
68pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};
70pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};
69pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
71pub use stage_split::{
70pub use record_rights::{RecordBlock, RecordFeature};
72 GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP, gallery_split, measured_stage,
71pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
73 speaker_split, strip_split, video_wants,
72pub use report::load_enabled as load_report_enabled;
74};
73pub use target::{is_echo_chat, plan_for_chat};
75pub use target::{is_echo_chat, plan_for_chat};
74pub use transcript::clock_label;
76pub use transcript::clock_label;
75pub use view_settings::{CallLayout, ViewSettings};
77pub use view_settings::{CallLayout, ViewSettings};
crates/app-state/src/call/people_actions.rs +146 −38
@@ -27,7 +27,11 @@ impl AppState {
27 27 }
28 28
29 29 pub fn set_call_lock(&mut self, locked: bool, _cx: &mut Context<Self>) {
30 if self.call.as_ref().is_some_and(|call| call.model.organizes_meeting()) {
30 if self
31 .call
32 .as_ref()
33 .is_some_and(|call| call.model.organizes_meeting())
34 {
31 35 self.send_call_command(CallCommand::SetLock(locked));
32 36 }
33 37 }
@@ -48,19 +52,43 @@ impl AppState {
48 52 allowed: bool,
49 53 _cx: &mut Context<Self>,
50 54 ) {
51 if self.call.as_ref().is_some_and(|call| call.model.can_change_roles(&mri)) {
52 self.send_call_command(CallCommand::SetAttendeeModality { mri, modality, allowed });
55 if self
56 .call
57 .as_ref()
58 .is_some_and(|call| call.model.can_change_roles(&mri))
59 {
60 self.send_call_command(CallCommand::SetAttendeeModality {
61 mri,
62 modality,
63 allowed,
64 });
53 65 }
54 66 }
55 67
56 pub fn set_call_attendee_restrictions(&mut self, mic_off: bool, camera_off: bool, _cx: &mut Context<Self>) {
57 if self.call.as_ref().is_some_and(|call| call.model.organizes_meeting()) {
58 self.send_call_command(CallCommand::SetAttendeeRestrictions { mic_off, camera_off });
68 pub fn set_call_attendee_restrictions(
69 &mut self,
70 mic_off: bool,
71 camera_off: bool,
72 _cx: &mut Context<Self>,
73 ) {
74 if self
75 .call
76 .as_ref()
77 .is_some_and(|call| call.model.organizes_meeting())
78 {
79 self.send_call_command(CallCommand::SetAttendeeRestrictions {
80 mic_off,
81 camera_off,
82 });
59 83 }
60 84 }
61 85
62 86 pub fn open_meeting_options(&mut self, cx: &mut Context<Self>) {
63 let Some(call) = self.call.as_mut().filter(|call| call.model.organizes_meeting()) else {
87 let Some(call) = self
88 .call
89 .as_mut()
90 .filter(|call| call.model.organizes_meeting())
91 else {
64 92 return;
65 93 };
66 94 call.options_dialog = Some(OptionsDialog::loading());
@@ -69,13 +97,21 @@ impl AppState {
69 97 }
70 98
71 99 pub fn close_meeting_options(&mut self, cx: &mut Context<Self>) {
72 if let Some(call) = self.call.as_mut().filter(|call| call.options_dialog.is_some()) {
100 if let Some(call) = self
101 .call
102 .as_mut()
103 .filter(|call| call.options_dialog.is_some())
104 {
73 105 call.options_dialog = None;
74 106 cx.notify();
75 107 }
76 108 }
77 109
78 pub fn edit_meeting_options(&mut self, edit: impl FnOnce(&mut MeetingOptions), cx: &mut Context<Self>) {
110 pub fn edit_meeting_options(
111 &mut self,
112 edit: impl FnOnce(&mut MeetingOptions),
113 cx: &mut Context<Self>,
114 ) {
79 115 let Some(draft) = self
80 116 .call
81 117 .as_mut()
@@ -104,7 +140,13 @@ impl AppState {
104 140 let present: Vec<&str> = self
105 141 .call
106 142 .as_ref()
107 .map(|call| call.model.tiles.iter().map(|tile| tile.mri.as_str()).collect())
143 .map(|call| {
144 call.model
145 .tiles
146 .iter()
147 .map(|tile| tile.mri.as_str())
148 .collect()
149 })
108 150 .unwrap_or_default();
109 151 self.transfer_candidates()
110 152 .into_iter()
@@ -112,12 +154,12 @@ impl AppState {
112 154 .collect()
113 155 }
114 156
115 pub fn open_invite_picker(
116 &mut self,
117 picker: AnyView,
118 cx: &mut Context<Self>,
119 ) {
120 if self.call.as_ref().is_some_and(|call| call.model.can_invite()) {
157 pub fn open_invite_picker(&mut self, picker: AnyView, cx: &mut Context<Self>) {
158 if self
159 .call
160 .as_ref()
161 .is_some_and(|call| call.model.can_invite())
162 {
121 163 self.transfer_picker = Some(picker);
122 164 cx.notify();
123 165 }
@@ -128,9 +170,14 @@ impl AppState {
128 170 let Some(call) = self.call.as_mut().filter(|call| call.model.can_invite()) else {
129 171 return;
130 172 };
131 let callee = Callee { mri: target.mri.clone(), display_name: target.name.clone() };
173 let callee = Callee {
174 mri: target.mri.clone(),
175 display_name: target.name.clone(),
176 };
132 177 if !call.model.tiles.iter().any(|tile| tile.mri == callee.mri) {
133 call.model.tiles.push(Tile::invited(&callee.mri, &callee.display_name));
178 call.model
179 .tiles
180 .push(Tile::invited(&callee.mri, &callee.display_name));
134 181 }
135 182 let one_to_one = call.model.kind == CallKind::Direct;
136 183 let peer_user_id = call
@@ -143,18 +190,27 @@ impl AppState {
143 190 cx.emit(AppEvent::Call);
144 191 cx.notify();
145 192 if !one_to_one || self.mode.demo {
146 self.send_call_command(CallCommand::Invite { callees: vec![callee], group_thread: None });
193 self.send_call_command(CallCommand::Invite {
194 callees: vec![callee],
195 group_thread: None,
196 });
147 197 return;
148 198 }
149 199 let (Some(engine), Some(peer_user_id), Some(invited_user_id)) =
150 200 (self.engine.clone(), peer_user_id, target.user_id.clone())
151 201 else {
152 let notice = if self.engine.is_none() { NOT_CONNECTED_NOTICE } else { NO_PEER_NOTICE };
202 let notice = if self.engine.is_none() {
203 NOT_CONNECTED_NOTICE
204 } else {
205 NO_PEER_NOTICE
206 };
153 207 self.raise_notice(notice.to_owned(), None, cx);
154 208 return;
155 209 };
156 210 let receiver = runtime::spawn(async move {
157 engine.create_group(&[peer_user_id, invited_user_id], None).await
211 engine
212 .create_group(&[peer_user_id, invited_user_id], None)
213 .await
158 214 });
159 215 cx.spawn(async move |this, cx| {
160 216 let created = receiver.await.ok().and_then(Result::ok);
@@ -179,8 +235,8 @@ mod tests {
179 235 use std::time::Instant;
180 236
181 237 use calling::{
182 CallCommand, CallControl, CallState, CallUpdate, MeetingCapability, MeetingOptions, MeetingRole,
183 Modality, RosterEntry, call_channel,
238 CallCommand, CallControl, CallState, CallUpdate, MeetingCapability, MeetingOptions,
239 MeetingRole, Modality, RosterEntry, call_channel,
184 240 };
185 241 use gpui_kit::{AppContext as _, Entity, TestAppContext};
186 242 use serde_json::json;
@@ -189,14 +245,21 @@ mod tests {
189 245 use crate::app_state::{AppState, Mode};
190 246 use crate::call::{ActiveCall, CallModel, TransferCandidate};
191 247
192 fn app_with_meeting(cx: &mut TestAppContext, organizer: bool) -> (Entity<AppState>, CallControl) {
248 fn app_with_meeting(
249 cx: &mut TestAppContext,
250 organizer: bool,
251 ) -> (Entity<AppState>, CallControl) {
193 252 cx.update(gpui_kit::init);
194 253 let store = Arc::new(Store::open_in_memory().unwrap());
195 254 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
196 255 let (handle, control) = call_channel();
197 256 let mut model = CallModel::meeting("Standup", organizer);
198 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
199 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
257 model.apply(CallUpdate::State(CallState::Connected {
258 since: Instant::now(),
259 }));
260 model.apply(CallUpdate::OwnIdentity {
261 mri: "8:orgid:me".into(),
262 });
200 263 model.apply(CallUpdate::Roster(vec![RosterEntry {
201 264 mri: "8:orgid:a".into(),
202 265 display_name: "Ana".into(),
@@ -218,7 +281,8 @@ mod tests {
218 281 }
219 282
220 283 fn options() -> MeetingOptions {
221 let option = |name: &str, value: serde_json::Value| json!({"name": name, "currentValue": value});
284 let option =
285 |name: &str, value: serde_json::Value| json!({"name": name, "currentValue": value});
222 286 MeetingOptions::from_response(&json!({"options": [
223 287 option("AutoAdmittedUsers", json!("EveryoneInCompany")),
224 288 option("PresenterOption", json!("Everyone")),
@@ -276,15 +340,25 @@ mod tests {
276 340 assert_eq!(control.try_recv_command(), Some(CallCommand::SetLock(true)));
277 341 assert_eq!(
278 342 control.try_recv_command(),
279 Some(CallCommand::SetRole { mri: "8:orgid:a".into(), role: MeetingRole::Presenter })
343 Some(CallCommand::SetRole {
344 mri: "8:orgid:a".into(),
345 role: MeetingRole::Presenter
346 })
280 347 );
281 348 assert_eq!(
282 349 control.try_recv_command(),
283 Some(CallCommand::SetAttendeeModality { mri: "8:orgid:a".into(), modality: Modality::Camera, allowed: false })
350 Some(CallCommand::SetAttendeeModality {
351 mri: "8:orgid:a".into(),
352 modality: Modality::Camera,
353 allowed: false
354 })
284 355 );
285 356 assert_eq!(
286 357 control.try_recv_command(),
287 Some(CallCommand::SetAttendeeRestrictions { mic_off: true, camera_off: true })
358 Some(CallCommand::SetAttendeeRestrictions {
359 mic_off: true,
360 camera_off: true
361 })
288 362 );
289 363 assert_eq!(control.try_recv_command(), None);
290 364 }
@@ -296,7 +370,10 @@ mod tests {
296 370 app.update(cx, |state, cx| {
297 371 state.apply_call_update(
298 372 7,
299 CallUpdate::Capability(MeetingCapability { locked: true, ..MeetingCapability::default() }),
373 CallUpdate::Capability(MeetingCapability {
374 locked: true,
375 ..MeetingCapability::default()
376 }),
300 377 cx,
301 378 )
302 379 })
@@ -305,16 +382,35 @@ mod tests {
305 382 }
306 383
307 384 #[gpui_kit::test]
308 fn the_options_dialog_loads_saves_only_changes_and_keeps_errors_inline(cx: &mut TestAppContext) {
385 fn the_options_dialog_loads_saves_only_changes_and_keeps_errors_inline(
386 cx: &mut TestAppContext,
387 ) {
309 388 let (app, mut control) = app_with_meeting(cx, true);
310 389 cx.update(|cx| app.update(cx, |state, cx| state.open_meeting_options(cx)));
311 assert_eq!(control.try_recv_command(), Some(CallCommand::LoadMeetingOptions));
390 assert_eq!(
391 control.try_recv_command(),
392 Some(CallCommand::LoadMeetingOptions)
393 );
312 394 cx.update(|cx| {
313 395 app.update(cx, |state, cx| {
314 state.apply_call_update(7, CallUpdate::MeetingOptions(Err("The options could not be read".into())), cx)
396 state.apply_call_update(
397 7,
398 CallUpdate::MeetingOptions(Err("The options could not be read".into())),
399 cx,
400 )
315 401 })
316 402 });
317 let error = cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.as_ref().unwrap().error.clone());
403 let error = cx.update(|cx| {
404 app.read(cx)
405 .call
406 .as_ref()
407 .unwrap()
408 .options_dialog
409 .as_ref()
410 .unwrap()
411 .error
412 .clone()
413 });
318 414 assert_eq!(error.as_deref(), Some("The options could not be read"));
319 415 cx.update(|cx| {
320 416 app.update(cx, |state, cx| {
@@ -332,7 +428,13 @@ mod tests {
332 428 assert_eq!(control.try_recv_command(), None);
333 429 cx.update(|cx| {
334 430 app.update(cx, |state, cx| {
335 state.apply_call_update(7, CallUpdate::MeetingOptionsSaved(Err("the service refused AllowMeetingChat".into())), cx)
431 state.apply_call_update(
432 7,
433 CallUpdate::MeetingOptionsSaved(Err(
434 "the service refused AllowMeetingChat".into()
435 )),
436 cx,
437 )
336 438 })
337 439 });
338 440 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.is_some()));
@@ -354,7 +456,11 @@ mod tests {
354 456 chat_id: "19:bo".into(),
355 457 };
356 458 cx.update(|cx| app.update(cx, |state, cx| state.invite_call_person(candidate, cx)));
357 let Some(CallCommand::Invite { callees, group_thread }) = control.try_recv_command() else {
459 let Some(CallCommand::Invite {
460 callees,
461 group_thread,
462 }) = control.try_recv_command()
463 else {
358 464 panic!("an invite command");
359 465 };
360 466 assert_eq!(callees.len(), 1);
@@ -362,7 +468,9 @@ mod tests {
362 468 assert_eq!(group_thread, None);
363 469 let ringing = cx.update(|cx| {
364 470 let tiles = &app.read(cx).call.as_ref().unwrap().model.tiles;
365 tiles.iter().any(|tile| tile.mri == "8:orgid:bo" && tile.invited)
471 tiles
472 .iter()
473 .any(|tile| tile.mri == "8:orgid:bo" && tile.invited)
366 474 });
367 475 assert!(ringing);
368 476 }
@@ -27,7 +27,11 @@ impl AppState {
27 }
27 }
28
28
29 pub fn set_call_lock(&mut self, locked: bool, _cx: &mut Context<Self>) {
29 pub fn set_call_lock(&mut self, locked: bool, _cx: &mut Context<Self>) {
30 if self.call.as_ref().is_some_and(|call| call.model.organizes_meeting()) {
30 if self
31 .call
32 .as_ref()
33 .is_some_and(|call| call.model.organizes_meeting())
34 {
31 self.send_call_command(CallCommand::SetLock(locked));
35 self.send_call_command(CallCommand::SetLock(locked));
32 }
36 }
33 }
37 }
@@ -48,19 +52,43 @@ impl AppState {
48 allowed: bool,
52 allowed: bool,
49 _cx: &mut Context<Self>,
53 _cx: &mut Context<Self>,
50 ) {
54 ) {
51 if self.call.as_ref().is_some_and(|call| call.model.can_change_roles(&mri)) {
55 if self
52 self.send_call_command(CallCommand::SetAttendeeModality { mri, modality, allowed });
56 .call
57 .as_ref()
58 .is_some_and(|call| call.model.can_change_roles(&mri))
59 {
60 self.send_call_command(CallCommand::SetAttendeeModality {
61 mri,
62 modality,
63 allowed,
64 });
53 }
65 }
54 }
66 }
55
67
56 pub fn set_call_attendee_restrictions(&mut self, mic_off: bool, camera_off: bool, _cx: &mut Context<Self>) {
68 pub fn set_call_attendee_restrictions(
57 if self.call.as_ref().is_some_and(|call| call.model.organizes_meeting()) {
69 &mut self,
58 self.send_call_command(CallCommand::SetAttendeeRestrictions { mic_off, camera_off });
70 mic_off: bool,
71 camera_off: bool,
72 _cx: &mut Context<Self>,
73 ) {
74 if self
75 .call
76 .as_ref()
77 .is_some_and(|call| call.model.organizes_meeting())
78 {
79 self.send_call_command(CallCommand::SetAttendeeRestrictions {
80 mic_off,
81 camera_off,
82 });
59 }
83 }
60 }
84 }
61
85
62 pub fn open_meeting_options(&mut self, cx: &mut Context<Self>) {
86 pub fn open_meeting_options(&mut self, cx: &mut Context<Self>) {
63 let Some(call) = self.call.as_mut().filter(|call| call.model.organizes_meeting()) else {
87 let Some(call) = self
88 .call
89 .as_mut()
90 .filter(|call| call.model.organizes_meeting())
91 else {
64 return;
92 return;
65 };
93 };
66 call.options_dialog = Some(OptionsDialog::loading());
94 call.options_dialog = Some(OptionsDialog::loading());
@@ -69,13 +97,21 @@ impl AppState {
69 }
97 }
70
98
71 pub fn close_meeting_options(&mut self, cx: &mut Context<Self>) {
99 pub fn close_meeting_options(&mut self, cx: &mut Context<Self>) {
72 if let Some(call) = self.call.as_mut().filter(|call| call.options_dialog.is_some()) {
100 if let Some(call) = self
101 .call
102 .as_mut()
103 .filter(|call| call.options_dialog.is_some())
104 {
73 call.options_dialog = None;
105 call.options_dialog = None;
74 cx.notify();
106 cx.notify();
75 }
107 }
76 }
108 }
77
109
78 pub fn edit_meeting_options(&mut self, edit: impl FnOnce(&mut MeetingOptions), cx: &mut Context<Self>) {
110 pub fn edit_meeting_options(
111 &mut self,
112 edit: impl FnOnce(&mut MeetingOptions),
113 cx: &mut Context<Self>,
114 ) {
79 let Some(draft) = self
115 let Some(draft) = self
80 .call
116 .call
81 .as_mut()
117 .as_mut()
@@ -104,7 +140,13 @@ impl AppState {
104 let present: Vec<&str> = self
140 let present: Vec<&str> = self
105 .call
141 .call
106 .as_ref()
142 .as_ref()
107 .map(|call| call.model.tiles.iter().map(|tile| tile.mri.as_str()).collect())
143 .map(|call| {
144 call.model
145 .tiles
146 .iter()
147 .map(|tile| tile.mri.as_str())
148 .collect()
149 })
108 .unwrap_or_default();
150 .unwrap_or_default();
109 self.transfer_candidates()
151 self.transfer_candidates()
110 .into_iter()
152 .into_iter()
@@ -112,12 +154,12 @@ impl AppState {
112 .collect()
154 .collect()
113 }
155 }
114
156
115 pub fn open_invite_picker(
157 pub fn open_invite_picker(&mut self, picker: AnyView, cx: &mut Context<Self>) {
116 &mut self,
158 if self
117 picker: AnyView,
159 .call
118 cx: &mut Context<Self>,
160 .as_ref()
119 ) {
161 .is_some_and(|call| call.model.can_invite())
120 if self.call.as_ref().is_some_and(|call| call.model.can_invite()) {
162 {
121 self.transfer_picker = Some(picker);
163 self.transfer_picker = Some(picker);
122 cx.notify();
164 cx.notify();
123 }
165 }
@@ -128,9 +170,14 @@ impl AppState {
128 let Some(call) = self.call.as_mut().filter(|call| call.model.can_invite()) else {
170 let Some(call) = self.call.as_mut().filter(|call| call.model.can_invite()) else {
129 return;
171 return;
130 };
172 };
131 let callee = Callee { mri: target.mri.clone(), display_name: target.name.clone() };
173 let callee = Callee {
174 mri: target.mri.clone(),
175 display_name: target.name.clone(),
176 };
132 if !call.model.tiles.iter().any(|tile| tile.mri == callee.mri) {
177 if !call.model.tiles.iter().any(|tile| tile.mri == callee.mri) {
133 call.model.tiles.push(Tile::invited(&callee.mri, &callee.display_name));
178 call.model
179 .tiles
180 .push(Tile::invited(&callee.mri, &callee.display_name));
134 }
181 }
135 let one_to_one = call.model.kind == CallKind::Direct;
182 let one_to_one = call.model.kind == CallKind::Direct;
136 let peer_user_id = call
183 let peer_user_id = call
@@ -143,18 +190,27 @@ impl AppState {
143 cx.emit(AppEvent::Call);
190 cx.emit(AppEvent::Call);
144 cx.notify();
191 cx.notify();
145 if !one_to_one || self.mode.demo {
192 if !one_to_one || self.mode.demo {
146 self.send_call_command(CallCommand::Invite { callees: vec![callee], group_thread: None });
193 self.send_call_command(CallCommand::Invite {
194 callees: vec![callee],
195 group_thread: None,
196 });
147 return;
197 return;
148 }
198 }
149 let (Some(engine), Some(peer_user_id), Some(invited_user_id)) =
199 let (Some(engine), Some(peer_user_id), Some(invited_user_id)) =
150 (self.engine.clone(), peer_user_id, target.user_id.clone())
200 (self.engine.clone(), peer_user_id, target.user_id.clone())
151 else {
201 else {
152 let notice = if self.engine.is_none() { NOT_CONNECTED_NOTICE } else { NO_PEER_NOTICE };
202 let notice = if self.engine.is_none() {
203 NOT_CONNECTED_NOTICE
204 } else {
205 NO_PEER_NOTICE
206 };
153 self.raise_notice(notice.to_owned(), None, cx);
207 self.raise_notice(notice.to_owned(), None, cx);
154 return;
208 return;
155 };
209 };
156 let receiver = runtime::spawn(async move {
210 let receiver = runtime::spawn(async move {
157 engine.create_group(&[peer_user_id, invited_user_id], None).await
211 engine
212 .create_group(&[peer_user_id, invited_user_id], None)
213 .await
158 });
214 });
159 cx.spawn(async move |this, cx| {
215 cx.spawn(async move |this, cx| {
160 let created = receiver.await.ok().and_then(Result::ok);
216 let created = receiver.await.ok().and_then(Result::ok);
@@ -179,8 +235,8 @@ mod tests {
179 use std::time::Instant;
235 use std::time::Instant;
180
236
181 use calling::{
237 use calling::{
182 CallCommand, CallControl, CallState, CallUpdate, MeetingCapability, MeetingOptions, MeetingRole,
238 CallCommand, CallControl, CallState, CallUpdate, MeetingCapability, MeetingOptions,
183 Modality, RosterEntry, call_channel,
239 MeetingRole, Modality, RosterEntry, call_channel,
184 };
240 };
185 use gpui_kit::{AppContext as _, Entity, TestAppContext};
241 use gpui_kit::{AppContext as _, Entity, TestAppContext};
186 use serde_json::json;
242 use serde_json::json;
@@ -189,14 +245,21 @@ mod tests {
189 use crate::app_state::{AppState, Mode};
245 use crate::app_state::{AppState, Mode};
190 use crate::call::{ActiveCall, CallModel, TransferCandidate};
246 use crate::call::{ActiveCall, CallModel, TransferCandidate};
191
247
192 fn app_with_meeting(cx: &mut TestAppContext, organizer: bool) -> (Entity<AppState>, CallControl) {
248 fn app_with_meeting(
249 cx: &mut TestAppContext,
250 organizer: bool,
251 ) -> (Entity<AppState>, CallControl) {
193 cx.update(gpui_kit::init);
252 cx.update(gpui_kit::init);
194 let store = Arc::new(Store::open_in_memory().unwrap());
253 let store = Arc::new(Store::open_in_memory().unwrap());
195 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
254 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
196 let (handle, control) = call_channel();
255 let (handle, control) = call_channel();
197 let mut model = CallModel::meeting("Standup", organizer);
256 let mut model = CallModel::meeting("Standup", organizer);
198 model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
257 model.apply(CallUpdate::State(CallState::Connected {
199 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
258 since: Instant::now(),
259 }));
260 model.apply(CallUpdate::OwnIdentity {
261 mri: "8:orgid:me".into(),
262 });
200 model.apply(CallUpdate::Roster(vec![RosterEntry {
263 model.apply(CallUpdate::Roster(vec![RosterEntry {
201 mri: "8:orgid:a".into(),
264 mri: "8:orgid:a".into(),
202 display_name: "Ana".into(),
265 display_name: "Ana".into(),
@@ -218,7 +281,8 @@ mod tests {
218 }
281 }
219
282
220 fn options() -> MeetingOptions {
283 fn options() -> MeetingOptions {
221 let option = |name: &str, value: serde_json::Value| json!({"name": name, "currentValue": value});
284 let option =
285 |name: &str, value: serde_json::Value| json!({"name": name, "currentValue": value});
222 MeetingOptions::from_response(&json!({"options": [
286 MeetingOptions::from_response(&json!({"options": [
223 option("AutoAdmittedUsers", json!("EveryoneInCompany")),
287 option("AutoAdmittedUsers", json!("EveryoneInCompany")),
224 option("PresenterOption", json!("Everyone")),
288 option("PresenterOption", json!("Everyone")),
@@ -276,15 +340,25 @@ mod tests {
276 assert_eq!(control.try_recv_command(), Some(CallCommand::SetLock(true)));
340 assert_eq!(control.try_recv_command(), Some(CallCommand::SetLock(true)));
277 assert_eq!(
341 assert_eq!(
278 control.try_recv_command(),
342 control.try_recv_command(),
279 Some(CallCommand::SetRole { mri: "8:orgid:a".into(), role: MeetingRole::Presenter })
343 Some(CallCommand::SetRole {
344 mri: "8:orgid:a".into(),
345 role: MeetingRole::Presenter
346 })
280 );
347 );
281 assert_eq!(
348 assert_eq!(
282 control.try_recv_command(),
349 control.try_recv_command(),
283 Some(CallCommand::SetAttendeeModality { mri: "8:orgid:a".into(), modality: Modality::Camera, allowed: false })
350 Some(CallCommand::SetAttendeeModality {
351 mri: "8:orgid:a".into(),
352 modality: Modality::Camera,
353 allowed: false
354 })
284 );
355 );
285 assert_eq!(
356 assert_eq!(
286 control.try_recv_command(),
357 control.try_recv_command(),
287 Some(CallCommand::SetAttendeeRestrictions { mic_off: true, camera_off: true })
358 Some(CallCommand::SetAttendeeRestrictions {
359 mic_off: true,
360 camera_off: true
361 })
288 );
362 );
289 assert_eq!(control.try_recv_command(), None);
363 assert_eq!(control.try_recv_command(), None);
290 }
364 }
@@ -296,7 +370,10 @@ mod tests {
296 app.update(cx, |state, cx| {
370 app.update(cx, |state, cx| {
297 state.apply_call_update(
371 state.apply_call_update(
298 7,
372 7,
299 CallUpdate::Capability(MeetingCapability { locked: true, ..MeetingCapability::default() }),
373 CallUpdate::Capability(MeetingCapability {
374 locked: true,
375 ..MeetingCapability::default()
376 }),
300 cx,
377 cx,
301 )
378 )
302 })
379 })
@@ -305,16 +382,35 @@ mod tests {
305 }
382 }
306
383
307 #[gpui_kit::test]
384 #[gpui_kit::test]
308 fn the_options_dialog_loads_saves_only_changes_and_keeps_errors_inline(cx: &mut TestAppContext) {
385 fn the_options_dialog_loads_saves_only_changes_and_keeps_errors_inline(
386 cx: &mut TestAppContext,
387 ) {
309 let (app, mut control) = app_with_meeting(cx, true);
388 let (app, mut control) = app_with_meeting(cx, true);
310 cx.update(|cx| app.update(cx, |state, cx| state.open_meeting_options(cx)));
389 cx.update(|cx| app.update(cx, |state, cx| state.open_meeting_options(cx)));
311 assert_eq!(control.try_recv_command(), Some(CallCommand::LoadMeetingOptions));
390 assert_eq!(
391 control.try_recv_command(),
392 Some(CallCommand::LoadMeetingOptions)
393 );
312 cx.update(|cx| {
394 cx.update(|cx| {
313 app.update(cx, |state, cx| {
395 app.update(cx, |state, cx| {
314 state.apply_call_update(7, CallUpdate::MeetingOptions(Err("The options could not be read".into())), cx)
396 state.apply_call_update(
397 7,
398 CallUpdate::MeetingOptions(Err("The options could not be read".into())),
399 cx,
400 )
315 })
401 })
316 });
402 });
317 let error = cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.as_ref().unwrap().error.clone());
403 let error = cx.update(|cx| {
404 app.read(cx)
405 .call
406 .as_ref()
407 .unwrap()
408 .options_dialog
409 .as_ref()
410 .unwrap()
411 .error
412 .clone()
413 });
318 assert_eq!(error.as_deref(), Some("The options could not be read"));
414 assert_eq!(error.as_deref(), Some("The options could not be read"));
319 cx.update(|cx| {
415 cx.update(|cx| {
320 app.update(cx, |state, cx| {
416 app.update(cx, |state, cx| {
@@ -332,7 +428,13 @@ mod tests {
332 assert_eq!(control.try_recv_command(), None);
428 assert_eq!(control.try_recv_command(), None);
333 cx.update(|cx| {
429 cx.update(|cx| {
334 app.update(cx, |state, cx| {
430 app.update(cx, |state, cx| {
335 state.apply_call_update(7, CallUpdate::MeetingOptionsSaved(Err("the service refused AllowMeetingChat".into())), cx)
431 state.apply_call_update(
432 7,
433 CallUpdate::MeetingOptionsSaved(Err(
434 "the service refused AllowMeetingChat".into()
435 )),
436 cx,
437 )
336 })
438 })
337 });
439 });
338 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.is_some()));
440 assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().options_dialog.is_some()));
@@ -354,7 +456,11 @@ mod tests {
354 chat_id: "19:bo".into(),
456 chat_id: "19:bo".into(),
355 };
457 };
356 cx.update(|cx| app.update(cx, |state, cx| state.invite_call_person(candidate, cx)));
458 cx.update(|cx| app.update(cx, |state, cx| state.invite_call_person(candidate, cx)));
357 let Some(CallCommand::Invite { callees, group_thread }) = control.try_recv_command() else {
459 let Some(CallCommand::Invite {
460 callees,
461 group_thread,
462 }) = control.try_recv_command()
463 else {
358 panic!("an invite command");
464 panic!("an invite command");
359 };
465 };
360 assert_eq!(callees.len(), 1);
466 assert_eq!(callees.len(), 1);
@@ -362,7 +468,9 @@ mod tests {
362 assert_eq!(group_thread, None);
468 assert_eq!(group_thread, None);
363 let ringing = cx.update(|cx| {
469 let ringing = cx.update(|cx| {
364 let tiles = &app.read(cx).call.as_ref().unwrap().model.tiles;
470 let tiles = &app.read(cx).call.as_ref().unwrap().model.tiles;
365 tiles.iter().any(|tile| tile.mri == "8:orgid:bo" && tile.invited)
471 tiles
472 .iter()
473 .any(|tile| tile.mri == "8:orgid:bo" && tile.invited)
366 });
474 });
367 assert!(ringing);
475 assert!(ringing);
368 }
476 }
crates/app-state/src/call/reminder.rs +4 −1
@@ -73,7 +73,10 @@ pub struct ReminderUpdate {
73 73 }
74 74
75 75 pub fn subtitle(toast: &MeetingToast, now: DateTime<Utc>, offset: FixedOffset) -> String {
76 let clock = toast.start.with_timezone(&offset).format(app_base::format::clock_format());
76 let clock = toast
77 .start
78 .with_timezone(&offset)
79 .format(app_base::format::clock_format());
77 80 match toast.phase {
78 81 ReminderPhase::Started => format!("{clock} - started"),
79 82 ReminderPhase::Live => format!("{clock} - live now"),
@@ -73,7 +73,10 @@ pub struct ReminderUpdate {
73}
73}
74
74
75pub fn subtitle(toast: &MeetingToast, now: DateTime<Utc>, offset: FixedOffset) -> String {
75pub fn subtitle(toast: &MeetingToast, now: DateTime<Utc>, offset: FixedOffset) -> String {
76 let clock = toast.start.with_timezone(&offset).format(app_base::format::clock_format());
76 let clock = toast
77 .start
78 .with_timezone(&offset)
79 .format(app_base::format::clock_format());
77 match toast.phase {
80 match toast.phase {
78 ReminderPhase::Started => format!("{clock} - started"),
81 ReminderPhase::Started => format!("{clock} - started"),
79 ReminderPhase::Live => format!("{clock} - live now"),
82 ReminderPhase::Live => format!("{clock} - live now"),
crates/app-state/src/call/remote_command.rs +9 −3
@@ -101,10 +101,16 @@ impl AppState {
101 101 }
102 102 Some(RemoteCommand::HangUp) => self.leave_call(cx),
103 103 Some(RemoteCommand::AdmitAll) => self.admit_all_call_guests(cx),
104 Some(RemoteCommand::Unmute) => self.send_call_command(CallCommand::Mute(MuteCommand::Unmute)),
105 Some(RemoteCommand::Mute) => self.send_call_command(CallCommand::Mute(MuteCommand::Mute)),
104 Some(RemoteCommand::Unmute) => {
105 self.send_call_command(CallCommand::Mute(MuteCommand::Unmute))
106 }
107 Some(RemoteCommand::Mute) => {
108 self.send_call_command(CallCommand::Mute(MuteCommand::Mute))
109 }
106 110 Some(RemoteCommand::Camera(on)) => self.send_call_command(CallCommand::SetCamera(on)),
107 Some(RemoteCommand::RefreshShareSources) => self.send_call_command(CallCommand::RefreshShareSources),
111 Some(RemoteCommand::RefreshShareSources) => {
112 self.send_call_command(CallCommand::RefreshShareSources)
113 }
108 114 Some(RemoteCommand::ShareScreen) => self.share_first_screen(),
109 115 Some(RemoteCommand::StopShare) => self.send_call_command(CallCommand::StopShare),
110 116 Some(RemoteCommand::Input(name)) => self.switch_input_for_test(&name),
@@ -101,10 +101,16 @@ impl AppState {
101 }
101 }
102 Some(RemoteCommand::HangUp) => self.leave_call(cx),
102 Some(RemoteCommand::HangUp) => self.leave_call(cx),
103 Some(RemoteCommand::AdmitAll) => self.admit_all_call_guests(cx),
103 Some(RemoteCommand::AdmitAll) => self.admit_all_call_guests(cx),
104 Some(RemoteCommand::Unmute) => self.send_call_command(CallCommand::Mute(MuteCommand::Unmute)),
104 Some(RemoteCommand::Unmute) => {
105 Some(RemoteCommand::Mute) => self.send_call_command(CallCommand::Mute(MuteCommand::Mute)),
105 self.send_call_command(CallCommand::Mute(MuteCommand::Unmute))
106 }
107 Some(RemoteCommand::Mute) => {
108 self.send_call_command(CallCommand::Mute(MuteCommand::Mute))
109 }
106 Some(RemoteCommand::Camera(on)) => self.send_call_command(CallCommand::SetCamera(on)),
110 Some(RemoteCommand::Camera(on)) => self.send_call_command(CallCommand::SetCamera(on)),
107 Some(RemoteCommand::RefreshShareSources) => self.send_call_command(CallCommand::RefreshShareSources),
111 Some(RemoteCommand::RefreshShareSources) => {
112 self.send_call_command(CallCommand::RefreshShareSources)
113 }
108 Some(RemoteCommand::ShareScreen) => self.share_first_screen(),
114 Some(RemoteCommand::ShareScreen) => self.share_first_screen(),
109 Some(RemoteCommand::StopShare) => self.send_call_command(CallCommand::StopShare),
115 Some(RemoteCommand::StopShare) => self.send_call_command(CallCommand::StopShare),
110 Some(RemoteCommand::Input(name)) => self.switch_input_for_test(&name),
116 Some(RemoteCommand::Input(name)) => self.switch_input_for_test(&name),
crates/app-state/src/call/share_actions.rs +61 −5
@@ -1,7 +1,10 @@
1 1 use calling::CallCommand;
2 2 use gpui_kit::*;
3 3
4 use super::share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY};
4 use super::share_view::{
5 SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_WIDTH_META_KEY, StripDrag,
6 clamp_strip_width,
7 };
5 8 use crate::app_state::{AppEvent, AppState};
6 9
7 10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -16,8 +19,16 @@ fn flag_text(on: bool) -> &'static str {
16 19 }
17 20
18 21 impl AppState {
19 fn change_share_stage(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut super::share_view::ShareStage)) {
20 let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
22 fn change_share_stage(
23 &mut self,
24 cx: &mut Context<Self>,
25 change: impl FnOnce(&mut super::share_view::ShareStage),
26 ) {
27 let Some(call) = self
28 .call
29 .as_mut()
30 .filter(|call| call.model.screen_sharer.is_some())
31 else {
21 32 return;
22 33 };
23 34 change(&mut call.share_stage);
@@ -25,7 +36,12 @@ impl AppState {
25 36 cx.notify();
26 37 }
27 38
28 pub fn zoom_share_wheel(&mut self, scroll_pixels: f32, position: (f32, f32), cx: &mut Context<Self>) {
39 pub fn zoom_share_wheel(
40 &mut self,
41 scroll_pixels: f32,
42 position: (f32, f32),
43 cx: &mut Context<Self>,
44 ) {
29 45 self.change_share_stage(cx, |stage| {
30 46 let (pointer, size) = (stage.pointer(position), stage.size());
31 47 stage.view.zoom_wheel(scroll_pixels, pointer, size);
@@ -53,7 +69,9 @@ impl AppState {
53 69 return;
54 70 };
55 71 let size = stage.size();
56 stage.view.pan_by((position.0 - from.0, position.1 - from.1), size);
72 stage
73 .view
74 .pan_by((position.0 - from.0, position.1 - from.1), size);
57 75 });
58 76 }
59 77
@@ -61,6 +79,44 @@ impl AppState {
61 79 self.change_share_stage(cx, |stage| stage.pan_from = None);
62 80 }
63 81
82 pub fn begin_strip_drag(&mut self, pointer_x: f32, cx: &mut Context<Self>) {
83 let start_width = self.call_strip_width;
84 self.change_share_stage(cx, |stage| {
85 stage.strip_drag = Some(StripDrag {
86 start_pointer: pointer_x,
87 start_width,
88 })
89 });
90 }
91
92 pub fn drag_strip_to(&mut self, pointer_x: f32, cx: &mut Context<Self>) {
93 let Some(drag) = self
94 .call
95 .as_ref()
96 .and_then(|call| call.share_stage.strip_drag)
97 else {
98 return;
99 };
100 self.call_strip_width = drag.width_at(pointer_x);
101 cx.notify();
102 }
103
104 pub fn end_strip_drag(&mut self, cx: &mut Context<Self>) {
105 if self
106 .call
107 .as_ref()
108 .is_none_or(|call| call.share_stage.strip_drag.is_none())
109 {
110 return;
111 }
112 let width = clamp_strip_width(self.call_strip_width);
113 self.call_strip_width = width;
114 let _ = self
115 .store
116 .set_meta(STRIP_WIDTH_META_KEY, &width.to_string());
117 self.change_share_stage(cx, |stage| stage.strip_drag = None);
118 }
119
64 120 pub fn pop_out_stage(&mut self, cx: &mut Context<Self>) {
65 121 self.change_share_stage(cx, |stage| stage.popped = true);
66 122 }
@@ -1,7 +1,10 @@
1use calling::CallCommand;
1use calling::CallCommand;
2use gpui_kit::*;
2use gpui_kit::*;
3
3
4use super::share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY};
4use super::share_view::{
5 SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_WIDTH_META_KEY, StripDrag,
6 clamp_strip_width,
7};
5use crate::app_state::{AppEvent, AppState};
8use crate::app_state::{AppEvent, AppState};
6
9
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -16,8 +19,16 @@ fn flag_text(on: bool) -> &'static str {
16}
19}
17
20
18impl AppState {
21impl AppState {
19 fn change_share_stage(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut super::share_view::ShareStage)) {
22 fn change_share_stage(
20 let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
23 &mut self,
24 cx: &mut Context<Self>,
25 change: impl FnOnce(&mut super::share_view::ShareStage),
26 ) {
27 let Some(call) = self
28 .call
29 .as_mut()
30 .filter(|call| call.model.screen_sharer.is_some())
31 else {
21 return;
32 return;
22 };
33 };
23 change(&mut call.share_stage);
34 change(&mut call.share_stage);
@@ -25,7 +36,12 @@ impl AppState {
25 cx.notify();
36 cx.notify();
26 }
37 }
27
38
28 pub fn zoom_share_wheel(&mut self, scroll_pixels: f32, position: (f32, f32), cx: &mut Context<Self>) {
39 pub fn zoom_share_wheel(
40 &mut self,
41 scroll_pixels: f32,
42 position: (f32, f32),
43 cx: &mut Context<Self>,
44 ) {
29 self.change_share_stage(cx, |stage| {
45 self.change_share_stage(cx, |stage| {
30 let (pointer, size) = (stage.pointer(position), stage.size());
46 let (pointer, size) = (stage.pointer(position), stage.size());
31 stage.view.zoom_wheel(scroll_pixels, pointer, size);
47 stage.view.zoom_wheel(scroll_pixels, pointer, size);
@@ -53,7 +69,9 @@ impl AppState {
53 return;
69 return;
54 };
70 };
55 let size = stage.size();
71 let size = stage.size();
56 stage.view.pan_by((position.0 - from.0, position.1 - from.1), size);
72 stage
73 .view
74 .pan_by((position.0 - from.0, position.1 - from.1), size);
57 });
75 });
58 }
76 }
59
77
@@ -61,6 +79,44 @@ impl AppState {
61 self.change_share_stage(cx, |stage| stage.pan_from = None);
79 self.change_share_stage(cx, |stage| stage.pan_from = None);
62 }
80 }
63
81
82 pub fn begin_strip_drag(&mut self, pointer_x: f32, cx: &mut Context<Self>) {
83 let start_width = self.call_strip_width;
84 self.change_share_stage(cx, |stage| {
85 stage.strip_drag = Some(StripDrag {
86 start_pointer: pointer_x,
87 start_width,
88 })
89 });
90 }
91
92 pub fn drag_strip_to(&mut self, pointer_x: f32, cx: &mut Context<Self>) {
93 let Some(drag) = self
94 .call
95 .as_ref()
96 .and_then(|call| call.share_stage.strip_drag)
97 else {
98 return;
99 };
100 self.call_strip_width = drag.width_at(pointer_x);
101 cx.notify();
102 }
103
104 pub fn end_strip_drag(&mut self, cx: &mut Context<Self>) {
105 if self
106 .call
107 .as_ref()
108 .is_none_or(|call| call.share_stage.strip_drag.is_none())
109 {
110 return;
111 }
112 let width = clamp_strip_width(self.call_strip_width);
113 self.call_strip_width = width;
114 let _ = self
115 .store
116 .set_meta(STRIP_WIDTH_META_KEY, &width.to_string());
117 self.change_share_stage(cx, |stage| stage.strip_drag = None);
118 }
119
64 pub fn pop_out_stage(&mut self, cx: &mut Context<Self>) {
120 pub fn pop_out_stage(&mut self, cx: &mut Context<Self>) {
65 self.change_share_stage(cx, |stage| stage.popped = true);
121 self.change_share_stage(cx, |stage| stage.popped = true);
66 }
122 }
crates/app-state/src/call/speed_dial.rs +7 −1
@@ -27,7 +27,13 @@ fn save(store: &Store, entries: &[SpeedDialEntry]) {
27 27 fn serialize(entries: &[SpeedDialEntry]) -> String {
28 28 entries
29 29 .iter()
30 .map(|entry| format!("{}\t{}", entry.user_id, entry.name.replace(['\t', '\n'], " ")))
30 .map(|entry| {
31 format!(
32 "{}\t{}",
33 entry.user_id,
34 entry.name.replace(['\t', '\n'], " ")
35 )
36 })
31 37 .collect::<Vec<_>>()
32 38 .join("\n")
33 39 }
@@ -27,7 +27,13 @@ fn save(store: &Store, entries: &[SpeedDialEntry]) {
27fn serialize(entries: &[SpeedDialEntry]) -> String {
27fn serialize(entries: &[SpeedDialEntry]) -> String {
28 entries
28 entries
29 .iter()
29 .iter()
30 .map(|entry| format!("{}\t{}", entry.user_id, entry.name.replace(['\t', '\n'], " ")))
30 .map(|entry| {
31 format!(
32 "{}\t{}",
33 entry.user_id,
34 entry.name.replace(['\t', '\n'], " ")
35 )
36 })
31 .collect::<Vec<_>>()
37 .collect::<Vec<_>>()
32 .join("\n")
38 .join("\n")
33}
39}
crates/app-state/src/call/target.rs +9 −2
@@ -133,14 +133,21 @@ mod tests {
133 133 let mut echo = chat(
134 134 "oneOnOne",
135 135 "Echo",
136 &[(Some("me-id"), "Me"), (Some(calling::signaling::ECHO_BOT_MRI), "Echo")],
136 &[
137 (Some("me-id"), "Me"),
138 (Some(calling::signaling::ECHO_BOT_MRI), "Echo"),
139 ],
137 140 );
138 141 assert!(is_echo_chat(&echo));
139 142 echo.members.truncate(1);
140 143 assert!(!is_echo_chat(&echo));
141 144 echo.id = "19:me-id_cf28171e-fcfd-47e4-a1d6-79460b0b3ca0@unq.gbl.spaces".into();
142 145 assert!(is_echo_chat(&echo));
143 let other = chat("oneOnOne", "", &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")]);
146 let other = chat(
147 "oneOnOne",
148 "",
149 &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")],
150 );
144 151 assert!(!is_echo_chat(&other));
145 152 }
146 153
@@ -133,14 +133,21 @@ mod tests {
133 let mut echo = chat(
133 let mut echo = chat(
134 "oneOnOne",
134 "oneOnOne",
135 "Echo",
135 "Echo",
136 &[(Some("me-id"), "Me"), (Some(calling::signaling::ECHO_BOT_MRI), "Echo")],
136 &[
137 (Some("me-id"), "Me"),
138 (Some(calling::signaling::ECHO_BOT_MRI), "Echo"),
139 ],
137 );
140 );
138 assert!(is_echo_chat(&echo));
141 assert!(is_echo_chat(&echo));
139 echo.members.truncate(1);
142 echo.members.truncate(1);
140 assert!(!is_echo_chat(&echo));
143 assert!(!is_echo_chat(&echo));
141 echo.id = "19:me-id_cf28171e-fcfd-47e4-a1d6-79460b0b3ca0@unq.gbl.spaces".into();
144 echo.id = "19:me-id_cf28171e-fcfd-47e4-a1d6-79460b0b3ca0@unq.gbl.spaces".into();
142 assert!(is_echo_chat(&echo));
145 assert!(is_echo_chat(&echo));
143 let other = chat("oneOnOne", "", &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")]);
146 let other = chat(
147 "oneOnOne",
148 "",
149 &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")],
150 );
144 assert!(!is_echo_chat(&other));
151 assert!(!is_echo_chat(&other));
145 }
152 }
146
153
crates/app-state/src/call/view_actions.rs +7 −19
@@ -3,11 +3,11 @@ use std::time::{Duration, Instant};
3 3 use calling::CallCommand;
4 4 use gpui_kit::*;
5 5
6 use super::caption_style::{CaptionPosition, CaptionSize};
7 use super::{gallery_page, measured_stage, video_wants};
8 6 use super::bubbles::{BUBBLE_SHOWN, ChatBubble, push_bubble};
7 use super::caption_style::{CaptionPosition, CaptionSize};
9 8 use super::fullscreen::{FullscreenState, HINT_SHOWN};
10 9 use super::view_settings::{CallLayout, ViewSettings};
10 use super::{measured_stage, video_wants};
11 11 use crate::app_state::{AppEvent, AppState};
12 12
13 13 const CHROME_TOUCH_THROTTLE: Duration = Duration::from_millis(250);
@@ -42,21 +42,6 @@ impl AppState {
42 42 self.change_call_view(|view| view.choose(layout), cx);
43 43 }
44 44
45 pub fn turn_call_gallery_page(&mut self, forward: bool, cx: &mut Context<Self>) {
46 let Some(call) = self.call.as_mut() else {
47 return;
48 };
49 let pages = gallery_page(&call.model).pages;
50 let page = call.model.gallery_page.min(pages - 1);
51 call.model.gallery_page = if forward {
52 (page + 1).min(pages - 1)
53 } else {
54 page.saturating_sub(1)
55 };
56 self.sync_video_wants();
57 cx.notify();
58 }
59
60 45 pub fn toggle_call_hide_no_video(&mut self, cx: &mut Context<Self>) {
61 46 self.change_call_view(|view| view.hide_no_video = !view.hide_no_video, cx);
62 47 }
@@ -97,12 +82,15 @@ impl AppState {
97 82 }
98 83
99 84 fn sync_video_wants(&mut self) {
85 let strip_width = self.call_strip_width;
100 86 let Some(call) = self.call.as_mut() else {
101 87 return;
102 88 };
103 let wants = video_wants(&call.model, measured_stage(call));
89 let wants = video_wants(&call.model, measured_stage(call), strip_width);
104 90 if wants != call.sent_wants {
105 let _ = call.commands.send(CallCommand::SetVideoWants(wants.clone()));
91 let _ = call
92 .commands
93 .send(CallCommand::SetVideoWants(wants.clone()));
106 94 call.sent_wants = wants;
107 95 }
108 96 }
@@ -3,11 +3,11 @@ use std::time::{Duration, Instant};
3use calling::CallCommand;
3use calling::CallCommand;
4use gpui_kit::*;
4use gpui_kit::*;
5
5
6use super::caption_style::{CaptionPosition, CaptionSize};
7use super::{gallery_page, measured_stage, video_wants};
8use super::bubbles::{BUBBLE_SHOWN, ChatBubble, push_bubble};
6use super::bubbles::{BUBBLE_SHOWN, ChatBubble, push_bubble};
7use super::caption_style::{CaptionPosition, CaptionSize};
9use super::fullscreen::{FullscreenState, HINT_SHOWN};
8use super::fullscreen::{FullscreenState, HINT_SHOWN};
10use super::view_settings::{CallLayout, ViewSettings};
9use super::view_settings::{CallLayout, ViewSettings};
10use super::{measured_stage, video_wants};
11use crate::app_state::{AppEvent, AppState};
11use crate::app_state::{AppEvent, AppState};
12
12
13const CHROME_TOUCH_THROTTLE: Duration = Duration::from_millis(250);
13const CHROME_TOUCH_THROTTLE: Duration = Duration::from_millis(250);
@@ -42,21 +42,6 @@ impl AppState {
42 self.change_call_view(|view| view.choose(layout), cx);
42 self.change_call_view(|view| view.choose(layout), cx);
43 }
43 }
44
44
45 pub fn turn_call_gallery_page(&mut self, forward: bool, cx: &mut Context<Self>) {
46 let Some(call) = self.call.as_mut() else {
47 return;
48 };
49 let pages = gallery_page(&call.model).pages;
50 let page = call.model.gallery_page.min(pages - 1);
51 call.model.gallery_page = if forward {
52 (page + 1).min(pages - 1)
53 } else {
54 page.saturating_sub(1)
55 };
56 self.sync_video_wants();
57 cx.notify();
58 }
59
60 pub fn toggle_call_hide_no_video(&mut self, cx: &mut Context<Self>) {
45 pub fn toggle_call_hide_no_video(&mut self, cx: &mut Context<Self>) {
61 self.change_call_view(|view| view.hide_no_video = !view.hide_no_video, cx);
46 self.change_call_view(|view| view.hide_no_video = !view.hide_no_video, cx);
62 }
47 }
@@ -97,12 +82,15 @@ impl AppState {
97 }
82 }
98
83
99 fn sync_video_wants(&mut self) {
84 fn sync_video_wants(&mut self) {
85 let strip_width = self.call_strip_width;
100 let Some(call) = self.call.as_mut() else {
86 let Some(call) = self.call.as_mut() else {
101 return;
87 return;
102 };
88 };
103 let wants = video_wants(&call.model, measured_stage(call));
89 let wants = video_wants(&call.model, measured_stage(call), strip_width);
104 if wants != call.sent_wants {
90 if wants != call.sent_wants {
105 let _ = call.commands.send(CallCommand::SetVideoWants(wants.clone()));
91 let _ = call
92 .commands
93 .send(CallCommand::SetVideoWants(wants.clone()));
106 call.sent_wants = wants;
94 call.sent_wants = wants;
107 }
95 }
108 }
96 }
crates/app-state/src/call_rows.rs +4 −3
@@ -322,9 +322,10 @@ fn recap_date_line(
322 322 });
323 323 format!(
324 324 "{} - {}",
325 slot.start
326 .with_timezone(&clock.offset)
327 .format(&format!("{RECAP_DATE_FORMAT} {}", app_base::format::clock_format())),
325 slot.start.with_timezone(&clock.offset).format(&format!(
326 "{RECAP_DATE_FORMAT} {}",
327 app_base::format::clock_format()
328 )),
328 329 slot.end
329 330 .with_timezone(&clock.offset)
330 331 .format(app_base::format::clock_format())
@@ -322,9 +322,10 @@ fn recap_date_line(
322 });
322 });
323 format!(
323 format!(
324 "{} - {}",
324 "{} - {}",
325 slot.start
325 slot.start.with_timezone(&clock.offset).format(&format!(
326 .with_timezone(&clock.offset)
326 "{RECAP_DATE_FORMAT} {}",
327 .format(&format!("{RECAP_DATE_FORMAT} {}", app_base::format::clock_format())),
327 app_base::format::clock_format()
328 )),
328 slot.end
329 slot.end
329 .with_timezone(&clock.offset)
330 .with_timezone(&clock.offset)
330 .format(app_base::format::clock_format())
331 .format(app_base::format::clock_format())
crates/app-state/src/card_actions.rs +1 −6
@@ -227,12 +227,7 @@ impl AppState {
227 227 cx.notify();
228 228 }
229 229
230 pub fn replace_card(
231 &mut self,
232 scope: &CardScope,
233 json: &str,
234 cx: &mut Context<Self>,
235 ) -> bool {
230 pub fn replace_card(&mut self, scope: &CardScope, json: &str, cx: &mut Context<Self>) -> bool {
236 231 let Some(card) = AdaptiveCard::parse(json) else {
237 232 return false;
238 233 };
@@ -227,12 +227,7 @@ impl AppState {
227 cx.notify();
227 cx.notify();
228 }
228 }
229
229
230 pub fn replace_card(
230 pub fn replace_card(&mut self, scope: &CardScope, json: &str, cx: &mut Context<Self>) -> bool {
231 &mut self,
232 scope: &CardScope,
233 json: &str,
234 cx: &mut Context<Self>,
235 ) -> bool {
236 let Some(card) = AdaptiveCard::parse(json) else {
231 let Some(card) = AdaptiveCard::parse(json) else {
237 return false;
232 return false;
238 };
233 };
crates/app-state/src/channel_filter.rs +30 −6
@@ -19,7 +19,8 @@ impl ChannelFilter {
19 19 teams
20 20 .iter()
21 21 .filter_map(|entry| {
22 let team_matches = needle.is_empty() || entry.team.name.to_lowercase().contains(&needle);
22 let team_matches =
23 needle.is_empty() || entry.team.name.to_lowercase().contains(&needle);
23 24 let channels: Vec<_> = entry
24 25 .channels
25 26 .iter()
@@ -76,7 +77,11 @@ mod tests {
76 77 teams
77 78 .iter()
78 79 .map(|entry| {
79 let channels = entry.channels.iter().map(|channel| channel.name.clone()).collect();
80 let channels = entry
81 .channels
82 .iter()
83 .map(|channel| channel.name.clone())
84 .collect();
80 85 (entry.team.name.clone(), channels)
81 86 })
82 87 .collect()
@@ -85,7 +90,13 @@ mod tests {
85 90 #[test]
86 91 fn text_matches_channel_names_or_the_whole_team() {
87 92 let teams = vec![
88 team("Platform", vec![channel("c1", "General", false), channel("c2", "Releases", true)]),
93 team(
94 "Platform",
95 vec![
96 channel("c1", "General", false),
97 channel("c2", "Releases", true),
98 ],
99 ),
89 100 team("Release crew", vec![channel("c3", "General", false)]),
90 101 ];
91 102 let filter = ChannelFilter {
@@ -100,20 +111,33 @@ mod tests {
100 111 ("Release crew".to_owned(), vec!["General".to_owned()]),
101 112 ]
102 113 );
103 assert!(filtered.iter().all(|entry| !entry.hidden && entry.hidden_channel_ids.is_empty()));
114 assert!(
115 filtered
116 .iter()
117 .all(|entry| !entry.hidden && entry.hidden_channel_ids.is_empty())
118 );
104 119 }
105 120
106 121 #[test]
107 122 fn unread_keeps_only_unread_channels() {
108 123 let teams = vec![
109 team("Platform", vec![channel("c1", "General", false), channel("c2", "Releases", true)]),
124 team(
125 "Platform",
126 vec![
127 channel("c1", "General", false),
128 channel("c2", "Releases", true),
129 ],
130 ),
110 131 team("Quiet", vec![channel("c3", "General", false)]),
111 132 ];
112 133 let filter = ChannelFilter {
113 134 text: String::new(),
114 135 unread_only: true,
115 136 };
116 assert_eq!(names(&filter.apply(&teams)), [("Platform".to_owned(), vec!["Releases".to_owned()])]);
137 assert_eq!(
138 names(&filter.apply(&teams)),
139 [("Platform".to_owned(), vec!["Releases".to_owned()])]
140 );
117 141 assert!(!ChannelFilter::default().is_active());
118 142 }
119 143 }
@@ -19,7 +19,8 @@ impl ChannelFilter {
19 teams
19 teams
20 .iter()
20 .iter()
21 .filter_map(|entry| {
21 .filter_map(|entry| {
22 let team_matches = needle.is_empty() || entry.team.name.to_lowercase().contains(&needle);
22 let team_matches =
23 needle.is_empty() || entry.team.name.to_lowercase().contains(&needle);
23 let channels: Vec<_> = entry
24 let channels: Vec<_> = entry
24 .channels
25 .channels
25 .iter()
26 .iter()
@@ -76,7 +77,11 @@ mod tests {
76 teams
77 teams
77 .iter()
78 .iter()
78 .map(|entry| {
79 .map(|entry| {
79 let channels = entry.channels.iter().map(|channel| channel.name.clone()).collect();
80 let channels = entry
81 .channels
82 .iter()
83 .map(|channel| channel.name.clone())
84 .collect();
80 (entry.team.name.clone(), channels)
85 (entry.team.name.clone(), channels)
81 })
86 })
82 .collect()
87 .collect()
@@ -85,7 +90,13 @@ mod tests {
85 #[test]
90 #[test]
86 fn text_matches_channel_names_or_the_whole_team() {
91 fn text_matches_channel_names_or_the_whole_team() {
87 let teams = vec![
92 let teams = vec![
88 team("Platform", vec![channel("c1", "General", false), channel("c2", "Releases", true)]),
93 team(
94 "Platform",
95 vec![
96 channel("c1", "General", false),
97 channel("c2", "Releases", true),
98 ],
99 ),
89 team("Release crew", vec![channel("c3", "General", false)]),
100 team("Release crew", vec![channel("c3", "General", false)]),
90 ];
101 ];
91 let filter = ChannelFilter {
102 let filter = ChannelFilter {
@@ -100,20 +111,33 @@ mod tests {
100 ("Release crew".to_owned(), vec!["General".to_owned()]),
111 ("Release crew".to_owned(), vec!["General".to_owned()]),
101 ]
112 ]
102 );
113 );
103 assert!(filtered.iter().all(|entry| !entry.hidden && entry.hidden_channel_ids.is_empty()));
114 assert!(
115 filtered
116 .iter()
117 .all(|entry| !entry.hidden && entry.hidden_channel_ids.is_empty())
118 );
104 }
119 }
105
120
106 #[test]
121 #[test]
107 fn unread_keeps_only_unread_channels() {
122 fn unread_keeps_only_unread_channels() {
108 let teams = vec![
123 let teams = vec![
109 team("Platform", vec![channel("c1", "General", false), channel("c2", "Releases", true)]),
124 team(
125 "Platform",
126 vec![
127 channel("c1", "General", false),
128 channel("c2", "Releases", true),
129 ],
130 ),
110 team("Quiet", vec![channel("c3", "General", false)]),
131 team("Quiet", vec![channel("c3", "General", false)]),
111 ];
132 ];
112 let filter = ChannelFilter {
133 let filter = ChannelFilter {
113 text: String::new(),
134 text: String::new(),
114 unread_only: true,
135 unread_only: true,
115 };
136 };
116 assert_eq!(names(&filter.apply(&teams)), [("Platform".to_owned(), vec!["Releases".to_owned()])]);
137 assert_eq!(
138 names(&filter.apply(&teams)),
139 [("Platform".to_owned(), vec!["Releases".to_owned()])]
140 );
117 assert!(!ChannelFilter::default().is_active());
141 assert!(!ChannelFilter::default().is_active());
118 }
142 }
119}
143}
crates/app-state/src/channel_menu.rs +26 −4
@@ -335,7 +335,11 @@ impl AppState {
335 335 return;
336 336 };
337 337 let owned_id = channel_id.to_owned();
338 self.link_from(async move { engine.channel_link(&owned_id).await }, link_use, cx);
338 self.link_from(
339 async move { engine.channel_link(&owned_id).await },
340 link_use,
341 cx,
342 );
339 343 }
340 344
341 345 pub fn copy_team_link(&mut self, team_id: &str, cx: &mut Context<Self>) {
@@ -360,7 +364,11 @@ impl AppState {
360 364 return;
361 365 };
362 366 let owned_id = team_id.to_owned();
363 self.link_from(async move { engine.team_link(&owned_id).await }, link_use, cx);
367 self.link_from(
368 async move { engine.team_link(&owned_id).await },
369 link_use,
370 cx,
371 );
364 372 }
365 373
366 374 pub fn channel_team_id(&self, channel_id: &str) -> Option<String> {
@@ -470,7 +478,14 @@ mod tests {
470 478 });
471 479 assert_eq!(
472 480 labels(&shown, ChannelMenuItem::label),
473 ["Channel notifications", "Pin", "Hide", "-", "Manage channel", "Copy link"]
481 [
482 "Channel notifications",
483 "Pin",
484 "Hide",
485 "-",
486 "Manage channel",
487 "Copy link"
488 ]
474 489 );
475 490 let hidden_pinned = channel_menu_entries(ChannelMenuState {
476 491 pinned: true,
@@ -479,7 +494,14 @@ mod tests {
479 494 });
480 495 assert_eq!(
481 496 labels(&hidden_pinned, ChannelMenuItem::label),
482 ["Channel notifications", "Unpin", "Show", "-", "Manage channel", "Copy link"]
497 [
498 "Channel notifications",
499 "Unpin",
500 "Show",
501 "-",
502 "Manage channel",
503 "Copy link"
504 ]
483 505 );
484 506 }
485 507
@@ -335,7 +335,11 @@ impl AppState {
335 return;
335 return;
336 };
336 };
337 let owned_id = channel_id.to_owned();
337 let owned_id = channel_id.to_owned();
338 self.link_from(async move { engine.channel_link(&owned_id).await }, link_use, cx);
338 self.link_from(
339 async move { engine.channel_link(&owned_id).await },
340 link_use,
341 cx,
342 );
339 }
343 }
340
344
341 pub fn copy_team_link(&mut self, team_id: &str, cx: &mut Context<Self>) {
345 pub fn copy_team_link(&mut self, team_id: &str, cx: &mut Context<Self>) {
@@ -360,7 +364,11 @@ impl AppState {
360 return;
364 return;
361 };
365 };
362 let owned_id = team_id.to_owned();
366 let owned_id = team_id.to_owned();
363 self.link_from(async move { engine.team_link(&owned_id).await }, link_use, cx);
367 self.link_from(
368 async move { engine.team_link(&owned_id).await },
369 link_use,
370 cx,
371 );
364 }
372 }
365
373
366 pub fn channel_team_id(&self, channel_id: &str) -> Option<String> {
374 pub fn channel_team_id(&self, channel_id: &str) -> Option<String> {
@@ -470,7 +478,14 @@ mod tests {
470 });
478 });
471 assert_eq!(
479 assert_eq!(
472 labels(&shown, ChannelMenuItem::label),
480 labels(&shown, ChannelMenuItem::label),
473 ["Channel notifications", "Pin", "Hide", "-", "Manage channel", "Copy link"]
481 [
482 "Channel notifications",
483 "Pin",
484 "Hide",
485 "-",
486 "Manage channel",
487 "Copy link"
488 ]
474 );
489 );
475 let hidden_pinned = channel_menu_entries(ChannelMenuState {
490 let hidden_pinned = channel_menu_entries(ChannelMenuState {
476 pinned: true,
491 pinned: true,
@@ -479,7 +494,14 @@ mod tests {
479 });
494 });
480 assert_eq!(
495 assert_eq!(
481 labels(&hidden_pinned, ChannelMenuItem::label),
496 labels(&hidden_pinned, ChannelMenuItem::label),
482 ["Channel notifications", "Unpin", "Show", "-", "Manage channel", "Copy link"]
497 [
498 "Channel notifications",
499 "Unpin",
500 "Show",
501 "-",
502 "Manage channel",
503 "Copy link"
504 ]
483 );
505 );
484 }
506 }
485
507
crates/app-state/src/chat_settings_actions.rs +6 −1
@@ -17,7 +17,12 @@ pub fn stored_markdown_mode(store: &Store) -> bool {
17 17 }
18 18
19 19 pub fn stored_actions_on_right_click(store: &Store) -> bool {
20 store.meta(META_ACTIONS_ON_RIGHT_CLICK).ok().flatten().as_deref() == Some("true")
20 store
21 .meta(META_ACTIONS_ON_RIGHT_CLICK)
22 .ok()
23 .flatten()
24 .as_deref()
25 == Some("true")
21 26 }
22 27
23 28 /// Teams shows no read state at all while the own read receipts setting is off.
@@ -17,7 +17,12 @@ pub fn stored_markdown_mode(store: &Store) -> bool {
17}
17}
18
18
19pub fn stored_actions_on_right_click(store: &Store) -> bool {
19pub fn stored_actions_on_right_click(store: &Store) -> bool {
20 store.meta(META_ACTIONS_ON_RIGHT_CLICK).ok().flatten().as_deref() == Some("true")
20 store
21 .meta(META_ACTIONS_ON_RIGHT_CLICK)
22 .ok()
23 .flatten()
24 .as_deref()
25 == Some("true")
21}
26}
22
27
23/// Teams shows no read state at all while the own read receipts setting is off.
28/// Teams shows no read state at all while the own read receipts setting is off.
crates/app-state/src/connection_banner.rs +7 −2
@@ -58,8 +58,13 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner
58 58 BannerKind::Connecting => text("Connecting..."),
59 59 BannerKind::Reconnecting => text("Reconnecting..."),
60 60 BannerKind::Offline => BannerText {
61 detail: last_sync
62 .map(|time| format!("Last synced {}", time.with_timezone(&Local).format(app_base::format::clock_format()))),
61 detail: last_sync.map(|time| {
62 format!(
63 "Last synced {}",
64 time.with_timezone(&Local)
65 .format(app_base::format::clock_format())
66 )
67 }),
63 68 ..text(OFFLINE_TEXT)
64 69 },
65 70 BannerKind::SignIn => text("Sign-in required. Sign in to Teams in the window that opened."),
@@ -58,8 +58,13 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner
58 BannerKind::Connecting => text("Connecting..."),
58 BannerKind::Connecting => text("Connecting..."),
59 BannerKind::Reconnecting => text("Reconnecting..."),
59 BannerKind::Reconnecting => text("Reconnecting..."),
60 BannerKind::Offline => BannerText {
60 BannerKind::Offline => BannerText {
61 detail: last_sync
61 detail: last_sync.map(|time| {
62 .map(|time| format!("Last synced {}", time.with_timezone(&Local).format(app_base::format::clock_format()))),
62 format!(
63 "Last synced {}",
64 time.with_timezone(&Local)
65 .format(app_base::format::clock_format())
66 )
67 }),
63 ..text(OFFLINE_TEXT)
68 ..text(OFFLINE_TEXT)
64 },
69 },
65 BannerKind::SignIn => text("Sign-in required. Sign in to Teams in the window that opened."),
70 BannerKind::SignIn => text("Sign-in required. Sign in to Teams in the window that opened."),
crates/app-state/src/demo.rs +8 −7
@@ -11,11 +11,10 @@ use store::{
11 11 Store, TeamLayoutRecord, TeamRecord,
12 12 };
13 13 use teams_core::{
14 ANNOUNCEMENT_BANNER_TYPE,
15 Activity, ActivityHorizons, ActivityItem, ActivitySnapshot, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
16 LanguageSettings, LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource,
17 PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior,
18 TranslationStatus,
14 ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,
15 CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
16 LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource, PinnedMessage,
17 SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
19 18 };
20 19
21 20 use crate::app_state::{AppState, Selection};
@@ -724,7 +723,8 @@ pub fn activity_snapshot() -> ActivitySnapshot {
724 723 activity_subtype: subtype.to_owned(),
725 724 source_thread_id: conversation_id.to_owned(),
726 725 source_message_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
727 source_reply_chain_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
726 source_reply_chain_id: (!source_message_id.is_empty())
727 .then(|| source_message_id.to_owned()),
728 728 source_user_id: Some(format!("8:orgid:{}", actor.0)),
729 729 source_user_name: actor.1.to_owned(),
730 730 preview: preview.to_owned(),
@@ -819,7 +819,8 @@ pub fn activity_snapshot() -> ActivitySnapshot {
819 819 source_user_id: None,
820 820 source_app_name: Some("Meeting Recaps".to_owned()),
821 821 preview_template: "previewUnavailable".to_owned(),
822 template_parameters: [("subject".to_owned(), "Following: Sprint Review ".to_owned())].into(),
822 template_parameters: [("subject".to_owned(), "Following: Sprint Review ".to_owned())]
823 .into(),
823 824 event_start_ms: Some(at(1, 10, 0).timestamp_millis()),
824 825 event_end_ms: Some(at(1, 11, 0).timestamp_millis()),
825 826 ..item(
@@ -11,11 +11,10 @@ use store::{
11 Store, TeamLayoutRecord, TeamRecord,
11 Store, TeamLayoutRecord, TeamRecord,
12};
12};
13use teams_core::{
13use teams_core::{
14 ANNOUNCEMENT_BANNER_TYPE,
14 ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,
15 Activity, ActivityHorizons, ActivityItem, ActivitySnapshot, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
15 CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
16 LanguageSettings, LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource,
16 LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource, PinnedMessage,
17 PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior,
17 SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
18 TranslationStatus,
19};
18};
20
19
21use crate::app_state::{AppState, Selection};
20use crate::app_state::{AppState, Selection};
@@ -724,7 +723,8 @@ pub fn activity_snapshot() -> ActivitySnapshot {
724 activity_subtype: subtype.to_owned(),
723 activity_subtype: subtype.to_owned(),
725 source_thread_id: conversation_id.to_owned(),
724 source_thread_id: conversation_id.to_owned(),
726 source_message_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
725 source_message_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
727 source_reply_chain_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
726 source_reply_chain_id: (!source_message_id.is_empty())
727 .then(|| source_message_id.to_owned()),
728 source_user_id: Some(format!("8:orgid:{}", actor.0)),
728 source_user_id: Some(format!("8:orgid:{}", actor.0)),
729 source_user_name: actor.1.to_owned(),
729 source_user_name: actor.1.to_owned(),
730 preview: preview.to_owned(),
730 preview: preview.to_owned(),
@@ -819,7 +819,8 @@ pub fn activity_snapshot() -> ActivitySnapshot {
819 source_user_id: None,
819 source_user_id: None,
820 source_app_name: Some("Meeting Recaps".to_owned()),
820 source_app_name: Some("Meeting Recaps".to_owned()),
821 preview_template: "previewUnavailable".to_owned(),
821 preview_template: "previewUnavailable".to_owned(),
822 template_parameters: [("subject".to_owned(), "Following: Sprint Review ".to_owned())].into(),
822 template_parameters: [("subject".to_owned(), "Following: Sprint Review ".to_owned())]
823 .into(),
823 event_start_ms: Some(at(1, 10, 0).timestamp_millis()),
824 event_start_ms: Some(at(1, 10, 0).timestamp_millis()),
824 event_end_ms: Some(at(1, 11, 0).timestamp_millis()),
825 event_end_ms: Some(at(1, 11, 0).timestamp_millis()),
825 ..item(
826 ..item(
crates/app-state/src/lib.rs +12 −14
@@ -1,22 +1,19 @@
1 1 pub mod activity;
2 pub mod banner_image;
3 2 pub mod agent_api;
4 3 pub mod agents;
5 4 pub mod app_state;
6 5 pub mod backend;
6 pub mod banner_image;
7 7 pub mod call;
8 8 pub mod call_rows;
9 9 pub mod card_actions;
10 10 pub mod card_inputs;
11 11 pub mod card_refresh;
12 12 pub mod card_state;
13 pub mod channel_filter;
13 14 pub mod channel_menu;
14 15 pub mod chat_actions;
15 mod sidebar_load;
16 pub mod channel_filter;
17 16 pub mod chat_filter;
18 pub mod find_in_chat;
19 pub mod forward_selection;
20 17 pub mod chat_members;
21 18 pub mod chat_settings_actions;
22 19 pub mod connection_banner;
@@ -27,22 +24,22 @@ pub mod demo;
27 24 pub mod demo_meetings;
28 25 pub mod demo_profiles;
29 26 pub mod emoji;
27 pub mod find_in_chat;
28 pub mod forward_selection;
30 29 pub mod gifs;
31 30 pub mod image_view_gallery;
32 31 pub mod importance;
33 32 pub mod local_previews;
34 pub mod manage_team;
35 33 pub mod message_actions;
36 34 pub mod notice;
37 35 pub mod notify;
38 36 pub mod outbox;
39 37 pub mod outgoing;
40 38 pub mod own_status;
41 pub mod presence_follow;
42 pub mod absence_notice;
43 39 pub mod pending_rows;
44 40 pub mod people;
45 41 pub mod post_follow;
42 pub mod presence_follow;
46 43 pub mod profile_model;
47 44 pub mod profile_state;
48 45 pub mod reaction_model;
@@ -53,6 +50,7 @@ pub mod scheduled_rows;
53 50 pub mod section_actions;
54 51 pub mod settings_section;
55 52 pub mod share_outlook;
53 mod sidebar_load;
56 54 pub mod sidebar_model;
57 55 pub mod sound_actions;
58 56 pub mod stored_outgoing;
@@ -60,13 +58,13 @@ pub mod task_dialog;
60 58 pub mod team_admin;
61 59 pub mod translation_actions;
62 60 pub mod typing;
63 mod warm_chats;
64 61 pub mod urgent_ack;
65 62
66 pub use app_ui_kit::render;
67 63 pub use app_base::{
68 APP_NAME, appearance, autostart, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
69 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
70 emoticons, image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
71 single_instance, stickers, theme, translation, updater, user_activity, zoom,
64 APP_NAME, appearance, autostart, avatar_image, channel_files, crash_log, demo_cards,
65 demo_chart_cards, demo_gifs, demo_input_cards, demo_library, demo_recap, diagnostics,
66 downloads, emoticons, format, frame_log, fuzzy, image_clipboard, image_view_math, inline_image,
67 presence_link, read_state, recap, remote_image, runtime, schedule_time, single_instance,
68 stickers, theme, translation, updater, user_activity, zoom,
72 69 };
70 pub use app_ui_kit::render;
@@ -1,22 +1,19 @@
1pub mod activity;
1pub mod activity;
2pub mod banner_image;
3pub mod agent_api;
2pub mod agent_api;
4pub mod agents;
3pub mod agents;
5pub mod app_state;
4pub mod app_state;
6pub mod backend;
5pub mod backend;
6pub mod banner_image;
7pub mod call;
7pub mod call;
8pub mod call_rows;
8pub mod call_rows;
9pub mod card_actions;
9pub mod card_actions;
10pub mod card_inputs;
10pub mod card_inputs;
11pub mod card_refresh;
11pub mod card_refresh;
12pub mod card_state;
12pub mod card_state;
13pub mod channel_filter;
13pub mod channel_menu;
14pub mod channel_menu;
14pub mod chat_actions;
15pub mod chat_actions;
15mod sidebar_load;
16pub mod channel_filter;
17pub mod chat_filter;
16pub mod chat_filter;
18pub mod find_in_chat;
19pub mod forward_selection;
20pub mod chat_members;
17pub mod chat_members;
21pub mod chat_settings_actions;
18pub mod chat_settings_actions;
22pub mod connection_banner;
19pub mod connection_banner;
@@ -27,22 +24,22 @@ pub mod demo;
27pub mod demo_meetings;
24pub mod demo_meetings;
28pub mod demo_profiles;
25pub mod demo_profiles;
29pub mod emoji;
26pub mod emoji;
27pub mod find_in_chat;
28pub mod forward_selection;
30pub mod gifs;
29pub mod gifs;
31pub mod image_view_gallery;
30pub mod image_view_gallery;
32pub mod importance;
31pub mod importance;
33pub mod local_previews;
32pub mod local_previews;
34pub mod manage_team;
35pub mod message_actions;
33pub mod message_actions;
36pub mod notice;
34pub mod notice;
37pub mod notify;
35pub mod notify;
38pub mod outbox;
36pub mod outbox;
39pub mod outgoing;
37pub mod outgoing;
40pub mod own_status;
38pub mod own_status;
41pub mod presence_follow;
42pub mod absence_notice;
43pub mod pending_rows;
39pub mod pending_rows;
44pub mod people;
40pub mod people;
45pub mod post_follow;
41pub mod post_follow;
42pub mod presence_follow;
46pub mod profile_model;
43pub mod profile_model;
47pub mod profile_state;
44pub mod profile_state;
48pub mod reaction_model;
45pub mod reaction_model;
@@ -53,6 +50,7 @@ pub mod scheduled_rows;
53pub mod section_actions;
50pub mod section_actions;
54pub mod settings_section;
51pub mod settings_section;
55pub mod share_outlook;
52pub mod share_outlook;
53mod sidebar_load;
56pub mod sidebar_model;
54pub mod sidebar_model;
57pub mod sound_actions;
55pub mod sound_actions;
58pub mod stored_outgoing;
56pub mod stored_outgoing;
@@ -60,13 +58,13 @@ pub mod task_dialog;
60pub mod team_admin;
58pub mod team_admin;
61pub mod translation_actions;
59pub mod translation_actions;
62pub mod typing;
60pub mod typing;
63mod warm_chats;
64pub mod urgent_ack;
61pub mod urgent_ack;
65
62
66pub use app_ui_kit::render;
67pub use app_base::{
63pub use app_base::{
68 APP_NAME, appearance, autostart, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
64 APP_NAME, appearance, autostart, avatar_image, channel_files, crash_log, demo_cards,
69 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
65 demo_chart_cards, demo_gifs, demo_input_cards, demo_library, demo_recap, diagnostics,
70 emoticons, image_clipboard, image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
66 downloads, emoticons, format, frame_log, fuzzy, image_clipboard, image_view_math, inline_image,
71 single_instance, stickers, theme, translation, updater, user_activity, zoom,
67 presence_link, read_state, recap, remote_image, runtime, schedule_time, single_instance,
68 stickers, theme, translation, updater, user_activity, zoom,
72};
69};
70pub use app_ui_kit::render;
crates/app-state/src/message_actions.rs +1 −5
@@ -97,11 +97,7 @@ fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {
97 97 }
98 98
99 99 impl AppState {
100 pub fn message_record(
101 &self,
102 conversation_id: &str,
103 message_id: &str,
104 ) -> Option<MessageRecord> {
100 pub fn message_record(&self, conversation_id: &str, message_id: &str) -> Option<MessageRecord> {
105 101 self.store
106 102 .messages_by_id(conversation_id, &[message_id.to_owned()])
107 103 .ok()?
@@ -97,11 +97,7 @@ fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {
97}
97}
98
98
99impl AppState {
99impl AppState {
100 pub fn message_record(
100 pub fn message_record(&self, conversation_id: &str, message_id: &str) -> Option<MessageRecord> {
101 &self,
102 conversation_id: &str,
103 message_id: &str,
104 ) -> Option<MessageRecord> {
105 self.store
101 self.store
106 .messages_by_id(conversation_id, &[message_id.to_owned()])
102 .messages_by_id(conversation_id, &[message_id.to_owned()])
107 .ok()?
103 .ok()?
crates/app-state/src/outbox.rs +4 −2
@@ -9,9 +9,9 @@ use uuid::Uuid;
9 9 use crate::app_state::{AppEvent, AppState};
10 10 use crate::backend::Engine;
11 11 use crate::notice::short_error;
12 use crate::outgoing::Outgoing;
12 13 use crate::runtime;
13 14 use crate::stored_outgoing::{decode, encode};
14 use crate::outgoing::Outgoing;
15 15
16 16 const RETRY_BACKOFF: [Duration; 3] = [
17 17 Duration::from_secs(2),
@@ -95,7 +95,9 @@ pub async fn deliver(
95 95 discard_banner_image(banner);
96 96 }
97 97 match posted {
98 Err(teams_core::Error::PostedWithoutBanner) => return Ok(Delivered::WithoutBanner),
98 Err(teams_core::Error::PostedWithoutBanner) => {
99 return Ok(Delivered::WithoutBanner);
100 }
99 101 other => other,
100 102 }
101 103 }
@@ -9,9 +9,9 @@ use uuid::Uuid;
9use crate::app_state::{AppEvent, AppState};
9use crate::app_state::{AppEvent, AppState};
10use crate::backend::Engine;
10use crate::backend::Engine;
11use crate::notice::short_error;
11use crate::notice::short_error;
12use crate::outgoing::Outgoing;
12use crate::runtime;
13use crate::runtime;
13use crate::stored_outgoing::{decode, encode};
14use crate::stored_outgoing::{decode, encode};
14use crate::outgoing::Outgoing;
15
15
16const RETRY_BACKOFF: [Duration; 3] = [
16const RETRY_BACKOFF: [Duration; 3] = [
17 Duration::from_secs(2),
17 Duration::from_secs(2),
@@ -95,7 +95,9 @@ pub async fn deliver(
95 discard_banner_image(banner);
95 discard_banner_image(banner);
96 }
96 }
97 match posted {
97 match posted {
98 Err(teams_core::Error::PostedWithoutBanner) => return Ok(Delivered::WithoutBanner),
98 Err(teams_core::Error::PostedWithoutBanner) => {
99 return Ok(Delivered::WithoutBanner);
100 }
99 other => other,
101 other => other,
100 }
102 }
101 }
103 }
crates/app-state/src/outgoing.rs +2 −3
@@ -4,9 +4,8 @@ use chrono::{DateTime, Utc};
4 4 use gpui_kit::Image;
5 5 use serde::{Deserialize, Serialize};
6 6 use teams_core::{
7 AnnouncementBanner,
8 Draft, FileKind, FileReference, HostedImage, LinkPreview, MentionInput, MessageExtras,
9 OBJECT_MARK, UploadedFile,
7 AnnouncementBanner, Draft, FileKind, FileReference, HostedImage, LinkPreview, MentionInput,
8 MessageExtras, OBJECT_MARK, UploadedFile,
10 9 };
11 10
12 11 use store::MessageImportance;
@@ -4,9 +4,8 @@ use chrono::{DateTime, Utc};
4use gpui_kit::Image;
4use gpui_kit::Image;
5use serde::{Deserialize, Serialize};
5use serde::{Deserialize, Serialize};
6use teams_core::{
6use teams_core::{
7 AnnouncementBanner,
7 AnnouncementBanner, Draft, FileKind, FileReference, HostedImage, LinkPreview, MentionInput,
8 Draft, FileKind, FileReference, HostedImage, LinkPreview, MentionInput, MessageExtras,
8 MessageExtras, OBJECT_MARK, UploadedFile,
9 OBJECT_MARK, UploadedFile,
10};
9};
11
10
12use store::MessageImportance;
11use store::MessageImportance;
crates/app-state/src/pending_rows.rs +6 −4
@@ -1,9 +1,9 @@
1 1 use chrono::{DateTime, Local, Utc};
2 2 use teams_core::{FileCard, QuoteInfo};
3 3
4 use crate::outgoing::{Outgoing, OutgoingImage};
4 5 use crate::render::{Block, layout_blocks};
5 6 use crate::rows::{Delivery, LocalImage, MessageRow, Receipt, Series};
6 use crate::outgoing::{Outgoing, OutgoingImage};
7 7
8 8 fn pending_blocks(outgoing: &Outgoing) -> Vec<Block> {
9 9 let quote = outgoing.reply.as_ref().map(|reply| {
@@ -42,9 +42,11 @@ pub fn pending_row(
42 42 .to_string(),
43 43 day_header: None,
44 44 blocks: pending_blocks(outgoing),
45 jumbo: (outgoing.reply.is_none() && outgoing.images.is_empty() && outgoing.files.is_empty())
46 .then(|| teams_core::jumbo_emoji(&outgoing.html()))
47 .flatten(),
45 jumbo: (outgoing.reply.is_none()
46 && outgoing.images.is_empty()
47 && outgoing.files.is_empty())
48 .then(|| teams_core::jumbo_emoji(&outgoing.html()))
49 .flatten(),
48 50 edited: false,
49 51 deleted: false,
50 52 reactions: Vec::new(),
@@ -1,9 +1,9 @@
1use chrono::{DateTime, Local, Utc};
1use chrono::{DateTime, Local, Utc};
2use teams_core::{FileCard, QuoteInfo};
2use teams_core::{FileCard, QuoteInfo};
3
3
4use crate::outgoing::{Outgoing, OutgoingImage};
4use crate::render::{Block, layout_blocks};
5use crate::render::{Block, layout_blocks};
5use crate::rows::{Delivery, LocalImage, MessageRow, Receipt, Series};
6use crate::rows::{Delivery, LocalImage, MessageRow, Receipt, Series};
6use crate::outgoing::{Outgoing, OutgoingImage};
7
7
8fn pending_blocks(outgoing: &Outgoing) -> Vec<Block> {
8fn pending_blocks(outgoing: &Outgoing) -> Vec<Block> {
9 let quote = outgoing.reply.as_ref().map(|reply| {
9 let quote = outgoing.reply.as_ref().map(|reply| {
@@ -42,9 +42,11 @@ pub fn pending_row(
42 .to_string(),
42 .to_string(),
43 day_header: None,
43 day_header: None,
44 blocks: pending_blocks(outgoing),
44 blocks: pending_blocks(outgoing),
45 jumbo: (outgoing.reply.is_none() && outgoing.images.is_empty() && outgoing.files.is_empty())
45 jumbo: (outgoing.reply.is_none()
46 .then(|| teams_core::jumbo_emoji(&outgoing.html()))
46 && outgoing.images.is_empty()
47 .flatten(),
47 && outgoing.files.is_empty())
48 .then(|| teams_core::jumbo_emoji(&outgoing.html()))
49 .flatten(),
48 edited: false,
50 edited: false,
49 deleted: false,
51 deleted: false,
50 reactions: Vec::new(),
52 reactions: Vec::new(),
crates/app-state/src/post_follow.rs +10 −3
@@ -95,7 +95,10 @@ impl AppState {
95 95 }
96 96 }
97 97 _ => {
98 state.post_follows.requested.remove(&post_key(&channel, &root));
98 state
99 .post_follows
100 .requested
101 .remove(&post_key(&channel, &root));
99 102 }
100 103 })
101 104 .ok();
@@ -130,7 +133,8 @@ impl AppState {
130 133 self.run_channel_action(
131 134 follow_failure(followed),
132 135 async move {
133 let annotation_failure = engine.set_post_followed(&channel, &root, followed).await?;
136 let annotation_failure =
137 engine.set_post_followed(&channel, &root, followed).await?;
134 138 if let Some(error) = annotation_failure {
135 139 log::warn!("post follow annotation not written: {error}");
136 140 }
@@ -157,7 +161,10 @@ mod tests {
157 161
158 162 #[test]
159 163 fn explicit_state_wins_over_participation() {
160 assert!(!post_followed(Some(PostFollowState::ExplicitUnfollow), true));
164 assert!(!post_followed(
165 Some(PostFollowState::ExplicitUnfollow),
166 true
167 ));
161 168 assert!(post_followed(Some(PostFollowState::ExplicitFollow), false));
162 169 assert!(post_followed(Some(PostFollowState::ImplicitFollow), false));
163 170 assert!(post_followed(None, true));
@@ -95,7 +95,10 @@ impl AppState {
95 }
95 }
96 }
96 }
97 _ => {
97 _ => {
98 state.post_follows.requested.remove(&post_key(&channel, &root));
98 state
99 .post_follows
100 .requested
101 .remove(&post_key(&channel, &root));
99 }
102 }
100 })
103 })
101 .ok();
104 .ok();
@@ -130,7 +133,8 @@ impl AppState {
130 self.run_channel_action(
133 self.run_channel_action(
131 follow_failure(followed),
134 follow_failure(followed),
132 async move {
135 async move {
133 let annotation_failure = engine.set_post_followed(&channel, &root, followed).await?;
136 let annotation_failure =
137 engine.set_post_followed(&channel, &root, followed).await?;
134 if let Some(error) = annotation_failure {
138 if let Some(error) = annotation_failure {
135 log::warn!("post follow annotation not written: {error}");
139 log::warn!("post follow annotation not written: {error}");
136 }
140 }
@@ -157,7 +161,10 @@ mod tests {
157
161
158 #[test]
162 #[test]
159 fn explicit_state_wins_over_participation() {
163 fn explicit_state_wins_over_participation() {
160 assert!(!post_followed(Some(PostFollowState::ExplicitUnfollow), true));
164 assert!(!post_followed(
165 Some(PostFollowState::ExplicitUnfollow),
166 true
167 ));
161 assert!(post_followed(Some(PostFollowState::ExplicitFollow), false));
168 assert!(post_followed(Some(PostFollowState::ExplicitFollow), false));
162 assert!(post_followed(Some(PostFollowState::ImplicitFollow), false));
169 assert!(post_followed(Some(PostFollowState::ImplicitFollow), false));
163 assert!(post_followed(None, true));
170 assert!(post_followed(None, true));
crates/app-state/src/presence_follow.rs +26 −6
@@ -118,7 +118,12 @@ impl AppState {
118 118 }
119 119 }
120 120
121 pub(crate) fn note_followed_change(&mut self, user_id: &str, previous: Presence, next: PresenceKind) {
121 pub(crate) fn note_followed_change(
122 &mut self,
123 user_id: &str,
124 previous: Presence,
125 next: PresenceKind,
126 ) {
122 127 if !self.is_presence_followed(user_id) {
123 128 return;
124 129 }
@@ -142,8 +147,14 @@ mod tests {
142 147 #[test]
143 148 fn only_a_change_to_available_or_offline_is_announced() {
144 149 let busy = Presence::Live(PresenceKind::Busy);
145 assert_eq!(status_change_text(busy, PresenceKind::Available), Some(NOW_AVAILABLE));
146 assert_eq!(status_change_text(busy, PresenceKind::Offline), Some(NOW_OFFLINE));
150 assert_eq!(
151 status_change_text(busy, PresenceKind::Available),
152 Some(NOW_AVAILABLE)
153 );
154 assert_eq!(
155 status_change_text(busy, PresenceKind::Offline),
156 Some(NOW_OFFLINE)
157 );
147 158 assert_eq!(status_change_text(busy, PresenceKind::Away), None);
148 159 assert_eq!(status_change_text(busy, PresenceKind::OutOfOffice), None);
149 160 let available = Presence::Live(PresenceKind::Available);
@@ -152,13 +163,22 @@ mod tests {
152 163
153 164 #[test]
154 165 fn the_first_known_status_is_not_announced() {
155 assert_eq!(status_change_text(Presence::Loading, PresenceKind::Available), None);
156 166 assert_eq!(
157 status_change_text(Presence::Cached(PresenceKind::Busy), PresenceKind::Available),
167 status_change_text(Presence::Loading, PresenceKind::Available),
168 None
169 );
170 assert_eq!(
171 status_change_text(
172 Presence::Cached(PresenceKind::Busy),
173 PresenceKind::Available
174 ),
158 175 None
159 176 );
160 177 assert_eq!(
161 status_change_text(Presence::Live(PresenceKind::Unknown), PresenceKind::Available),
178 status_change_text(
179 Presence::Live(PresenceKind::Unknown),
180 PresenceKind::Available
181 ),
162 182 None
163 183 );
164 184 }
@@ -118,7 +118,12 @@ impl AppState {
118 }
118 }
119 }
119 }
120
120
121 pub(crate) fn note_followed_change(&mut self, user_id: &str, previous: Presence, next: PresenceKind) {
121 pub(crate) fn note_followed_change(
122 &mut self,
123 user_id: &str,
124 previous: Presence,
125 next: PresenceKind,
126 ) {
122 if !self.is_presence_followed(user_id) {
127 if !self.is_presence_followed(user_id) {
123 return;
128 return;
124 }
129 }
@@ -142,8 +147,14 @@ mod tests {
142 #[test]
147 #[test]
143 fn only_a_change_to_available_or_offline_is_announced() {
148 fn only_a_change_to_available_or_offline_is_announced() {
144 let busy = Presence::Live(PresenceKind::Busy);
149 let busy = Presence::Live(PresenceKind::Busy);
145 assert_eq!(status_change_text(busy, PresenceKind::Available), Some(NOW_AVAILABLE));
150 assert_eq!(
146 assert_eq!(status_change_text(busy, PresenceKind::Offline), Some(NOW_OFFLINE));
151 status_change_text(busy, PresenceKind::Available),
152 Some(NOW_AVAILABLE)
153 );
154 assert_eq!(
155 status_change_text(busy, PresenceKind::Offline),
156 Some(NOW_OFFLINE)
157 );
147 assert_eq!(status_change_text(busy, PresenceKind::Away), None);
158 assert_eq!(status_change_text(busy, PresenceKind::Away), None);
148 assert_eq!(status_change_text(busy, PresenceKind::OutOfOffice), None);
159 assert_eq!(status_change_text(busy, PresenceKind::OutOfOffice), None);
149 let available = Presence::Live(PresenceKind::Available);
160 let available = Presence::Live(PresenceKind::Available);
@@ -152,13 +163,22 @@ mod tests {
152
163
153 #[test]
164 #[test]
154 fn the_first_known_status_is_not_announced() {
165 fn the_first_known_status_is_not_announced() {
155 assert_eq!(status_change_text(Presence::Loading, PresenceKind::Available), None);
156 assert_eq!(
166 assert_eq!(
157 status_change_text(Presence::Cached(PresenceKind::Busy), PresenceKind::Available),
167 status_change_text(Presence::Loading, PresenceKind::Available),
168 None
169 );
170 assert_eq!(
171 status_change_text(
172 Presence::Cached(PresenceKind::Busy),
173 PresenceKind::Available
174 ),
158 None
175 None
159 );
176 );
160 assert_eq!(
177 assert_eq!(
161 status_change_text(Presence::Live(PresenceKind::Unknown), PresenceKind::Available),
178 status_change_text(
179 Presence::Live(PresenceKind::Unknown),
180 PresenceKind::Available
181 ),
162 None
182 None
163 );
183 );
164 }
184 }
crates/app-state/src/profile_model.rs +5 −1
@@ -36,7 +36,11 @@ pub fn status_line(availability: &str, local_time: Option<&str>) -> String {
36 36
37 37 pub fn local_time_label(profile: &PersonProfile, now: DateTime<Utc>) -> Option<String> {
38 38 let zone = profile.time_zone.as_deref()?;
39 Some(local_time(zone, now)?.format(app_base::format::clock_format()).to_string())
39 Some(
40 local_time(zone, now)?
41 .format(app_base::format::clock_format())
42 .to_string(),
43 )
40 44 }
41 45
42 46 pub fn work_location_label(location: WorkLocation) -> &'static str {
@@ -36,7 +36,11 @@ pub fn status_line(availability: &str, local_time: Option<&str>) -> String {
36
36
37pub fn local_time_label(profile: &PersonProfile, now: DateTime<Utc>) -> Option<String> {
37pub fn local_time_label(profile: &PersonProfile, now: DateTime<Utc>) -> Option<String> {
38 let zone = profile.time_zone.as_deref()?;
38 let zone = profile.time_zone.as_deref()?;
39 Some(local_time(zone, now)?.format(app_base::format::clock_format()).to_string())
39 Some(
40 local_time(zone, now)?
41 .format(app_base::format::clock_format())
42 .to_string(),
43 )
40}
44}
41
45
42pub fn work_location_label(location: WorkLocation) -> &'static str {
46pub fn work_location_label(location: WorkLocation) -> &'static str {
crates/app-state/src/rows.rs +57 −23
@@ -7,13 +7,11 @@ use gpui_kit::Image;
7 7 use store::{MessageImportance, MessageRecord};
8 8 use teams_core::roster_event::{RosterEvent, roster_event};
9 9 use teams_core::{
10 AnnouncementBanner, attachments,
11 JumboEmoji, jumbo_emoji,
12 AdaptiveCard, CallEvent, CallPhase, Draft, FileCard, ForwardHeader, ForwardInfo,
13 ImageRef, LinkPreview, forwards,
14 ReactionInfo, Span, adaptive_cards, call_event, card_texts, files,
15 forwarded_texts, images, is_forwarded, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans, quotes,
16 reactions, readable_text, translated_spans,
10 AdaptiveCard, AnnouncementBanner, CallEvent, CallPhase, Draft, FileCard, ForwardHeader,
11 ForwardInfo, ImageRef, JumboEmoji, LinkPreview, ReactionInfo, Span, adaptive_cards,
12 attachments, call_event, card_texts, files, forwarded_texts, forwards, images, is_forwarded,
13 jumbo_emoji, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans,
14 quotes, reactions, readable_text, translated_spans,
17 15 };
18 16
19 17 pub use crate::call_rows::{
@@ -140,7 +138,10 @@ pub enum Receipt {
140 138 pub fn receipt_label(state: &teams_core::ReceiptState) -> Option<String> {
141 139 match state {
142 140 teams_core::ReceiptState::Sent => Some("Sent".to_owned()),
143 teams_core::ReceiptState::Read { readers, total_others } if *total_others > 1 => {
141 teams_core::ReceiptState::Read {
142 readers,
143 total_others,
144 } if *total_others > 1 => {
144 145 if readers.len() >= *total_others {
145 146 Some("Seen by everyone".to_owned())
146 147 } else {
@@ -816,8 +817,16 @@ pub fn quoted_texts(records: &[MessageRecord]) -> HashMap<String, String> {
816 817 if text.is_empty() {
817 818 text = forwarded_texts(record).join("\n");
818 819 }
819 let lines: Vec<&str> = text.lines().filter(|line| !line.trim().is_empty()).collect();
820 let mut shown = lines.iter().take(QUOTE_LINES).copied().collect::<Vec<_>>().join("\n");
820 let lines: Vec<&str> = text
821 .lines()
822 .filter(|line| !line.trim().is_empty())
823 .collect();
824 let mut shown = lines
825 .iter()
826 .take(QUOTE_LINES)
827 .copied()
828 .collect::<Vec<_>>()
829 .join("\n");
821 830 if lines.len() > QUOTE_LINES {
822 831 shown.push_str(" …");
823 832 }
@@ -1104,7 +1113,10 @@ fn is_blank_system_record(record: &MessageRecord) -> bool {
1104 1113 record.sender_id.is_none()
1105 1114 && record.call_event_json.is_none()
1106 1115 && record.body_html.trim().is_empty()
1107 && record.subject.as_deref().is_none_or(|subject| subject.trim().is_empty())
1116 && record
1117 .subject
1118 .as_deref()
1119 .is_none_or(|subject| subject.trim().is_empty())
1108 1120 && record.attachments_json.trim() == "[]"
1109 1121 }
1110 1122
@@ -1263,12 +1275,21 @@ mod tests {
1263 1275 at: Utc::now(),
1264 1276 };
1265 1277 let read = |readers: Vec<teams_core::ReceiptReader>, total_others| {
1266 receipt_label(&teams_core::ReceiptState::Read { readers, total_others })
1278 receipt_label(&teams_core::ReceiptState::Read {
1279 readers,
1280 total_others,
1281 })
1267 1282 };
1268 1283 assert_eq!(read(vec![reader("Bea")], 1).as_deref(), Some("Seen"));
1269 assert_eq!(read(vec![reader("Bea"), reader("Cy")], 2).as_deref(), Some("Seen by everyone"));
1284 assert_eq!(
1285 read(vec![reader("Bea"), reader("Cy")], 2).as_deref(),
1286 Some("Seen by everyone")
1287 );
1270 1288 assert_eq!(read(vec![reader("Bea")], 3).as_deref(), Some("Seen by Bea"));
1271 assert_eq!(receipt_label(&teams_core::ReceiptState::Sent).as_deref(), Some("Sent"));
1289 assert_eq!(
1290 receipt_label(&teams_core::ReceiptState::Sent).as_deref(),
1291 Some("Sent")
1292 );
1272 1293 assert_eq!(receipt_label(&teams_core::ReceiptState::Unknown), None);
1273 1294 }
1274 1295
@@ -1309,7 +1330,9 @@ mod tests {
1309 1330 _ => None,
1310 1331 })
1311 1332 .unwrap();
1312 let Some(Block::Reply { children, .. }) = reply.first() else { panic!("{reply:?}") };
1333 let Some(Block::Reply { children, .. }) = reply.first() else {
1334 panic!("{reply:?}")
1335 };
1313 1336 let text = format!("{children:?}");
1314 1337 assert!(text.contains(r"first link\nsecond link"), "{text}");
1315 1338 }
@@ -1383,15 +1406,26 @@ mod tests {
1383 1406 assert_eq!(reaction_text(key), ":absolute-cinema:");
1384 1407 assert_eq!(reaction_text("like"), "\u{1F44D}");
1385 1408 let image = custom_emoji_image(key).expect("image");
1386 assert!(image.url.ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim"));
1409 assert!(
1410 image
1411 .url
1412 .ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim")
1413 );
1387 1414 assert_eq!(custom_emoji_image("like"), None);
1388 1415 }
1389 1416
1390 1417 #[test]
1391 1418 fn teams_only_emoticon_loads_its_cdn_image() {
1392 1419 let image = custom_emoji_image("oreoyum").expect("image");
1393 assert!(image.url.ends_with("/oreoyum/default/50_f.png"), "{}", image.url);
1394 assert_eq!(custom_emoji_image("(oreoyum)").map(|image| image.url), Some(image.url));
1420 assert!(
1421 image.url.ends_with("/oreoyum/default/50_f.png"),
1422 "{}",
1423 image.url
1424 );
1425 assert_eq!(
1426 custom_emoji_image("(oreoyum)").map(|image| image.url),
1427 Some(image.url)
1428 );
1395 1429 }
1396 1430
1397 1431 #[test]
@@ -1445,7 +1479,10 @@ mod tests {
1445 1479 };
1446 1480 let lines: Vec<String> = children.iter().filter_map(Block::markdown).collect();
1447 1481 assert!(lines[0].contains("Priya Nair Yesterday 07:00"), "{lines:?}");
1448 assert!(lines.iter().any(|line| line.contains("original words")), "{lines:?}");
1482 assert!(
1483 lines.iter().any(|line| line.contains("original words")),
1484 "{lines:?}"
1485 );
1449 1486 assert_eq!(reply_excerpt(&forwarded), "original words");
1450 1487 assert_eq!(message_text(&forwarded), "original words");
1451 1488 }
@@ -2361,10 +2398,7 @@ mod tests {
2361 2398 assert_eq!(post.hidden_reply_count, 0);
2362 2399 let saved = post.replies[0].call.as_ref().unwrap();
2363 2400 assert_eq!(saved.icon, CallIcon::Saved);
2364 assert_eq!(
2365 saved.notice.text,
2366 "Recording has been saved to OneDrive."
2367 );
2401 assert_eq!(saved.notice.text, "Recording has been saved to OneDrive.");
2368 2402 let thread = thread_rows(&records, &root_id, &call_context());
2369 2403 let calls = thread
2370 2404 .iter()
@@ -7,13 +7,11 @@ use gpui_kit::Image;
7use store::{MessageImportance, MessageRecord};
7use store::{MessageImportance, MessageRecord};
8use teams_core::roster_event::{RosterEvent, roster_event};
8use teams_core::roster_event::{RosterEvent, roster_event};
9use teams_core::{
9use teams_core::{
10 AnnouncementBanner, attachments,
10 AdaptiveCard, AnnouncementBanner, CallEvent, CallPhase, Draft, FileCard, ForwardHeader,
11 JumboEmoji, jumbo_emoji,
11 ForwardInfo, ImageRef, JumboEmoji, LinkPreview, ReactionInfo, Span, adaptive_cards,
12 AdaptiveCard, CallEvent, CallPhase, Draft, FileCard, ForwardHeader, ForwardInfo,
12 attachments, call_event, card_texts, files, forwarded_texts, forwards, images, is_forwarded,
13 ImageRef, LinkPreview, forwards,
13 jumbo_emoji, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans,
14 ReactionInfo, Span, adaptive_cards, call_event, card_texts, files,
14 quotes, reactions, readable_text, translated_spans,
15 forwarded_texts, images, is_forwarded, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans, quotes,
16 reactions, readable_text, translated_spans,
17};
15};
18
16
19pub use crate::call_rows::{
17pub use crate::call_rows::{
@@ -140,7 +138,10 @@ pub enum Receipt {
140pub fn receipt_label(state: &teams_core::ReceiptState) -> Option<String> {
138pub fn receipt_label(state: &teams_core::ReceiptState) -> Option<String> {
141 match state {
139 match state {
142 teams_core::ReceiptState::Sent => Some("Sent".to_owned()),
140 teams_core::ReceiptState::Sent => Some("Sent".to_owned()),
143 teams_core::ReceiptState::Read { readers, total_others } if *total_others > 1 => {
141 teams_core::ReceiptState::Read {
142 readers,
143 total_others,
144 } if *total_others > 1 => {
144 if readers.len() >= *total_others {
145 if readers.len() >= *total_others {
145 Some("Seen by everyone".to_owned())
146 Some("Seen by everyone".to_owned())
146 } else {
147 } else {
@@ -816,8 +817,16 @@ pub fn quoted_texts(records: &[MessageRecord]) -> HashMap<String, String> {
816 if text.is_empty() {
817 if text.is_empty() {
817 text = forwarded_texts(record).join("\n");
818 text = forwarded_texts(record).join("\n");
818 }
819 }
819 let lines: Vec<&str> = text.lines().filter(|line| !line.trim().is_empty()).collect();
820 let lines: Vec<&str> = text
820 let mut shown = lines.iter().take(QUOTE_LINES).copied().collect::<Vec<_>>().join("\n");
821 .lines()
822 .filter(|line| !line.trim().is_empty())
823 .collect();
824 let mut shown = lines
825 .iter()
826 .take(QUOTE_LINES)
827 .copied()
828 .collect::<Vec<_>>()
829 .join("\n");
821 if lines.len() > QUOTE_LINES {
830 if lines.len() > QUOTE_LINES {
822 shown.push_str(" …");
831 shown.push_str(" …");
823 }
832 }
@@ -1104,7 +1113,10 @@ fn is_blank_system_record(record: &MessageRecord) -> bool {
1104 record.sender_id.is_none()
1113 record.sender_id.is_none()
1105 && record.call_event_json.is_none()
1114 && record.call_event_json.is_none()
1106 && record.body_html.trim().is_empty()
1115 && record.body_html.trim().is_empty()
1107 && record.subject.as_deref().is_none_or(|subject| subject.trim().is_empty())
1116 && record
1117 .subject
1118 .as_deref()
1119 .is_none_or(|subject| subject.trim().is_empty())
1108 && record.attachments_json.trim() == "[]"
1120 && record.attachments_json.trim() == "[]"
1109}
1121}
1110
1122
@@ -1263,12 +1275,21 @@ mod tests {
1263 at: Utc::now(),
1275 at: Utc::now(),
1264 };
1276 };
1265 let read = |readers: Vec<teams_core::ReceiptReader>, total_others| {
1277 let read = |readers: Vec<teams_core::ReceiptReader>, total_others| {
1266 receipt_label(&teams_core::ReceiptState::Read { readers, total_others })
1278 receipt_label(&teams_core::ReceiptState::Read {
1279 readers,
1280 total_others,
1281 })
1267 };
1282 };
1268 assert_eq!(read(vec![reader("Bea")], 1).as_deref(), Some("Seen"));
1283 assert_eq!(read(vec![reader("Bea")], 1).as_deref(), Some("Seen"));
1269 assert_eq!(read(vec![reader("Bea"), reader("Cy")], 2).as_deref(), Some("Seen by everyone"));
1284 assert_eq!(
1285 read(vec![reader("Bea"), reader("Cy")], 2).as_deref(),
1286 Some("Seen by everyone")
1287 );
1270 assert_eq!(read(vec![reader("Bea")], 3).as_deref(), Some("Seen by Bea"));
1288 assert_eq!(read(vec![reader("Bea")], 3).as_deref(), Some("Seen by Bea"));
1271 assert_eq!(receipt_label(&teams_core::ReceiptState::Sent).as_deref(), Some("Sent"));
1289 assert_eq!(
1290 receipt_label(&teams_core::ReceiptState::Sent).as_deref(),
1291 Some("Sent")
1292 );
1272 assert_eq!(receipt_label(&teams_core::ReceiptState::Unknown), None);
1293 assert_eq!(receipt_label(&teams_core::ReceiptState::Unknown), None);
1273 }
1294 }
1274
1295
@@ -1309,7 +1330,9 @@ mod tests {
1309 _ => None,
1330 _ => None,
1310 })
1331 })
1311 .unwrap();
1332 .unwrap();
1312 let Some(Block::Reply { children, .. }) = reply.first() else { panic!("{reply:?}") };
1333 let Some(Block::Reply { children, .. }) = reply.first() else {
1334 panic!("{reply:?}")
1335 };
1313 let text = format!("{children:?}");
1336 let text = format!("{children:?}");
1314 assert!(text.contains(r"first link\nsecond link"), "{text}");
1337 assert!(text.contains(r"first link\nsecond link"), "{text}");
1315 }
1338 }
@@ -1383,15 +1406,26 @@ mod tests {
1383 assert_eq!(reaction_text(key), ":absolute-cinema:");
1406 assert_eq!(reaction_text(key), ":absolute-cinema:");
1384 assert_eq!(reaction_text("like"), "\u{1F44D}");
1407 assert_eq!(reaction_text("like"), "\u{1F44D}");
1385 let image = custom_emoji_image(key).expect("image");
1408 let image = custom_emoji_image(key).expect("image");
1386 assert!(image.url.ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim"));
1409 assert!(
1410 image
1411 .url
1412 .ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim")
1413 );
1387 assert_eq!(custom_emoji_image("like"), None);
1414 assert_eq!(custom_emoji_image("like"), None);
1388 }
1415 }
1389
1416
1390 #[test]
1417 #[test]
1391 fn teams_only_emoticon_loads_its_cdn_image() {
1418 fn teams_only_emoticon_loads_its_cdn_image() {
1392 let image = custom_emoji_image("oreoyum").expect("image");
1419 let image = custom_emoji_image("oreoyum").expect("image");
1393 assert!(image.url.ends_with("/oreoyum/default/50_f.png"), "{}", image.url);
1420 assert!(
1394 assert_eq!(custom_emoji_image("(oreoyum)").map(|image| image.url), Some(image.url));
1421 image.url.ends_with("/oreoyum/default/50_f.png"),
1422 "{}",
1423 image.url
1424 );
1425 assert_eq!(
1426 custom_emoji_image("(oreoyum)").map(|image| image.url),
1427 Some(image.url)
1428 );
1395 }
1429 }
1396
1430
1397 #[test]
1431 #[test]
@@ -1445,7 +1479,10 @@ mod tests {
1445 };
1479 };
1446 let lines: Vec<String> = children.iter().filter_map(Block::markdown).collect();
1480 let lines: Vec<String> = children.iter().filter_map(Block::markdown).collect();
1447 assert!(lines[0].contains("Priya Nair Yesterday 07:00"), "{lines:?}");
1481 assert!(lines[0].contains("Priya Nair Yesterday 07:00"), "{lines:?}");
1448 assert!(lines.iter().any(|line| line.contains("original words")), "{lines:?}");
1482 assert!(
1483 lines.iter().any(|line| line.contains("original words")),
1484 "{lines:?}"
1485 );
1449 assert_eq!(reply_excerpt(&forwarded), "original words");
1486 assert_eq!(reply_excerpt(&forwarded), "original words");
1450 assert_eq!(message_text(&forwarded), "original words");
1487 assert_eq!(message_text(&forwarded), "original words");
1451 }
1488 }
@@ -2361,10 +2398,7 @@ mod tests {
2361 assert_eq!(post.hidden_reply_count, 0);
2398 assert_eq!(post.hidden_reply_count, 0);
2362 let saved = post.replies[0].call.as_ref().unwrap();
2399 let saved = post.replies[0].call.as_ref().unwrap();
2363 assert_eq!(saved.icon, CallIcon::Saved);
2400 assert_eq!(saved.icon, CallIcon::Saved);
2364 assert_eq!(
2401 assert_eq!(saved.notice.text, "Recording has been saved to OneDrive.");
2365 saved.notice.text,
2366 "Recording has been saved to OneDrive."
2367 );
2368 let thread = thread_rows(&records, &root_id, &call_context());
2402 let thread = thread_rows(&records, &root_id, &call_context());
2369 let calls = thread
2403 let calls = thread
2370 .iter()
2404 .iter()
crates/app-state/src/scheduled_rows.rs +1 −1
@@ -1,11 +1,11 @@
1 1 use chrono::{DateTime, Local, Utc};
2 2 use teams_core::{Draft, ScheduledDraft, html_to_spans};
3 3
4 use crate::outgoing::Outgoing;
4 5 use crate::pending_rows::pending_row;
5 6 use crate::rows::{Delivery, MessageRow, ScheduledState};
6 7 use crate::schedule_time::describe;
7 8 use crate::scheduled::{conversation_of, thread_root_of};
8 use crate::outgoing::Outgoing;
9 9
10 10 pub const SCHEDULED_KEY_PREFIX: &str = "scheduled-";
11 11
@@ -1,11 +1,11 @@
1use chrono::{DateTime, Local, Utc};
1use chrono::{DateTime, Local, Utc};
2use teams_core::{Draft, ScheduledDraft, html_to_spans};
2use teams_core::{Draft, ScheduledDraft, html_to_spans};
3
3
4use crate::outgoing::Outgoing;
4use crate::pending_rows::pending_row;
5use crate::pending_rows::pending_row;
5use crate::rows::{Delivery, MessageRow, ScheduledState};
6use crate::rows::{Delivery, MessageRow, ScheduledState};
6use crate::schedule_time::describe;
7use crate::schedule_time::describe;
7use crate::scheduled::{conversation_of, thread_root_of};
8use crate::scheduled::{conversation_of, thread_root_of};
8use crate::outgoing::Outgoing;
9
9
10pub const SCHEDULED_KEY_PREFIX: &str = "scheduled-";
10pub const SCHEDULED_KEY_PREFIX: &str = "scheduled-";
11
11
crates/app-state/src/sidebar_load.rs +9 −4
@@ -133,7 +133,14 @@ mod tests {
133 133 }
134 134
135 135 fn listed(app: &gpui_kit::Entity<AppState>, cx: &mut TestAppContext) -> Vec<String> {
136 cx.update(|cx| app.read(cx).sidebar.chats.iter().map(|chat| chat.id.clone()).collect())
136 cx.update(|cx| {
137 app.read(cx)
138 .sidebar
139 .chats
140 .iter()
141 .map(|chat| chat.id.clone())
142 .collect()
143 })
137 144 }
138 145
139 146 fn sidebar_changed(app: &gpui_kit::Entity<AppState>, cx: &mut TestAppContext) {
@@ -145,9 +152,7 @@ mod tests {
145 152 }
146 153
147 154 #[gpui_kit::test]
148 fn a_synced_sidebar_loads_in_the_background_and_bursts_load_once_more(
149 cx: &mut TestAppContext,
150 ) {
155 fn a_synced_sidebar_loads_in_the_background_and_bursts_load_once_more(cx: &mut TestAppContext) {
151 156 cx.update(gpui_kit::init);
152 157 let store = Arc::new(Store::open_in_memory().unwrap());
153 158 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
@@ -133,7 +133,14 @@ mod tests {
133 }
133 }
134
134
135 fn listed(app: &gpui_kit::Entity<AppState>, cx: &mut TestAppContext) -> Vec<String> {
135 fn listed(app: &gpui_kit::Entity<AppState>, cx: &mut TestAppContext) -> Vec<String> {
136 cx.update(|cx| app.read(cx).sidebar.chats.iter().map(|chat| chat.id.clone()).collect())
136 cx.update(|cx| {
137 app.read(cx)
138 .sidebar
139 .chats
140 .iter()
141 .map(|chat| chat.id.clone())
142 .collect()
143 })
137 }
144 }
138
145
139 fn sidebar_changed(app: &gpui_kit::Entity<AppState>, cx: &mut TestAppContext) {
146 fn sidebar_changed(app: &gpui_kit::Entity<AppState>, cx: &mut TestAppContext) {
@@ -145,9 +152,7 @@ mod tests {
145 }
152 }
146
153
147 #[gpui_kit::test]
154 #[gpui_kit::test]
148 fn a_synced_sidebar_loads_in_the_background_and_bursts_load_once_more(
155 fn a_synced_sidebar_loads_in_the_background_and_bursts_load_once_more(cx: &mut TestAppContext) {
149 cx: &mut TestAppContext,
150 ) {
151 cx.update(gpui_kit::init);
156 cx.update(gpui_kit::init);
152 let store = Arc::new(Store::open_in_memory().unwrap());
157 let store = Arc::new(Store::open_in_memory().unwrap());
153 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
158 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
crates/app-state/src/sidebar_model.rs +5 −6
@@ -522,11 +522,7 @@ pub fn step_id(ids: &[&str], current: Option<&str>, step: Step) -> Option<String
522 522 ids.get(target).map(|id| (*id).to_owned())
523 523 }
524 524
525 pub fn step_unread_id(
526 sections: &[Section],
527 current: Option<&str>,
528 step: Step,
529 ) -> Option<String> {
525 pub fn step_unread_id(sections: &[Section], current: Option<&str>, step: Step) -> Option<String> {
530 526 let items: Vec<&ChatItem> = sections
531 527 .iter()
532 528 .filter(|section| !section.collapsed)
@@ -870,7 +866,10 @@ mod tests {
870 866 step_unread_id(&sections, None, Step::Next).as_deref(),
871 867 Some(first_unread)
872 868 );
873 assert_eq!(step_unread_id(&sections, Some(last_unread), Step::Next), None);
869 assert_eq!(
870 step_unread_id(&sections, Some(last_unread), Step::Next),
871 None
872 );
874 873 assert_eq!(
875 874 step_unread_id(&sections, Some(last_unread), Step::Previous).as_deref(),
876 875 Some(first_unread)
@@ -522,11 +522,7 @@ pub fn step_id(ids: &[&str], current: Option<&str>, step: Step) -> Option<String
522 ids.get(target).map(|id| (*id).to_owned())
522 ids.get(target).map(|id| (*id).to_owned())
523}
523}
524
524
525pub fn step_unread_id(
525pub fn step_unread_id(sections: &[Section], current: Option<&str>, step: Step) -> Option<String> {
526 sections: &[Section],
527 current: Option<&str>,
528 step: Step,
529) -> Option<String> {
530 let items: Vec<&ChatItem> = sections
526 let items: Vec<&ChatItem> = sections
531 .iter()
527 .iter()
532 .filter(|section| !section.collapsed)
528 .filter(|section| !section.collapsed)
@@ -870,7 +866,10 @@ mod tests {
870 step_unread_id(&sections, None, Step::Next).as_deref(),
866 step_unread_id(&sections, None, Step::Next).as_deref(),
871 Some(first_unread)
867 Some(first_unread)
872 );
868 );
873 assert_eq!(step_unread_id(&sections, Some(last_unread), Step::Next), None);
869 assert_eq!(
870 step_unread_id(&sections, Some(last_unread), Step::Next),
871 None
872 );
874 assert_eq!(
873 assert_eq!(
875 step_unread_id(&sections, Some(last_unread), Step::Previous).as_deref(),
874 step_unread_id(&sections, Some(last_unread), Step::Previous).as_deref(),
876 Some(first_unread)
875 Some(first_unread)
crates/app-state/src/stored_outgoing.rs +1 −1
@@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize};
5 5 use store::{AttachmentImage, MessageImportance};
6 6 use teams_core::{AnnouncementBanner, Draft, DraftLine, LinkPreview, MentionInput};
7 7
8 use crate::remote_image::{RemoteImage, RemoteKind};
9 8 use crate::outgoing::{InlineImage, Outgoing, OutgoingFile, OutgoingImage, ReplyPreview};
9 use crate::remote_image::{RemoteImage, RemoteKind};
10 10
11 11 const IMAGE_FORMATS: [ImageFormat; 9] = [
12 12 ImageFormat::Png,
@@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize};
5use store::{AttachmentImage, MessageImportance};
5use store::{AttachmentImage, MessageImportance};
6use teams_core::{AnnouncementBanner, Draft, DraftLine, LinkPreview, MentionInput};
6use teams_core::{AnnouncementBanner, Draft, DraftLine, LinkPreview, MentionInput};
7
7
8use crate::remote_image::{RemoteImage, RemoteKind};
9use crate::outgoing::{InlineImage, Outgoing, OutgoingFile, OutgoingImage, ReplyPreview};
8use crate::outgoing::{InlineImage, Outgoing, OutgoingFile, OutgoingImage, ReplyPreview};
9use crate::remote_image::{RemoteImage, RemoteKind};
10
10
11const IMAGE_FORMATS: [ImageFormat; 9] = [
11const IMAGE_FORMATS: [ImageFormat; 9] = [
12 ImageFormat::Png,
12 ImageFormat::Png,
crates/app/build.rs +15 −5
@@ -11,8 +11,13 @@ fn main() {
11 11 .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
12 12 };
13 13 let commit = git(&["rev-parse", "--short", "HEAD"]).unwrap_or_else(|| "unknown".to_owned());
14 let timestamp = git(&["log", "-1", "--format=%cd", "--date=format-local:%Y%m%dT%H%M%SZ"])
15 .unwrap_or_else(|| chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string());
14 let timestamp = git(&[
15 "log",
16 "-1",
17 "--format=%cd",
18 "--date=format-local:%Y%m%dT%H%M%SZ",
19 ])
20 .unwrap_or_else(|| chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string());
16 21 println!("cargo:rustc-env=TEAMS_BUILD_VERSION={commit}-{timestamp}");
17 22 println!("cargo:rerun-if-env-changed=GITHUB_REF_NAME");
18 23 println!("cargo:rerun-if-env-changed=GITHUB_REF_TYPE");
@@ -27,9 +32,14 @@ fn main() {
27 32 if let Some(head) = git(&["rev-parse", "--path-format=absolute", "--git-path", "HEAD"]) {
28 33 println!("cargo:rerun-if-changed={head}");
29 34 }
30 if let Some(reference) = git(&["symbolic-ref", "-q", "HEAD"])
31 .and_then(|reference| git(&["rev-parse", "--path-format=absolute", "--git-path", &reference]))
32 {
35 if let Some(reference) = git(&["symbolic-ref", "-q", "HEAD"]).and_then(|reference| {
36 git(&[
37 "rev-parse",
38 "--path-format=absolute",
39 "--git-path",
40 &reference,
41 ])
42 }) {
33 43 println!("cargo:rerun-if-changed={reference}");
34 44 }
35 45 if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
@@ -11,8 +11,13 @@ fn main() {
11 .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
11 .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
12 };
12 };
13 let commit = git(&["rev-parse", "--short", "HEAD"]).unwrap_or_else(|| "unknown".to_owned());
13 let commit = git(&["rev-parse", "--short", "HEAD"]).unwrap_or_else(|| "unknown".to_owned());
14 let timestamp = git(&["log", "-1", "--format=%cd", "--date=format-local:%Y%m%dT%H%M%SZ"])
14 let timestamp = git(&[
15 .unwrap_or_else(|| chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string());
15 "log",
16 "-1",
17 "--format=%cd",
18 "--date=format-local:%Y%m%dT%H%M%SZ",
19 ])
20 .unwrap_or_else(|| chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string());
16 println!("cargo:rustc-env=TEAMS_BUILD_VERSION={commit}-{timestamp}");
21 println!("cargo:rustc-env=TEAMS_BUILD_VERSION={commit}-{timestamp}");
17 println!("cargo:rerun-if-env-changed=GITHUB_REF_NAME");
22 println!("cargo:rerun-if-env-changed=GITHUB_REF_NAME");
18 println!("cargo:rerun-if-env-changed=GITHUB_REF_TYPE");
23 println!("cargo:rerun-if-env-changed=GITHUB_REF_TYPE");
@@ -27,9 +32,14 @@ fn main() {
27 if let Some(head) = git(&["rev-parse", "--path-format=absolute", "--git-path", "HEAD"]) {
32 if let Some(head) = git(&["rev-parse", "--path-format=absolute", "--git-path", "HEAD"]) {
28 println!("cargo:rerun-if-changed={head}");
33 println!("cargo:rerun-if-changed={head}");
29 }
34 }
30 if let Some(reference) = git(&["symbolic-ref", "-q", "HEAD"])
35 if let Some(reference) = git(&["symbolic-ref", "-q", "HEAD"]).and_then(|reference| {
31 .and_then(|reference| git(&["rev-parse", "--path-format=absolute", "--git-path", &reference]))
36 git(&[
32 {
37 "rev-parse",
38 "--path-format=absolute",
39 "--git-path",
40 &reference,
41 ])
42 }) {
33 println!("cargo:rerun-if-changed={reference}");
43 println!("cargo:rerun-if-changed={reference}");
34 }
44 }
35 if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
45 if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
crates/app/src/agents/agents_panel.rs +2 −2
@@ -1,5 +1,5 @@
1 use gpui_kit::component::scroll::ScrollableElement as _;
2 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 3 use gpui_kit::component::{h_flex, v_flex};
4 4 use gpui_kit::prelude::FluentBuilder as _;
5 5 use gpui_kit::*;
@@ -178,8 +178,8 @@ impl Render for AgentsPanel {
178 178 #[cfg(test)]
179 179 mod tests {
180 180 use super::split_runs;
181 use crate::agents::runs::RunState;
182 181 use crate::agents::fixtures::finished_run;
182 use crate::agents::runs::RunState;
183 183
184 184 #[test]
185 185 fn running_runs_go_first_and_done_is_capped_at_fifty() {
@@ -1,5 +1,5 @@
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
5use gpui_kit::*;
@@ -178,8 +178,8 @@ impl Render for AgentsPanel {
178#[cfg(test)]
178#[cfg(test)]
179mod tests {
179mod tests {
180 use super::split_runs;
180 use super::split_runs;
181 use crate::agents::runs::RunState;
182 use crate::agents::fixtures::finished_run;
181 use crate::agents::fixtures::finished_run;
182 use crate::agents::runs::RunState;
183
183
184 #[test]
184 #[test]
185 fn running_runs_go_first_and_done_is_capped_at_fifty() {
185 fn running_runs_go_first_and_done_is_capped_at_fifty() {
crates/app/src/agents/mod.rs +1 −1
@@ -5,8 +5,8 @@ mod settings_section;
5 5 mod start_dialog;
6 6 mod start_dialog_pickers;
7 7
8 pub use state::agents::*;
9 8 pub use agents_panel::{AgentsPanel, AgentsPanelEvent};
10 9 pub use run_chip::run_chip;
11 10 pub use settings_section::AgentsSettings;
12 11 pub use start_dialog::{StartDialog, StartDialogEvent};
12 pub use state::agents::*;
@@ -5,8 +5,8 @@ mod settings_section;
5mod start_dialog;
5mod start_dialog;
6mod start_dialog_pickers;
6mod start_dialog_pickers;
7
7
8pub use state::agents::*;
9pub use agents_panel::{AgentsPanel, AgentsPanelEvent};
8pub use agents_panel::{AgentsPanel, AgentsPanelEvent};
10pub use run_chip::run_chip;
9pub use run_chip::run_chip;
11pub use settings_section::AgentsSettings;
10pub use settings_section::AgentsSettings;
12pub use start_dialog::{StartDialog, StartDialogEvent};
11pub use start_dialog::{StartDialog, StartDialogEvent};
12pub use state::agents::*;
crates/app/src/agents/settings_forms.rs +185 −51
@@ -1,6 +1,6 @@
1 1 use std::rc::Rc;
2 2
3 use agents::{Environment, OutputFormat};
3 use agents::{AgentBackend, Environment, OutputFormat};
4 4 use gpui_kit::assets::IconName;
5 5 use gpui_kit::component::{ActiveTheme as _, h_flex, input::Textarea, v_flex};
6 6 use gpui_kit::prelude::FluentBuilder as _;
@@ -27,9 +27,17 @@ const PLACEHOLDER_CHIPS: [&str; 9] = [
27 27 "agent",
28 28 ];
29 29
30 fn host_label() -> &'static str {
31 if cfg!(windows) {
32 "Windows"
33 } else {
34 "This computer"
35 }
36 }
37
30 38 fn environment_choices() -> [(&'static str, Environment); 3] {
31 39 [
32 ("Windows", Environment::Host),
40 (host_label(), Environment::Host),
33 41 ("WSL - default distro", Environment::Wsl { distro: None }),
34 42 (
35 43 "WSL - named distro",
@@ -115,7 +123,7 @@ impl AgentsSettings {
115 123 let environment_label = environment_choices()
116 124 .into_iter()
117 125 .find(|(_, environment)| same_environment_kind(environment, &profile.environment))
118 .map_or("Windows", |(label, _)| label);
126 .map_or(host_label(), |(label, _)| label);
119 127 let output_entries: Vec<MenuEntry> = output_choices()
120 128 .into_iter()
121 129 .map(|(label, output)| {
@@ -137,12 +145,68 @@ impl AgentsSettings {
137 145 let open_problem =
138 146 placeholder_problem(&problems, &profile.id, &profile.open_session_command);
139 147 let named_distro = matches!(profile.environment, Environment::Wsl { distro: Some(_) });
148 let chat = profile.is_chat();
140 149 let status = match &self.probe {
141 150 Probe::Idle => None,
142 Probe::Running => Some(("Testing...".to_owned(), theme::text_muted())),
143 Probe::Found(line) => Some((format!("Found: {line}"), theme::green())),
151 Probe::Running => Some((
152 if chat {
153 "Loading models...".to_owned()
154 } else {
155 "Testing...".to_owned()
156 },
157 theme::text_muted(),
158 )),
159 Probe::Found(line) => Some((
160 if chat {
161 line.clone()
162 } else {
163 format!("Found: {line}")
164 },
165 theme::green(),
166 )),
144 167 Probe::Missing(error) => Some((error.clone(), theme::red_soft())),
145 168 };
169 let shows_base = matches!(profile.backend, AgentBackend::OpenAi { .. });
170 let key_saved = match &profile.backend {
171 AgentBackend::OpenAi { api_key, .. } | AgentBackend::Anthropic { api_key, .. } => {
172 !api_key.is_empty()
173 }
174 AgentBackend::Command => false,
175 };
176 let model_problem = problems.iter().find_map(|problem| match problem {
177 agents::SettingsProblem::EmptyModel { agent_id } if agent_id == &profile.id => {
178 Some("Choose a model".to_owned())
179 }
180 _ => None,
181 });
182 let current_model = form_state.model.read(cx).value().trim().to_owned();
183 let mut model_names = self.models.clone();
184 if !current_model.is_empty() && !model_names.iter().any(|name| name == &current_model) {
185 model_names.insert(0, current_model.clone());
186 }
187 let model_entries: Vec<MenuEntry> = model_names
188 .iter()
189 .map(|name| {
190 let this = this.clone();
191 let label = name.clone();
192 let chosen = label.clone();
193 let selected = label == current_model;
194 let choose: Choice = Rc::new(move |window, cx| {
195 let name = chosen.clone();
196 this.update(cx, |this, cx| this.set_model(name, window, cx))
197 });
198 MenuEntry {
199 label,
200 selected,
201 choose,
202 }
203 })
204 .collect();
205 let model_label = if current_model.is_empty() {
206 "Choose a model".to_owned()
207 } else {
208 current_model
209 };
146 210 let test_this = this.clone();
147 211 let delete_this = this.clone();
148 212 v_flex()
@@ -156,22 +220,76 @@ impl AgentsSettings {
156 220 None,
157 221 )
158 222 .into_any_element(),
159 field(
160 "Runs in",
161 dropdown(
162 "agent-environment",
163 environment_label.to_owned(),
164 environment_entries,
165 ),
166 Some(hint(
167 "Windows or a WSL distro. Paths below are in that system.",
168 )),
169 None,
170 )
171 .into_any_element(),
172 223 div()
173 224 .w_full()
174 .when(named_distro, |slot| {
225 .when(chat && shows_base, |slot| {
226 slot.child(field(
227 "Base URL",
228 text_field(&form_state.base_url, true, false, cx),
229 Some(hint("OpenAI-compatible, including /v1.")),
230 None,
231 ))
232 })
233 .into_any_element(),
234 div()
235 .w_full()
236 .when(chat && !model_entries.is_empty(), |slot| {
237 slot.child(field(
238 "Installed models",
239 dropdown("agent-model", model_label, model_entries),
240 Some(hint("Loaded from the endpoint. The choice fills Model.")),
241 None,
242 ))
243 })
244 .into_any_element(),
245 div()
246 .w_full()
247 .when(chat, |slot| {
248 slot.child(field(
249 "Model",
250 text_field(&form_state.model, true, model_problem.is_some(), cx),
251 Some(hint(
252 "Pick a loaded model, or type an id. Leave the URL or key field to reload.",
253 )),
254 model_problem.clone(),
255 ))
256 })
257 .into_any_element(),
258 div()
259 .w_full()
260 .when(chat, |slot| {
261 slot.child(field(
262 "API key",
263 text_field(&form_state.api_key, true, false, cx),
264 Some(hint(if key_saved {
265 "A key is saved. Type a new one to replace it. Ollama can stay empty."
266 } else {
267 "Stored in the local app database. Ollama can stay empty."
268 })),
269 None,
270 ))
271 })
272 .into_any_element(),
273 div()
274 .w_full()
275 .when(!chat, |slot| {
276 slot.child(field(
277 "Runs in",
278 dropdown(
279 "agent-environment",
280 environment_label.to_owned(),
281 environment_entries,
282 ),
283 Some(hint(
284 "This computer or a WSL distro. Paths below are in that system.",
285 )),
286 None,
287 ))
288 })
289 .into_any_element(),
290 div()
291 .w_full()
292 .when(!chat && named_distro, |slot| {
175 293 slot.child(field(
176 294 "Distro name",
177 295 text_field(&form_state.distro, false, false, cx),
@@ -180,38 +298,54 @@ impl AgentsSettings {
180 298 ))
181 299 })
182 300 .into_any_element(),
183 field(
184 "Command",
185 text_field(&form_state.command, true, command_problem.is_some(), cx),
186 Some(hint(
187 "The prompt goes to stdin unless the command has {prompt}.",
188 )),
189 command_problem,
190 )
191 .into_any_element(),
192 field(
193 "Output",
194 dropdown("agent-output", output_label.to_owned(), output_entries),
195 Some(hint("Plain text shows only the time and the last line.")),
196 None,
197 )
198 .into_any_element(),
199 field(
200 "MCP config flag",
201 text_field(&form_state.mcp_flag, true, false, cx),
202 Some(hint(
203 "Passes the Teams MCP endpoint to the agent. Empty = none.",
204 )),
205 None,
206 )
207 .into_any_element(),
208 field(
209 "Open session",
210 text_field(&form_state.open_session, true, open_problem.is_some(), cx),
211 Some(hint("Available: {cwd} and {session_id}.")),
212 open_problem,
213 )
214 .into_any_element(),
301 div()
302 .w_full()
303 .when(!chat, |slot| {
304 slot.child(field(
305 "Command",
306 text_field(&form_state.command, true, command_problem.is_some(), cx),
307 Some(hint(
308 "The prompt goes to stdin unless the command has {prompt}.",
309 )),
310 command_problem,
311 ))
312 })
313 .into_any_element(),
314 div()
315 .w_full()
316 .when(!chat, |slot| {
317 slot.child(field(
318 "Output",
319 dropdown("agent-output", output_label.to_owned(), output_entries),
320 Some(hint("Plain text shows only the time and the last line.")),
321 None,
322 ))
323 })
324 .into_any_element(),
325 div()
326 .w_full()
327 .when(!chat, |slot| {
328 slot.child(field(
329 "MCP config flag",
330 text_field(&form_state.mcp_flag, true, false, cx),
331 Some(hint(
332 "Passes the Teams MCP endpoint to the agent. Empty = none.",
333 )),
334 None,
335 ))
336 })
337 .into_any_element(),
338 div()
339 .w_full()
340 .when(!chat, |slot| {
341 slot.child(field(
342 "Open session",
343 text_field(&form_state.open_session, true, open_problem.is_some(), cx),
344 Some(hint("Available: {cwd} and {session_id}.")),
345 open_problem,
346 ))
347 })
348 .into_any_element(),
215 349 h_flex()
216 350 .w_full()
217 351 .gap(px(8.))
@@ -1,6 +1,6 @@
1use std::rc::Rc;
1use std::rc::Rc;
2
2
3use agents::{Environment, OutputFormat};
3use agents::{AgentBackend, Environment, OutputFormat};
4use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{ActiveTheme as _, h_flex, input::Textarea, v_flex};
5use gpui_kit::component::{ActiveTheme as _, h_flex, input::Textarea, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::prelude::FluentBuilder as _;
@@ -27,9 +27,17 @@ const PLACEHOLDER_CHIPS: [&str; 9] = [
27 "agent",
27 "agent",
28];
28];
29
29
30fn host_label() -> &'static str {
31 if cfg!(windows) {
32 "Windows"
33 } else {
34 "This computer"
35 }
36}
37
30fn environment_choices() -> [(&'static str, Environment); 3] {
38fn environment_choices() -> [(&'static str, Environment); 3] {
31 [
39 [
32 ("Windows", Environment::Host),
40 (host_label(), Environment::Host),
33 ("WSL - default distro", Environment::Wsl { distro: None }),
41 ("WSL - default distro", Environment::Wsl { distro: None }),
34 (
42 (
35 "WSL - named distro",
43 "WSL - named distro",
@@ -115,7 +123,7 @@ impl AgentsSettings {
115 let environment_label = environment_choices()
123 let environment_label = environment_choices()
116 .into_iter()
124 .into_iter()
117 .find(|(_, environment)| same_environment_kind(environment, &profile.environment))
125 .find(|(_, environment)| same_environment_kind(environment, &profile.environment))
118 .map_or("Windows", |(label, _)| label);
126 .map_or(host_label(), |(label, _)| label);
119 let output_entries: Vec<MenuEntry> = output_choices()
127 let output_entries: Vec<MenuEntry> = output_choices()
120 .into_iter()
128 .into_iter()
121 .map(|(label, output)| {
129 .map(|(label, output)| {
@@ -137,12 +145,68 @@ impl AgentsSettings {
137 let open_problem =
145 let open_problem =
138 placeholder_problem(&problems, &profile.id, &profile.open_session_command);
146 placeholder_problem(&problems, &profile.id, &profile.open_session_command);
139 let named_distro = matches!(profile.environment, Environment::Wsl { distro: Some(_) });
147 let named_distro = matches!(profile.environment, Environment::Wsl { distro: Some(_) });
148 let chat = profile.is_chat();
140 let status = match &self.probe {
149 let status = match &self.probe {
141 Probe::Idle => None,
150 Probe::Idle => None,
142 Probe::Running => Some(("Testing...".to_owned(), theme::text_muted())),
151 Probe::Running => Some((
143 Probe::Found(line) => Some((format!("Found: {line}"), theme::green())),
152 if chat {
153 "Loading models...".to_owned()
154 } else {
155 "Testing...".to_owned()
156 },
157 theme::text_muted(),
158 )),
159 Probe::Found(line) => Some((
160 if chat {
161 line.clone()
162 } else {
163 format!("Found: {line}")
164 },
165 theme::green(),
166 )),
144 Probe::Missing(error) => Some((error.clone(), theme::red_soft())),
167 Probe::Missing(error) => Some((error.clone(), theme::red_soft())),
145 };
168 };
169 let shows_base = matches!(profile.backend, AgentBackend::OpenAi { .. });
170 let key_saved = match &profile.backend {
171 AgentBackend::OpenAi { api_key, .. } | AgentBackend::Anthropic { api_key, .. } => {
172 !api_key.is_empty()
173 }
174 AgentBackend::Command => false,
175 };
176 let model_problem = problems.iter().find_map(|problem| match problem {
177 agents::SettingsProblem::EmptyModel { agent_id } if agent_id == &profile.id => {
178 Some("Choose a model".to_owned())
179 }
180 _ => None,
181 });
182 let current_model = form_state.model.read(cx).value().trim().to_owned();
183 let mut model_names = self.models.clone();
184 if !current_model.is_empty() && !model_names.iter().any(|name| name == &current_model) {
185 model_names.insert(0, current_model.clone());
186 }
187 let model_entries: Vec<MenuEntry> = model_names
188 .iter()
189 .map(|name| {
190 let this = this.clone();
191 let label = name.clone();
192 let chosen = label.clone();
193 let selected = label == current_model;
194 let choose: Choice = Rc::new(move |window, cx| {
195 let name = chosen.clone();
196 this.update(cx, |this, cx| this.set_model(name, window, cx))
197 });
198 MenuEntry {
199 label,
200 selected,
201 choose,
202 }
203 })
204 .collect();
205 let model_label = if current_model.is_empty() {
206 "Choose a model".to_owned()
207 } else {
208 current_model
209 };
146 let test_this = this.clone();
210 let test_this = this.clone();
147 let delete_this = this.clone();
211 let delete_this = this.clone();
148 v_flex()
212 v_flex()
@@ -156,22 +220,76 @@ impl AgentsSettings {
156 None,
220 None,
157 )
221 )
158 .into_any_element(),
222 .into_any_element(),
159 field(
160 "Runs in",
161 dropdown(
162 "agent-environment",
163 environment_label.to_owned(),
164 environment_entries,
165 ),
166 Some(hint(
167 "Windows or a WSL distro. Paths below are in that system.",
168 )),
169 None,
170 )
171 .into_any_element(),
172 div()
223 div()
173 .w_full()
224 .w_full()
174 .when(named_distro, |slot| {
225 .when(chat && shows_base, |slot| {
226 slot.child(field(
227 "Base URL",
228 text_field(&form_state.base_url, true, false, cx),
229 Some(hint("OpenAI-compatible, including /v1.")),
230 None,
231 ))
232 })
233 .into_any_element(),
234 div()
235 .w_full()
236 .when(chat && !model_entries.is_empty(), |slot| {
237 slot.child(field(
238 "Installed models",
239 dropdown("agent-model", model_label, model_entries),
240 Some(hint("Loaded from the endpoint. The choice fills Model.")),
241 None,
242 ))
243 })
244 .into_any_element(),
245 div()
246 .w_full()
247 .when(chat, |slot| {
248 slot.child(field(
249 "Model",
250 text_field(&form_state.model, true, model_problem.is_some(), cx),
251 Some(hint(
252 "Pick a loaded model, or type an id. Leave the URL or key field to reload.",
253 )),
254 model_problem.clone(),
255 ))
256 })
257 .into_any_element(),
258 div()
259 .w_full()
260 .when(chat, |slot| {
261 slot.child(field(
262 "API key",
263 text_field(&form_state.api_key, true, false, cx),
264 Some(hint(if key_saved {
265 "A key is saved. Type a new one to replace it. Ollama can stay empty."
266 } else {
267 "Stored in the local app database. Ollama can stay empty."
268 })),
269 None,
270 ))
271 })
272 .into_any_element(),
273 div()
274 .w_full()
275 .when(!chat, |slot| {
276 slot.child(field(
277 "Runs in",
278 dropdown(
279 "agent-environment",
280 environment_label.to_owned(),
281 environment_entries,
282 ),
283 Some(hint(
284 "This computer or a WSL distro. Paths below are in that system.",
285 )),
286 None,
287 ))
288 })
289 .into_any_element(),
290 div()
291 .w_full()
292 .when(!chat && named_distro, |slot| {
175 slot.child(field(
293 slot.child(field(
176 "Distro name",
294 "Distro name",
177 text_field(&form_state.distro, false, false, cx),
295 text_field(&form_state.distro, false, false, cx),
@@ -180,38 +298,54 @@ impl AgentsSettings {
180 ))
298 ))
181 })
299 })
182 .into_any_element(),
300 .into_any_element(),
183 field(
301 div()
184 "Command",
302 .w_full()
185 text_field(&form_state.command, true, command_problem.is_some(), cx),
303 .when(!chat, |slot| {
186 Some(hint(
304 slot.child(field(
187 "The prompt goes to stdin unless the command has {prompt}.",
305 "Command",
188 )),
306 text_field(&form_state.command, true, command_problem.is_some(), cx),
189 command_problem,
307 Some(hint(
190 )
308 "The prompt goes to stdin unless the command has {prompt}.",
191 .into_any_element(),
309 )),
192 field(
310 command_problem,
193 "Output",
311 ))
194 dropdown("agent-output", output_label.to_owned(), output_entries),
312 })
195 Some(hint("Plain text shows only the time and the last line.")),
313 .into_any_element(),
196 None,
314 div()
197 )
315 .w_full()
198 .into_any_element(),
316 .when(!chat, |slot| {
199 field(
317 slot.child(field(
200 "MCP config flag",
318 "Output",
201 text_field(&form_state.mcp_flag, true, false, cx),
319 dropdown("agent-output", output_label.to_owned(), output_entries),
202 Some(hint(
320 Some(hint("Plain text shows only the time and the last line.")),
203 "Passes the Teams MCP endpoint to the agent. Empty = none.",
321 None,
204 )),
322 ))
205 None,
323 })
206 )
324 .into_any_element(),
207 .into_any_element(),
325 div()
208 field(
326 .w_full()
209 "Open session",
327 .when(!chat, |slot| {
210 text_field(&form_state.open_session, true, open_problem.is_some(), cx),
328 slot.child(field(
211 Some(hint("Available: {cwd} and {session_id}.")),
329 "MCP config flag",
212 open_problem,
330 text_field(&form_state.mcp_flag, true, false, cx),
213 )
331 Some(hint(
214 .into_any_element(),
332 "Passes the Teams MCP endpoint to the agent. Empty = none.",
333 )),
334 None,
335 ))
336 })
337 .into_any_element(),
338 div()
339 .w_full()
340 .when(!chat, |slot| {
341 slot.child(field(
342 "Open session",
343 text_field(&form_state.open_session, true, open_problem.is_some(), cx),
344 Some(hint("Available: {cwd} and {session_id}.")),
345 open_problem,
346 ))
347 })
348 .into_any_element(),
215 h_flex()
349 h_flex()
216 .w_full()
350 .w_full()
217 .gap(px(8.))
351 .gap(px(8.))
crates/app/src/agents/settings_section.rs +321 −19
@@ -1,4 +1,4 @@
1 use agents::{AgentAction, AgentProfile, Environment, OutputFormat};
1 use agents::{AgentAction, AgentBackend, AgentProfile, Environment, OutputFormat};
2 2 use gpui_kit::assets::IconName;
3 3 use gpui_kit::component::{
4 4 button::{Button, ButtonVariants as _},
@@ -11,7 +11,9 @@ use gpui_kit::*;
11 11
12 12 use super::environment_label;
13 13 use super::runs::AgentRuns;
14 use super::settings_controls::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};
14 use super::settings_controls::{
15 Choice, MenuEntry, PAGE_PADDING, dropdown, link_dropdown, section_header,
16 };
15 17 use super::settings_forms::resume_toggle;
16 18 use crate::runtime;
17 19 use crate::theme;
@@ -44,6 +46,9 @@ pub(super) struct AgentForm {
44 46 pub command: Entity<InputState>,
45 47 pub open_session: Entity<InputState>,
46 48 pub mcp_flag: Entity<InputState>,
49 pub base_url: Entity<InputState>,
50 pub model: Entity<InputState>,
51 pub api_key: Entity<InputState>,
47 52 }
48 53
49 54 pub(super) struct ActionForm {
@@ -60,6 +65,10 @@ pub struct AgentsSettings {
60 65 pub(super) agent_form: Option<AgentForm>,
61 66 pub(super) action_form: Option<ActionForm>,
62 67 pub(super) probe: Probe,
68 pub(super) models: Vec<String>,
69 models_request: u64,
70 pub(super) found: Vec<agents::CliHit>,
71 scanned: bool,
63 72 form_subscriptions: Vec<Subscription>,
64 73 _runs_subscription: Subscription,
65 74 }
@@ -98,6 +107,10 @@ impl AgentsSettings {
98 107 agent_form: None,
99 108 action_form: None,
100 109 probe: Probe::Idle,
110 models: Vec::new(),
111 models_request: 0,
112 found: Vec::new(),
113 scanned: false,
101 114 form_subscriptions: Vec::new(),
102 115 _runs_subscription: subscription,
103 116 }
@@ -109,6 +122,8 @@ impl AgentsSettings {
109 122 self.action_form = None;
110 123 self.form_subscriptions.clear();
111 124 self.probe = Probe::Idle;
125 self.models.clear();
126 self.models_request += 1;
112 127 cx.notify();
113 128 }
114 129
@@ -151,6 +166,13 @@ impl AgentsSettings {
151 166 } => distro.clone(),
152 167 _ => String::new(),
153 168 };
169 let (base_url, model) = match &profile.backend {
170 AgentBackend::OpenAi {
171 base_url, model, ..
172 } => (base_url.clone(), model.clone()),
173 AgentBackend::Anthropic { model, .. } => (String::new(), model.clone()),
174 AgentBackend::Command => (String::new(), String::new()),
175 };
154 176 self.agent_form = Some(AgentForm {
155 177 id: profile.id.clone(),
156 178 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
@@ -163,11 +185,35 @@ impl AgentsSettings {
163 185 Self::commit_agent,
164 186 ),
165 187 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
188 base_url: self.line_input(&base_url, window, cx, Self::commit_agent),
189 model: self.line_input(&model, window, cx, Self::commit_agent),
190 api_key: self.line_input("", window, cx, Self::commit_agent),
166 191 });
192 let inputs = self
193 .agent_form
194 .as_ref()
195 .map(|form| (form.base_url.clone(), form.api_key.clone()));
196 if let Some((base_url, api_key)) = inputs {
197 self.watch_model_refresh(&base_url, cx);
198 self.watch_model_refresh(&api_key, cx);
199 }
167 200 self.page = Page::Agent;
201 if profile.is_chat() {
202 self.refresh_models(cx);
203 }
168 204 cx.notify();
169 205 }
170 206
207 fn watch_model_refresh(&mut self, input: &Entity<InputState>, cx: &mut Context<Self>) {
208 self.form_subscriptions
209 .push(cx.subscribe(input, |this, _, event: &InputEvent, cx| {
210 if matches!(event, InputEvent::Blur) {
211 this.commit_agent(cx);
212 this.refresh_models(cx);
213 }
214 }));
215 }
216
171 217 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
172 218 let Some(action) = self
173 219 .runs
@@ -213,6 +259,9 @@ impl AgentsSettings {
213 259 let command = form.command.read(cx).value().to_string();
214 260 let open_session = form.open_session.read(cx).value().to_string();
215 261 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
262 let base_url = form.base_url.read(cx).value().trim().to_owned();
263 let model = form.model.read(cx).value().trim().to_owned();
264 let typed_key = form.api_key.read(cx).value().trim().to_owned();
216 265 self.runs.update(cx, |runs, cx| {
217 266 runs.update_settings(
218 267 |settings| {
@@ -221,20 +270,96 @@ impl AgentsSettings {
221 270 return;
222 271 };
223 272 agent.name = name;
224 agent.command = command;
225 agent.open_session_command = open_session;
226 agent.mcp_config_flag = mcp_flag;
227 if let Environment::Wsl {
228 distro: Some(current),
229 } = &mut agent.environment
230 {
231 *current = distro;
273 if agent.is_chat() {
274 match &mut agent.backend {
275 AgentBackend::OpenAi {
276 base_url: url,
277 model: current,
278 api_key,
279 } => {
280 *url = base_url;
281 *current = model;
282 if !typed_key.is_empty() {
283 *api_key = typed_key;
284 }
285 }
286 AgentBackend::Anthropic {
287 model: current,
288 api_key,
289 } => {
290 *current = model;
291 if !typed_key.is_empty() {
292 *api_key = typed_key;
293 }
294 }
295 AgentBackend::Command => {}
296 }
297 } else {
298 agent.command = command;
299 agent.open_session_command = open_session;
300 agent.mcp_config_flag = mcp_flag;
301 if let Environment::Wsl {
302 distro: Some(current),
303 } = &mut agent.environment
304 {
305 *current = distro;
306 }
232 307 }
233 308 },
234 309 cx,
235 310 )
236 311 });
237 self.probe = Probe::Idle;
312 }
313
314 pub(super) fn set_model(&mut self, model: String, window: &mut Window, cx: &mut Context<Self>) {
315 let Some(form) = &self.agent_form else {
316 return;
317 };
318 form.model
319 .update(cx, |input, cx| input.set_value(model, window, cx));
320 self.commit_agent(cx);
321 }
322
323 pub(super) fn refresh_models(&mut self, cx: &mut Context<Self>) {
324 let Some(profile) = self.current_agent(cx) else {
325 return;
326 };
327 if !profile.is_chat() {
328 return;
329 }
330 self.models_request += 1;
331 let ticket = self.models_request;
332 self.probe = Probe::Running;
333 cx.notify();
334 let receiver = runtime::spawn(async move { agents::list_models(&profile).await });
335 cx.spawn(async move |this, cx| {
336 let result = receiver
337 .await
338 .unwrap_or_else(|_| Err("cancelled".to_owned()));
339 this.update(cx, |this, cx| {
340 if this.models_request != ticket {
341 return;
342 }
343 match result {
344 Ok(names) => {
345 let count = names.len();
346 this.models = names;
347 this.probe = Probe::Found(if count == 1 {
348 "1 model".to_owned()
349 } else {
350 format!("{count} models")
351 });
352 }
353 Err(error) => {
354 this.models.clear();
355 this.probe = Probe::Missing(error);
356 }
357 }
358 cx.notify();
359 })
360 .ok();
361 })
362 .detach();
238 363 }
239 364
240 365 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
@@ -319,6 +444,18 @@ impl AgentsSettings {
319 444 self.update_action(cx, move |action| action.agent_id = agent_id);
320 445 }
321 446
447 pub(super) fn set_write_with(&mut self, agent_id: String, cx: &mut Context<Self>) {
448 self.runs.update(cx, |runs, cx| {
449 runs.update_settings(|settings| settings.write_with = agent_id, cx)
450 });
451 }
452
453 pub(super) fn rescan(&mut self, cx: &mut Context<Self>) {
454 self.found = agents::scan_clis();
455 self.scanned = true;
456 cx.notify();
457 }
458
322 459 pub(super) fn set_resume_interrupted_runs(&mut self, resume: bool, cx: &mut Context<Self>) {
323 460 self.runs.update(cx, |runs, cx| {
324 461 runs.update_settings(|settings| settings.resume_interrupted_runs = resume, cx)
@@ -393,6 +530,10 @@ impl AgentsSettings {
393 530 let Some(profile) = self.current_agent(cx) else {
394 531 return;
395 532 };
533 if profile.is_chat() {
534 self.refresh_models(cx);
535 return;
536 }
396 537 if profile.command.trim().is_empty() {
397 538 self.probe = Probe::Missing("The command is empty".to_owned());
398 539 cx.notify();
@@ -443,8 +584,28 @@ impl AgentsSettings {
443 584 existing.iter().any(|id| id == candidate)
444 585 });
445 586 let id = profile.id.clone();
587 let chat = profile.is_chat();
588 let mut action = AgentAction::answer_this(&id);
589 action.extra_args.clear();
590 action.label = format!("Answer with {}", profile.name);
591 action.id = unique_id(&format!("answer-{id}"), |candidate| {
592 self.runs
593 .read(cx)
594 .settings()
595 .actions
596 .iter()
597 .any(|action| action.id == candidate)
598 });
446 599 self.runs.update(cx, |runs, cx| {
447 runs.update_settings(|settings| settings.agents.push(profile), cx)
600 runs.update_settings(
601 |settings| {
602 settings.agents.push(profile);
603 if chat {
604 settings.actions.push(action);
605 }
606 },
607 cx,
608 )
448 609 });
449 610 self.open_agent(&id, window, cx);
450 611 }
@@ -482,26 +643,83 @@ impl AgentsSettings {
482 643
483 644 type Preset = (&'static str, fn() -> AgentProfile);
484 645
485 fn agent_presets() -> [Preset; 4] {
646 fn agent_presets() -> [Preset; 9] {
486 647 fn custom() -> AgentProfile {
487 648 AgentProfile {
488 649 id: "custom".to_owned(),
489 650 name: "Custom agent".to_owned(),
490 651 environment: Environment::Host,
491 command: String::new(),
492 652 output: OutputFormat::Text,
493 open_session_command: String::new(),
494 mcp_config_flag: String::new(),
653 ..AgentProfile::default()
495 654 }
496 655 }
497 656 [
498 ("Claude Code (WSL)", AgentProfile::claude_wsl),
657 (
658 "Claude Code (WSL)",
659 AgentProfile::claude_wsl as fn() -> AgentProfile,
660 ),
499 661 ("Claude Code (Windows)", AgentProfile::claude_host),
500 662 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
663 ("Ollama", AgentProfile::ollama),
664 ("OpenAI", AgentProfile::openai),
665 ("OpenRouter", AgentProfile::openrouter),
666 ("Anthropic", AgentProfile::anthropic),
667 ("OpenAI-compatible", AgentProfile::openai_compatible),
501 668 ("Custom", custom),
502 669 ]
503 670 }
504 671
672 fn write_with_label(settings: &agents::AgentSettings) -> String {
673 if settings.write_with.is_empty() {
674 return "Microsoft Copilot".to_owned();
675 }
676 settings
677 .agents
678 .iter()
679 .find(|agent| agent.id == settings.write_with && agent.is_chat())
680 .map(|agent| agent.name.clone())
681 .unwrap_or_else(|| "Microsoft Copilot".to_owned())
682 }
683
684 fn write_with_entries(
685 settings: &agents::AgentSettings,
686 this: &Entity<AgentsSettings>,
687 ) -> Vec<MenuEntry> {
688 let mut entries = vec![write_with_entry(
689 this,
690 "Microsoft Copilot",
691 "",
692 settings.write_with.is_empty(),
693 )];
694 for agent in settings.agents.iter().filter(|agent| agent.is_chat()) {
695 entries.push(write_with_entry(
696 this,
697 &agent.name,
698 &agent.id,
699 settings.write_with == agent.id,
700 ));
701 }
702 entries
703 }
704
705 fn write_with_entry(
706 this: &Entity<AgentsSettings>,
707 label: &str,
708 agent_id: &str,
709 selected: bool,
710 ) -> MenuEntry {
711 let (this, agent_id) = (this.clone(), agent_id.to_owned());
712 let choose: Choice = std::rc::Rc::new(move |_, cx| {
713 let agent_id = agent_id.clone();
714 this.update(cx, |this, cx| this.set_write_with(agent_id, cx))
715 });
716 MenuEntry {
717 label: label.to_owned(),
718 selected,
719 choose,
720 }
721 }
722
505 723 fn list_row(
506 724 id: (&'static str, usize),
507 725 leading: Option<AnyElement>,
@@ -568,7 +786,17 @@ fn small_button(id: (&'static str, usize), name: IconName, enabled: bool) -> Sta
568 786
569 787 impl AgentsSettings {
570 788 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
789 if !self.scanned {
790 self.found = agents::scan_clis();
791 self.scanned = true;
792 }
571 793 let settings = self.runs.read(cx).settings().clone();
794 let found: Vec<agents::CliHit> = self
795 .found
796 .iter()
797 .filter(|hit| !agents::already_installed(&settings.agents, &hit.profile))
798 .cloned()
799 .collect();
572 800 let this = cx.entity();
573 801 let preset_entries: Vec<MenuEntry> = agent_presets()
574 802 .into_iter()
@@ -611,8 +839,12 @@ impl AgentsSettings {
611 839 .into_any_element(),
612 840 ),
613 841 agent.name.clone(),
614 environment_label(&agent.environment),
615 Some(agent.command.clone()),
842 if agent.is_chat() {
843 agent.backend_label()
844 } else {
845 environment_label(&agent.environment)
846 },
847 agent.is_command().then(|| agent.command.clone()),
616 848 )
617 849 .on_click(move |_, window, cx| {
618 850 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
@@ -660,8 +892,58 @@ impl AgentsSettings {
660 892 ),
661 893 )
662 894 });
895 let write_entries = write_with_entries(&settings, &this);
896 let write_label = write_with_label(&settings);
897 let rescan = this.clone();
898 let found_rows = found.iter().enumerate().map(|(index, hit)| {
899 let (this, profile) = (this.clone(), hit.profile.clone());
900 list_row(
901 ("found-cli", index),
902 None,
903 hit.profile.name.clone(),
904 hit.binary.display().to_string(),
905 Some(hit.profile.command.clone()),
906 )
907 .child(
908 Button::new(("add-found", index))
909 .link()
910 .label("Add")
911 .on_click(move |_, window, cx| {
912 let profile = profile.clone();
913 this.update(cx, |this, cx| this.add_agent(profile, window, cx))
914 }),
915 )
916 });
663 917 v_flex()
664 918 .w_full()
919 .child(section_header(
920 "ON THIS COMPUTER",
921 Some(
922 Button::new("rescan-clis")
923 .link()
924 .label("Scan again")
925 .on_click(move |_, _, cx| {
926 rescan.update(cx, |this, cx| this.rescan(cx))
927 })
928 .into_any_element(),
929 ),
930 ))
931 .child(
932 v_flex()
933 .w_full()
934 .px(px(8.))
935 .children(found_rows)
936 .when(found.is_empty(), |rows| {
937 rows.child(
938 div()
939 .px(px(12.))
940 .py(px(8.))
941 .text_size(px(12.))
942 .text_color(theme::text_muted())
943 .child("No Claude, Copilot, Codex, Cursor or Antigravity CLI is waiting to be added."),
944 )
945 }),
946 )
665 947 .child(section_header(
666 948 "AGENTS",
667 949 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
@@ -672,6 +954,26 @@ impl AgentsSettings {
672 954 Some(add_action.into_any_element()),
673 955 ))
674 956 .child(v_flex().w_full().px(px(8.)).children(action_rows))
957 .child(
958 v_flex()
959 .w_full()
960 .px(px(PAGE_PADDING))
961 .pt(px(16.))
962 .gap(px(6.))
963 .child(
964 div()
965 .text_size(px(14.))
966 .font_weight(FontWeight::SEMIBOLD)
967 .child("Write with"),
968 )
969 .child(
970 div()
971 .text_size(px(12.))
972 .text_color(theme::text_muted())
973 .child("Rewrite and proofread in the composer. Microsoft Copilot needs the licence."),
974 )
975 .child(dropdown("write-with", write_label, write_entries)),
976 )
675 977 .child(resume_toggle(settings.resume_interrupted_runs, this))
676 978 .child(
677 979 div()
@@ -1,4 +1,4 @@
1use agents::{AgentAction, AgentProfile, Environment, OutputFormat};
1use agents::{AgentAction, AgentBackend, AgentProfile, Environment, OutputFormat};
2use gpui_kit::assets::IconName;
2use gpui_kit::assets::IconName;
3use gpui_kit::component::{
3use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
4 button::{Button, ButtonVariants as _},
@@ -11,7 +11,9 @@ use gpui_kit::*;
11
11
12use super::environment_label;
12use super::environment_label;
13use super::runs::AgentRuns;
13use super::runs::AgentRuns;
14use super::settings_controls::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};
14use super::settings_controls::{
15 Choice, MenuEntry, PAGE_PADDING, dropdown, link_dropdown, section_header,
16};
15use super::settings_forms::resume_toggle;
17use super::settings_forms::resume_toggle;
16use crate::runtime;
18use crate::runtime;
17use crate::theme;
19use crate::theme;
@@ -44,6 +46,9 @@ pub(super) struct AgentForm {
44 pub command: Entity<InputState>,
46 pub command: Entity<InputState>,
45 pub open_session: Entity<InputState>,
47 pub open_session: Entity<InputState>,
46 pub mcp_flag: Entity<InputState>,
48 pub mcp_flag: Entity<InputState>,
49 pub base_url: Entity<InputState>,
50 pub model: Entity<InputState>,
51 pub api_key: Entity<InputState>,
47}
52}
48
53
49pub(super) struct ActionForm {
54pub(super) struct ActionForm {
@@ -60,6 +65,10 @@ pub struct AgentsSettings {
60 pub(super) agent_form: Option<AgentForm>,
65 pub(super) agent_form: Option<AgentForm>,
61 pub(super) action_form: Option<ActionForm>,
66 pub(super) action_form: Option<ActionForm>,
62 pub(super) probe: Probe,
67 pub(super) probe: Probe,
68 pub(super) models: Vec<String>,
69 models_request: u64,
70 pub(super) found: Vec<agents::CliHit>,
71 scanned: bool,
63 form_subscriptions: Vec<Subscription>,
72 form_subscriptions: Vec<Subscription>,
64 _runs_subscription: Subscription,
73 _runs_subscription: Subscription,
65}
74}
@@ -98,6 +107,10 @@ impl AgentsSettings {
98 agent_form: None,
107 agent_form: None,
99 action_form: None,
108 action_form: None,
100 probe: Probe::Idle,
109 probe: Probe::Idle,
110 models: Vec::new(),
111 models_request: 0,
112 found: Vec::new(),
113 scanned: false,
101 form_subscriptions: Vec::new(),
114 form_subscriptions: Vec::new(),
102 _runs_subscription: subscription,
115 _runs_subscription: subscription,
103 }
116 }
@@ -109,6 +122,8 @@ impl AgentsSettings {
109 self.action_form = None;
122 self.action_form = None;
110 self.form_subscriptions.clear();
123 self.form_subscriptions.clear();
111 self.probe = Probe::Idle;
124 self.probe = Probe::Idle;
125 self.models.clear();
126 self.models_request += 1;
112 cx.notify();
127 cx.notify();
113 }
128 }
114
129
@@ -151,6 +166,13 @@ impl AgentsSettings {
151 } => distro.clone(),
166 } => distro.clone(),
152 _ => String::new(),
167 _ => String::new(),
153 };
168 };
169 let (base_url, model) = match &profile.backend {
170 AgentBackend::OpenAi {
171 base_url, model, ..
172 } => (base_url.clone(), model.clone()),
173 AgentBackend::Anthropic { model, .. } => (String::new(), model.clone()),
174 AgentBackend::Command => (String::new(), String::new()),
175 };
154 self.agent_form = Some(AgentForm {
176 self.agent_form = Some(AgentForm {
155 id: profile.id.clone(),
177 id: profile.id.clone(),
156 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
178 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
@@ -163,11 +185,35 @@ impl AgentsSettings {
163 Self::commit_agent,
185 Self::commit_agent,
164 ),
186 ),
165 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
187 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
188 base_url: self.line_input(&base_url, window, cx, Self::commit_agent),
189 model: self.line_input(&model, window, cx, Self::commit_agent),
190 api_key: self.line_input("", window, cx, Self::commit_agent),
166 });
191 });
192 let inputs = self
193 .agent_form
194 .as_ref()
195 .map(|form| (form.base_url.clone(), form.api_key.clone()));
196 if let Some((base_url, api_key)) = inputs {
197 self.watch_model_refresh(&base_url, cx);
198 self.watch_model_refresh(&api_key, cx);
199 }
167 self.page = Page::Agent;
200 self.page = Page::Agent;
201 if profile.is_chat() {
202 self.refresh_models(cx);
203 }
168 cx.notify();
204 cx.notify();
169 }
205 }
170
206
207 fn watch_model_refresh(&mut self, input: &Entity<InputState>, cx: &mut Context<Self>) {
208 self.form_subscriptions
209 .push(cx.subscribe(input, |this, _, event: &InputEvent, cx| {
210 if matches!(event, InputEvent::Blur) {
211 this.commit_agent(cx);
212 this.refresh_models(cx);
213 }
214 }));
215 }
216
171 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
217 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
172 let Some(action) = self
218 let Some(action) = self
173 .runs
219 .runs
@@ -213,6 +259,9 @@ impl AgentsSettings {
213 let command = form.command.read(cx).value().to_string();
259 let command = form.command.read(cx).value().to_string();
214 let open_session = form.open_session.read(cx).value().to_string();
260 let open_session = form.open_session.read(cx).value().to_string();
215 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
261 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
262 let base_url = form.base_url.read(cx).value().trim().to_owned();
263 let model = form.model.read(cx).value().trim().to_owned();
264 let typed_key = form.api_key.read(cx).value().trim().to_owned();
216 self.runs.update(cx, |runs, cx| {
265 self.runs.update(cx, |runs, cx| {
217 runs.update_settings(
266 runs.update_settings(
218 |settings| {
267 |settings| {
@@ -221,20 +270,96 @@ impl AgentsSettings {
221 return;
270 return;
222 };
271 };
223 agent.name = name;
272 agent.name = name;
224 agent.command = command;
273 if agent.is_chat() {
225 agent.open_session_command = open_session;
274 match &mut agent.backend {
226 agent.mcp_config_flag = mcp_flag;
275 AgentBackend::OpenAi {
227 if let Environment::Wsl {
276 base_url: url,
228 distro: Some(current),
277 model: current,
229 } = &mut agent.environment
278 api_key,
230 {
279 } => {
231 *current = distro;
280 *url = base_url;
281 *current = model;
282 if !typed_key.is_empty() {
283 *api_key = typed_key;
284 }
285 }
286 AgentBackend::Anthropic {
287 model: current,
288 api_key,
289 } => {
290 *current = model;
291 if !typed_key.is_empty() {
292 *api_key = typed_key;
293 }
294 }
295 AgentBackend::Command => {}
296 }
297 } else {
298 agent.command = command;
299 agent.open_session_command = open_session;
300 agent.mcp_config_flag = mcp_flag;
301 if let Environment::Wsl {
302 distro: Some(current),
303 } = &mut agent.environment
304 {
305 *current = distro;
306 }
232 }
307 }
233 },
308 },
234 cx,
309 cx,
235 )
310 )
236 });
311 });
237 self.probe = Probe::Idle;
312 }
313
314 pub(super) fn set_model(&mut self, model: String, window: &mut Window, cx: &mut Context<Self>) {
315 let Some(form) = &self.agent_form else {
316 return;
317 };
318 form.model
319 .update(cx, |input, cx| input.set_value(model, window, cx));
320 self.commit_agent(cx);
321 }
322
323 pub(super) fn refresh_models(&mut self, cx: &mut Context<Self>) {
324 let Some(profile) = self.current_agent(cx) else {
325 return;
326 };
327 if !profile.is_chat() {
328 return;
329 }
330 self.models_request += 1;
331 let ticket = self.models_request;
332 self.probe = Probe::Running;
333 cx.notify();
334 let receiver = runtime::spawn(async move { agents::list_models(&profile).await });
335 cx.spawn(async move |this, cx| {
336 let result = receiver
337 .await
338 .unwrap_or_else(|_| Err("cancelled".to_owned()));
339 this.update(cx, |this, cx| {
340 if this.models_request != ticket {
341 return;
342 }
343 match result {
344 Ok(names) => {
345 let count = names.len();
346 this.models = names;
347 this.probe = Probe::Found(if count == 1 {
348 "1 model".to_owned()
349 } else {
350 format!("{count} models")
351 });
352 }
353 Err(error) => {
354 this.models.clear();
355 this.probe = Probe::Missing(error);
356 }
357 }
358 cx.notify();
359 })
360 .ok();
361 })
362 .detach();
238 }
363 }
239
364
240 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
365 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
@@ -319,6 +444,18 @@ impl AgentsSettings {
319 self.update_action(cx, move |action| action.agent_id = agent_id);
444 self.update_action(cx, move |action| action.agent_id = agent_id);
320 }
445 }
321
446
447 pub(super) fn set_write_with(&mut self, agent_id: String, cx: &mut Context<Self>) {
448 self.runs.update(cx, |runs, cx| {
449 runs.update_settings(|settings| settings.write_with = agent_id, cx)
450 });
451 }
452
453 pub(super) fn rescan(&mut self, cx: &mut Context<Self>) {
454 self.found = agents::scan_clis();
455 self.scanned = true;
456 cx.notify();
457 }
458
322 pub(super) fn set_resume_interrupted_runs(&mut self, resume: bool, cx: &mut Context<Self>) {
459 pub(super) fn set_resume_interrupted_runs(&mut self, resume: bool, cx: &mut Context<Self>) {
323 self.runs.update(cx, |runs, cx| {
460 self.runs.update(cx, |runs, cx| {
324 runs.update_settings(|settings| settings.resume_interrupted_runs = resume, cx)
461 runs.update_settings(|settings| settings.resume_interrupted_runs = resume, cx)
@@ -393,6 +530,10 @@ impl AgentsSettings {
393 let Some(profile) = self.current_agent(cx) else {
530 let Some(profile) = self.current_agent(cx) else {
394 return;
531 return;
395 };
532 };
533 if profile.is_chat() {
534 self.refresh_models(cx);
535 return;
536 }
396 if profile.command.trim().is_empty() {
537 if profile.command.trim().is_empty() {
397 self.probe = Probe::Missing("The command is empty".to_owned());
538 self.probe = Probe::Missing("The command is empty".to_owned());
398 cx.notify();
539 cx.notify();
@@ -443,8 +584,28 @@ impl AgentsSettings {
443 existing.iter().any(|id| id == candidate)
584 existing.iter().any(|id| id == candidate)
444 });
585 });
445 let id = profile.id.clone();
586 let id = profile.id.clone();
587 let chat = profile.is_chat();
588 let mut action = AgentAction::answer_this(&id);
589 action.extra_args.clear();
590 action.label = format!("Answer with {}", profile.name);
591 action.id = unique_id(&format!("answer-{id}"), |candidate| {
592 self.runs
593 .read(cx)
594 .settings()
595 .actions
596 .iter()
597 .any(|action| action.id == candidate)
598 });
446 self.runs.update(cx, |runs, cx| {
599 self.runs.update(cx, |runs, cx| {
447 runs.update_settings(|settings| settings.agents.push(profile), cx)
600 runs.update_settings(
601 |settings| {
602 settings.agents.push(profile);
603 if chat {
604 settings.actions.push(action);
605 }
606 },
607 cx,
608 )
448 });
609 });
449 self.open_agent(&id, window, cx);
610 self.open_agent(&id, window, cx);
450 }
611 }
@@ -482,26 +643,83 @@ impl AgentsSettings {
482
643
483type Preset = (&'static str, fn() -> AgentProfile);
644type Preset = (&'static str, fn() -> AgentProfile);
484
645
485fn agent_presets() -> [Preset; 4] {
646fn agent_presets() -> [Preset; 9] {
486 fn custom() -> AgentProfile {
647 fn custom() -> AgentProfile {
487 AgentProfile {
648 AgentProfile {
488 id: "custom".to_owned(),
649 id: "custom".to_owned(),
489 name: "Custom agent".to_owned(),
650 name: "Custom agent".to_owned(),
490 environment: Environment::Host,
651 environment: Environment::Host,
491 command: String::new(),
492 output: OutputFormat::Text,
652 output: OutputFormat::Text,
493 open_session_command: String::new(),
653 ..AgentProfile::default()
494 mcp_config_flag: String::new(),
495 }
654 }
496 }
655 }
497 [
656 [
498 ("Claude Code (WSL)", AgentProfile::claude_wsl),
657 (
658 "Claude Code (WSL)",
659 AgentProfile::claude_wsl as fn() -> AgentProfile,
660 ),
499 ("Claude Code (Windows)", AgentProfile::claude_host),
661 ("Claude Code (Windows)", AgentProfile::claude_host),
500 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
662 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
663 ("Ollama", AgentProfile::ollama),
664 ("OpenAI", AgentProfile::openai),
665 ("OpenRouter", AgentProfile::openrouter),
666 ("Anthropic", AgentProfile::anthropic),
667 ("OpenAI-compatible", AgentProfile::openai_compatible),
501 ("Custom", custom),
668 ("Custom", custom),
502 ]
669 ]
503}
670}
504
671
672fn write_with_label(settings: &agents::AgentSettings) -> String {
673 if settings.write_with.is_empty() {
674 return "Microsoft Copilot".to_owned();
675 }
676 settings
677 .agents
678 .iter()
679 .find(|agent| agent.id == settings.write_with && agent.is_chat())
680 .map(|agent| agent.name.clone())
681 .unwrap_or_else(|| "Microsoft Copilot".to_owned())
682}
683
684fn write_with_entries(
685 settings: &agents::AgentSettings,
686 this: &Entity<AgentsSettings>,
687) -> Vec<MenuEntry> {
688 let mut entries = vec![write_with_entry(
689 this,
690 "Microsoft Copilot",
691 "",
692 settings.write_with.is_empty(),
693 )];
694 for agent in settings.agents.iter().filter(|agent| agent.is_chat()) {
695 entries.push(write_with_entry(
696 this,
697 &agent.name,
698 &agent.id,
699 settings.write_with == agent.id,
700 ));
701 }
702 entries
703}
704
705fn write_with_entry(
706 this: &Entity<AgentsSettings>,
707 label: &str,
708 agent_id: &str,
709 selected: bool,
710) -> MenuEntry {
711 let (this, agent_id) = (this.clone(), agent_id.to_owned());
712 let choose: Choice = std::rc::Rc::new(move |_, cx| {
713 let agent_id = agent_id.clone();
714 this.update(cx, |this, cx| this.set_write_with(agent_id, cx))
715 });
716 MenuEntry {
717 label: label.to_owned(),
718 selected,
719 choose,
720 }
721}
722
505fn list_row(
723fn list_row(
506 id: (&'static str, usize),
724 id: (&'static str, usize),
507 leading: Option<AnyElement>,
725 leading: Option<AnyElement>,
@@ -568,7 +786,17 @@ fn small_button(id: (&'static str, usize), name: IconName, enabled: bool) -> Sta
568
786
569impl AgentsSettings {
787impl AgentsSettings {
570 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
788 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
789 if !self.scanned {
790 self.found = agents::scan_clis();
791 self.scanned = true;
792 }
571 let settings = self.runs.read(cx).settings().clone();
793 let settings = self.runs.read(cx).settings().clone();
794 let found: Vec<agents::CliHit> = self
795 .found
796 .iter()
797 .filter(|hit| !agents::already_installed(&settings.agents, &hit.profile))
798 .cloned()
799 .collect();
572 let this = cx.entity();
800 let this = cx.entity();
573 let preset_entries: Vec<MenuEntry> = agent_presets()
801 let preset_entries: Vec<MenuEntry> = agent_presets()
574 .into_iter()
802 .into_iter()
@@ -611,8 +839,12 @@ impl AgentsSettings {
611 .into_any_element(),
839 .into_any_element(),
612 ),
840 ),
613 agent.name.clone(),
841 agent.name.clone(),
614 environment_label(&agent.environment),
842 if agent.is_chat() {
615 Some(agent.command.clone()),
843 agent.backend_label()
844 } else {
845 environment_label(&agent.environment)
846 },
847 agent.is_command().then(|| agent.command.clone()),
616 )
848 )
617 .on_click(move |_, window, cx| {
849 .on_click(move |_, window, cx| {
618 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
850 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
@@ -660,8 +892,58 @@ impl AgentsSettings {
660 ),
892 ),
661 )
893 )
662 });
894 });
895 let write_entries = write_with_entries(&settings, &this);
896 let write_label = write_with_label(&settings);
897 let rescan = this.clone();
898 let found_rows = found.iter().enumerate().map(|(index, hit)| {
899 let (this, profile) = (this.clone(), hit.profile.clone());
900 list_row(
901 ("found-cli", index),
902 None,
903 hit.profile.name.clone(),
904 hit.binary.display().to_string(),
905 Some(hit.profile.command.clone()),
906 )
907 .child(
908 Button::new(("add-found", index))
909 .link()
910 .label("Add")
911 .on_click(move |_, window, cx| {
912 let profile = profile.clone();
913 this.update(cx, |this, cx| this.add_agent(profile, window, cx))
914 }),
915 )
916 });
663 v_flex()
917 v_flex()
664 .w_full()
918 .w_full()
919 .child(section_header(
920 "ON THIS COMPUTER",
921 Some(
922 Button::new("rescan-clis")
923 .link()
924 .label("Scan again")
925 .on_click(move |_, _, cx| {
926 rescan.update(cx, |this, cx| this.rescan(cx))
927 })
928 .into_any_element(),
929 ),
930 ))
931 .child(
932 v_flex()
933 .w_full()
934 .px(px(8.))
935 .children(found_rows)
936 .when(found.is_empty(), |rows| {
937 rows.child(
938 div()
939 .px(px(12.))
940 .py(px(8.))
941 .text_size(px(12.))
942 .text_color(theme::text_muted())
943 .child("No Claude, Copilot, Codex, Cursor or Antigravity CLI is waiting to be added."),
944 )
945 }),
946 )
665 .child(section_header(
947 .child(section_header(
666 "AGENTS",
948 "AGENTS",
667 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
949 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
@@ -672,6 +954,26 @@ impl AgentsSettings {
672 Some(add_action.into_any_element()),
954 Some(add_action.into_any_element()),
673 ))
955 ))
674 .child(v_flex().w_full().px(px(8.)).children(action_rows))
956 .child(v_flex().w_full().px(px(8.)).children(action_rows))
957 .child(
958 v_flex()
959 .w_full()
960 .px(px(PAGE_PADDING))
961 .pt(px(16.))
962 .gap(px(6.))
963 .child(
964 div()
965 .text_size(px(14.))
966 .font_weight(FontWeight::SEMIBOLD)
967 .child("Write with"),
968 )
969 .child(
970 div()
971 .text_size(px(12.))
972 .text_color(theme::text_muted())
973 .child("Rewrite and proofread in the composer. Microsoft Copilot needs the licence."),
974 )
975 .child(dropdown("write-with", write_label, write_entries)),
976 )
675 .child(resume_toggle(settings.resume_interrupted_runs, this))
977 .child(resume_toggle(settings.resume_interrupted_runs, this))
676 .child(
978 .child(
677 div()
979 div()
crates/app/src/agents/start_dialog.rs +8 −2
@@ -58,6 +58,7 @@ pub struct StartDialog {
58 58 working_dir: String,
59 59 recent_working_dirs: Vec<String>,
60 60 offers_sessions: bool,
61 asks_for_directory: bool,
61 62 scans_external: bool,
62 63 run_sessions: Vec<SessionOption>,
63 64 external_sessions: Vec<SessionOption>,
@@ -108,6 +109,7 @@ impl StartDialog {
108 109 })
109 110 .unwrap_or_default();
110 111 let offers_sessions = profile.as_ref().is_some_and(agents::supports_resume);
112 let asks_for_directory = profile.as_ref().is_none_or(|profile| profile.is_command());
111 113 let run_sessions = match runs {
112 114 Some(runs) if offers_sessions => {
113 115 run_options(&runs.for_agent(&action.agent_id), app.read(cx), Utc::now())
@@ -131,6 +133,7 @@ impl StartDialog {
131 133 working_dir: action.working_dir.clone(),
132 134 recent_working_dirs,
133 135 offers_sessions,
136 asks_for_directory,
134 137 scans_external: profile
135 138 .is_some_and(|profile| profile.output == agents::OutputFormat::ClaudeStreamJson)
136 139 && offers_sessions,
@@ -361,7 +364,8 @@ impl StartDialog {
361 364 .text_size(px(12.))
362 365 .line_height(relative(1.4))
363 366 .text_color(theme::text_soft())
364 .line_clamp(QUOTE_LINES).text_ellipsis()
367 .line_clamp(QUOTE_LINES)
368 .text_ellipsis()
365 369 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
366 370 }
367 371
@@ -486,7 +490,9 @@ impl StartDialog {
486 490 .w_full()
487 491 .gap(px(8.))
488 492 .children(session_row)
489 .child(picker_row("Working dir", working_dir_control))
493 .when(self.asks_for_directory, |rows| {
494 rows.child(picker_row("Working dir", working_dir_control))
495 })
490 496 }
491 497
492 498 fn field(&self, window: &Window, cx: &App) -> Div {
@@ -58,6 +58,7 @@ pub struct StartDialog {
58 working_dir: String,
58 working_dir: String,
59 recent_working_dirs: Vec<String>,
59 recent_working_dirs: Vec<String>,
60 offers_sessions: bool,
60 offers_sessions: bool,
61 asks_for_directory: bool,
61 scans_external: bool,
62 scans_external: bool,
62 run_sessions: Vec<SessionOption>,
63 run_sessions: Vec<SessionOption>,
63 external_sessions: Vec<SessionOption>,
64 external_sessions: Vec<SessionOption>,
@@ -108,6 +109,7 @@ impl StartDialog {
108 })
109 })
109 .unwrap_or_default();
110 .unwrap_or_default();
110 let offers_sessions = profile.as_ref().is_some_and(agents::supports_resume);
111 let offers_sessions = profile.as_ref().is_some_and(agents::supports_resume);
112 let asks_for_directory = profile.as_ref().is_none_or(|profile| profile.is_command());
111 let run_sessions = match runs {
113 let run_sessions = match runs {
112 Some(runs) if offers_sessions => {
114 Some(runs) if offers_sessions => {
113 run_options(&runs.for_agent(&action.agent_id), app.read(cx), Utc::now())
115 run_options(&runs.for_agent(&action.agent_id), app.read(cx), Utc::now())
@@ -131,6 +133,7 @@ impl StartDialog {
131 working_dir: action.working_dir.clone(),
133 working_dir: action.working_dir.clone(),
132 recent_working_dirs,
134 recent_working_dirs,
133 offers_sessions,
135 offers_sessions,
136 asks_for_directory,
134 scans_external: profile
137 scans_external: profile
135 .is_some_and(|profile| profile.output == agents::OutputFormat::ClaudeStreamJson)
138 .is_some_and(|profile| profile.output == agents::OutputFormat::ClaudeStreamJson)
136 && offers_sessions,
139 && offers_sessions,
@@ -361,7 +364,8 @@ impl StartDialog {
361 .text_size(px(12.))
364 .text_size(px(12.))
362 .line_height(relative(1.4))
365 .line_height(relative(1.4))
363 .text_color(theme::text_soft())
366 .text_color(theme::text_soft())
364 .line_clamp(QUOTE_LINES).text_ellipsis()
367 .line_clamp(QUOTE_LINES)
368 .text_ellipsis()
365 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
369 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
366 }
370 }
367
371
@@ -486,7 +490,9 @@ impl StartDialog {
486 .w_full()
490 .w_full()
487 .gap(px(8.))
491 .gap(px(8.))
488 .children(session_row)
492 .children(session_row)
489 .child(picker_row("Working dir", working_dir_control))
493 .when(self.asks_for_directory, |rows| {
494 rows.child(picker_row("Working dir", working_dir_control))
495 })
490 }
496 }
491
497
492 fn field(&self, window: &Window, cx: &App) -> Div {
498 fn field(&self, window: &Window, cx: &App) -> Div {
crates/app/src/call/mod.rs +1 −1
@@ -1,4 +1,4 @@
1 1 mod overlay;
2 2
3 pub use state::call::*;
4 3 pub use overlay::CallWindows;
4 pub use state::call::*;
@@ -1,4 +1,4 @@
1mod overlay;
1mod overlay;
2
2
3pub use state::call::*;
4pub use overlay::CallWindows;
3pub use overlay::CallWindows;
4pub use state::call::*;
crates/app/src/layout_guard.rs +75 −31
@@ -172,46 +172,46 @@ mod frames {
172 172 use crate::app_state::{AppHandle, AppState, Mode, Selection};
173 173 use crate::call::{ActiveCall, CallModel, ConsultCall};
174 174 use crate::demo;
175 use crate::render::{CODE_BLOCK_TAG, CODE_LINE_TAG};
175 176 use crate::settings::select_selector;
176 177 use crate::settings::{item_selector, label, label_selector, metrics};
177 178 use crate::settings_section::SettingsSection;
178 179 use crate::user_activity::UserInput;
180 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
179 181 use crate::views::call_transcript::TranscriptPanel;
180 182 use crate::views::call_view::CHAT_PANEL_TAG;
181 183 use crate::views::composer::delivery::{
182 COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG,
183 DELIVERY_MENU_TAG,
184 COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG, DELIVERY_MENU_TAG,
184 185 };
185 186 use crate::views::composer::plus_menu::{COMPOSER_PLUS_TAG, PlusAction};
186 187 use crate::views::composer::{
187 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
188 COMPOSER_ACTIONS_TAG, COMPOSER_FORMAT_TAG, COMPOSER_INPUT_TAG, COMPOSER_SEND_TAG, COMPOSER_STACKED_ACTIONS_TAG,
189 POST_ANNOUNCEMENT_TAG, POST_ANNOUNCEMENT_TOGGLE_TAG, POST_AUDIENCE_TAG, POST_CARD_DIVIDER_TAG, POST_CARD_FOOTER_TAG, POST_CARD_HEADER_TAG, POST_CARD_SEND_TAG,
190 POST_CARD_SUBJECT_TAG,
188 COMPOSER_ACTIONS_TAG, COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG,
189 COMPOSER_FORMAT_DIVIDER_TAG, COMPOSER_FORMAT_TAG, COMPOSER_INPUT_TAG, COMPOSER_SEND_TAG,
190 COMPOSER_STACKED_ACTIONS_TAG, POST_ANNOUNCEMENT_TAG, POST_ANNOUNCEMENT_TOGGLE_TAG,
191 POST_AUDIENCE_TAG, POST_CARD_DIVIDER_TAG, POST_CARD_FOOTER_TAG, POST_CARD_HEADER_TAG,
192 POST_CARD_SEND_TAG, POST_CARD_SUBJECT_TAG,
191 193 };
192 194 use crate::views::call_window::CALL_WINDOW_TAG;
193 195 use crate::views::conversation::{
194 196 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
195 197 CHANNEL_DETAILS_TAG,
196 198 };
197 use crate::render::{CODE_BLOCK_TAG, CODE_LINE_TAG};
198 199 use crate::views::conversation::{
199 200 FEED_EDGE_TAG, FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG,
200 201 FORWARD_FOOTER_TAG, HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG,
201 202 };
202 use crate::views::group_name::{GROUP_NAME_BUTTON, GROUP_NAME_FORM};
203 use crate::views::post_card::{
204 POST_AVATAR_TAG, POST_BODY_TAG, POST_CARD_TAG, POST_FOOTER_AVATAR_TAG,
205 };
206 203 use crate::views::find_panel::{
207 204 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
208 205 };
209 206 use crate::views::forward_dialog::{FORWARD_CARD_TAG, FORWARD_PREVIEW_TAG};
207 use crate::views::group_name::{GROUP_NAME_BUTTON, GROUP_NAME_FORM};
210 208 use crate::views::message_row::{
211 209 BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y, select_box_selector,
212 210 };
213 211 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
214 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
212 use crate::views::post_card::{
213 POST_AVATAR_TAG, POST_BODY_TAG, POST_CARD_TAG, POST_FOOTER_AVATAR_TAG,
214 };
215 215 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
216 216 use crate::views::reaction_proposal_pill::REACTION_PILL;
217 217 use crate::views::recap_tab::RECAP_REGION;
@@ -219,14 +219,14 @@ mod frames {
219 219 AppShell, Startup, bind_keys, install_globals,
220 220 };
221 221 use crate::views::shortcuts::{
222 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
223 OpenCalendar, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
222 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCalendar,
223 OpenCallsTab, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
224 224 };
225 225 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
226 use crate::views::sidebar::chat_row_selector;
227 226 use crate::views::sidebar::chat_filter_bar::{
228 227 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
229 228 };
229 use crate::views::sidebar::chat_row_selector;
230 230 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
231 231 use crate::views::widgets::{
232 232 COUNT_BADGE, RAIL_BADGE, badge_ink_centre, badge_pill, badge_selector, badge_text_origin,
@@ -1047,9 +1047,12 @@ mod frames {
1047 1047 .find(|(path, _)| *path == wanted)
1048 1048 .map(|(_, bounds)| *bounds)
1049 1049 };
1050 let first_island = bounds_of("shell/islands/sidebar").or_else(|| bounds_of(CALENDAR));
1051 if let (Some(rail), Some(island)) = (bounds_of("shell/islands/rail"), first_island) {
1052 let gap = f32::from(island.origin.x) - f32::from(rail.origin.x + rail.size.width);
1050 let first_island =
1051 bounds_of("shell/islands/sidebar").or_else(|| bounds_of(CALENDAR));
1052 if let (Some(rail), Some(island)) = (bounds_of("shell/islands/rail"), first_island)
1053 {
1054 let gap =
1055 f32::from(island.origin.x) - f32::from(rail.origin.x + rail.size.width);
1053 1056 if gap.abs() > 0.5 {
1054 1057 found.push((
1055 1058 "shell/islands/rail:gap".to_owned(),
@@ -1169,20 +1172,38 @@ mod frames {
1169 1172 visual.simulate_resize(size(px(760.), px(700.)));
1170 1173 collect(&mut visual, Some(COMPOSER_STACKED_ACTIONS_TAG));
1171 1174 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
1172 visual.debug_bounds(path).unwrap_or_else(|| panic!("{path} missing"))
1175 visual
1176 .debug_bounds(path)
1177 .unwrap_or_else(|| panic!("{path} missing"))
1173 1178 };
1174 1179 let card = bounds_of(&mut visual, COMPOSER_BOX_TAG);
1175 1180 let input = bounds_of(&mut visual, COMPOSER_INPUT_TAG);
1176 1181 let stacked = bounds_of(&mut visual, COMPOSER_STACKED_ACTIONS_TAG);
1177 1182 let send = bounds_of(&mut visual, COMPOSER_SEND_TAG);
1178 assert!(input.bottom() <= stacked.top(), "actions {} not below input {}", describe(stacked), describe(input));
1179 assert!(contains(card, stacked) && contains(stacked, send), "send {} outside {}", describe(send), describe(stacked));
1183 assert!(
1184 input.bottom() <= stacked.top(),
1185 "actions {} not below input {}",
1186 describe(stacked),
1187 describe(input)
1188 );
1189 assert!(
1190 contains(card, stacked) && contains(stacked, send),
1191 "send {} outside {}",
1192 describe(send),
1193 describe(stacked)
1194 );
1180 1195 let side = f32::from(card.right() - send.right());
1181 1196 let bottom = f32::from(card.bottom() - send.bottom());
1182 assert!((side - bottom).abs() < TOLERANCE, "send insets: side {side}, bottom {bottom}");
1197 assert!(
1198 (side - bottom).abs() < TOLERANCE,
1199 "send insets: side {side}, bottom {bottom}"
1200 );
1183 1201 visual.simulate_resize(size(px(1280.), px(800.)));
1184 1202 collect(&mut visual, Some(COMPOSER_SEND_TAG));
1185 assert!(visual.debug_bounds(COMPOSER_STACKED_ACTIONS_TAG).is_none(), "wide composer stacked");
1203 assert!(
1204 visual.debug_bounds(COMPOSER_STACKED_ACTIONS_TAG).is_none(),
1205 "wide composer stacked"
1206 );
1186 1207 }
1187 1208
1188 1209 const TITLE_SEARCH: &str = "shell/title-bar/search";
@@ -1511,7 +1532,10 @@ mod frames {
1511 1532
1512 1533 // Not a platform assertion: on macOS the camera effects worker schedules onto
1513 1534 // the deterministic test scheduler while this dialog is open.
1514 #[cfg_attr(target_os = "macos", ignore = "camera effects thread trips the test scheduler")]
1535 #[cfg_attr(
1536 target_os = "macos",
1537 ignore = "camera effects thread trips the test scheduler"
1538 )]
1515 1539 #[gpui_kit::test]
1516 1540 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1517 1541 check_settings_dialog(cx, &SETTINGS_SECTIONS);
@@ -1711,7 +1735,10 @@ mod frames {
1711 1735 .expect("group name button rendered");
1712 1736 visual.simulate_click(button.center(), Default::default());
1713 1737 collect(&mut visual, Some(GROUP_NAME_FORM));
1714 assert!(visual.debug_bounds(GROUP_NAME_FORM).is_some(), "group name form open");
1738 assert!(
1739 visual.debug_bounds(GROUP_NAME_FORM).is_some(),
1740 "group name form open"
1741 );
1715 1742 visual.simulate_keystrokes("backspace x space y enter");
1716 1743 visual.run_until_parked();
1717 1744 let title = visual.update(|_, cx| {
@@ -2340,8 +2367,13 @@ mod frames {
2340 2367 let toggle = visual
2341 2368 .debug_bounds(POST_ANNOUNCEMENT_TOGGLE_TAG)
2342 2369 .expect("announcement toggle in the format bar");
2343 let format_bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("format bar");
2344 assert!(format_bar.contains(&toggle.center()), "toggle outside the format bar");
2370 let format_bar = visual
2371 .debug_bounds(COMPOSER_FORMAT_BAR_TAG)
2372 .expect("format bar");
2373 assert!(
2374 format_bar.contains(&toggle.center()),
2375 "toggle outside the format bar"
2376 );
2345 2377 visual.simulate_click(toggle.center(), Default::default());
2346 2378 collect(&mut visual, Some(POST_ANNOUNCEMENT_TAG));
2347 2379 let mut bounds_of = |path: &'static str| {
@@ -2357,10 +2389,16 @@ mod frames {
2357 2389 let gap = f32::from(subject.top() - banner.bottom());
2358 2390 assert!(gap >= 6., "subheading {gap} px under the banner");
2359 2391 let audience = bounds_of(POST_AUDIENCE_TAG);
2360 assert!(audience.bottom() <= card.top(), "audience hint not above the card");
2392 assert!(
2393 audience.bottom() <= card.top(),
2394 "audience hint not above the card"
2395 );
2361 2396 let left = f32::from(banner.left() - card.left());
2362 2397 let right = f32::from(card.right() - banner.right());
2363 assert!((left - right).abs() < TOLERANCE, "banner insets: left {left}, right {right}");
2398 assert!(
2399 (left - right).abs() < TOLERANCE,
2400 "banner insets: left {left}, right {right}"
2401 );
2364 2402 }
2365 2403
2366 2404 #[gpui_kit::test]
@@ -2378,8 +2416,14 @@ mod frames {
2378 2416 let side = f32::from(avatar.left() - card.left());
2379 2417 let checks = [
2380 2418 ("body left", f32::from(body.left() - avatar.left())),
2381 ("footer avatar left", f32::from(footer_avatar.left() - avatar.left())),
2382 ("body right inset", f32::from(card.right() - body.right()) - side),
2419 (
2420 "footer avatar left",
2421 f32::from(footer_avatar.left() - avatar.left()),
2422 ),
2423 (
2424 "body right inset",
2425 f32::from(card.right() - body.right()) - side,
2426 ),
2383 2427 ];
2384 2428 for (name, gap) in checks {
2385 2429 assert!(
@@ -172,46 +172,46 @@ mod frames {
172 use crate::app_state::{AppHandle, AppState, Mode, Selection};
172 use crate::app_state::{AppHandle, AppState, Mode, Selection};
173 use crate::call::{ActiveCall, CallModel, ConsultCall};
173 use crate::call::{ActiveCall, CallModel, ConsultCall};
174 use crate::demo;
174 use crate::demo;
175 use crate::render::{CODE_BLOCK_TAG, CODE_LINE_TAG};
175 use crate::settings::select_selector;
176 use crate::settings::select_selector;
176 use crate::settings::{item_selector, label, label_selector, metrics};
177 use crate::settings::{item_selector, label, label_selector, metrics};
177 use crate::settings_section::SettingsSection;
178 use crate::settings_section::SettingsSection;
178 use crate::user_activity::UserInput;
179 use crate::user_activity::UserInput;
180 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
179 use crate::views::call_transcript::TranscriptPanel;
181 use crate::views::call_transcript::TranscriptPanel;
180 use crate::views::call_view::CHAT_PANEL_TAG;
182 use crate::views::call_view::CHAT_PANEL_TAG;
181 use crate::views::composer::delivery::{
183 use crate::views::composer::delivery::{
182 COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG,
184 COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG, DELIVERY_MENU_TAG,
183 DELIVERY_MENU_TAG,
184 };
185 };
185 use crate::views::composer::plus_menu::{COMPOSER_PLUS_TAG, PlusAction};
186 use crate::views::composer::plus_menu::{COMPOSER_PLUS_TAG, PlusAction};
186 use crate::views::composer::{
187 use crate::views::composer::{
187 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
188 COMPOSER_ACTIONS_TAG, COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG,
188 COMPOSER_ACTIONS_TAG, COMPOSER_FORMAT_TAG, COMPOSER_INPUT_TAG, COMPOSER_SEND_TAG, COMPOSER_STACKED_ACTIONS_TAG,
189 COMPOSER_FORMAT_DIVIDER_TAG, COMPOSER_FORMAT_TAG, COMPOSER_INPUT_TAG, COMPOSER_SEND_TAG,
189 POST_ANNOUNCEMENT_TAG, POST_ANNOUNCEMENT_TOGGLE_TAG, POST_AUDIENCE_TAG, POST_CARD_DIVIDER_TAG, POST_CARD_FOOTER_TAG, POST_CARD_HEADER_TAG, POST_CARD_SEND_TAG,
190 COMPOSER_STACKED_ACTIONS_TAG, POST_ANNOUNCEMENT_TAG, POST_ANNOUNCEMENT_TOGGLE_TAG,
190 POST_CARD_SUBJECT_TAG,
191 POST_AUDIENCE_TAG, POST_CARD_DIVIDER_TAG, POST_CARD_FOOTER_TAG, POST_CARD_HEADER_TAG,
192 POST_CARD_SEND_TAG, POST_CARD_SUBJECT_TAG,
191 };
193 };
192 use crate::views::call_window::CALL_WINDOW_TAG;
194 use crate::views::call_window::CALL_WINDOW_TAG;
193 use crate::views::conversation::{
195 use crate::views::conversation::{
194 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
196 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
195 CHANNEL_DETAILS_TAG,
197 CHANNEL_DETAILS_TAG,
196 };
198 };
197 use crate::render::{CODE_BLOCK_TAG, CODE_LINE_TAG};
198 use crate::views::conversation::{
199 use crate::views::conversation::{
199 FEED_EDGE_TAG, FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG,
200 FEED_EDGE_TAG, FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG,
200 FORWARD_FOOTER_TAG, HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG,
201 FORWARD_FOOTER_TAG, HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG,
201 };
202 };
202 use crate::views::group_name::{GROUP_NAME_BUTTON, GROUP_NAME_FORM};
203 use crate::views::post_card::{
204 POST_AVATAR_TAG, POST_BODY_TAG, POST_CARD_TAG, POST_FOOTER_AVATAR_TAG,
205 };
206 use crate::views::find_panel::{
203 use crate::views::find_panel::{
207 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
204 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
208 };
205 };
209 use crate::views::forward_dialog::{FORWARD_CARD_TAG, FORWARD_PREVIEW_TAG};
206 use crate::views::forward_dialog::{FORWARD_CARD_TAG, FORWARD_PREVIEW_TAG};
207 use crate::views::group_name::{GROUP_NAME_BUTTON, GROUP_NAME_FORM};
210 use crate::views::message_row::{
208 use crate::views::message_row::{
211 BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y, select_box_selector,
209 BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y, select_box_selector,
212 };
210 };
213 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
211 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
214 use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
212 use crate::views::post_card::{
213 POST_AVATAR_TAG, POST_BODY_TAG, POST_CARD_TAG, POST_FOOTER_AVATAR_TAG,
214 };
215 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
215 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
216 use crate::views::reaction_proposal_pill::REACTION_PILL;
216 use crate::views::reaction_proposal_pill::REACTION_PILL;
217 use crate::views::recap_tab::RECAP_REGION;
217 use crate::views::recap_tab::RECAP_REGION;
@@ -219,14 +219,14 @@ mod frames {
219 AppShell, Startup, bind_keys, install_globals,
219 AppShell, Startup, bind_keys, install_globals,
220 };
220 };
221 use crate::views::shortcuts::{
221 use crate::views::shortcuts::{
222 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
222 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCalendar,
223 OpenCalendar, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
223 OpenCallsTab, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
224 };
224 };
225 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
225 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
226 use crate::views::sidebar::chat_row_selector;
227 use crate::views::sidebar::chat_filter_bar::{
226 use crate::views::sidebar::chat_filter_bar::{
228 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
227 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
229 };
228 };
229 use crate::views::sidebar::chat_row_selector;
230 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
230 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
231 use crate::views::widgets::{
231 use crate::views::widgets::{
232 COUNT_BADGE, RAIL_BADGE, badge_ink_centre, badge_pill, badge_selector, badge_text_origin,
232 COUNT_BADGE, RAIL_BADGE, badge_ink_centre, badge_pill, badge_selector, badge_text_origin,
@@ -1047,9 +1047,12 @@ mod frames {
1047 .find(|(path, _)| *path == wanted)
1047 .find(|(path, _)| *path == wanted)
1048 .map(|(_, bounds)| *bounds)
1048 .map(|(_, bounds)| *bounds)
1049 };
1049 };
1050 let first_island = bounds_of("shell/islands/sidebar").or_else(|| bounds_of(CALENDAR));
1050 let first_island =
1051 if let (Some(rail), Some(island)) = (bounds_of("shell/islands/rail"), first_island) {
1051 bounds_of("shell/islands/sidebar").or_else(|| bounds_of(CALENDAR));
1052 let gap = f32::from(island.origin.x) - f32::from(rail.origin.x + rail.size.width);
1052 if let (Some(rail), Some(island)) = (bounds_of("shell/islands/rail"), first_island)
1053 {
1054 let gap =
1055 f32::from(island.origin.x) - f32::from(rail.origin.x + rail.size.width);
1053 if gap.abs() > 0.5 {
1056 if gap.abs() > 0.5 {
1054 found.push((
1057 found.push((
1055 "shell/islands/rail:gap".to_owned(),
1058 "shell/islands/rail:gap".to_owned(),
@@ -1169,20 +1172,38 @@ mod frames {
1169 visual.simulate_resize(size(px(760.), px(700.)));
1172 visual.simulate_resize(size(px(760.), px(700.)));
1170 collect(&mut visual, Some(COMPOSER_STACKED_ACTIONS_TAG));
1173 collect(&mut visual, Some(COMPOSER_STACKED_ACTIONS_TAG));
1171 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
1174 let bounds_of = |visual: &mut VisualTestContext, path: &'static str| {
1172 visual.debug_bounds(path).unwrap_or_else(|| panic!("{path} missing"))
1175 visual
1176 .debug_bounds(path)
1177 .unwrap_or_else(|| panic!("{path} missing"))
1173 };
1178 };
1174 let card = bounds_of(&mut visual, COMPOSER_BOX_TAG);
1179 let card = bounds_of(&mut visual, COMPOSER_BOX_TAG);
1175 let input = bounds_of(&mut visual, COMPOSER_INPUT_TAG);
1180 let input = bounds_of(&mut visual, COMPOSER_INPUT_TAG);
1176 let stacked = bounds_of(&mut visual, COMPOSER_STACKED_ACTIONS_TAG);
1181 let stacked = bounds_of(&mut visual, COMPOSER_STACKED_ACTIONS_TAG);
1177 let send = bounds_of(&mut visual, COMPOSER_SEND_TAG);
1182 let send = bounds_of(&mut visual, COMPOSER_SEND_TAG);
1178 assert!(input.bottom() <= stacked.top(), "actions {} not below input {}", describe(stacked), describe(input));
1183 assert!(
1179 assert!(contains(card, stacked) && contains(stacked, send), "send {} outside {}", describe(send), describe(stacked));
1184 input.bottom() <= stacked.top(),
1185 "actions {} not below input {}",
1186 describe(stacked),
1187 describe(input)
1188 );
1189 assert!(
1190 contains(card, stacked) && contains(stacked, send),
1191 "send {} outside {}",
1192 describe(send),
1193 describe(stacked)
1194 );
1180 let side = f32::from(card.right() - send.right());
1195 let side = f32::from(card.right() - send.right());
1181 let bottom = f32::from(card.bottom() - send.bottom());
1196 let bottom = f32::from(card.bottom() - send.bottom());
1182 assert!((side - bottom).abs() < TOLERANCE, "send insets: side {side}, bottom {bottom}");
1197 assert!(
1198 (side - bottom).abs() < TOLERANCE,
1199 "send insets: side {side}, bottom {bottom}"
1200 );
1183 visual.simulate_resize(size(px(1280.), px(800.)));
1201 visual.simulate_resize(size(px(1280.), px(800.)));
1184 collect(&mut visual, Some(COMPOSER_SEND_TAG));
1202 collect(&mut visual, Some(COMPOSER_SEND_TAG));
1185 assert!(visual.debug_bounds(COMPOSER_STACKED_ACTIONS_TAG).is_none(), "wide composer stacked");
1203 assert!(
1204 visual.debug_bounds(COMPOSER_STACKED_ACTIONS_TAG).is_none(),
1205 "wide composer stacked"
1206 );
1186 }
1207 }
1187
1208
1188 const TITLE_SEARCH: &str = "shell/title-bar/search";
1209 const TITLE_SEARCH: &str = "shell/title-bar/search";
@@ -1511,7 +1532,10 @@ mod frames {
1511
1532
1512 // Not a platform assertion: on macOS the camera effects worker schedules onto
1533 // Not a platform assertion: on macOS the camera effects worker schedules onto
1513 // the deterministic test scheduler while this dialog is open.
1534 // the deterministic test scheduler while this dialog is open.
1514 #[cfg_attr(target_os = "macos", ignore = "camera effects thread trips the test scheduler")]
1535 #[cfg_attr(
1536 target_os = "macos",
1537 ignore = "camera effects thread trips the test scheduler"
1538 )]
1515 #[gpui_kit::test]
1539 #[gpui_kit::test]
1516 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1540 fn settings_dialog_keeps_its_inset_at_every_size(cx: &mut TestAppContext) {
1517 check_settings_dialog(cx, &SETTINGS_SECTIONS);
1541 check_settings_dialog(cx, &SETTINGS_SECTIONS);
@@ -1711,7 +1735,10 @@ mod frames {
1711 .expect("group name button rendered");
1735 .expect("group name button rendered");
1712 visual.simulate_click(button.center(), Default::default());
1736 visual.simulate_click(button.center(), Default::default());
1713 collect(&mut visual, Some(GROUP_NAME_FORM));
1737 collect(&mut visual, Some(GROUP_NAME_FORM));
1714 assert!(visual.debug_bounds(GROUP_NAME_FORM).is_some(), "group name form open");
1738 assert!(
1739 visual.debug_bounds(GROUP_NAME_FORM).is_some(),
1740 "group name form open"
1741 );
1715 visual.simulate_keystrokes("backspace x space y enter");
1742 visual.simulate_keystrokes("backspace x space y enter");
1716 visual.run_until_parked();
1743 visual.run_until_parked();
1717 let title = visual.update(|_, cx| {
1744 let title = visual.update(|_, cx| {
@@ -2340,8 +2367,13 @@ mod frames {
2340 let toggle = visual
2367 let toggle = visual
2341 .debug_bounds(POST_ANNOUNCEMENT_TOGGLE_TAG)
2368 .debug_bounds(POST_ANNOUNCEMENT_TOGGLE_TAG)
2342 .expect("announcement toggle in the format bar");
2369 .expect("announcement toggle in the format bar");
2343 let format_bar = visual.debug_bounds(COMPOSER_FORMAT_BAR_TAG).expect("format bar");
2370 let format_bar = visual
2344 assert!(format_bar.contains(&toggle.center()), "toggle outside the format bar");
2371 .debug_bounds(COMPOSER_FORMAT_BAR_TAG)
2372 .expect("format bar");
2373 assert!(
2374 format_bar.contains(&toggle.center()),
2375 "toggle outside the format bar"
2376 );
2345 visual.simulate_click(toggle.center(), Default::default());
2377 visual.simulate_click(toggle.center(), Default::default());
2346 collect(&mut visual, Some(POST_ANNOUNCEMENT_TAG));
2378 collect(&mut visual, Some(POST_ANNOUNCEMENT_TAG));
2347 let mut bounds_of = |path: &'static str| {
2379 let mut bounds_of = |path: &'static str| {
@@ -2357,10 +2389,16 @@ mod frames {
2357 let gap = f32::from(subject.top() - banner.bottom());
2389 let gap = f32::from(subject.top() - banner.bottom());
2358 assert!(gap >= 6., "subheading {gap} px under the banner");
2390 assert!(gap >= 6., "subheading {gap} px under the banner");
2359 let audience = bounds_of(POST_AUDIENCE_TAG);
2391 let audience = bounds_of(POST_AUDIENCE_TAG);
2360 assert!(audience.bottom() <= card.top(), "audience hint not above the card");
2392 assert!(
2393 audience.bottom() <= card.top(),
2394 "audience hint not above the card"
2395 );
2361 let left = f32::from(banner.left() - card.left());
2396 let left = f32::from(banner.left() - card.left());
2362 let right = f32::from(card.right() - banner.right());
2397 let right = f32::from(card.right() - banner.right());
2363 assert!((left - right).abs() < TOLERANCE, "banner insets: left {left}, right {right}");
2398 assert!(
2399 (left - right).abs() < TOLERANCE,
2400 "banner insets: left {left}, right {right}"
2401 );
2364 }
2402 }
2365
2403
2366 #[gpui_kit::test]
2404 #[gpui_kit::test]
@@ -2378,8 +2416,14 @@ mod frames {
2378 let side = f32::from(avatar.left() - card.left());
2416 let side = f32::from(avatar.left() - card.left());
2379 let checks = [
2417 let checks = [
2380 ("body left", f32::from(body.left() - avatar.left())),
2418 ("body left", f32::from(body.left() - avatar.left())),
2381 ("footer avatar left", f32::from(footer_avatar.left() - avatar.left())),
2419 (
2382 ("body right inset", f32::from(card.right() - body.right()) - side),
2420 "footer avatar left",
2421 f32::from(footer_avatar.left() - avatar.left()),
2422 ),
2423 (
2424 "body right inset",
2425 f32::from(card.right() - body.right()) - side,
2426 ),
2383 ];
2427 ];
2384 for (name, gap) in checks {
2428 for (name, gap) in checks {
2385 assert!(
2429 assert!(
crates/app/src/main.rs +71 −69
@@ -4,7 +4,6 @@
4 4 )]
5 5
6 6 mod active_appearance;
7 mod agent_direct;
8 7 pub mod agents;
9 8 pub mod call;
10 9 mod inline_video;
@@ -170,6 +169,8 @@ fn main() {
170 169 data_path(crash_log::CRASH_LOG_FILE),
171 170 );
172 171 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
172 #[cfg(target_os = "linux")]
173 app_base::linux_fonts::hide_system_color_emoji();
173 174 let arguments = parse_arguments();
174 175 if !arguments.demo && arguments.database.is_none() {
175 176 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -225,79 +226,80 @@ fn main() {
225 226 application = application.with_http_client(Arc::new(http_client));
226 227 }
227 228
228 application.with_assets(app_base::assets::AppAssets).run(move |cx| {
229 gpui_kit::init(cx);
230 cx.on_app_quit(|_| {
231 updater::exit_after_grace();
232 async {}
233 })
234 .detach();
235 theme::load_fonts(cx);
236 active_appearance::install(&store, cx);
237 theme::apply(cx);
238 bind_keys(cx);
239 let state = cx.new(|_| {
240 let mut state = AppState::new(store, mode);
241 state.start_on_channels = arguments.channels_tab;
242 state
243 });
244 views::shell::install_globals(&state, user_input, cx);
245 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
246 agents::install(state.clone(), cx);
247 agent_direct::install(state.clone(), cx);
248 if arguments.demo {
249 demo::start_session(&state, cx);
250 }
251 if let Some(mut receiver) = receiver {
252 let state = state.clone();
253 cx.spawn(async move |cx| {
254 while let Some(event) = receiver.recv().await {
255 let kind = event.kind();
256 let started = std::time::Instant::now();
257 state.update(cx, |state, cx| state.apply(event, cx));
258 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
259 }
229 application
230 .with_assets(app_base::assets::AppAssets)
231 .run(move |cx| {
232 gpui_kit::init(cx);
233 cx.on_app_quit(|_| {
234 updater::exit_after_grace();
235 async {}
260 236 })
261 237 .detach();
262 }
238 theme::load_fonts(cx);
239 active_appearance::install(&store, cx);
240 theme::apply(cx);
241 bind_keys(cx);
242 let state = cx.new(|_| {
243 let mut state = AppState::new(store, mode);
244 state.start_on_channels = arguments.channels_tab;
245 state
246 });
247 views::shell::install_globals(&state, user_input, cx);
248 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
249 agents::install(state.clone(), cx);
250 if arguments.demo {
251 demo::start_session(&state, cx);
252 }
253 if let Some(mut receiver) = receiver {
254 let state = state.clone();
255 cx.spawn(async move |cx| {
256 while let Some(event) = receiver.recv().await {
257 let kind = event.kind();
258 let started = std::time::Instant::now();
259 state.update(cx, |state, cx| state.apply(event, cx));
260 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
261 }
262 })
263 .detach();
264 }
263 265
264 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
265 let mut options = TitleBar::window_options();
266 options.window_bounds = Some(WindowBounds::Windowed(bounds));
267 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
268 options.app_id = Some(LINUX_APP_ID.to_owned());
269 if let Some(titlebar) = options.titlebar.as_mut() {
270 titlebar.title = Some(APP_NAME.into());
271 }
272 let open_target = arguments.open_target;
273 let startup = Startup {
274 switcher_query: arguments.switcher_query,
275 composer_text: arguments.composer_text,
276 reply_to_last: arguments.reply_to_last,
277 launched_by_autostart: arguments.autostart,
278 };
279 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
280 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
281 })
282 .expect("failed to open window");
283 let main_window_id = main_window.window_id();
284 cx.on_window_closed(move |cx, closed| {
285 if closed == main_window_id {
286 cx.quit();
266 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
267 let mut options = TitleBar::window_options();
268 options.window_bounds = Some(WindowBounds::Windowed(bounds));
269 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
270 options.app_id = Some(LINUX_APP_ID.to_owned());
271 if let Some(titlebar) = options.titlebar.as_mut() {
272 titlebar.title = Some(APP_NAME.into());
287 273 }
288 })
289 .detach();
290 if !arguments.autostart {
291 cx.activate(true);
292 }
293 cx.spawn(async move |cx| {
294 loop {
295 app_base::native_dumps::heartbeat();
296 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
274 let open_target = arguments.open_target;
275 let startup = Startup {
276 switcher_query: arguments.switcher_query,
277 composer_text: arguments.composer_text,
278 reply_to_last: arguments.reply_to_last,
279 launched_by_autostart: arguments.autostart,
280 };
281 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
282 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
283 })
284 .expect("failed to open window");
285 let main_window_id = main_window.window_id();
286 cx.on_window_closed(move |cx, closed| {
287 if closed == main_window_id {
288 cx.quit();
289 }
290 })
291 .detach();
292 if !arguments.autostart {
293 cx.activate(true);
297 294 }
298 })
299 .detach();
300 });
295 cx.spawn(async move |cx| {
296 loop {
297 app_base::native_dumps::heartbeat();
298 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
299 }
300 })
301 .detach();
302 });
301 303 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
302 304 #[cfg(windows)]
303 305 updater::exit_now();
@@ -4,7 +4,6 @@
4)]
4)]
5
5
6mod active_appearance;
6mod active_appearance;
7mod agent_direct;
8pub mod agents;
7pub mod agents;
9pub mod call;
8pub mod call;
10mod inline_video;
9mod inline_video;
@@ -170,6 +169,8 @@ fn main() {
170 data_path(crash_log::CRASH_LOG_FILE),
169 data_path(crash_log::CRASH_LOG_FILE),
171 );
170 );
172 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
171 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
172 #[cfg(target_os = "linux")]
173 app_base::linux_fonts::hide_system_color_emoji();
173 let arguments = parse_arguments();
174 let arguments = parse_arguments();
174 if !arguments.demo && arguments.database.is_none() {
175 if !arguments.demo && arguments.database.is_none() {
175 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
176 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -225,79 +226,80 @@ fn main() {
225 application = application.with_http_client(Arc::new(http_client));
226 application = application.with_http_client(Arc::new(http_client));
226 }
227 }
227
228
228 application.with_assets(app_base::assets::AppAssets).run(move |cx| {
229 application
229 gpui_kit::init(cx);
230 .with_assets(app_base::assets::AppAssets)
230 cx.on_app_quit(|_| {
231 .run(move |cx| {
231 updater::exit_after_grace();
232 gpui_kit::init(cx);
232 async {}
233 cx.on_app_quit(|_| {
233 })
234 updater::exit_after_grace();
234 .detach();
235 async {}
235 theme::load_fonts(cx);
236 active_appearance::install(&store, cx);
237 theme::apply(cx);
238 bind_keys(cx);
239 let state = cx.new(|_| {
240 let mut state = AppState::new(store, mode);
241 state.start_on_channels = arguments.channels_tab;
242 state
243 });
244 views::shell::install_globals(&state, user_input, cx);
245 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
246 agents::install(state.clone(), cx);
247 agent_direct::install(state.clone(), cx);
248 if arguments.demo {
249 demo::start_session(&state, cx);
250 }
251 if let Some(mut receiver) = receiver {
252 let state = state.clone();
253 cx.spawn(async move |cx| {
254 while let Some(event) = receiver.recv().await {
255 let kind = event.kind();
256 let started = std::time::Instant::now();
257 state.update(cx, |state, cx| state.apply(event, cx));
258 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
259 }
260 })
236 })
261 .detach();
237 .detach();
262 }
238 theme::load_fonts(cx);
239 active_appearance::install(&store, cx);
240 theme::apply(cx);
241 bind_keys(cx);
242 let state = cx.new(|_| {
243 let mut state = AppState::new(store, mode);
244 state.start_on_channels = arguments.channels_tab;
245 state
246 });
247 views::shell::install_globals(&state, user_input, cx);
248 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
249 agents::install(state.clone(), cx);
250 if arguments.demo {
251 demo::start_session(&state, cx);
252 }
253 if let Some(mut receiver) = receiver {
254 let state = state.clone();
255 cx.spawn(async move |cx| {
256 while let Some(event) = receiver.recv().await {
257 let kind = event.kind();
258 let started = std::time::Instant::now();
259 state.update(cx, |state, cx| state.apply(event, cx));
260 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
261 }
262 })
263 .detach();
264 }
263
265
264 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
266 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
265 let mut options = TitleBar::window_options();
267 let mut options = TitleBar::window_options();
266 options.window_bounds = Some(WindowBounds::Windowed(bounds));
268 options.window_bounds = Some(WindowBounds::Windowed(bounds));
267 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
269 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
268 options.app_id = Some(LINUX_APP_ID.to_owned());
270 options.app_id = Some(LINUX_APP_ID.to_owned());
269 if let Some(titlebar) = options.titlebar.as_mut() {
271 if let Some(titlebar) = options.titlebar.as_mut() {
270 titlebar.title = Some(APP_NAME.into());
272 titlebar.title = Some(APP_NAME.into());
271 }
272 let open_target = arguments.open_target;
273 let startup = Startup {
274 switcher_query: arguments.switcher_query,
275 composer_text: arguments.composer_text,
276 reply_to_last: arguments.reply_to_last,
277 launched_by_autostart: arguments.autostart,
278 };
279 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
280 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
281 })
282 .expect("failed to open window");
283 let main_window_id = main_window.window_id();
284 cx.on_window_closed(move |cx, closed| {
285 if closed == main_window_id {
286 cx.quit();
287 }
273 }
288 })
274 let open_target = arguments.open_target;
289 .detach();
275 let startup = Startup {
290 if !arguments.autostart {
276 switcher_query: arguments.switcher_query,
291 cx.activate(true);
277 composer_text: arguments.composer_text,
292 }
278 reply_to_last: arguments.reply_to_last,
293 cx.spawn(async move |cx| {
279 launched_by_autostart: arguments.autostart,
294 loop {
280 };
295 app_base::native_dumps::heartbeat();
281 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
296 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
282 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
283 })
284 .expect("failed to open window");
285 let main_window_id = main_window.window_id();
286 cx.on_window_closed(move |cx, closed| {
287 if closed == main_window_id {
288 cx.quit();
289 }
290 })
291 .detach();
292 if !arguments.autostart {
293 cx.activate(true);
297 }
294 }
298 })
295 cx.spawn(async move |cx| {
299 .detach();
296 loop {
300 });
297 app_base::native_dumps::heartbeat();
298 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
299 }
300 })
301 .detach();
302 });
301 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
303 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
302 #[cfg(windows)]
304 #[cfg(windows)]
303 updater::exit_now();
305 updater::exit_now();
crates/app/src/notify/agent_toast.rs +2 −1
@@ -116,7 +116,8 @@ pub(super) fn agent_toast_content(
116 116 .text_size(px(PREVIEW_SIZE))
117 117 .line_height(px(18.))
118 118 .text_color(theme::text_soft())
119 .line_clamp(PREVIEW_MAX_LINES).text_ellipsis()
119 .line_clamp(PREVIEW_MAX_LINES)
120 .text_ellipsis()
120 121 .child(agent.body.clone()),
121 122 )
122 123 .child(
@@ -116,7 +116,8 @@ pub(super) fn agent_toast_content(
116 .text_size(px(PREVIEW_SIZE))
116 .text_size(px(PREVIEW_SIZE))
117 .line_height(px(18.))
117 .line_height(px(18.))
118 .text_color(theme::text_soft())
118 .text_color(theme::text_soft())
119 .line_clamp(PREVIEW_MAX_LINES).text_ellipsis()
119 .line_clamp(PREVIEW_MAX_LINES)
120 .text_ellipsis()
120 .child(agent.body.clone()),
121 .child(agent.body.clone()),
121 )
122 )
122 .child(
123 .child(
crates/app/src/notify/center.rs +15 −7
@@ -33,8 +33,8 @@ use crate::activity::ActivityCenter;
33 33 use crate::agent_api::{self, pending::PendingProposal};
34 34 use crate::agents::{AgentRun, AgentRunsEvent, RunState};
35 35 use crate::app_state::{AppEvent, AppState, selection_for};
36 use crate::autostart::{self, StartupSettings};
37 36 use crate::appearance::AppIcon;
37 use crate::autostart::{self, StartupSettings};
38 38 use crate::call::DemoScene;
39 39 use crate::data::{self, Directory, PresenceKind};
40 40 use crate::runtime;
@@ -289,7 +289,11 @@ impl NotificationCenter {
289 289 && let Err(error) = autostart::set_enabled(crate::APP_NAME, enabled)
290 290 {
291 291 self.app.update(cx, |state, cx| {
292 state.raise_notice(format!("Auto-start could not be changed: {error}"), None, cx)
292 state.raise_notice(
293 format!("Auto-start could not be changed: {error}"),
294 None,
295 cx,
296 )
293 297 });
294 298 return;
295 299 }
@@ -539,11 +543,14 @@ impl NotificationCenter {
539 543 .find(|person| person.user_id == user_id)
540 544 .map(|person| person.name.clone())
541 545 .unwrap_or_default();
542 (name, state.one_on_one_chat_with(user_id).unwrap_or_default())
546 (
547 name,
548 state.one_on_one_chat_with(user_id).unwrap_or_default(),
549 )
543 550 };
544 let id = self
545 .stack
546 .push_status_change(user_id, &name, text, &conversation_id, Instant::now());
551 let id =
552 self.stack
553 .push_status_change(user_id, &name, text, &conversation_id, Instant::now());
547 554 if let Some(model) = self.stack.get_mut(id) {
548 555 model.time = chrono::Local::now()
549 556 .format(crate::format::clock_format())
@@ -1153,7 +1160,8 @@ impl NotificationCenter {
1153 1160
1154 1161 pub fn accept_ring(&mut self, ring_id: u64, mode: calling::AcceptMode, cx: &mut Context<Self>) {
1155 1162 self.raise_main_window(cx);
1156 self.app.update(cx, |state, cx| state.accept_ring(ring_id, mode, cx));
1163 self.app
1164 .update(cx, |state, cx| state.accept_ring(ring_id, mode, cx));
1157 1165 }
1158 1166
1159 1167 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
@@ -33,8 +33,8 @@ use crate::activity::ActivityCenter;
33use crate::agent_api::{self, pending::PendingProposal};
33use crate::agent_api::{self, pending::PendingProposal};
34use crate::agents::{AgentRun, AgentRunsEvent, RunState};
34use crate::agents::{AgentRun, AgentRunsEvent, RunState};
35use crate::app_state::{AppEvent, AppState, selection_for};
35use crate::app_state::{AppEvent, AppState, selection_for};
36use crate::autostart::{self, StartupSettings};
37use crate::appearance::AppIcon;
36use crate::appearance::AppIcon;
37use crate::autostart::{self, StartupSettings};
38use crate::call::DemoScene;
38use crate::call::DemoScene;
39use crate::data::{self, Directory, PresenceKind};
39use crate::data::{self, Directory, PresenceKind};
40use crate::runtime;
40use crate::runtime;
@@ -289,7 +289,11 @@ impl NotificationCenter {
289 && let Err(error) = autostart::set_enabled(crate::APP_NAME, enabled)
289 && let Err(error) = autostart::set_enabled(crate::APP_NAME, enabled)
290 {
290 {
291 self.app.update(cx, |state, cx| {
291 self.app.update(cx, |state, cx| {
292 state.raise_notice(format!("Auto-start could not be changed: {error}"), None, cx)
292 state.raise_notice(
293 format!("Auto-start could not be changed: {error}"),
294 None,
295 cx,
296 )
293 });
297 });
294 return;
298 return;
295 }
299 }
@@ -539,11 +543,14 @@ impl NotificationCenter {
539 .find(|person| person.user_id == user_id)
543 .find(|person| person.user_id == user_id)
540 .map(|person| person.name.clone())
544 .map(|person| person.name.clone())
541 .unwrap_or_default();
545 .unwrap_or_default();
542 (name, state.one_on_one_chat_with(user_id).unwrap_or_default())
546 (
547 name,
548 state.one_on_one_chat_with(user_id).unwrap_or_default(),
549 )
543 };
550 };
544 let id = self
551 let id =
545 .stack
552 self.stack
546 .push_status_change(user_id, &name, text, &conversation_id, Instant::now());
553 .push_status_change(user_id, &name, text, &conversation_id, Instant::now());
547 if let Some(model) = self.stack.get_mut(id) {
554 if let Some(model) = self.stack.get_mut(id) {
548 model.time = chrono::Local::now()
555 model.time = chrono::Local::now()
549 .format(crate::format::clock_format())
556 .format(crate::format::clock_format())
@@ -1153,7 +1160,8 @@ impl NotificationCenter {
1153
1160
1154 pub fn accept_ring(&mut self, ring_id: u64, mode: calling::AcceptMode, cx: &mut Context<Self>) {
1161 pub fn accept_ring(&mut self, ring_id: u64, mode: calling::AcceptMode, cx: &mut Context<Self>) {
1155 self.raise_main_window(cx);
1162 self.raise_main_window(cx);
1156 self.app.update(cx, |state, cx| state.accept_ring(ring_id, mode, cx));
1163 self.app
1164 .update(cx, |state, cx| state.accept_ring(ring_id, mode, cx));
1157 }
1165 }
1158
1166
1159 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
1167 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
crates/app/src/notify/meeting_view.rs +11 −5
@@ -81,11 +81,17 @@ impl Render for MeetingToastView {
81 81 cx.stop_propagation();
82 82 dismiss_app.update(cx, |state, cx| state.dismiss_meeting_toast(toast_id, cx));
83 83 });
84 let join = answer_button("meeting-join", "Join", IconName::Video, theme::accent(), theme::on_accent())
85 .on_click(move |_, _, cx| {
86 cx.stop_propagation();
87 join_center.update(cx, |center, cx| center.join_meeting_toast(toast_id, cx));
88 });
84 let join = answer_button(
85 "meeting-join",
86 "Join",
87 IconName::Video,
88 theme::accent(),
89 theme::on_accent(),
90 )
91 .on_click(move |_, _, cx| {
92 cx.stop_propagation();
93 join_center.update(cx, |center, cx| center.join_meeting_toast(toast_id, cx));
94 });
89 95 let live = toast.phase == ReminderPhase::Live;
90 96 let buttons = if toast.phase == ReminderPhase::Soon {
91 97 h_flex().mt(px(8.)).gap(px(6.)).child(snooze).child(join)
@@ -81,11 +81,17 @@ impl Render for MeetingToastView {
81 cx.stop_propagation();
81 cx.stop_propagation();
82 dismiss_app.update(cx, |state, cx| state.dismiss_meeting_toast(toast_id, cx));
82 dismiss_app.update(cx, |state, cx| state.dismiss_meeting_toast(toast_id, cx));
83 });
83 });
84 let join = answer_button("meeting-join", "Join", IconName::Video, theme::accent(), theme::on_accent())
84 let join = answer_button(
85 .on_click(move |_, _, cx| {
85 "meeting-join",
86 cx.stop_propagation();
86 "Join",
87 join_center.update(cx, |center, cx| center.join_meeting_toast(toast_id, cx));
87 IconName::Video,
88 });
88 theme::accent(),
89 theme::on_accent(),
90 )
91 .on_click(move |_, _, cx| {
92 cx.stop_propagation();
93 join_center.update(cx, |center, cx| center.join_meeting_toast(toast_id, cx));
94 });
89 let live = toast.phase == ReminderPhase::Live;
95 let live = toast.phase == ReminderPhase::Live;
90 let buttons = if toast.phase == ReminderPhase::Soon {
96 let buttons = if toast.phase == ReminderPhase::Soon {
91 h_flex().mt(px(8.)).gap(px(6.)).child(snooze).child(join)
97 h_flex().mt(px(8.)).gap(px(6.)).child(snooze).child(join)
crates/app/src/notify/mod.rs +1 −1
@@ -4,5 +4,5 @@ mod meeting_view;
4 4 mod ring_view;
5 5 mod toast;
6 6
7 pub use state::notify::*;
8 7 pub use center::NotificationCenter;
8 pub use state::notify::*;
@@ -4,5 +4,5 @@ mod meeting_view;
4mod ring_view;
4mod ring_view;
5mod toast;
5mod toast;
6
6
7pub use state::notify::*;
8pub use center::NotificationCenter;
7pub use center::NotificationCenter;
8pub use state::notify::*;
crates/app/src/notify/ring_view.rs +17 −7
@@ -103,11 +103,17 @@ impl Render for RingView {
103 103 let ring_id = self.ring_id;
104 104 let decline_app = self.app.clone();
105 105 let accept_center = self.center.clone();
106 let decline = answer_button("ring-decline", "Decline", IconName::PhoneOff, theme::red(), theme::white())
107 .on_click(move |_, _, cx| {
108 cx.stop_propagation();
109 decline_app.update(cx, |state, cx| state.decline_ring(ring_id, cx));
110 });
106 let decline = answer_button(
107 "ring-decline",
108 "Decline",
109 IconName::PhoneOff,
110 theme::red(),
111 theme::white(),
112 )
113 .on_click(move |_, _, cx| {
114 cx.stop_propagation();
115 decline_app.update(cx, |state, cx| state.decline_ring(ring_id, cx));
116 });
111 117 let accept = answer_button(
112 118 "ring-accept",
113 119 entry.accept_label(),
@@ -117,7 +123,9 @@ impl Render for RingView {
117 123 )
118 124 .on_click(move |_, _, cx| {
119 125 cx.stop_propagation();
120 accept_center.update(cx, |center, cx| center.accept_ring(ring_id, AcceptMode::Audio, cx));
126 accept_center.update(cx, |center, cx| {
127 center.accept_ring(ring_id, AcceptMode::Audio, cx)
128 });
121 129 });
122 130 let video_center = self.center.clone();
123 131 let accept_video = entry.ring.video.then(|| {
@@ -130,7 +138,9 @@ impl Render for RingView {
130 138 )
131 139 .on_click(move |_, _, cx| {
132 140 cx.stop_propagation();
133 video_center.update(cx, |center, cx| center.accept_ring(ring_id, AcceptMode::Video, cx));
141 video_center.update(cx, |center, cx| {
142 center.accept_ring(ring_id, AcceptMode::Video, cx)
143 });
134 144 })
135 145 });
136 146 div()
@@ -103,11 +103,17 @@ impl Render for RingView {
103 let ring_id = self.ring_id;
103 let ring_id = self.ring_id;
104 let decline_app = self.app.clone();
104 let decline_app = self.app.clone();
105 let accept_center = self.center.clone();
105 let accept_center = self.center.clone();
106 let decline = answer_button("ring-decline", "Decline", IconName::PhoneOff, theme::red(), theme::white())
106 let decline = answer_button(
107 .on_click(move |_, _, cx| {
107 "ring-decline",
108 cx.stop_propagation();
108 "Decline",
109 decline_app.update(cx, |state, cx| state.decline_ring(ring_id, cx));
109 IconName::PhoneOff,
110 });
110 theme::red(),
111 theme::white(),
112 )
113 .on_click(move |_, _, cx| {
114 cx.stop_propagation();
115 decline_app.update(cx, |state, cx| state.decline_ring(ring_id, cx));
116 });
111 let accept = answer_button(
117 let accept = answer_button(
112 "ring-accept",
118 "ring-accept",
113 entry.accept_label(),
119 entry.accept_label(),
@@ -117,7 +123,9 @@ impl Render for RingView {
117 )
123 )
118 .on_click(move |_, _, cx| {
124 .on_click(move |_, _, cx| {
119 cx.stop_propagation();
125 cx.stop_propagation();
120 accept_center.update(cx, |center, cx| center.accept_ring(ring_id, AcceptMode::Audio, cx));
126 accept_center.update(cx, |center, cx| {
127 center.accept_ring(ring_id, AcceptMode::Audio, cx)
128 });
121 });
129 });
122 let video_center = self.center.clone();
130 let video_center = self.center.clone();
123 let accept_video = entry.ring.video.then(|| {
131 let accept_video = entry.ring.video.then(|| {
@@ -130,7 +138,9 @@ impl Render for RingView {
130 )
138 )
131 .on_click(move |_, _, cx| {
139 .on_click(move |_, _, cx| {
132 cx.stop_propagation();
140 cx.stop_propagation();
133 video_center.update(cx, |center, cx| center.accept_ring(ring_id, AcceptMode::Video, cx));
141 video_center.update(cx, |center, cx| {
142 center.accept_ring(ring_id, AcceptMode::Video, cx)
143 });
134 })
144 })
135 });
145 });
136 div()
146 div()
crates/app/src/notify/toast.rs +6 −2
@@ -176,7 +176,8 @@ fn highlighted_preview(text: &str, mention: bool) -> AnyElement {
176 176 .text_size(px(PREVIEW_SIZE))
177 177 .line_height(px(18.))
178 178 .text_color(theme::text())
179 .line_clamp(PREVIEW_MAX_LINES).text_ellipsis()
179 .line_clamp(PREVIEW_MAX_LINES)
180 .text_ellipsis()
180 181 .child(styled)
181 182 .into_any_element()
182 183 }
@@ -485,7 +486,10 @@ impl Render for ToastView {
485 486 let id = self.id;
486 487 let (model, preview_on) = {
487 488 let center = self.center.read(cx);
488 (center.model(id).cloned(), center.settings().account.show_preview)
489 (
490 center.model(id).cloned(),
491 center.settings().account.show_preview,
492 )
489 493 };
490 494 let Some(model) = model else {
491 495 return div().size_full().bg(theme::popup()).into_any_element();
@@ -176,7 +176,8 @@ fn highlighted_preview(text: &str, mention: bool) -> AnyElement {
176 .text_size(px(PREVIEW_SIZE))
176 .text_size(px(PREVIEW_SIZE))
177 .line_height(px(18.))
177 .line_height(px(18.))
178 .text_color(theme::text())
178 .text_color(theme::text())
179 .line_clamp(PREVIEW_MAX_LINES).text_ellipsis()
179 .line_clamp(PREVIEW_MAX_LINES)
180 .text_ellipsis()
180 .child(styled)
181 .child(styled)
181 .into_any_element()
182 .into_any_element()
182}
183}
@@ -485,7 +486,10 @@ impl Render for ToastView {
485 let id = self.id;
486 let id = self.id;
486 let (model, preview_on) = {
487 let (model, preview_on) = {
487 let center = self.center.read(cx);
488 let center = self.center.read(cx);
488 (center.model(id).cloned(), center.settings().account.show_preview)
489 (
490 center.model(id).cloned(),
491 center.settings().account.show_preview,
492 )
489 };
493 };
490 let Some(model) = model else {
494 let Some(model) = model else {
491 return div().size_full().bg(theme::popup()).into_any_element();
495 return div().size_full().bg(theme::popup()).into_any_element();
crates/app/src/settings/appearance.rs +5 −1
@@ -203,7 +203,11 @@ fn scheme_preview(palette: &Palette) -> Div {
203 203 .rounded(px(6.))
204 204 .bg(fill(palette.surface))
205 205 .child(h_flex().child(bubble(palette.bubble_other, 64.)))
206 .child(h_flex().justify_end().child(bubble(palette.bubble_own, 52.)))
206 .child(
207 h_flex()
208 .justify_end()
209 .child(bubble(palette.bubble_own, 52.)),
210 )
207 211 .child(h_flex().child(bubble(palette.bubble_other, 40.)))
208 212 .child(
209 213 h_flex()
@@ -203,7 +203,11 @@ fn scheme_preview(palette: &Palette) -> Div {
203 .rounded(px(6.))
203 .rounded(px(6.))
204 .bg(fill(palette.surface))
204 .bg(fill(palette.surface))
205 .child(h_flex().child(bubble(palette.bubble_other, 64.)))
205 .child(h_flex().child(bubble(palette.bubble_other, 64.)))
206 .child(h_flex().justify_end().child(bubble(palette.bubble_own, 52.)))
206 .child(
207 h_flex()
208 .justify_end()
209 .child(bubble(palette.bubble_own, 52.)),
210 )
207 .child(h_flex().child(bubble(palette.bubble_other, 40.)))
211 .child(h_flex().child(bubble(palette.bubble_other, 40.)))
208 .child(
212 .child(
209 h_flex()
213 h_flex()
crates/app/src/settings/calls.rs +1 −5
@@ -5,7 +5,6 @@ use super::rows::{Choice, caption, control_row, select, text_button};
5 5 use crate::notify::NotificationCenter;
6 6 use crate::notify::sounds::{Ringtone, RingtoneCallType};
7 7
8
9 8 pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {
10 9 let ringtones = center.read(cx).settings().sounds.ringtones;
11 10 let rows = RingtoneCallType::ALL
@@ -14,10 +13,7 @@ pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {
14 13 *call_type == RingtoneCallType::Regular || ringtones.get(*call_type) != Ringtone::Ring
15 14 })
16 15 .map(|call_type| ringtone_row(center, call_type, ringtones.get(call_type)));
17 v_flex()
18 .w_full()
19 .child(caption("RINGTONES"))
20 .children(rows)
16 v_flex().w_full().child(caption("RINGTONES")).children(rows)
21 17 }
22 18
23 19 fn ringtone_row(
@@ -5,7 +5,6 @@ use super::rows::{Choice, caption, control_row, select, text_button};
5use crate::notify::NotificationCenter;
5use crate::notify::NotificationCenter;
6use crate::notify::sounds::{Ringtone, RingtoneCallType};
6use crate::notify::sounds::{Ringtone, RingtoneCallType};
7
7
8
9pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {
8pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {
10 let ringtones = center.read(cx).settings().sounds.ringtones;
9 let ringtones = center.read(cx).settings().sounds.ringtones;
11 let rows = RingtoneCallType::ALL
10 let rows = RingtoneCallType::ALL
@@ -14,10 +13,7 @@ pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {
14 *call_type == RingtoneCallType::Regular || ringtones.get(*call_type) != Ringtone::Ring
13 *call_type == RingtoneCallType::Regular || ringtones.get(*call_type) != Ringtone::Ring
15 })
14 })
16 .map(|call_type| ringtone_row(center, call_type, ringtones.get(call_type)));
15 .map(|call_type| ringtone_row(center, call_type, ringtones.get(call_type)));
17 v_flex()
16 v_flex().w_full().child(caption("RINGTONES")).children(rows)
18 .w_full()
19 .child(caption("RINGTONES"))
20 .children(rows)
21}
17}
22
18
23fn ringtone_row(
19fn ringtone_row(
crates/app/src/settings/dialog.rs +10 −6
@@ -1,7 +1,7 @@
1 1 use app_ui_kit::settings_controls::PAGE_PADDING;
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 2 use gpui_kit::assets::IconName;
4 3 use gpui_kit::component::input::{Input, InputEvent, InputState};
4 use gpui_kit::component::scroll::ScrollableElement as _;
5 5 use gpui_kit::component::{h_flex, v_flex};
6 6 use gpui_kit::*;
7 7
@@ -85,11 +85,15 @@ impl SettingsDialog {
85 85 let subscriptions = [
86 86 cx.observe(&center, |_, _, cx| cx.notify()),
87 87 cx.observe(&app, |_, _, cx| cx.notify()),
88 cx.subscribe_in(&search, window, |this, _, event: &InputEvent, window, cx| {
89 if matches!(event, InputEvent::Change) {
90 this.follow_search(window, cx);
91 }
92 }),
88 cx.subscribe_in(
89 &search,
90 window,
91 |this, _, event: &InputEvent, window, cx| {
92 if matches!(event, InputEvent::Change) {
93 this.follow_search(window, cx);
94 }
95 },
96 ),
93 97 ];
94 98 let focus_handle = cx.focus_handle();
95 99 window.focus(&focus_handle, cx);
@@ -1,7 +1,7 @@
1use app_ui_kit::settings_controls::PAGE_PADDING;
1use app_ui_kit::settings_controls::PAGE_PADDING;
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::assets::IconName;
2use gpui_kit::assets::IconName;
4use gpui_kit::component::input::{Input, InputEvent, InputState};
3use gpui_kit::component::input::{Input, InputEvent, InputState};
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::*;
6use gpui_kit::*;
7
7
@@ -85,11 +85,15 @@ impl SettingsDialog {
85 let subscriptions = [
85 let subscriptions = [
86 cx.observe(&center, |_, _, cx| cx.notify()),
86 cx.observe(&center, |_, _, cx| cx.notify()),
87 cx.observe(&app, |_, _, cx| cx.notify()),
87 cx.observe(&app, |_, _, cx| cx.notify()),
88 cx.subscribe_in(&search, window, |this, _, event: &InputEvent, window, cx| {
88 cx.subscribe_in(
89 if matches!(event, InputEvent::Change) {
89 &search,
90 this.follow_search(window, cx);
90 window,
91 }
91 |this, _, event: &InputEvent, window, cx| {
92 }),
92 if matches!(event, InputEvent::Change) {
93 this.follow_search(window, cx);
94 }
95 },
96 ),
93 ];
97 ];
94 let focus_handle = cx.focus_handle();
98 let focus_handle = cx.focus_handle();
95 window.focus(&focus_handle, cx);
99 window.focus(&focus_handle, cx);
crates/app/src/settings/mcp.rs +1 −1
@@ -1,8 +1,8 @@
1 1 use std::collections::{BTreeSet, HashMap};
2 2 use std::time::Duration;
3 3
4 use gpui_kit::component::scroll::ScrollableElement as _;
5 4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::scroll::ScrollableElement as _;
6 6 use gpui_kit::component::{
7 7 ActiveTheme as _, h_flex,
8 8 input::{Input, InputEvent, InputState},
@@ -1,8 +1,8 @@
1use std::collections::{BTreeSet, HashMap};
1use std::collections::{BTreeSet, HashMap};
2use std::time::Duration;
2use std::time::Duration;
3
3
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
5use gpui_kit::component::scroll::ScrollableElement as _;
6use gpui_kit::component::{
6use gpui_kit::component::{
7 ActiveTheme as _, h_flex,
7 ActiveTheme as _, h_flex,
8 input::{Input, InputEvent, InputState},
8 input::{Input, InputEvent, InputState},
crates/app/src/settings/nav.rs +28 −21
@@ -1,5 +1,5 @@
1 use gpui_kit::component::scroll::ScrollableElement as _;
2 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 3 use gpui_kit::component::{h_flex, v_flex};
4 4 use gpui_kit::prelude::FluentBuilder as _;
5 5 use gpui_kit::*;
@@ -232,25 +232,29 @@ pub fn render_nav(
232 232 .child(NO_RESULTS),
233 233 )
234 234 })
235 .when(!rusty.is_empty(), |groups| groups.child(
236 div()
237 .debug_selector(|| "settings/nav/divider".into())
238 .w_full()
239 .h(px(1.))
240 .flex_none()
241 .mt(px(10.))
242 .bg(theme::border_strong()),
243 )
244 .child(
245 div()
246 .px(px(2. * NAV_PADDING_X))
247 .pt(px(12.))
248 .pb(px(6.))
249 .text_size(px(12.))
250 .font_weight(FontWeight::SEMIBOLD)
251 .text_color(theme::text_muted())
252 .child("RUSTY TEAMS"),
253 ).child(group(rusty))),
235 .when(!rusty.is_empty(), |groups| {
236 groups
237 .child(
238 div()
239 .debug_selector(|| "settings/nav/divider".into())
240 .w_full()
241 .h(px(1.))
242 .flex_none()
243 .mt(px(10.))
244 .bg(theme::border_strong()),
245 )
246 .child(
247 div()
248 .px(px(2. * NAV_PADDING_X))
249 .pt(px(12.))
250 .pb(px(6.))
251 .text_size(px(12.))
252 .font_weight(FontWeight::SEMIBOLD)
253 .text_color(theme::text_muted())
254 .child("RUSTY TEAMS"),
255 )
256 .child(group(rusty))
257 }),
254 258 )
255 259 .when(about_shown, |nav| {
256 260 nav.child(
@@ -326,7 +330,10 @@ mod tests {
326 330 fn every_search_term_names_a_setting_on_its_page() {
327 331 let pages = [
328 332 (SettingsSection::General, include_str!("general.rs")),
329 (SettingsSection::Notifications, include_str!("notifications.rs")),
333 (
334 SettingsSection::Notifications,
335 include_str!("notifications.rs"),
336 ),
330 337 (SettingsSection::Appearance, include_str!("appearance.rs")),
331 338 (SettingsSection::Chats, include_str!("chats.rs")),
332 339 (SettingsSection::Devices, include_str!("devices.rs")),
@@ -1,5 +1,5 @@
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
5use gpui_kit::*;
@@ -232,25 +232,29 @@ pub fn render_nav(
232 .child(NO_RESULTS),
232 .child(NO_RESULTS),
233 )
233 )
234 })
234 })
235 .when(!rusty.is_empty(), |groups| groups.child(
235 .when(!rusty.is_empty(), |groups| {
236 div()
236 groups
237 .debug_selector(|| "settings/nav/divider".into())
237 .child(
238 .w_full()
238 div()
239 .h(px(1.))
239 .debug_selector(|| "settings/nav/divider".into())
240 .flex_none()
240 .w_full()
241 .mt(px(10.))
241 .h(px(1.))
242 .bg(theme::border_strong()),
242 .flex_none()
243 )
243 .mt(px(10.))
244 .child(
244 .bg(theme::border_strong()),
245 div()
245 )
246 .px(px(2. * NAV_PADDING_X))
246 .child(
247 .pt(px(12.))
247 div()
248 .pb(px(6.))
248 .px(px(2. * NAV_PADDING_X))
249 .text_size(px(12.))
249 .pt(px(12.))
250 .font_weight(FontWeight::SEMIBOLD)
250 .pb(px(6.))
251 .text_color(theme::text_muted())
251 .text_size(px(12.))
252 .child("RUSTY TEAMS"),
252 .font_weight(FontWeight::SEMIBOLD)
253 ).child(group(rusty))),
253 .text_color(theme::text_muted())
254 .child("RUSTY TEAMS"),
255 )
256 .child(group(rusty))
257 }),
254 )
258 )
255 .when(about_shown, |nav| {
259 .when(about_shown, |nav| {
256 nav.child(
260 nav.child(
@@ -326,7 +330,10 @@ mod tests {
326 fn every_search_term_names_a_setting_on_its_page() {
330 fn every_search_term_names_a_setting_on_its_page() {
327 let pages = [
331 let pages = [
328 (SettingsSection::General, include_str!("general.rs")),
332 (SettingsSection::General, include_str!("general.rs")),
329 (SettingsSection::Notifications, include_str!("notifications.rs")),
333 (
334 SettingsSection::Notifications,
335 include_str!("notifications.rs"),
336 ),
330 (SettingsSection::Appearance, include_str!("appearance.rs")),
337 (SettingsSection::Appearance, include_str!("appearance.rs")),
331 (SettingsSection::Chats, include_str!("chats.rs")),
338 (SettingsSection::Chats, include_str!("chats.rs")),
332 (SettingsSection::Devices, include_str!("devices.rs")),
339 (SettingsSection::Devices, include_str!("devices.rs")),
crates/app/src/settings/notifications.rs +3 −1
@@ -9,10 +9,12 @@ use super::account::{
9 9 };
10 10 use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};
11 11 use crate::app_state::AppState;
12 use crate::presence_follow::{MANAGE_STATUS_NOTIFICATIONS, STATUS_NOTIFICATIONS_DESCRIPTION, TURN_OFF};
13 12 use crate::notify::NotificationCenter;
14 13 use crate::notify::rules::{Corner, Settings};
15 14 use crate::notify::sounds::AlertSound;
15 use crate::presence_follow::{
16 MANAGE_STATUS_NOTIFICATIONS, STATUS_NOTIFICATIONS_DESCRIPTION, TURN_OFF,
17 };
16 18 use crate::theme;
17 19
18 20 type Accessor = fn(&mut Settings) -> &mut bool;
@@ -9,10 +9,12 @@ use super::account::{
9};
9};
10use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};
10use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};
11use crate::app_state::AppState;
11use crate::app_state::AppState;
12use crate::presence_follow::{MANAGE_STATUS_NOTIFICATIONS, STATUS_NOTIFICATIONS_DESCRIPTION, TURN_OFF};
13use crate::notify::NotificationCenter;
12use crate::notify::NotificationCenter;
14use crate::notify::rules::{Corner, Settings};
13use crate::notify::rules::{Corner, Settings};
15use crate::notify::sounds::AlertSound;
14use crate::notify::sounds::AlertSound;
15use crate::presence_follow::{
16 MANAGE_STATUS_NOTIFICATIONS, STATUS_NOTIFICATIONS_DESCRIPTION, TURN_OFF,
17};
16use crate::theme;
18use crate::theme;
17
19
18type Accessor = fn(&mut Settings) -> &mut bool;
20type Accessor = fn(&mut Settings) -> &mut bool;
crates/app/src/views/activity_panel.rs +71 −18
@@ -3,8 +3,8 @@ use std::ops::Range;
3 3 use std::rc::Rc;
4 4
5 5 use chrono::{DateTime, Local, NaiveDate, Offset, TimeZone, Utc};
6 use gpui_kit::component::scroll::ScrollableElement as _;
7 6 use gpui_kit::assets::IconName;
7 use gpui_kit::component::scroll::ScrollableElement as _;
8 8 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
9 9 use gpui_kit::prelude::FluentBuilder as _;
10 10 use gpui_kit::*;
@@ -404,7 +404,9 @@ fn row_frame(parts: RowParts) -> Stateful<Div> {
404 404 .gap(px(2.))
405 405 .child(
406 406 div()
407 .when(headline_wraps, |headline| headline.line_clamp(2).text_ellipsis())
407 .when(headline_wraps, |headline| {
408 headline.line_clamp(2).text_ellipsis()
409 })
408 410 .when(!headline_wraps, |headline| headline.truncate())
409 411 .text_size(px(13.))
410 412 .line_height(px(HEADLINE_LINE_HEIGHT))
@@ -594,7 +596,10 @@ fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, S
594 596 (Kind::Posted, "channelReplyMessage") => format!("{names} replied"),
595 597 (Kind::Posted, _) => format!("{names} posted a new message"),
596 598 (Kind::Team, "promotedToTeamAdmin") => {
597 return format!("{actor} made you an owner of {}", team_label(entry, channel));
599 return format!(
600 "{actor} made you an owner of {}",
601 team_label(entry, channel)
602 );
598 603 }
599 604 (Kind::Team, _) => {
600 605 return format!("{actor} added you to {}", team_label(entry, channel));
@@ -712,7 +717,11 @@ impl RowText {
712 717 }
713 718
714 719 fn row_height(headline_wraps: bool, extra_lines: usize) -> f32 {
715 let headline_extra = if headline_wraps { HEADLINE_LINE_HEIGHT } else { 0. };
720 let headline_extra = if headline_wraps {
721 HEADLINE_LINE_HEIGHT
722 } else {
723 0.
724 };
716 725 ROW_HEIGHT + headline_extra + extra_lines as f32 * EVENT_LINE_HEIGHT
717 726 }
718 727
@@ -854,7 +863,11 @@ impl Render for ActivityPanel {
854 863 } else {
855 864 f32::from(window.viewport_size().height).max(FALLBACK_VIEWPORT)
856 865 };
857 let visible = visible_slots(&heights, top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
866 let visible = visible_slots(
867 &heights,
868 top - VIEWPORT_MARGIN,
869 top + height + VIEWPORT_MARGIN,
870 );
858 871 let visible_slots = &slots[visible.range.clone()];
859 872 let unresolved: Vec<String> = visible_slots
860 873 .iter()
@@ -1007,9 +1020,15 @@ mod tests {
1007 1020 let start = chrono::DateTime::from_timestamp_millis(1793865600000).unwrap();
1008 1021 let end = chrono::DateTime::from_timestamp_millis(1793869200000).unwrap();
1009 1022 let berlin = chrono::FixedOffset::east_opt(3600).unwrap();
1010 assert_eq!(super::event_line(start, end, &berlin), "Nov 5, 09:00 - 10:00");
1023 assert_eq!(
1024 super::event_line(start, end, &berlin),
1025 "Nov 5, 09:00 - 10:00"
1026 );
1011 1027 let next_day = chrono::DateTime::from_timestamp_millis(1793955600000).unwrap();
1012 assert_eq!(super::event_line(start, next_day, &berlin), "Nov 5, 09:00 - Nov 6, 10:00");
1028 assert_eq!(
1029 super::event_line(start, next_day, &berlin),
1030 "Nov 5, 09:00 - Nov 6, 10:00"
1031 );
1013 1032 }
1014 1033
1015 1034 #[test]
@@ -1023,15 +1042,39 @@ mod tests {
1023 1042 teams: Vec::new(),
1024 1043 };
1025 1044 let cases = [
1026 (with(Kind::Mention, "mentionInChat", "person", 1), "Anna mentioned you"),
1027 (with(Kind::Mention, "mentionInChat", "everyone", 1), "Anna mentioned Everyone"),
1028 (with(Kind::Reaction, "reactionInChat", "like", 1), "Anna reacted to your message"),
1029 (with(Kind::Reaction, "reactionInChat", "like", 3), "Anna +2 reacted to your message"),
1030 (with(Kind::Reply, "reply", "", 1), "Anna replied to your post"),
1045 (
1046 with(Kind::Mention, "mentionInChat", "person", 1),
1047 "Anna mentioned you",
1048 ),
1049 (
1050 with(Kind::Mention, "mentionInChat", "everyone", 1),
1051 "Anna mentioned Everyone",
1052 ),
1053 (
1054 with(Kind::Reaction, "reactionInChat", "like", 1),
1055 "Anna reacted to your message",
1056 ),
1057 (
1058 with(Kind::Reaction, "reactionInChat", "like", 3),
1059 "Anna +2 reacted to your message",
1060 ),
1061 (
1062 with(Kind::Reply, "reply", "", 1),
1063 "Anna replied to your post",
1064 ),
1031 1065 (with(Kind::Reply, "replyToReply", "", 1), "Anna replied"),
1032 (with(Kind::MissedCall, "call", "missedCall", 1), "Missed call from Anna"),
1033 (with(Kind::Call, "call", "missedMeetingNudge", 1), "Anna asked you to join a meeting"),
1034 (with(Kind::Posted, "follow", "channelNewMessage", 1), "Anna posted a new message"),
1066 (
1067 with(Kind::MissedCall, "call", "missedCall", 1),
1068 "Missed call from Anna",
1069 ),
1070 (
1071 with(Kind::Call, "call", "missedMeetingNudge", 1),
1072 "Anna asked you to join a meeting",
1073 ),
1074 (
1075 with(Kind::Posted, "follow", "channelNewMessage", 1),
1076 "Anna posted a new message",
1077 ),
1035 1078 ];
1036 1079 for (entry, expected) in cases {
1037 1080 assert_eq!(headline(&entry, &sidebar, &HashMap::new()), expected);
@@ -1063,7 +1106,11 @@ mod tests {
1063 1106 }],
1064 1107 };
1065 1108 assert_eq!(
1066 headline(&with(Kind::Mention, "mention", "channel", 1), &sidebar, &HashMap::new()),
1109 headline(
1110 &with(Kind::Mention, "mention", "channel", 1),
1111 &sidebar,
1112 &HashMap::new()
1113 ),
1067 1114 "Anna mentioned Releases"
1068 1115 );
1069 1116 assert_eq!(
@@ -1071,7 +1118,11 @@ mod tests {
1071 1118 Some("Platform > Releases")
1072 1119 );
1073 1120 assert_eq!(
1074 headline(&with(Kind::Mention, "mention", "team", 1), &sidebar, &HashMap::new()),
1121 headline(
1122 &with(Kind::Mention, "mention", "team", 1),
1123 &sidebar,
1124 &HashMap::new()
1125 ),
1075 1126 "Anna mentioned Platform"
1076 1127 );
1077 1128 assert_eq!(
@@ -1135,7 +1186,9 @@ mod tests {
1135 1186 let first_row = cx.debug_bounds(selector).unwrap();
1136 1187 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
1137 1188 cx.update(|window, cx| window.draw(cx).clear(cx));
1138 cx.update(|_, cx| activity.update(cx, |activity, cx| activity.mark_read(&first_unread, cx)));
1189 cx.update(|_, cx| {
1190 activity.update(cx, |activity, cx| activity.mark_read(&first_unread, cx))
1191 });
1139 1192 cx.update(|window, cx| window.draw(cx).clear(cx));
1140 1193 }
1141 1194 }
@@ -3,8 +3,8 @@ use std::ops::Range;
3use std::rc::Rc;
3use std::rc::Rc;
4
4
5use chrono::{DateTime, Local, NaiveDate, Offset, TimeZone, Utc};
5use chrono::{DateTime, Local, NaiveDate, Offset, TimeZone, Utc};
6use gpui_kit::component::scroll::ScrollableElement as _;
7use gpui_kit::assets::IconName;
6use gpui_kit::assets::IconName;
7use gpui_kit::component::scroll::ScrollableElement as _;
8use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
8use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
9use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
10use gpui_kit::*;
@@ -404,7 +404,9 @@ fn row_frame(parts: RowParts) -> Stateful<Div> {
404 .gap(px(2.))
404 .gap(px(2.))
405 .child(
405 .child(
406 div()
406 div()
407 .when(headline_wraps, |headline| headline.line_clamp(2).text_ellipsis())
407 .when(headline_wraps, |headline| {
408 headline.line_clamp(2).text_ellipsis()
409 })
408 .when(!headline_wraps, |headline| headline.truncate())
410 .when(!headline_wraps, |headline| headline.truncate())
409 .text_size(px(13.))
411 .text_size(px(13.))
410 .line_height(px(HEADLINE_LINE_HEIGHT))
412 .line_height(px(HEADLINE_LINE_HEIGHT))
@@ -594,7 +596,10 @@ fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, S
594 (Kind::Posted, "channelReplyMessage") => format!("{names} replied"),
596 (Kind::Posted, "channelReplyMessage") => format!("{names} replied"),
595 (Kind::Posted, _) => format!("{names} posted a new message"),
597 (Kind::Posted, _) => format!("{names} posted a new message"),
596 (Kind::Team, "promotedToTeamAdmin") => {
598 (Kind::Team, "promotedToTeamAdmin") => {
597 return format!("{actor} made you an owner of {}", team_label(entry, channel));
599 return format!(
600 "{actor} made you an owner of {}",
601 team_label(entry, channel)
602 );
598 }
603 }
599 (Kind::Team, _) => {
604 (Kind::Team, _) => {
600 return format!("{actor} added you to {}", team_label(entry, channel));
605 return format!("{actor} added you to {}", team_label(entry, channel));
@@ -712,7 +717,11 @@ impl RowText {
712}
717}
713
718
714fn row_height(headline_wraps: bool, extra_lines: usize) -> f32 {
719fn row_height(headline_wraps: bool, extra_lines: usize) -> f32 {
715 let headline_extra = if headline_wraps { HEADLINE_LINE_HEIGHT } else { 0. };
720 let headline_extra = if headline_wraps {
721 HEADLINE_LINE_HEIGHT
722 } else {
723 0.
724 };
716 ROW_HEIGHT + headline_extra + extra_lines as f32 * EVENT_LINE_HEIGHT
725 ROW_HEIGHT + headline_extra + extra_lines as f32 * EVENT_LINE_HEIGHT
717}
726}
718
727
@@ -854,7 +863,11 @@ impl Render for ActivityPanel {
854 } else {
863 } else {
855 f32::from(window.viewport_size().height).max(FALLBACK_VIEWPORT)
864 f32::from(window.viewport_size().height).max(FALLBACK_VIEWPORT)
856 };
865 };
857 let visible = visible_slots(&heights, top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
866 let visible = visible_slots(
867 &heights,
868 top - VIEWPORT_MARGIN,
869 top + height + VIEWPORT_MARGIN,
870 );
858 let visible_slots = &slots[visible.range.clone()];
871 let visible_slots = &slots[visible.range.clone()];
859 let unresolved: Vec<String> = visible_slots
872 let unresolved: Vec<String> = visible_slots
860 .iter()
873 .iter()
@@ -1007,9 +1020,15 @@ mod tests {
1007 let start = chrono::DateTime::from_timestamp_millis(1793865600000).unwrap();
1020 let start = chrono::DateTime::from_timestamp_millis(1793865600000).unwrap();
1008 let end = chrono::DateTime::from_timestamp_millis(1793869200000).unwrap();
1021 let end = chrono::DateTime::from_timestamp_millis(1793869200000).unwrap();
1009 let berlin = chrono::FixedOffset::east_opt(3600).unwrap();
1022 let berlin = chrono::FixedOffset::east_opt(3600).unwrap();
1010 assert_eq!(super::event_line(start, end, &berlin), "Nov 5, 09:00 - 10:00");
1023 assert_eq!(
1024 super::event_line(start, end, &berlin),
1025 "Nov 5, 09:00 - 10:00"
1026 );
1011 let next_day = chrono::DateTime::from_timestamp_millis(1793955600000).unwrap();
1027 let next_day = chrono::DateTime::from_timestamp_millis(1793955600000).unwrap();
1012 assert_eq!(super::event_line(start, next_day, &berlin), "Nov 5, 09:00 - Nov 6, 10:00");
1028 assert_eq!(
1029 super::event_line(start, next_day, &berlin),
1030 "Nov 5, 09:00 - Nov 6, 10:00"
1031 );
1013 }
1032 }
1014
1033
1015 #[test]
1034 #[test]
@@ -1023,15 +1042,39 @@ mod tests {
1023 teams: Vec::new(),
1042 teams: Vec::new(),
1024 };
1043 };
1025 let cases = [
1044 let cases = [
1026 (with(Kind::Mention, "mentionInChat", "person", 1), "Anna mentioned you"),
1045 (
1027 (with(Kind::Mention, "mentionInChat", "everyone", 1), "Anna mentioned Everyone"),
1046 with(Kind::Mention, "mentionInChat", "person", 1),
1028 (with(Kind::Reaction, "reactionInChat", "like", 1), "Anna reacted to your message"),
1047 "Anna mentioned you",
1029 (with(Kind::Reaction, "reactionInChat", "like", 3), "Anna +2 reacted to your message"),
1048 ),
1030 (with(Kind::Reply, "reply", "", 1), "Anna replied to your post"),
1049 (
1050 with(Kind::Mention, "mentionInChat", "everyone", 1),
1051 "Anna mentioned Everyone",
1052 ),
1053 (
1054 with(Kind::Reaction, "reactionInChat", "like", 1),
1055 "Anna reacted to your message",
1056 ),
1057 (
1058 with(Kind::Reaction, "reactionInChat", "like", 3),
1059 "Anna +2 reacted to your message",
1060 ),
1061 (
1062 with(Kind::Reply, "reply", "", 1),
1063 "Anna replied to your post",
1064 ),
1031 (with(Kind::Reply, "replyToReply", "", 1), "Anna replied"),
1065 (with(Kind::Reply, "replyToReply", "", 1), "Anna replied"),
1032 (with(Kind::MissedCall, "call", "missedCall", 1), "Missed call from Anna"),
1066 (
1033 (with(Kind::Call, "call", "missedMeetingNudge", 1), "Anna asked you to join a meeting"),
1067 with(Kind::MissedCall, "call", "missedCall", 1),
1034 (with(Kind::Posted, "follow", "channelNewMessage", 1), "Anna posted a new message"),
1068 "Missed call from Anna",
1069 ),
1070 (
1071 with(Kind::Call, "call", "missedMeetingNudge", 1),
1072 "Anna asked you to join a meeting",
1073 ),
1074 (
1075 with(Kind::Posted, "follow", "channelNewMessage", 1),
1076 "Anna posted a new message",
1077 ),
1035 ];
1078 ];
1036 for (entry, expected) in cases {
1079 for (entry, expected) in cases {
1037 assert_eq!(headline(&entry, &sidebar, &HashMap::new()), expected);
1080 assert_eq!(headline(&entry, &sidebar, &HashMap::new()), expected);
@@ -1063,7 +1106,11 @@ mod tests {
1063 }],
1106 }],
1064 };
1107 };
1065 assert_eq!(
1108 assert_eq!(
1066 headline(&with(Kind::Mention, "mention", "channel", 1), &sidebar, &HashMap::new()),
1109 headline(
1110 &with(Kind::Mention, "mention", "channel", 1),
1111 &sidebar,
1112 &HashMap::new()
1113 ),
1067 "Anna mentioned Releases"
1114 "Anna mentioned Releases"
1068 );
1115 );
1069 assert_eq!(
1116 assert_eq!(
@@ -1071,7 +1118,11 @@ mod tests {
1071 Some("Platform > Releases")
1118 Some("Platform > Releases")
1072 );
1119 );
1073 assert_eq!(
1120 assert_eq!(
1074 headline(&with(Kind::Mention, "mention", "team", 1), &sidebar, &HashMap::new()),
1121 headline(
1122 &with(Kind::Mention, "mention", "team", 1),
1123 &sidebar,
1124 &HashMap::new()
1125 ),
1075 "Anna mentioned Platform"
1126 "Anna mentioned Platform"
1076 );
1127 );
1077 assert_eq!(
1128 assert_eq!(
@@ -1135,7 +1186,9 @@ mod tests {
1135 let first_row = cx.debug_bounds(selector).unwrap();
1186 let first_row = cx.debug_bounds(selector).unwrap();
1136 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
1187 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
1137 cx.update(|window, cx| window.draw(cx).clear(cx));
1188 cx.update(|window, cx| window.draw(cx).clear(cx));
1138 cx.update(|_, cx| activity.update(cx, |activity, cx| activity.mark_read(&first_unread, cx)));
1189 cx.update(|_, cx| {
1190 activity.update(cx, |activity, cx| activity.mark_read(&first_unread, cx))
1191 });
1139 cx.update(|window, cx| window.draw(cx).clear(cx));
1192 cx.update(|window, cx| window.draw(cx).clear(cx));
1140 }
1193 }
1141}
1194}
crates/app/src/views/adaptive_card.rs +6 −1
@@ -493,7 +493,12 @@ fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
493 493 (true, Some(lines)) => element.text_ellipsis().line_clamp(lines),
494 494 (true, None) => element,
495 495 })
496 .child(render_blocks(&layout_card_blocks(&text.spans), id, false, cx))
496 .child(render_blocks(
497 &layout_card_blocks(&text.spans),
498 id,
499 false,
500 cx,
501 ))
497 502 .into_any_element()
498 503 }
499 504
@@ -493,7 +493,12 @@ fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
493 (true, Some(lines)) => element.text_ellipsis().line_clamp(lines),
493 (true, Some(lines)) => element.text_ellipsis().line_clamp(lines),
494 (true, None) => element,
494 (true, None) => element,
495 })
495 })
496 .child(render_blocks(&layout_card_blocks(&text.spans), id, false, cx))
496 .child(render_blocks(
497 &layout_card_blocks(&text.spans),
498 id,
499 false,
500 cx,
501 ))
497 .into_any_element()
502 .into_any_element()
498}
503}
499
504
crates/app/src/views/attachment_tray.rs +9 −2
@@ -261,7 +261,12 @@ impl AttachmentTray {
261 261 }
262 262
263 263 /// A file already in the cloud goes out by reference; it was never uploaded, so removing it deletes nothing.
264 pub fn add_cloud_file(&mut self, name: String, size: u64, reference: FileReference) -> Option<u64> {
264 pub fn add_cloud_file(
265 &mut self,
266 name: String,
267 size: u64,
268 reference: FileReference,
269 ) -> Option<u64> {
265 270 self.notice = None;
266 271 if self.items.len() >= MAX_ATTACHMENTS {
267 272 self.notice = Some(limit_notice(1));
@@ -1093,7 +1098,9 @@ mod tests {
1093 1098 #[test]
1094 1099 fn a_cloud_file_is_ready_at_once_and_removing_it_deletes_nothing() {
1095 1100 let mut tray = AttachmentTray::default();
1096 let id = tray.add_cloud_file("plan.pdf".into(), 12, reference("plan.pdf")).unwrap();
1101 let id = tray
1102 .add_cloud_file("plan.pdf".into(), 12, reference("plan.pdf"))
1103 .unwrap();
1097 1104 assert!(!tray.blocks_send());
1098 1105 assert_eq!(tray.outgoing_files()[0].reference, reference("plan.pdf"));
1099 1106 assert!(tray.retry(id).is_none());
@@ -261,7 +261,12 @@ impl AttachmentTray {
261 }
261 }
262
262
263 /// A file already in the cloud goes out by reference; it was never uploaded, so removing it deletes nothing.
263 /// A file already in the cloud goes out by reference; it was never uploaded, so removing it deletes nothing.
264 pub fn add_cloud_file(&mut self, name: String, size: u64, reference: FileReference) -> Option<u64> {
264 pub fn add_cloud_file(
265 &mut self,
266 name: String,
267 size: u64,
268 reference: FileReference,
269 ) -> Option<u64> {
265 self.notice = None;
270 self.notice = None;
266 if self.items.len() >= MAX_ATTACHMENTS {
271 if self.items.len() >= MAX_ATTACHMENTS {
267 self.notice = Some(limit_notice(1));
272 self.notice = Some(limit_notice(1));
@@ -1093,7 +1098,9 @@ mod tests {
1093 #[test]
1098 #[test]
1094 fn a_cloud_file_is_ready_at_once_and_removing_it_deletes_nothing() {
1099 fn a_cloud_file_is_ready_at_once_and_removing_it_deletes_nothing() {
1095 let mut tray = AttachmentTray::default();
1100 let mut tray = AttachmentTray::default();
1096 let id = tray.add_cloud_file("plan.pdf".into(), 12, reference("plan.pdf")).unwrap();
1101 let id = tray
1102 .add_cloud_file("plan.pdf".into(), 12, reference("plan.pdf"))
1103 .unwrap();
1097 assert!(!tray.blocks_send());
1104 assert!(!tray.blocks_send());
1098 assert_eq!(tray.outgoing_files()[0].reference, reference("plan.pdf"));
1105 assert_eq!(tray.outgoing_files()[0].reference, reference("plan.pdf"));
1099 assert!(tray.retry(id).is_none());
1106 assert!(tray.retry(id).is_none());
crates/app/src/views/attachments.rs +13 −6
@@ -274,9 +274,11 @@ fn save_button(
274 274 }
275 275
276 276 fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stateful<Div>> {
277 let image = card
278 .preview()
279 .and_then(|preview| directory.image(&preview.url).map(|entry| entry.path.clone()));
277 let image = card.preview().and_then(|preview| {
278 directory
279 .image(&preview.url)
280 .map(|entry| entry.path.clone())
281 });
280 282 if image.is_none() && card.kind != FileKind::Video {
281 283 return None;
282 284 }
@@ -288,9 +290,14 @@ fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stat
288 290 .overflow_hidden()
289 291 .bg(theme::code_surface());
290 292 let frame = match image {
291 Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => frame
292 .bg(theme::white())
293 .child(img(bounded(path)).w_full().h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO)).object_fit(ObjectFit::Cover)),
293 Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => {
294 frame.bg(theme::white()).child(
295 img(bounded(path))
296 .w_full()
297 .h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO))
298 .object_fit(ObjectFit::Cover),
299 )
300 }
294 301 Some(path) => frame.child(img(bounded(path)).size_full().object_fit(match card.kind {
295 302 FileKind::Video | FileKind::PowerPoint => ObjectFit::Cover,
296 303 _ => ObjectFit::Contain,
@@ -274,9 +274,11 @@ fn save_button(
274}
274}
275
275
276fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stateful<Div>> {
276fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stateful<Div>> {
277 let image = card
277 let image = card.preview().and_then(|preview| {
278 .preview()
278 directory
279 .and_then(|preview| directory.image(&preview.url).map(|entry| entry.path.clone()));
279 .image(&preview.url)
280 .map(|entry| entry.path.clone())
281 });
280 if image.is_none() && card.kind != FileKind::Video {
282 if image.is_none() && card.kind != FileKind::Video {
281 return None;
283 return None;
282 }
284 }
@@ -288,9 +290,14 @@ fn file_preview(card: &FileCard, id: &str, directory: &Directory) -> Option<Stat
288 .overflow_hidden()
290 .overflow_hidden()
289 .bg(theme::code_surface());
291 .bg(theme::code_surface());
290 let frame = match image {
292 let frame = match image {
291 Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => frame
293 Some(path) if card.kind.is_document() && card.kind != FileKind::PowerPoint => {
292 .bg(theme::white())
294 frame.bg(theme::white()).child(
293 .child(img(bounded(path)).w_full().h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO)).object_fit(ObjectFit::Cover)),
295 img(bounded(path))
296 .w_full()
297 .h(px(FILE_CARD_WIDTH * PORTRAIT_PAGE_RATIO))
298 .object_fit(ObjectFit::Cover),
299 )
300 }
294 Some(path) => frame.child(img(bounded(path)).size_full().object_fit(match card.kind {
301 Some(path) => frame.child(img(bounded(path)).size_full().object_fit(match card.kind {
295 FileKind::Video | FileKind::PowerPoint => ObjectFit::Cover,
302 FileKind::Video | FileKind::PowerPoint => ObjectFit::Cover,
296 _ => ObjectFit::Contain,
303 _ => ObjectFit::Contain,
crates/app/src/views/avatar.rs +7 −1
@@ -336,7 +336,13 @@ pub fn square_avatar(name: &str, key: &str, size: f32, radius: f32) -> Div {
336 336 .child(format::team_initials(name))
337 337 }
338 338
339 pub fn team_avatar(photo: Option<&AvatarState>, name: &str, key: &str, size: f32, radius: f32) -> AnyElement {
339 pub fn team_avatar(
340 photo: Option<&AvatarState>,
341 name: &str,
342 key: &str,
343 size: f32,
344 radius: f32,
345 ) -> AnyElement {
340 346 match photo {
341 347 Some(AvatarState::Ready(photo)) => div()
342 348 .size(px(size))
@@ -336,7 +336,13 @@ pub fn square_avatar(name: &str, key: &str, size: f32, radius: f32) -> Div {
336 .child(format::team_initials(name))
336 .child(format::team_initials(name))
337}
337}
338
338
339pub fn team_avatar(photo: Option<&AvatarState>, name: &str, key: &str, size: f32, radius: f32) -> AnyElement {
339pub fn team_avatar(
340 photo: Option<&AvatarState>,
341 name: &str,
342 key: &str,
343 size: f32,
344 radius: f32,
345) -> AnyElement {
340 match photo {
346 match photo {
341 Some(AvatarState::Ready(photo)) => div()
347 Some(AvatarState::Ready(photo)) => div()
342 .size(px(size))
348 .size(px(size))
crates/app/src/views/calendar_date_picker.rs +22 −18
@@ -64,7 +64,8 @@ impl DatePicker {
64 64
65 65 fn day_cell(&self, date: NaiveDate, today: NaiveDate, cx: &mut Context<Self>) -> Stateful<Div> {
66 66 let in_month = date.month() == self.month.month();
67 let shown = self.shown_start <= date && date < self.shown_start + Duration::days(self.shown_days);
67 let shown =
68 self.shown_start <= date && date < self.shown_start + Duration::days(self.shown_days);
68 69 let is_today = date == today;
69 70 div()
70 71 .id(SharedString::from(format!("date-picker-{date}")))
@@ -84,7 +85,9 @@ impl DatePicker {
84 85 .when(is_today, |cell| {
85 86 cell.bg(theme::accent()).text_color(theme::on_accent())
86 87 })
87 .when(!is_today, |cell| cell.hover(|cell| cell.bg(theme::border_strong())))
88 .when(!is_today, |cell| {
89 cell.hover(|cell| cell.bg(theme::border_strong()))
90 })
88 91 .child(date.day().to_string())
89 92 .on_click(cx.listener(move |this, _, window, cx| this.pick(date, window, cx)))
90 93 }
@@ -132,7 +135,9 @@ impl Render for DatePicker {
132 135 .ghost()
133 136 .icon(IconName::ChevronLeft)
134 137 .tooltip("Previous month")
135 .on_click(cx.listener(|this, _, _, cx| this.move_month(false, cx))),
138 .on_click(
139 cx.listener(|this, _, _, cx| this.move_month(false, cx)),
140 ),
136 141 )
137 142 .child(
138 143 Button::new("date-picker-forward")
@@ -140,22 +145,22 @@ impl Render for DatePicker {
140 145 .ghost()
141 146 .icon(IconName::ChevronRight)
142 147 .tooltip("Next month")
143 .on_click(cx.listener(|this, _, _, cx| this.move_month(true, cx))),
148 .on_click(
149 cx.listener(|this, _, _, cx| this.move_month(true, cx)),
150 ),
144 151 ),
145 152 ),
146 153 )
147 .child(
148 h_flex().children(WEEKDAY_LETTERS.iter().map(|letter| {
149 div()
150 .size(px(CELL_SIZE))
151 .flex()
152 .items_center()
153 .justify_center()
154 .text_size(px(11.))
155 .text_color(theme::text_muted())
156 .child(*letter)
157 })),
158 )
154 .child(h_flex().children(WEEKDAY_LETTERS.iter().map(|letter| {
155 div()
156 .size(px(CELL_SIZE))
157 .flex()
158 .items_center()
159 .justify_center()
160 .text_size(px(11.))
161 .text_color(theme::text_muted())
162 .child(*letter)
163 })))
159 164 .children(weeks)
160 165 }
161 166 }
@@ -191,8 +196,7 @@ pub fn date_picker_button(
191 196 }
192 197 let popover = cx.entity().downgrade();
193 198 let app = app.clone();
194 let created =
195 cx.new(|_| DatePicker::new(app, shown_start, shown_days, month, popover));
199 let created = cx.new(|_| DatePicker::new(app, shown_start, shown_days, month, popover));
196 200 *picker.borrow_mut() = Some(created.clone());
197 201 created
198 202 })
@@ -64,7 +64,8 @@ impl DatePicker {
64
64
65 fn day_cell(&self, date: NaiveDate, today: NaiveDate, cx: &mut Context<Self>) -> Stateful<Div> {
65 fn day_cell(&self, date: NaiveDate, today: NaiveDate, cx: &mut Context<Self>) -> Stateful<Div> {
66 let in_month = date.month() == self.month.month();
66 let in_month = date.month() == self.month.month();
67 let shown = self.shown_start <= date && date < self.shown_start + Duration::days(self.shown_days);
67 let shown =
68 self.shown_start <= date && date < self.shown_start + Duration::days(self.shown_days);
68 let is_today = date == today;
69 let is_today = date == today;
69 div()
70 div()
70 .id(SharedString::from(format!("date-picker-{date}")))
71 .id(SharedString::from(format!("date-picker-{date}")))
@@ -84,7 +85,9 @@ impl DatePicker {
84 .when(is_today, |cell| {
85 .when(is_today, |cell| {
85 cell.bg(theme::accent()).text_color(theme::on_accent())
86 cell.bg(theme::accent()).text_color(theme::on_accent())
86 })
87 })
87 .when(!is_today, |cell| cell.hover(|cell| cell.bg(theme::border_strong())))
88 .when(!is_today, |cell| {
89 cell.hover(|cell| cell.bg(theme::border_strong()))
90 })
88 .child(date.day().to_string())
91 .child(date.day().to_string())
89 .on_click(cx.listener(move |this, _, window, cx| this.pick(date, window, cx)))
92 .on_click(cx.listener(move |this, _, window, cx| this.pick(date, window, cx)))
90 }
93 }
@@ -132,7 +135,9 @@ impl Render for DatePicker {
132 .ghost()
135 .ghost()
133 .icon(IconName::ChevronLeft)
136 .icon(IconName::ChevronLeft)
134 .tooltip("Previous month")
137 .tooltip("Previous month")
135 .on_click(cx.listener(|this, _, _, cx| this.move_month(false, cx))),
138 .on_click(
139 cx.listener(|this, _, _, cx| this.move_month(false, cx)),
140 ),
136 )
141 )
137 .child(
142 .child(
138 Button::new("date-picker-forward")
143 Button::new("date-picker-forward")
@@ -140,22 +145,22 @@ impl Render for DatePicker {
140 .ghost()
145 .ghost()
141 .icon(IconName::ChevronRight)
146 .icon(IconName::ChevronRight)
142 .tooltip("Next month")
147 .tooltip("Next month")
143 .on_click(cx.listener(|this, _, _, cx| this.move_month(true, cx))),
148 .on_click(
149 cx.listener(|this, _, _, cx| this.move_month(true, cx)),
150 ),
144 ),
151 ),
145 ),
152 ),
146 )
153 )
147 .child(
154 .child(h_flex().children(WEEKDAY_LETTERS.iter().map(|letter| {
148 h_flex().children(WEEKDAY_LETTERS.iter().map(|letter| {
155 div()
149 div()
156 .size(px(CELL_SIZE))
150 .size(px(CELL_SIZE))
157 .flex()
151 .flex()
158 .items_center()
152 .items_center()
159 .justify_center()
153 .justify_center()
160 .text_size(px(11.))
154 .text_size(px(11.))
161 .text_color(theme::text_muted())
155 .text_color(theme::text_muted())
162 .child(*letter)
156 .child(*letter)
163 })))
157 })),
158 )
159 .children(weeks)
164 .children(weeks)
160 }
165 }
161}
166}
@@ -191,8 +196,7 @@ pub fn date_picker_button(
191 }
196 }
192 let popover = cx.entity().downgrade();
197 let popover = cx.entity().downgrade();
193 let app = app.clone();
198 let app = app.clone();
194 let created =
199 let created = cx.new(|_| DatePicker::new(app, shown_start, shown_days, month, popover));
195 cx.new(|_| DatePicker::new(app, shown_start, shown_days, month, popover));
196 *picker.borrow_mut() = Some(created.clone());
200 *picker.borrow_mut() = Some(created.clone());
197 created
201 created
198 })
202 })
crates/app/src/views/calendar_month.rs +7 −6
@@ -53,13 +53,14 @@ fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
53 53 .bg(theme::accent().opacity(if event.all_day { 0.28 } else { 0.14 }))
54 54 .text_size(px(11.5))
55 55 .text_color(theme::text())
56 .children(time.map(|time| {
56 .children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))
57 .child(
57 58 div()
58 .flex_none()
59 .text_color(theme::text_soft())
60 .child(time)
61 }))
62 .child(div().flex_1().min_w_0().truncate().child(event.subject.clone()))
59 .flex_1()
60 .min_w_0()
61 .truncate()
62 .child(event.subject.clone()),
63 )
63 64 }
64 65
65 66 fn day_cell(
@@ -53,13 +53,14 @@ fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
53 .bg(theme::accent().opacity(if event.all_day { 0.28 } else { 0.14 }))
53 .bg(theme::accent().opacity(if event.all_day { 0.28 } else { 0.14 }))
54 .text_size(px(11.5))
54 .text_size(px(11.5))
55 .text_color(theme::text())
55 .text_color(theme::text())
56 .children(time.map(|time| {
56 .children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))
57 .child(
57 div()
58 div()
58 .flex_none()
59 .flex_1()
59 .text_color(theme::text_soft())
60 .min_w_0()
60 .child(time)
61 .truncate()
61 }))
62 .child(event.subject.clone()),
62 .child(div().flex_1().min_w_0().truncate().child(event.subject.clone()))
63 )
63}
64}
64
65
65fn day_cell(
66fn day_cell(
crates/app/src/views/calendar_view.rs +20 −20
@@ -11,10 +11,9 @@ use gpui_kit::*;
11 11
12 12 use super::calendar_date_picker::date_picker_button;
13 13 use super::calendar_month::month_grid;
14 use super::meeting_proposal_card::meeting_proposal_cards;
15 use super::rsvp_menu::rsvp_menu;
16 14 use super::join_dialog::open_join_with_id;
17 15 use super::new_meeting_dialog::open_new_meeting;
16 use super::rsvp_menu::rsvp_menu;
18 17 use crate::app_state::AppState;
19 18 use crate::call::join_available;
20 19 use crate::call::week_grid::{
@@ -48,19 +47,16 @@ pub struct CalendarView {
48 47 scroll: ScrollHandle,
49 48 scrolled_to_morning: bool,
50 49 _observation: Subscription,
51 _agent_observation: Option<Subscription>,
52 50 }
53 51
54 52 impl CalendarView {
55 53 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
56 54 let observation = cx.observe(&state, |_, _, cx| cx.notify());
57 let agent_observation = crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
58 55 CalendarView {
59 56 state,
60 57 scroll: ScrollHandle::new(),
61 58 scrolled_to_morning: false,
62 59 _observation: observation,
63 _agent_observation: agent_observation,
64 60 }
65 61 }
66 62
@@ -123,19 +119,17 @@ impl CalendarView {
123 119 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
124 120 }),
125 121 )
126 .child(
127 h_flex().flex_1().min_w_0().child(date_picker_button(
128 &self.state,
129 span.title(start),
130 start,
131 span.days(),
132 if span == CalendarSpan::Month {
133 month_shown(start)
134 } else {
135 start
136 },
137 )),
138 )
122 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
123 &self.state,
124 span.title(start),
125 start,
126 span.days(),
127 if span == CalendarSpan::Month {
128 month_shown(start)
129 } else {
130 start
131 },
132 )))
139 133 .child(
140 134 Button::new("calendar-span")
141 135 .small()
@@ -600,10 +594,16 @@ impl Render for CalendarView {
600 594 .bg(theme::surface())
601 595 .overflow_hidden()
602 596 .child(self.header(start, span, compact))
603 .children(meeting_proposal_cards(cx))
604 597 .map(|calendar| {
605 598 if span == CalendarSpan::Month {
606 calendar.child(month_grid(&self.state, start, &days, &events, today, offset))
599 calendar.child(month_grid(
600 &self.state,
601 start,
602 &days,
603 &events,
604 today,
605 offset,
606 ))
607 607 } else {
608 608 calendar
609 609 .child(self.day_headers(&days, today))
@@ -11,10 +11,9 @@ use gpui_kit::*;
11
11
12use super::calendar_date_picker::date_picker_button;
12use super::calendar_date_picker::date_picker_button;
13use super::calendar_month::month_grid;
13use super::calendar_month::month_grid;
14use super::meeting_proposal_card::meeting_proposal_cards;
15use super::rsvp_menu::rsvp_menu;
16use super::join_dialog::open_join_with_id;
14use super::join_dialog::open_join_with_id;
17use super::new_meeting_dialog::open_new_meeting;
15use super::new_meeting_dialog::open_new_meeting;
16use super::rsvp_menu::rsvp_menu;
18use crate::app_state::AppState;
17use crate::app_state::AppState;
19use crate::call::join_available;
18use crate::call::join_available;
20use crate::call::week_grid::{
19use crate::call::week_grid::{
@@ -48,19 +47,16 @@ pub struct CalendarView {
48 scroll: ScrollHandle,
47 scroll: ScrollHandle,
49 scrolled_to_morning: bool,
48 scrolled_to_morning: bool,
50 _observation: Subscription,
49 _observation: Subscription,
51 _agent_observation: Option<Subscription>,
52}
50}
53
51
54impl CalendarView {
52impl CalendarView {
55 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
53 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
56 let observation = cx.observe(&state, |_, _, cx| cx.notify());
54 let observation = cx.observe(&state, |_, _, cx| cx.notify());
57 let agent_observation = crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
58 CalendarView {
55 CalendarView {
59 state,
56 state,
60 scroll: ScrollHandle::new(),
57 scroll: ScrollHandle::new(),
61 scrolled_to_morning: false,
58 scrolled_to_morning: false,
62 _observation: observation,
59 _observation: observation,
63 _agent_observation: agent_observation,
64 }
60 }
65 }
61 }
66
62
@@ -123,19 +119,17 @@ impl CalendarView {
123 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
119 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
124 }),
120 }),
125 )
121 )
126 .child(
122 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
127 h_flex().flex_1().min_w_0().child(date_picker_button(
123 &self.state,
128 &self.state,
124 span.title(start),
129 span.title(start),
125 start,
130 start,
126 span.days(),
131 span.days(),
127 if span == CalendarSpan::Month {
132 if span == CalendarSpan::Month {
128 month_shown(start)
133 month_shown(start)
129 } else {
134 } else {
130 start
135 start
131 },
136 },
132 )))
137 )),
138 )
139 .child(
133 .child(
140 Button::new("calendar-span")
134 Button::new("calendar-span")
141 .small()
135 .small()
@@ -600,10 +594,16 @@ impl Render for CalendarView {
600 .bg(theme::surface())
594 .bg(theme::surface())
601 .overflow_hidden()
595 .overflow_hidden()
602 .child(self.header(start, span, compact))
596 .child(self.header(start, span, compact))
603 .children(meeting_proposal_cards(cx))
604 .map(|calendar| {
597 .map(|calendar| {
605 if span == CalendarSpan::Month {
598 if span == CalendarSpan::Month {
606 calendar.child(month_grid(&self.state, start, &days, &events, today, offset))
599 calendar.child(month_grid(
600 &self.state,
601 start,
602 &days,
603 &events,
604 today,
605 offset,
606 ))
607 } else {
607 } else {
608 calendar
608 calendar
609 .child(self.day_headers(&days, today))
609 .child(self.day_headers(&days, today))
crates/app/src/views/call_card.rs +3 −5
@@ -44,11 +44,9 @@ fn icon_circle(call: &CallCard) -> Div {
44 44 CallIcon::Missed => (theme::red().opacity(0.2), "call_missed", theme::red_soft()),
45 45 CallIcon::Call => (theme::popup(), "call", theme::text()),
46 46 CallIcon::Video => (theme::popup(), "videocam", theme::text()),
47 CallIcon::Record | CallIcon::Saved => (
48 theme::popup(),
49 "radio_button_checked",
50 theme::accent_text(),
51 ),
47 CallIcon::Record | CallIcon::Saved => {
48 (theme::popup(), "radio_button_checked", theme::accent_text())
49 }
52 50 CallIcon::RecordStop => (theme::popup(), "stop_circle", theme::text()),
53 51 CallIcon::Roster => (theme::popup(), "group", theme::text()),
54 52 };
@@ -44,11 +44,9 @@ fn icon_circle(call: &CallCard) -> Div {
44 CallIcon::Missed => (theme::red().opacity(0.2), "call_missed", theme::red_soft()),
44 CallIcon::Missed => (theme::red().opacity(0.2), "call_missed", theme::red_soft()),
45 CallIcon::Call => (theme::popup(), "call", theme::text()),
45 CallIcon::Call => (theme::popup(), "call", theme::text()),
46 CallIcon::Video => (theme::popup(), "videocam", theme::text()),
46 CallIcon::Video => (theme::popup(), "videocam", theme::text()),
47 CallIcon::Record | CallIcon::Saved => (
47 CallIcon::Record | CallIcon::Saved => {
48 theme::popup(),
48 (theme::popup(), "radio_button_checked", theme::accent_text())
49 "radio_button_checked",
49 }
50 theme::accent_text(),
51 ),
52 CallIcon::RecordStop => (theme::popup(), "stop_circle", theme::text()),
50 CallIcon::RecordStop => (theme::popup(), "stop_circle", theme::text()),
53 CallIcon::Roster => (theme::popup(), "group", theme::text()),
51 CallIcon::Roster => (theme::popup(), "group", theme::text()),
54 };
52 };
crates/app/src/views/call_control_fold.rs +70 −57
@@ -4,14 +4,15 @@ use gpui_kit::component::Icon;
4 4 use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
5 5 use gpui_kit::*;
6 6
7 use super::call_toolbar::{GROUP_DIVIDER_WIDTH, GROUP_GAP, SPLIT_CHEVRON_WIDTH, TOOL_GAP, TOOL_WIDTH};
8 use super::call_view::reaction_glyph;
7 use super::call_organizer::CAMERA_MENU_WIDTH;
8 use super::call_view::{CONTROL_SIZE, reaction_glyph};
9 9 use super::call_view_menu::view_items;
10 10 use crate::app_state::AppState;
11 11 use crate::call::CallModel;
12 12
13 pub(super) const TITLE_RESERVE: f32 = 280.;
14 const LEAVE_WIDTH: f32 = 96.;
13 pub(super) const CONTROL_GAP: f32 = 12.;
14 pub(super) const CONTROLS_PADDING: f32 = 16.;
15 const LEAVE_WIDTH: f32 = 116.;
15 16
16 17 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
17 18 pub enum Foldable {
@@ -37,40 +38,33 @@ impl FoldedControls {
37 38 }
38 39 }
39 40
40 pub fn fixed_controls_width(has_camera_menu: bool, has_more: bool, has_leave_menu: bool, has_pop_out: bool) -> f32 {
41 let devices = [
42 TOOL_WIDTH + if has_camera_menu { SPLIT_CHEVRON_WIDTH } else { 0. },
43 TOOL_WIDTH + SPLIT_CHEVRON_WIDTH,
44 TOOL_WIDTH,
41 pub fn fixed_controls_width(has_camera_menu: bool, has_more: bool, has_leave_menu: bool) -> f32 {
42 let mut widths = vec![
43 CONTROL_SIZE + CAMERA_MENU_WIDTH,
44 CONTROL_SIZE
45 + if has_camera_menu {
46 CAMERA_MENU_WIDTH
47 } else {
48 0.
49 },
50 CONTROL_SIZE,
51 LEAVE_WIDTH,
45 52 ];
46 let devices_width = devices.iter().sum::<f32>() + TOOL_GAP * (devices.len() - 1) as f32;
47 let more_width = if has_more { TOOL_WIDTH } else { 0. } + if has_pop_out { TOOL_WIDTH + TOOL_GAP } else { 0. };
48 let leave_width = LEAVE_WIDTH
49 + if has_leave_menu {
50 SPLIT_CHEVRON_WIDTH + 4. + 1.
51 } else {
52 0.
53 };
54 devices_width + more_width + leave_width + 5. * GROUP_GAP + 2. * GROUP_DIVIDER_WIDTH
55 }
56
57 pub fn in_more_menu(folded: Vec<Foldable>) -> Vec<Foldable> {
58 let mut items = vec![Foldable::View];
59 for control in folded {
60 items.push(control);
61 if control == Foldable::Reactions {
62 items.push(Foldable::RaiseHand);
63 }
53 if has_more {
54 widths.push(CONTROL_SIZE);
55 }
56 if has_leave_menu {
57 widths.push(CONTROL_SIZE);
64 58 }
65 items
59 widths.iter().sum::<f32>() + CONTROL_GAP * (widths.len() - 1) as f32
66 60 }
67 61
68 62 pub fn folded_for_width(available: f32, fixed: f32, present: &[Foldable]) -> Vec<Foldable> {
69 let room = available - TITLE_RESERVE - fixed;
63 let room = available - 2. * CONTROLS_PADDING - fixed;
70 64 let fitting = if room <= 0. {
71 65 0
72 66 } else {
73 (room / (TOOL_WIDTH + TOOL_GAP)).floor() as usize
67 (room / (CONTROL_SIZE + CONTROL_GAP)).floor() as usize
74 68 };
75 69 let folded_count = present.len().saturating_sub(fitting);
76 70 present[..folded_count].to_vec()
@@ -136,11 +130,17 @@ fn reactions_submenu(
136 130 for reaction in Reaction::ALL {
137 131 let app = app.clone();
138 132 menu = menu.item(
139 PopupMenuItem::new(format!("{} {}", reaction_glyph(&reaction), reaction.name()))
140 .disabled(!can_react)
141 .on_click(move |_, _, cx| {
142 app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx))
143 }),
133 PopupMenuItem::new(format!(
134 "{} {}",
135 reaction_glyph(&reaction),
136 reaction.name()
137 ))
138 .disabled(!can_react)
139 .on_click(move |_, _, cx| {
140 app.update(cx, |state, cx| {
141 state.send_call_reaction(reaction.clone(), cx)
142 })
143 }),
144 144 );
145 145 }
146 146 menu
@@ -162,9 +162,13 @@ fn hand_item(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> Pop
162 162 fn people_item(popup: PopupMenu, app: &Entity<AppState>, open: bool) -> PopupMenu {
163 163 let app = app.clone();
164 164 popup.item(
165 PopupMenuItem::new(if open { "Close the people list" } else { "Show people" })
166 .icon(IconName::Users)
167 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_people(cx))),
165 PopupMenuItem::new(if open {
166 "Close the people list"
167 } else {
168 "Show people"
169 })
170 .icon(IconName::Users)
171 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_people(cx))),
168 172 )
169 173 }
170 174
@@ -184,28 +188,37 @@ fn chat_item(popup: PopupMenu, app: &Entity<AppState>, folded: &FoldedControls)
184 188
185 189 #[cfg(test)]
186 190 mod tests {
187 use super::{Foldable, TITLE_RESERVE, fixed_controls_width, folded_for_width, in_more_menu};
188
189 const ALL: [Foldable; 3] = [Foldable::Reactions, Foldable::People, Foldable::Chat];
190 const SLOT: f32 = 56. + 2.;
191 use super::{CONTROLS_PADDING, Foldable, fixed_controls_width, folded_for_width};
192
193 const ALL: [Foldable; 5] = [
194 Foldable::View,
195 Foldable::Reactions,
196 Foldable::RaiseHand,
197 Foldable::People,
198 Foldable::Chat,
199 ];
200 const SLOT: f32 = 44. + 12.;
191 201 const FIXED: f32 = 400.;
192 202
193 203 fn width_for(fitting: f32) -> f32 {
194 FIXED + TITLE_RESERVE + fitting * SLOT
204 FIXED + 2. * CONTROLS_PADDING + fitting * SLOT
195 205 }
196 206
197 207 #[test]
198 208 fn nothing_folds_when_everything_fits() {
199 assert!(folded_for_width(width_for(3.), FIXED, &ALL).is_empty());
209 assert!(folded_for_width(width_for(5.), FIXED, &ALL).is_empty());
200 210 assert!(folded_for_width(width_for(9.), FIXED, &ALL).is_empty());
201 211 }
202 212
203 213 #[test]
204 fn folds_reactions_first_then_people() {
205 assert_eq!(folded_for_width(width_for(2.), FIXED, &ALL), [Foldable::Reactions]);
214 fn folds_view_first_then_reactions() {
215 assert_eq!(
216 folded_for_width(width_for(4.), FIXED, &ALL),
217 [Foldable::View]
218 );
206 219 assert_eq!(
207 folded_for_width(width_for(1.), FIXED, &ALL),
208 [Foldable::Reactions, Foldable::People]
220 folded_for_width(width_for(3.), FIXED, &ALL),
221 [Foldable::View, Foldable::Reactions]
209 222 );
210 223 }
211 224
@@ -216,20 +229,20 @@ mod tests {
216 229 }
217 230
218 231 #[test]
219 fn view_always_sits_in_more_and_the_hand_follows_the_reactions() {
220 assert_eq!(in_more_menu(Vec::new()), [Foldable::View]);
232 fn only_present_controls_are_counted() {
233 let present = [Foldable::View, Foldable::People];
234 assert!(folded_for_width(width_for(2.), FIXED, &present).is_empty());
221 235 assert_eq!(
222 in_more_menu(vec![Foldable::Reactions, Foldable::Chat]),
223 [Foldable::View, Foldable::Reactions, Foldable::RaiseHand, Foldable::Chat]
236 folded_for_width(width_for(1.), FIXED, &present),
237 [Foldable::View]
224 238 );
225 239 }
226 240
227 241 #[test]
228 242 fn fixed_width_counts_optional_controls() {
229 let base = fixed_controls_width(false, false, false, false);
230 assert_eq!(fixed_controls_width(true, false, false, false), base + 20.);
231 assert_eq!(fixed_controls_width(false, true, false, false), base + 56.);
232 assert_eq!(fixed_controls_width(false, false, true, false), base + 25.);
233 assert_eq!(fixed_controls_width(false, false, false, true), base + 58.);
243 let base = fixed_controls_width(false, false, false);
244 assert_eq!(fixed_controls_width(true, false, false), base + 28.);
245 assert_eq!(fixed_controls_width(false, true, false), base + 44. + 12.);
246 assert_eq!(fixed_controls_width(false, false, true), base + 44. + 12.);
234 247 }
235 248 }
@@ -4,14 +4,15 @@ use gpui_kit::component::Icon;
4use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
4use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
5use gpui_kit::*;
5use gpui_kit::*;
6
6
7use super::call_toolbar::{GROUP_DIVIDER_WIDTH, GROUP_GAP, SPLIT_CHEVRON_WIDTH, TOOL_GAP, TOOL_WIDTH};
7use super::call_organizer::CAMERA_MENU_WIDTH;
8use super::call_view::reaction_glyph;
8use super::call_view::{CONTROL_SIZE, reaction_glyph};
9use super::call_view_menu::view_items;
9use super::call_view_menu::view_items;
10use crate::app_state::AppState;
10use crate::app_state::AppState;
11use crate::call::CallModel;
11use crate::call::CallModel;
12
12
13pub(super) const TITLE_RESERVE: f32 = 280.;
13pub(super) const CONTROL_GAP: f32 = 12.;
14const LEAVE_WIDTH: f32 = 96.;
14pub(super) const CONTROLS_PADDING: f32 = 16.;
15const LEAVE_WIDTH: f32 = 116.;
15
16
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Foldable {
18pub enum Foldable {
@@ -37,40 +38,33 @@ impl FoldedControls {
37 }
38 }
38}
39}
39
40
40pub fn fixed_controls_width(has_camera_menu: bool, has_more: bool, has_leave_menu: bool, has_pop_out: bool) -> f32 {
41pub fn fixed_controls_width(has_camera_menu: bool, has_more: bool, has_leave_menu: bool) -> f32 {
41 let devices = [
42 let mut widths = vec![
42 TOOL_WIDTH + if has_camera_menu { SPLIT_CHEVRON_WIDTH } else { 0. },
43 CONTROL_SIZE + CAMERA_MENU_WIDTH,
43 TOOL_WIDTH + SPLIT_CHEVRON_WIDTH,
44 CONTROL_SIZE
44 TOOL_WIDTH,
45 + if has_camera_menu {
46 CAMERA_MENU_WIDTH
47 } else {
48 0.
49 },
50 CONTROL_SIZE,
51 LEAVE_WIDTH,
45 ];
52 ];
46 let devices_width = devices.iter().sum::<f32>() + TOOL_GAP * (devices.len() - 1) as f32;
53 if has_more {
47 let more_width = if has_more { TOOL_WIDTH } else { 0. } + if has_pop_out { TOOL_WIDTH + TOOL_GAP } else { 0. };
54 widths.push(CONTROL_SIZE);
48 let leave_width = LEAVE_WIDTH
55 }
49 + if has_leave_menu {
56 if has_leave_menu {
50 SPLIT_CHEVRON_WIDTH + 4. + 1.
57 widths.push(CONTROL_SIZE);
51 } else {
52 0.
53 };
54 devices_width + more_width + leave_width + 5. * GROUP_GAP + 2. * GROUP_DIVIDER_WIDTH
55}
56
57pub fn in_more_menu(folded: Vec<Foldable>) -> Vec<Foldable> {
58 let mut items = vec![Foldable::View];
59 for control in folded {
60 items.push(control);
61 if control == Foldable::Reactions {
62 items.push(Foldable::RaiseHand);
63 }
64 }
58 }
65 items
59 widths.iter().sum::<f32>() + CONTROL_GAP * (widths.len() - 1) as f32
66}
60}
67
61
68pub fn folded_for_width(available: f32, fixed: f32, present: &[Foldable]) -> Vec<Foldable> {
62pub fn folded_for_width(available: f32, fixed: f32, present: &[Foldable]) -> Vec<Foldable> {
69 let room = available - TITLE_RESERVE - fixed;
63 let room = available - 2. * CONTROLS_PADDING - fixed;
70 let fitting = if room <= 0. {
64 let fitting = if room <= 0. {
71 0
65 0
72 } else {
66 } else {
73 (room / (TOOL_WIDTH + TOOL_GAP)).floor() as usize
67 (room / (CONTROL_SIZE + CONTROL_GAP)).floor() as usize
74 };
68 };
75 let folded_count = present.len().saturating_sub(fitting);
69 let folded_count = present.len().saturating_sub(fitting);
76 present[..folded_count].to_vec()
70 present[..folded_count].to_vec()
@@ -136,11 +130,17 @@ fn reactions_submenu(
136 for reaction in Reaction::ALL {
130 for reaction in Reaction::ALL {
137 let app = app.clone();
131 let app = app.clone();
138 menu = menu.item(
132 menu = menu.item(
139 PopupMenuItem::new(format!("{} {}", reaction_glyph(&reaction), reaction.name()))
133 PopupMenuItem::new(format!(
140 .disabled(!can_react)
134 "{} {}",
141 .on_click(move |_, _, cx| {
135 reaction_glyph(&reaction),
142 app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx))
136 reaction.name()
143 }),
137 ))
138 .disabled(!can_react)
139 .on_click(move |_, _, cx| {
140 app.update(cx, |state, cx| {
141 state.send_call_reaction(reaction.clone(), cx)
142 })
143 }),
144 );
144 );
145 }
145 }
146 menu
146 menu
@@ -162,9 +162,13 @@ fn hand_item(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> Pop
162fn people_item(popup: PopupMenu, app: &Entity<AppState>, open: bool) -> PopupMenu {
162fn people_item(popup: PopupMenu, app: &Entity<AppState>, open: bool) -> PopupMenu {
163 let app = app.clone();
163 let app = app.clone();
164 popup.item(
164 popup.item(
165 PopupMenuItem::new(if open { "Close the people list" } else { "Show people" })
165 PopupMenuItem::new(if open {
166 .icon(IconName::Users)
166 "Close the people list"
167 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_people(cx))),
167 } else {
168 "Show people"
169 })
170 .icon(IconName::Users)
171 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_people(cx))),
168 )
172 )
169}
173}
170
174
@@ -184,28 +188,37 @@ fn chat_item(popup: PopupMenu, app: &Entity<AppState>, folded: &FoldedControls)
184
188
185#[cfg(test)]
189#[cfg(test)]
186mod tests {
190mod tests {
187 use super::{Foldable, TITLE_RESERVE, fixed_controls_width, folded_for_width, in_more_menu};
191 use super::{CONTROLS_PADDING, Foldable, fixed_controls_width, folded_for_width};
188
192
189 const ALL: [Foldable; 3] = [Foldable::Reactions, Foldable::People, Foldable::Chat];
193 const ALL: [Foldable; 5] = [
190 const SLOT: f32 = 56. + 2.;
194 Foldable::View,
195 Foldable::Reactions,
196 Foldable::RaiseHand,
197 Foldable::People,
198 Foldable::Chat,
199 ];
200 const SLOT: f32 = 44. + 12.;
191 const FIXED: f32 = 400.;
201 const FIXED: f32 = 400.;
192
202
193 fn width_for(fitting: f32) -> f32 {
203 fn width_for(fitting: f32) -> f32 {
194 FIXED + TITLE_RESERVE + fitting * SLOT
204 FIXED + 2. * CONTROLS_PADDING + fitting * SLOT
195 }
205 }
196
206
197 #[test]
207 #[test]
198 fn nothing_folds_when_everything_fits() {
208 fn nothing_folds_when_everything_fits() {
199 assert!(folded_for_width(width_for(3.), FIXED, &ALL).is_empty());
209 assert!(folded_for_width(width_for(5.), FIXED, &ALL).is_empty());
200 assert!(folded_for_width(width_for(9.), FIXED, &ALL).is_empty());
210 assert!(folded_for_width(width_for(9.), FIXED, &ALL).is_empty());
201 }
211 }
202
212
203 #[test]
213 #[test]
204 fn folds_reactions_first_then_people() {
214 fn folds_view_first_then_reactions() {
205 assert_eq!(folded_for_width(width_for(2.), FIXED, &ALL), [Foldable::Reactions]);
215 assert_eq!(
216 folded_for_width(width_for(4.), FIXED, &ALL),
217 [Foldable::View]
218 );
206 assert_eq!(
219 assert_eq!(
207 folded_for_width(width_for(1.), FIXED, &ALL),
220 folded_for_width(width_for(3.), FIXED, &ALL),
208 [Foldable::Reactions, Foldable::People]
221 [Foldable::View, Foldable::Reactions]
209 );
222 );
210 }
223 }
211
224
@@ -216,20 +229,20 @@ mod tests {
216 }
229 }
217
230
218 #[test]
231 #[test]
219 fn view_always_sits_in_more_and_the_hand_follows_the_reactions() {
232 fn only_present_controls_are_counted() {
220 assert_eq!(in_more_menu(Vec::new()), [Foldable::View]);
233 let present = [Foldable::View, Foldable::People];
234 assert!(folded_for_width(width_for(2.), FIXED, &present).is_empty());
221 assert_eq!(
235 assert_eq!(
222 in_more_menu(vec![Foldable::Reactions, Foldable::Chat]),
236 folded_for_width(width_for(1.), FIXED, &present),
223 [Foldable::View, Foldable::Reactions, Foldable::RaiseHand, Foldable::Chat]
237 [Foldable::View]
224 );
238 );
225 }
239 }
226
240
227 #[test]
241 #[test]
228 fn fixed_width_counts_optional_controls() {
242 fn fixed_width_counts_optional_controls() {
229 let base = fixed_controls_width(false, false, false, false);
243 let base = fixed_controls_width(false, false, false);
230 assert_eq!(fixed_controls_width(true, false, false, false), base + 20.);
244 assert_eq!(fixed_controls_width(true, false, false), base + 28.);
231 assert_eq!(fixed_controls_width(false, true, false, false), base + 56.);
245 assert_eq!(fixed_controls_width(false, true, false), base + 44. + 12.);
232 assert_eq!(fixed_controls_width(false, false, true, false), base + 25.);
246 assert_eq!(fixed_controls_width(false, false, true), base + 44. + 12.);
233 assert_eq!(fixed_controls_width(false, false, false, true), base + 58.);
234 }
247 }
235}
248}
crates/app/src/views/call_controls.rs +20 −4
@@ -64,7 +64,9 @@ pub fn header_call_controls(
64 64 .font_weight(FontWeight::SEMIBOLD)
65 65 .cursor_pointer()
66 66 .hover(|button| button.opacity(0.85))
67 .when(running, |button| button.child(icon(IconName::Phone, 14., foreground)))
67 .when(running, |button| {
68 button.child(icon(IconName::Phone, 14., foreground))
69 })
68 70 .child("Join")
69 71 .on_click(move |_, _, cx| {
70 72 join_app.update(cx, |state, cx| state.join_chat_meeting(&join_id, cx));
@@ -105,8 +107,18 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
105 107 Button::new(HEADER_VIDEO_CALL_TAG)
106 108 .ghost()
107 109 .h(px(BUTTON_SIZE))
108 .map(|button| if labelled { button.px(px(8.)) } else { button.p_0().w(px(BUTTON_SIZE)) })
109 .tooltip(if meet_now { MEET_NOW_LABEL } else { VIDEO_CALL_LABEL })
110 .map(|button| {
111 if labelled {
112 button.px(px(8.))
113 } else {
114 button.p_0().w(px(BUTTON_SIZE))
115 }
116 })
117 .tooltip(if meet_now {
118 MEET_NOW_LABEL
119 } else {
120 VIDEO_CALL_LABEL
121 })
110 122 .debug_selector(|| HEADER_VIDEO_CALL_TAG.into())
111 123 .child(
112 124 h_flex()
@@ -133,7 +145,11 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
133 145 .h(px(BUTTON_SIZE))
134 146 .tooltip(CALL_OPTIONS_LABEL)
135 147 .debug_selector(|| HEADER_CALL_OPTIONS_TAG.into())
136 .child(icon(IconName::ChevronDown, CHEVRON_GLYPH, theme::text_soft()))
148 .child(icon(
149 IconName::ChevronDown,
150 CHEVRON_GLYPH,
151 theme::text_soft(),
152 ))
137 153 .dropdown_menu(move |popup, _, _| {
138 154 let (video, audio) = (menu_app.clone(), menu_app.clone());
139 155 let popup = if meet_now {
@@ -64,7 +64,9 @@ pub fn header_call_controls(
64 .font_weight(FontWeight::SEMIBOLD)
64 .font_weight(FontWeight::SEMIBOLD)
65 .cursor_pointer()
65 .cursor_pointer()
66 .hover(|button| button.opacity(0.85))
66 .hover(|button| button.opacity(0.85))
67 .when(running, |button| button.child(icon(IconName::Phone, 14., foreground)))
67 .when(running, |button| {
68 button.child(icon(IconName::Phone, 14., foreground))
69 })
68 .child("Join")
70 .child("Join")
69 .on_click(move |_, _, cx| {
71 .on_click(move |_, _, cx| {
70 join_app.update(cx, |state, cx| state.join_chat_meeting(&join_id, cx));
72 join_app.update(cx, |state, cx| state.join_chat_meeting(&join_id, cx));
@@ -105,8 +107,18 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
105 Button::new(HEADER_VIDEO_CALL_TAG)
107 Button::new(HEADER_VIDEO_CALL_TAG)
106 .ghost()
108 .ghost()
107 .h(px(BUTTON_SIZE))
109 .h(px(BUTTON_SIZE))
108 .map(|button| if labelled { button.px(px(8.)) } else { button.p_0().w(px(BUTTON_SIZE)) })
110 .map(|button| {
109 .tooltip(if meet_now { MEET_NOW_LABEL } else { VIDEO_CALL_LABEL })
111 if labelled {
112 button.px(px(8.))
113 } else {
114 button.p_0().w(px(BUTTON_SIZE))
115 }
116 })
117 .tooltip(if meet_now {
118 MEET_NOW_LABEL
119 } else {
120 VIDEO_CALL_LABEL
121 })
110 .debug_selector(|| HEADER_VIDEO_CALL_TAG.into())
122 .debug_selector(|| HEADER_VIDEO_CALL_TAG.into())
111 .child(
123 .child(
112 h_flex()
124 h_flex()
@@ -133,7 +145,11 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
133 .h(px(BUTTON_SIZE))
145 .h(px(BUTTON_SIZE))
134 .tooltip(CALL_OPTIONS_LABEL)
146 .tooltip(CALL_OPTIONS_LABEL)
135 .debug_selector(|| HEADER_CALL_OPTIONS_TAG.into())
147 .debug_selector(|| HEADER_CALL_OPTIONS_TAG.into())
136 .child(icon(IconName::ChevronDown, CHEVRON_GLYPH, theme::text_soft()))
148 .child(icon(
149 IconName::ChevronDown,
150 CHEVRON_GLYPH,
151 theme::text_soft(),
152 ))
137 .dropdown_menu(move |popup, _, _| {
153 .dropdown_menu(move |popup, _, _| {
138 let (video, audio) = (menu_app.clone(), menu_app.clone());
154 let (video, audio) = (menu_app.clone(), menu_app.clone());
139 let popup = if meet_now {
155 let popup = if meet_now {
crates/app/src/views/call_extras.rs +18 −5
@@ -32,7 +32,11 @@ fn dark_text() -> Hsla {
32 32 }
33 33
34 34 pub fn recording_chip(model: &CallModel) -> Option<AnyElement> {
35 let chip = crate::call::recording_chip(model.recording, model.recording_audio_only, model.transcribing)?;
35 let chip = crate::call::recording_chip(
36 model.recording,
37 model.recording_audio_only,
38 model.transcribing,
39 )?;
36 40 let color = match chip {
37 41 RecordingChip::Transcribing => theme::accent_text(),
38 42 RecordingChip::Recording | RecordingChip::RecordingAudio => theme::red(),
@@ -278,7 +282,12 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
278 282 )
279 283 }
280 284
281 pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, window: &mut Window, cx: &mut App) {
285 pub fn confirm_record_action(
286 app: &Entity<AppState>,
287 action: RecordAction,
288 window: &mut Window,
289 cx: &mut App,
290 ) {
282 291 let Some(title) = action.confirm_title() else {
283 292 app.update(cx, |state, cx| state.run_call_record_action(action, cx));
284 293 return;
@@ -302,14 +311,18 @@ pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, windo
302 311 pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
303 312 let candidates = app.read(cx).transfer_candidates();
304 313 let picker_app = app.clone();
305 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
306 app.update(cx, |state, cx| state.open_transfer_picker(picker.into(), cx));
314 let picker =
315 cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
316 app.update(cx, |state, cx| {
317 state.open_transfer_picker(picker.into(), cx)
318 });
307 319 }
308 320
309 321 pub fn open_invite_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
310 322 let candidates = app.read(cx).invite_candidates();
311 323 let picker_app = app.clone();
312 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
324 let picker =
325 cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
313 326 app.update(cx, |state, cx| state.open_invite_picker(picker.into(), cx));
314 327 }
315 328
@@ -32,7 +32,11 @@ fn dark_text() -> Hsla {
32}
32}
33
33
34pub fn recording_chip(model: &CallModel) -> Option<AnyElement> {
34pub fn recording_chip(model: &CallModel) -> Option<AnyElement> {
35 let chip = crate::call::recording_chip(model.recording, model.recording_audio_only, model.transcribing)?;
35 let chip = crate::call::recording_chip(
36 model.recording,
37 model.recording_audio_only,
38 model.transcribing,
39 )?;
36 let color = match chip {
40 let color = match chip {
37 RecordingChip::Transcribing => theme::accent_text(),
41 RecordingChip::Transcribing => theme::accent_text(),
38 RecordingChip::Recording | RecordingChip::RecordingAudio => theme::red(),
42 RecordingChip::Recording | RecordingChip::RecordingAudio => theme::red(),
@@ -278,7 +282,12 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
278 )
282 )
279}
283}
280
284
281pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, window: &mut Window, cx: &mut App) {
285pub fn confirm_record_action(
286 app: &Entity<AppState>,
287 action: RecordAction,
288 window: &mut Window,
289 cx: &mut App,
290) {
282 let Some(title) = action.confirm_title() else {
291 let Some(title) = action.confirm_title() else {
283 app.update(cx, |state, cx| state.run_call_record_action(action, cx));
292 app.update(cx, |state, cx| state.run_call_record_action(action, cx));
284 return;
293 return;
@@ -302,14 +311,18 @@ pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, windo
302pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
311pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
303 let candidates = app.read(cx).transfer_candidates();
312 let candidates = app.read(cx).transfer_candidates();
304 let picker_app = app.clone();
313 let picker_app = app.clone();
305 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
314 let picker =
306 app.update(cx, |state, cx| state.open_transfer_picker(picker.into(), cx));
315 cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
316 app.update(cx, |state, cx| {
317 state.open_transfer_picker(picker.into(), cx)
318 });
307}
319}
308
320
309pub fn open_invite_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
321pub fn open_invite_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
310 let candidates = app.read(cx).invite_candidates();
322 let candidates = app.read(cx).invite_candidates();
311 let picker_app = app.clone();
323 let picker_app = app.clone();
312 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
324 let picker =
325 cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
313 app.update(cx, |state, cx| state.open_invite_picker(picker.into(), cx));
326 app.update(cx, |state, cx| state.open_invite_picker(picker.into(), cx));
314}
327}
315
328
crates/app/src/views/call_health.rs +13 −6
@@ -93,9 +93,12 @@ fn health_popover(model: &CallModel) -> Div {
93 93 None => v_flex().child(row("Quality", "Measuring...".to_owned())),
94 94 };
95 95 let transport = health.iter().flat_map(|health| {
96 [Some(transport_text(health)), media_text(health, &model.peer_name)]
97 .into_iter()
98 .flatten()
96 [
97 Some(transport_text(health)),
98 media_text(health, &model.peer_name),
99 ]
100 .into_iter()
101 .flatten()
99 102 });
100 103 v_flex()
101 104 .debug_selector(|| "shell/islands/main/call-health-popover".into())
@@ -108,7 +111,12 @@ fn health_popover(model: &CallModel) -> Div {
108 111 .font_weight(FontWeight::SEMIBOLD)
109 112 .child("Call health"),
110 113 )
111 .child(v_flex().gap(px(6.)).child(section_title("Network")).child(network))
114 .child(
115 v_flex()
116 .gap(px(6.))
117 .child(section_title("Network"))
118 .child(network),
119 )
112 120 .child(
113 121 v_flex()
114 122 .gap(px(6.))
@@ -200,8 +208,7 @@ pub fn health_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEle
200 208 .hover(|button| button.bg(dark_text().opacity(0.12)))
201 209 .child(symbol("close", 16., dark_text()))
202 210 .on_click(move |_, _, cx| {
203 close_app
204 .update(cx, |state, cx| state.close_call_health_banner(banner, cx))
211 close_app.update(cx, |state, cx| state.close_call_health_banner(banner, cx))
205 212 }),
206 213 )
207 214 .into_any_element(),
@@ -93,9 +93,12 @@ fn health_popover(model: &CallModel) -> Div {
93 None => v_flex().child(row("Quality", "Measuring...".to_owned())),
93 None => v_flex().child(row("Quality", "Measuring...".to_owned())),
94 };
94 };
95 let transport = health.iter().flat_map(|health| {
95 let transport = health.iter().flat_map(|health| {
96 [Some(transport_text(health)), media_text(health, &model.peer_name)]
96 [
97 .into_iter()
97 Some(transport_text(health)),
98 .flatten()
98 media_text(health, &model.peer_name),
99 ]
100 .into_iter()
101 .flatten()
99 });
102 });
100 v_flex()
103 v_flex()
101 .debug_selector(|| "shell/islands/main/call-health-popover".into())
104 .debug_selector(|| "shell/islands/main/call-health-popover".into())
@@ -108,7 +111,12 @@ fn health_popover(model: &CallModel) -> Div {
108 .font_weight(FontWeight::SEMIBOLD)
111 .font_weight(FontWeight::SEMIBOLD)
109 .child("Call health"),
112 .child("Call health"),
110 )
113 )
111 .child(v_flex().gap(px(6.)).child(section_title("Network")).child(network))
114 .child(
115 v_flex()
116 .gap(px(6.))
117 .child(section_title("Network"))
118 .child(network),
119 )
112 .child(
120 .child(
113 v_flex()
121 v_flex()
114 .gap(px(6.))
122 .gap(px(6.))
@@ -200,8 +208,7 @@ pub fn health_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEle
200 .hover(|button| button.bg(dark_text().opacity(0.12)))
208 .hover(|button| button.bg(dark_text().opacity(0.12)))
201 .child(symbol("close", 16., dark_text()))
209 .child(symbol("close", 16., dark_text()))
202 .on_click(move |_, _, cx| {
210 .on_click(move |_, _, cx| {
203 close_app
211 close_app.update(cx, |state, cx| state.close_call_health_banner(banner, cx))
204 .update(cx, |state, cx| state.close_call_health_banner(banner, cx))
205 }),
212 }),
206 )
213 )
207 .into_any_element(),
214 .into_any_element(),
crates/app/src/views/call_layouts.rs +94 −82
@@ -1,7 +1,7 @@
1 1 use std::time::Instant;
2 2
3 use gpui_kit::component::scroll::ScrollableElement as _;
4 3 use gpui_kit::assets::IconName;
4 use gpui_kit::component::scroll::ScrollableElement as _;
5 5 use gpui_kit::component::{
6 6 button::{Button, ButtonVariants as _},
7 7 h_flex,
@@ -18,14 +18,16 @@ use super::call_view::{own_tile, person_tile};
18 18 use super::widgets::icon;
19 19 use crate::app_state::AppState;
20 20 use crate::call::{
21 ActiveCall, CallLayout, CallModel, GRID_PADDING, STRIP_GAP, SpeakerSplit,
22 StripSplit, TILE_GAP, Tile, TileSize, focus_stage_size, gallery_grid, gallery_page,
23 measured_stage, shown_bubbles, speaker_split, strip_split,
21 ActiveCall, CallLayout, CallModel, GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP,
22 Tile, TileSize, focus_stage_size, gallery_grid, gallery_split, measured_stage, shown_bubbles,
23 speaker_split, strip_split,
24 24 };
25 25 use crate::theme;
26 26
27 27 const MEASURE_TOLERANCE: f32 = 0.5;
28 28 const OVERLAY_INSET: f32 = 16.;
29 const DIVIDER_LINE: f32 = 4.;
30 const DIVIDER_LENGTH: f32 = 48.;
29 31 const CHIP_TOP: f32 = 12.;
30 32 const TILE_RADIUS: f32 = 12.;
31 33 const HIDDEN_LIST_WIDTH: f32 = 260.;
@@ -40,10 +42,6 @@ const BUBBLE_FADE_FROM: f32 = 0.9;
40 42 const BUBBLE_BACKGROUND: f32 = 0.72;
41 43 const CHIP_BACKGROUND: f32 = 0.6;
42 44 pub const FULLSCREEN_HINT: &str = "Press Esc to exit full screen";
43 pub const GALLERY_PAGER_TAG: &str = "shell/islands/main/call-stage/pager";
44 const PAGER_HEIGHT: f32 = 32.;
45 const PAGER_BUTTON: f32 = 28.;
46 const PAGER_ICON: f32 = 16.;
47 45
48 46 fn measure_stage(call: &ActiveCall) -> impl IntoElement {
49 47 let stage_size = call.stage_size.clone();
@@ -352,58 +350,6 @@ fn rows_of(cells: Vec<AnyElement>, columns: usize) -> Vec<Div> {
352 350 }
353 351 }
354 352
355 fn pager_button(
356 app: &Entity<AppState>,
357 id: &'static str,
358 glyph: IconName,
359 tooltip: &'static str,
360 forward: bool,
361 enabled: bool,
362 ) -> AnyElement {
363 let app = app.clone();
364 let color = if enabled { theme::text() } else { theme::text_faint() };
365 div()
366 .id(id)
367 .size(px(PAGER_BUTTON))
368 .flex()
369 .items_center()
370 .justify_center()
371 .rounded_full()
372 .child(icon(glyph, PAGER_ICON, color))
373 .when(enabled, |button| {
374 button
375 .cursor_pointer()
376 .hover(|button| button.bg(theme::row_hover()))
377 .tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx))
378 .on_click(move |_, _, cx| {
379 app.update(cx, |state, cx| state.turn_call_gallery_page(forward, cx));
380 })
381 })
382 .into_any_element()
383 }
384
385 fn gallery_pager(app: &Entity<AppState>, page: usize, pages: usize) -> AnyElement {
386 h_flex()
387 .debug_selector(|| GALLERY_PAGER_TAG.into())
388 .h(px(PAGER_HEIGHT))
389 .px(px(2.))
390 .gap(px(4.))
391 .items_center()
392 .rounded_full()
393 .bg(theme::row_hover())
394 .child(pager_button(app, "call-gallery-previous", IconName::ChevronLeft, "Previous page", false, page > 0))
395 .child(
396 div()
397 .min_w(px(40.))
398 .text_center()
399 .text_size(px(12.))
400 .text_color(theme::text_soft())
401 .child(format!("{} / {}", page + 1, pages)),
402 )
403 .child(pager_button(app, "call-gallery-next", IconName::ChevronRight, "Next page", true, page + 1 < pages))
404 .into_any_element()
405 }
406
407 353 fn gallery_body(
408 354 app: &Entity<AppState>,
409 355 state: &AppState,
@@ -411,28 +357,30 @@ fn gallery_body(
411 357 now: Instant,
412 358 stage: (f32, f32),
413 359 ) -> AnyElement {
414 let page = gallery_page(model);
415 let paged = page.pages > 1;
416 let pager_room = if paged { PAGER_HEIGHT + TILE_GAP } else { 0. };
417 let cells = page.tiles.len() + usize::from(page.own);
360 let (others, overflow) = gallery_split(model);
361 let own_cells = model.own_cells();
362 let cells = overflow.shown + own_cells + usize::from(overflow.hidden > 0);
418 363 let grid = gallery_grid(
419 364 cells,
420 365 stage.0 - 2. * GRID_PADDING,
421 stage.1 - 2. * GRID_PADDING - pager_room,
366 stage.1 - 2. * GRID_PADDING,
422 367 TILE_GAP,
423 368 );
424 369 let size = TileSize::sixteen_by_nine(grid.tile_width.floor());
425 let mut tiles: Vec<AnyElement> = page
426 .tiles
370 let shown = &others[..overflow.shown];
371 let mut tiles: Vec<AnyElement> = shown
427 372 .iter()
428 373 .map(|tile| person_tile(app, state, model, tile, size, now))
429 374 .collect();
430 if page.own {
375 if own_cells > 0 {
431 376 tiles.insert(
432 own_slot(model, &page.tiles),
377 own_slot(model, shown),
433 378 own_tile(app, state, model, size, now),
434 379 );
435 380 }
381 if overflow.hidden > 0 {
382 tiles.push(overflow_tile(app, state, size, &others[overflow.shown..]));
383 }
436 384 v_flex()
437 385 .absolute()
438 386 .inset_0()
@@ -440,7 +388,6 @@ fn gallery_body(
440 388 .justify_center()
441 389 .gap(px(TILE_GAP))
442 390 .children(rows_of(tiles, grid.columns))
443 .when(paged, |body| body.child(gallery_pager(app, page.page, page.pages)))
444 391 .into_any_element()
445 392 }
446 393
@@ -451,10 +398,20 @@ fn speaker_body(
451 398 now: Instant,
452 399 stage: (f32, f32),
453 400 ) -> AnyElement {
454 let SpeakerSplit { focus, others, own_cells, plan } = speaker_split(model, stage);
401 let SpeakerSplit {
402 focus,
403 others,
404 own_cells,
405 plan,
406 } = speaker_split(model, stage);
455 407 let size = TileSize::sixteen_by_nine(plan.tile_width.floor());
456 408 let has_filmstrip = plan.overflow.shown + own_cells + usize::from(plan.overflow.hidden > 0) > 0;
457 let focus_size = focus_stage_size(stage, GRID_PADDING, TILE_GAP, has_filmstrip.then_some(size.height));
409 let focus_size = focus_stage_size(
410 stage,
411 GRID_PADDING,
412 TILE_GAP,
413 has_filmstrip.then_some(size.height),
414 );
458 415 let main = focus
459 416 .as_ref()
460 417 .and_then(|focus| render_focus_stage(app, state, focus, focus_size, now));
@@ -512,7 +469,11 @@ fn people_strip(
512 469 now: Instant,
513 470 stage: (f32, f32),
514 471 ) -> Stateful<Div> {
515 let StripSplit { others, plan } = strip_split(model, stage);
472 let StripSplit {
473 width,
474 others,
475 plan,
476 } = strip_split(model, state.call_strip_width, stage);
516 477 let size = TileSize::sixteen_by_nine(plan.tile_width);
517 478 let shown = &others[..plan.overflow.shown];
518 479 let mut cells: Vec<AnyElement> = shown
@@ -524,18 +485,51 @@ fn people_strip(
524 485 cells.insert(own_index, own_tile(app, state, model, size, now));
525 486 }
526 487 if plan.overflow.hidden > 0 {
527 cells.push(overflow_tile(app, state, size, &others[plan.overflow.shown..]));
488 cells.push(overflow_tile(
489 app,
490 state,
491 size,
492 &others[plan.overflow.shown..],
493 ));
528 494 }
529 h_flex()
495 v_flex()
530 496 .id("call-strip")
531 497 .debug_selector(|| "shell/islands/main/call-stage/share-strip".into())
532 498 .flex_none()
533 .w_full()
534 .justify_center()
499 .w(px(width))
500 .items_center()
535 501 .gap(px(STRIP_GAP))
536 502 .children(cells)
537 503 }
538 504
505 fn strip_divider(app: &Entity<AppState>, dragging: bool) -> Stateful<Div> {
506 let app = app.clone();
507 h_flex()
508 .id("call-strip-divider")
509 .debug_selector(|| "shell/islands/main/call-stage/share-divider".into())
510 .flex_none()
511 .w(px(TILE_GAP))
512 .h_full()
513 .items_center()
514 .justify_center()
515 .cursor_col_resize()
516 .child(
517 div()
518 .w(px(DIVIDER_LINE))
519 .h(px(DIVIDER_LENGTH))
520 .rounded_full()
521 .bg(if dragging {
522 theme::accent()
523 } else {
524 theme::border()
525 }),
526 )
527 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
528 let pointer_x = f32::from(event.position.x);
529 app.update(cx, |state, cx| state.begin_strip_drag(pointer_x, cx));
530 })
531 }
532
539 533 fn share_body(
540 534 app: &Entity<AppState>,
541 535 state: &AppState,
@@ -545,16 +539,34 @@ fn share_body(
545 539 layout: CallLayout,
546 540 stage: (f32, f32),
547 541 ) -> AnyElement {
548 v_flex()
542 let move_app = app.clone();
543 let up_app = app.clone();
544 let up_out_app = app.clone();
545 let dragging = state
546 .call
547 .as_ref()
548 .is_some_and(|call| call.share_stage.strip_drag.is_some());
549 h_flex()
549 550 .id("call-share-body")
550 551 .absolute()
551 552 .inset_0()
552 553 .p(px(GRID_PADDING))
553 .gap(px(STRIP_GAP))
554 .when(layout != CallLayout::Content, |column| {
555 column.child(people_strip(app, state, model, now, stage))
554 .items_center()
555 .on_mouse_move(move |event, _, cx| {
556 let pointer_x = f32::from(event.position.x);
557 move_app.update(cx, |state, cx| state.drag_strip_to(pointer_x, cx));
558 })
559 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
560 up_app.update(cx, |state, cx| state.end_strip_drag(cx));
561 })
562 .on_mouse_up_out(MouseButton::Left, move |_, _, cx| {
563 up_out_app.update(cx, |state, cx| state.end_strip_drag(cx));
564 })
565 .child(share)
566 .when(layout != CallLayout::Content, |row| {
567 row.child(strip_divider(app, dragging))
568 .child(people_strip(app, state, model, now, stage))
556 569 })
557 .child(h_flex().flex_1().min_h_0().w_full().child(share))
558 570 .into_any_element()
559 571 }
560 572
@@ -1,7 +1,7 @@
1use std::time::Instant;
1use std::time::Instant;
2
2
3use gpui_kit::component::scroll::ScrollableElement as _;
4use gpui_kit::assets::IconName;
3use gpui_kit::assets::IconName;
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::component::{
5use gpui_kit::component::{
6 button::{Button, ButtonVariants as _},
6 button::{Button, ButtonVariants as _},
7 h_flex,
7 h_flex,
@@ -18,14 +18,16 @@ use super::call_view::{own_tile, person_tile};
18use super::widgets::icon;
18use super::widgets::icon;
19use crate::app_state::AppState;
19use crate::app_state::AppState;
20use crate::call::{
20use crate::call::{
21 ActiveCall, CallLayout, CallModel, GRID_PADDING, STRIP_GAP, SpeakerSplit,
21 ActiveCall, CallLayout, CallModel, GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP,
22 StripSplit, TILE_GAP, Tile, TileSize, focus_stage_size, gallery_grid, gallery_page,
22 Tile, TileSize, focus_stage_size, gallery_grid, gallery_split, measured_stage, shown_bubbles,
23 measured_stage, shown_bubbles, speaker_split, strip_split,
23 speaker_split, strip_split,
24};
24};
25use crate::theme;
25use crate::theme;
26
26
27const MEASURE_TOLERANCE: f32 = 0.5;
27const MEASURE_TOLERANCE: f32 = 0.5;
28const OVERLAY_INSET: f32 = 16.;
28const OVERLAY_INSET: f32 = 16.;
29const DIVIDER_LINE: f32 = 4.;
30const DIVIDER_LENGTH: f32 = 48.;
29const CHIP_TOP: f32 = 12.;
31const CHIP_TOP: f32 = 12.;
30const TILE_RADIUS: f32 = 12.;
32const TILE_RADIUS: f32 = 12.;
31const HIDDEN_LIST_WIDTH: f32 = 260.;
33const HIDDEN_LIST_WIDTH: f32 = 260.;
@@ -40,10 +42,6 @@ const BUBBLE_FADE_FROM: f32 = 0.9;
40const BUBBLE_BACKGROUND: f32 = 0.72;
42const BUBBLE_BACKGROUND: f32 = 0.72;
41const CHIP_BACKGROUND: f32 = 0.6;
43const CHIP_BACKGROUND: f32 = 0.6;
42pub const FULLSCREEN_HINT: &str = "Press Esc to exit full screen";
44pub const FULLSCREEN_HINT: &str = "Press Esc to exit full screen";
43pub const GALLERY_PAGER_TAG: &str = "shell/islands/main/call-stage/pager";
44const PAGER_HEIGHT: f32 = 32.;
45const PAGER_BUTTON: f32 = 28.;
46const PAGER_ICON: f32 = 16.;
47
45
48fn measure_stage(call: &ActiveCall) -> impl IntoElement {
46fn measure_stage(call: &ActiveCall) -> impl IntoElement {
49 let stage_size = call.stage_size.clone();
47 let stage_size = call.stage_size.clone();
@@ -352,58 +350,6 @@ fn rows_of(cells: Vec<AnyElement>, columns: usize) -> Vec<Div> {
352 }
350 }
353}
351}
354
352
355fn pager_button(
356 app: &Entity<AppState>,
357 id: &'static str,
358 glyph: IconName,
359 tooltip: &'static str,
360 forward: bool,
361 enabled: bool,
362) -> AnyElement {
363 let app = app.clone();
364 let color = if enabled { theme::text() } else { theme::text_faint() };
365 div()
366 .id(id)
367 .size(px(PAGER_BUTTON))
368 .flex()
369 .items_center()
370 .justify_center()
371 .rounded_full()
372 .child(icon(glyph, PAGER_ICON, color))
373 .when(enabled, |button| {
374 button
375 .cursor_pointer()
376 .hover(|button| button.bg(theme::row_hover()))
377 .tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx))
378 .on_click(move |_, _, cx| {
379 app.update(cx, |state, cx| state.turn_call_gallery_page(forward, cx));
380 })
381 })
382 .into_any_element()
383}
384
385fn gallery_pager(app: &Entity<AppState>, page: usize, pages: usize) -> AnyElement {
386 h_flex()
387 .debug_selector(|| GALLERY_PAGER_TAG.into())
388 .h(px(PAGER_HEIGHT))
389 .px(px(2.))
390 .gap(px(4.))
391 .items_center()
392 .rounded_full()
393 .bg(theme::row_hover())
394 .child(pager_button(app, "call-gallery-previous", IconName::ChevronLeft, "Previous page", false, page > 0))
395 .child(
396 div()
397 .min_w(px(40.))
398 .text_center()
399 .text_size(px(12.))
400 .text_color(theme::text_soft())
401 .child(format!("{} / {}", page + 1, pages)),
402 )
403 .child(pager_button(app, "call-gallery-next", IconName::ChevronRight, "Next page", true, page + 1 < pages))
404 .into_any_element()
405}
406
407fn gallery_body(
353fn gallery_body(
408 app: &Entity<AppState>,
354 app: &Entity<AppState>,
409 state: &AppState,
355 state: &AppState,
@@ -411,28 +357,30 @@ fn gallery_body(
411 now: Instant,
357 now: Instant,
412 stage: (f32, f32),
358 stage: (f32, f32),
413) -> AnyElement {
359) -> AnyElement {
414 let page = gallery_page(model);
360 let (others, overflow) = gallery_split(model);
415 let paged = page.pages > 1;
361 let own_cells = model.own_cells();
416 let pager_room = if paged { PAGER_HEIGHT + TILE_GAP } else { 0. };
362 let cells = overflow.shown + own_cells + usize::from(overflow.hidden > 0);
417 let cells = page.tiles.len() + usize::from(page.own);
418 let grid = gallery_grid(
363 let grid = gallery_grid(
419 cells,
364 cells,
420 stage.0 - 2. * GRID_PADDING,
365 stage.0 - 2. * GRID_PADDING,
421 stage.1 - 2. * GRID_PADDING - pager_room,
366 stage.1 - 2. * GRID_PADDING,
422 TILE_GAP,
367 TILE_GAP,
423 );
368 );
424 let size = TileSize::sixteen_by_nine(grid.tile_width.floor());
369 let size = TileSize::sixteen_by_nine(grid.tile_width.floor());
425 let mut tiles: Vec<AnyElement> = page
370 let shown = &others[..overflow.shown];
426 .tiles
371 let mut tiles: Vec<AnyElement> = shown
427 .iter()
372 .iter()
428 .map(|tile| person_tile(app, state, model, tile, size, now))
373 .map(|tile| person_tile(app, state, model, tile, size, now))
429 .collect();
374 .collect();
430 if page.own {
375 if own_cells > 0 {
431 tiles.insert(
376 tiles.insert(
432 own_slot(model, &page.tiles),
377 own_slot(model, shown),
433 own_tile(app, state, model, size, now),
378 own_tile(app, state, model, size, now),
434 );
379 );
435 }
380 }
381 if overflow.hidden > 0 {
382 tiles.push(overflow_tile(app, state, size, &others[overflow.shown..]));
383 }
436 v_flex()
384 v_flex()
437 .absolute()
385 .absolute()
438 .inset_0()
386 .inset_0()
@@ -440,7 +388,6 @@ fn gallery_body(
440 .justify_center()
388 .justify_center()
441 .gap(px(TILE_GAP))
389 .gap(px(TILE_GAP))
442 .children(rows_of(tiles, grid.columns))
390 .children(rows_of(tiles, grid.columns))
443 .when(paged, |body| body.child(gallery_pager(app, page.page, page.pages)))
444 .into_any_element()
391 .into_any_element()
445}
392}
446
393
@@ -451,10 +398,20 @@ fn speaker_body(
451 now: Instant,
398 now: Instant,
452 stage: (f32, f32),
399 stage: (f32, f32),
453) -> AnyElement {
400) -> AnyElement {
454 let SpeakerSplit { focus, others, own_cells, plan } = speaker_split(model, stage);
401 let SpeakerSplit {
402 focus,
403 others,
404 own_cells,
405 plan,
406 } = speaker_split(model, stage);
455 let size = TileSize::sixteen_by_nine(plan.tile_width.floor());
407 let size = TileSize::sixteen_by_nine(plan.tile_width.floor());
456 let has_filmstrip = plan.overflow.shown + own_cells + usize::from(plan.overflow.hidden > 0) > 0;
408 let has_filmstrip = plan.overflow.shown + own_cells + usize::from(plan.overflow.hidden > 0) > 0;
457 let focus_size = focus_stage_size(stage, GRID_PADDING, TILE_GAP, has_filmstrip.then_some(size.height));
409 let focus_size = focus_stage_size(
410 stage,
411 GRID_PADDING,
412 TILE_GAP,
413 has_filmstrip.then_some(size.height),
414 );
458 let main = focus
415 let main = focus
459 .as_ref()
416 .as_ref()
460 .and_then(|focus| render_focus_stage(app, state, focus, focus_size, now));
417 .and_then(|focus| render_focus_stage(app, state, focus, focus_size, now));
@@ -512,7 +469,11 @@ fn people_strip(
512 now: Instant,
469 now: Instant,
513 stage: (f32, f32),
470 stage: (f32, f32),
514) -> Stateful<Div> {
471) -> Stateful<Div> {
515 let StripSplit { others, plan } = strip_split(model, stage);
472 let StripSplit {
473 width,
474 others,
475 plan,
476 } = strip_split(model, state.call_strip_width, stage);
516 let size = TileSize::sixteen_by_nine(plan.tile_width);
477 let size = TileSize::sixteen_by_nine(plan.tile_width);
517 let shown = &others[..plan.overflow.shown];
478 let shown = &others[..plan.overflow.shown];
518 let mut cells: Vec<AnyElement> = shown
479 let mut cells: Vec<AnyElement> = shown
@@ -524,18 +485,51 @@ fn people_strip(
524 cells.insert(own_index, own_tile(app, state, model, size, now));
485 cells.insert(own_index, own_tile(app, state, model, size, now));
525 }
486 }
526 if plan.overflow.hidden > 0 {
487 if plan.overflow.hidden > 0 {
527 cells.push(overflow_tile(app, state, size, &others[plan.overflow.shown..]));
488 cells.push(overflow_tile(
489 app,
490 state,
491 size,
492 &others[plan.overflow.shown..],
493 ));
528 }
494 }
529 h_flex()
495 v_flex()
530 .id("call-strip")
496 .id("call-strip")
531 .debug_selector(|| "shell/islands/main/call-stage/share-strip".into())
497 .debug_selector(|| "shell/islands/main/call-stage/share-strip".into())
532 .flex_none()
498 .flex_none()
533 .w_full()
499 .w(px(width))
534 .justify_center()
500 .items_center()
535 .gap(px(STRIP_GAP))
501 .gap(px(STRIP_GAP))
536 .children(cells)
502 .children(cells)
537}
503}
538
504
505fn strip_divider(app: &Entity<AppState>, dragging: bool) -> Stateful<Div> {
506 let app = app.clone();
507 h_flex()
508 .id("call-strip-divider")
509 .debug_selector(|| "shell/islands/main/call-stage/share-divider".into())
510 .flex_none()
511 .w(px(TILE_GAP))
512 .h_full()
513 .items_center()
514 .justify_center()
515 .cursor_col_resize()
516 .child(
517 div()
518 .w(px(DIVIDER_LINE))
519 .h(px(DIVIDER_LENGTH))
520 .rounded_full()
521 .bg(if dragging {
522 theme::accent()
523 } else {
524 theme::border()
525 }),
526 )
527 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
528 let pointer_x = f32::from(event.position.x);
529 app.update(cx, |state, cx| state.begin_strip_drag(pointer_x, cx));
530 })
531}
532
539fn share_body(
533fn share_body(
540 app: &Entity<AppState>,
534 app: &Entity<AppState>,
541 state: &AppState,
535 state: &AppState,
@@ -545,16 +539,34 @@ fn share_body(
545 layout: CallLayout,
539 layout: CallLayout,
546 stage: (f32, f32),
540 stage: (f32, f32),
547) -> AnyElement {
541) -> AnyElement {
548 v_flex()
542 let move_app = app.clone();
543 let up_app = app.clone();
544 let up_out_app = app.clone();
545 let dragging = state
546 .call
547 .as_ref()
548 .is_some_and(|call| call.share_stage.strip_drag.is_some());
549 h_flex()
549 .id("call-share-body")
550 .id("call-share-body")
550 .absolute()
551 .absolute()
551 .inset_0()
552 .inset_0()
552 .p(px(GRID_PADDING))
553 .p(px(GRID_PADDING))
553 .gap(px(STRIP_GAP))
554 .items_center()
554 .when(layout != CallLayout::Content, |column| {
555 .on_mouse_move(move |event, _, cx| {
555 column.child(people_strip(app, state, model, now, stage))
556 let pointer_x = f32::from(event.position.x);
557 move_app.update(cx, |state, cx| state.drag_strip_to(pointer_x, cx));
558 })
559 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
560 up_app.update(cx, |state, cx| state.end_strip_drag(cx));
561 })
562 .on_mouse_up_out(MouseButton::Left, move |_, _, cx| {
563 up_out_app.update(cx, |state, cx| state.end_strip_drag(cx));
564 })
565 .child(share)
566 .when(layout != CallLayout::Content, |row| {
567 row.child(strip_divider(app, dragging))
568 .child(people_strip(app, state, model, now, stage))
556 })
569 })
557 .child(h_flex().flex_1().min_h_0().w_full().child(share))
558 .into_any_element()
570 .into_any_element()
559}
571}
560
572
crates/app/src/views/call_mini.rs added +153 −0
@@ -0,0 +1,153 @@
1 use std::time::Instant;
2
3 use gpui_kit::assets::IconName;
4 use gpui_kit::component::h_flex;
5 use gpui_kit::*;
6
7 use super::call_mini_window::{
8 ControlIds, WINDOW_RADIUS, chip, controls_row, self_view, speaker_layer, speaker_name_chip,
9 speaker_speaking, tinted_chip,
10 };
11 use super::call_view::status_line;
12 use super::toolbar_placement::TimelineBounds;
13 use super::widgets::icon;
14 use crate::app_state::AppState;
15 use crate::theme;
16 use app_ui_kit::layout::ROW_PADDING;
17
18 const MINI_WIDTH: f32 = 256.;
19 const MINI_HEIGHT: f32 = 144.;
20 const MINI_RIGHT: f32 = 16.;
21 const MINI_BOTTOM: f32 = 40.;
22
23 pub struct CallMiniView {
24 app: Entity<AppState>,
25 timeline: TimelineBounds,
26 _app_subscription: Subscription,
27 _media_subscription: Option<Subscription>,
28 }
29
30 impl CallMiniView {
31 pub fn new(app: Entity<AppState>, timeline: TimelineBounds, cx: &mut Context<Self>) -> Self {
32 let app_subscription = cx.observe(&app, |_, _, cx| cx.notify());
33 let media_subscription = app
34 .read(cx)
35 .call_media
36 .clone()
37 .map(|media| cx.observe(&media, |_, _, cx| cx.notify()));
38 CallMiniView {
39 app,
40 timeline,
41 _app_subscription: app_subscription,
42 _media_subscription: media_subscription,
43 }
44 }
45 }
46
47 fn stop_sharing_pill(app: &Entity<AppState>) -> Stateful<Div> {
48 let stop_app = app.clone();
49 div()
50 .id("call-mini-stop-sharing")
51 .absolute()
52 .top(px(8.))
53 .right(px(8.))
54 .h(px(24.))
55 .px(px(10.))
56 .flex()
57 .items_center()
58 .gap(px(4.))
59 .rounded_full()
60 .bg(theme::red())
61 .text_color(theme::white())
62 .text_size(px(12.))
63 .font_weight(FontWeight::SEMIBOLD)
64 .cursor_pointer()
65 .hover(|button| button.opacity(0.85))
66 .child(icon(IconName::ScreenShare, 14., theme::white()))
67 .child("Stop")
68 .on_click(move |_, _, cx| {
69 cx.stop_propagation();
70 stop_app.update(cx, |state, cx| state.stop_call_share(cx));
71 })
72 }
73
74 impl Render for CallMiniView {
75 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
76 let state = self.app.read(cx);
77 let Some(call) = state.call.as_ref().filter(|call| !call.viewing) else {
78 return div().into_any_element();
79 };
80 let model = &call.model;
81 let now = Instant::now();
82 let (status, _) = status_line(model, now);
83 let viewport = window.viewport_size();
84 let (right, bottom) =
85 self.timeline
86 .get()
87 .map_or((px(MINI_RIGHT), px(MINI_BOTTOM)), |timeline| {
88 (
89 viewport.width - timeline.right() + px(ROW_PADDING),
90 viewport.height - timeline.bottom() + px(MINI_RIGHT),
91 )
92 });
93 let sharing = model.local_share.is_some();
94 let open_app = self.app.clone();
95 let back_app = self.app.clone();
96 let speaker_name = speaker_name_chip(state, model, now);
97 let border = if sharing {
98 theme::red()
99 } else if speaker_speaking(model) {
100 theme::green()
101 } else {
102 theme::border_strong()
103 };
104 let top_left = if sharing {
105 tinted_chip("Sharing".to_owned(), theme::red())
106 } else {
107 chip(status)
108 };
109 div()
110 .id("call-mini")
111 .group("call-mini")
112 .occlude()
113 .absolute()
114 .right(right)
115 .bottom(bottom)
116 .w(px(MINI_WIDTH))
117 .h(px(MINI_HEIGHT))
118 .overflow_hidden()
119 .rounded(px(WINDOW_RADIUS))
120 .bg(theme::surface())
121 .border_2()
122 .border_color(border)
123 .text_color(theme::text())
124 .shadow(theme::flyout_shadow())
125 .cursor_pointer()
126 .on_click(move |_, _, cx| {
127 open_app.update(cx, |state, cx| state.show_call(true, cx));
128 })
129 .child(speaker_layer(state, model, now))
130 .child(div().absolute().top(px(8.)).left(px(8.)).child(top_left))
131 .children(
132 speaker_name
133 .map(|name| h_flex().absolute().bottom(px(6.)).left(px(8.)).child(name)),
134 )
135 .children(if sharing {
136 Some(stop_sharing_pill(&self.app).into_any_element())
137 } else {
138 self_view(state, model, now)
139 })
140 .child(controls_row(
141 &self.app,
142 model,
143 ControlIds {
144 mute: "call-mini-mute",
145 back: "call-mini-back",
146 leave: "call-mini-leave",
147 },
148 "call-mini",
149 move |cx| back_app.update(cx, |state, cx| state.show_call(true, cx)),
150 ))
151 .into_any_element()
152 }
153 }
@@ -0,0 +1,153 @@
1use std::time::Instant;
2
3use gpui_kit::assets::IconName;
4use gpui_kit::component::h_flex;
5use gpui_kit::*;
6
7use super::call_mini_window::{
8 ControlIds, WINDOW_RADIUS, chip, controls_row, self_view, speaker_layer, speaker_name_chip,
9 speaker_speaking, tinted_chip,
10};
11use super::call_view::status_line;
12use super::toolbar_placement::TimelineBounds;
13use super::widgets::icon;
14use crate::app_state::AppState;
15use crate::theme;
16use app_ui_kit::layout::ROW_PADDING;
17
18const MINI_WIDTH: f32 = 256.;
19const MINI_HEIGHT: f32 = 144.;
20const MINI_RIGHT: f32 = 16.;
21const MINI_BOTTOM: f32 = 40.;
22
23pub struct CallMiniView {
24 app: Entity<AppState>,
25 timeline: TimelineBounds,
26 _app_subscription: Subscription,
27 _media_subscription: Option<Subscription>,
28}
29
30impl CallMiniView {
31 pub fn new(app: Entity<AppState>, timeline: TimelineBounds, cx: &mut Context<Self>) -> Self {
32 let app_subscription = cx.observe(&app, |_, _, cx| cx.notify());
33 let media_subscription = app
34 .read(cx)
35 .call_media
36 .clone()
37 .map(|media| cx.observe(&media, |_, _, cx| cx.notify()));
38 CallMiniView {
39 app,
40 timeline,
41 _app_subscription: app_subscription,
42 _media_subscription: media_subscription,
43 }
44 }
45}
46
47fn stop_sharing_pill(app: &Entity<AppState>) -> Stateful<Div> {
48 let stop_app = app.clone();
49 div()
50 .id("call-mini-stop-sharing")
51 .absolute()
52 .top(px(8.))
53 .right(px(8.))
54 .h(px(24.))
55 .px(px(10.))
56 .flex()
57 .items_center()
58 .gap(px(4.))
59 .rounded_full()
60 .bg(theme::red())
61 .text_color(theme::white())
62 .text_size(px(12.))
63 .font_weight(FontWeight::SEMIBOLD)
64 .cursor_pointer()
65 .hover(|button| button.opacity(0.85))
66 .child(icon(IconName::ScreenShare, 14., theme::white()))
67 .child("Stop")
68 .on_click(move |_, _, cx| {
69 cx.stop_propagation();
70 stop_app.update(cx, |state, cx| state.stop_call_share(cx));
71 })
72}
73
74impl Render for CallMiniView {
75 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
76 let state = self.app.read(cx);
77 let Some(call) = state.call.as_ref().filter(|call| !call.viewing) else {
78 return div().into_any_element();
79 };
80 let model = &call.model;
81 let now = Instant::now();
82 let (status, _) = status_line(model, now);
83 let viewport = window.viewport_size();
84 let (right, bottom) =
85 self.timeline
86 .get()
87 .map_or((px(MINI_RIGHT), px(MINI_BOTTOM)), |timeline| {
88 (
89 viewport.width - timeline.right() + px(ROW_PADDING),
90 viewport.height - timeline.bottom() + px(MINI_RIGHT),
91 )
92 });
93 let sharing = model.local_share.is_some();
94 let open_app = self.app.clone();
95 let back_app = self.app.clone();
96 let speaker_name = speaker_name_chip(state, model, now);
97 let border = if sharing {
98 theme::red()
99 } else if speaker_speaking(model) {
100 theme::green()
101 } else {
102 theme::border_strong()
103 };
104 let top_left = if sharing {
105 tinted_chip("Sharing".to_owned(), theme::red())
106 } else {
107 chip(status)
108 };
109 div()
110 .id("call-mini")
111 .group("call-mini")
112 .occlude()
113 .absolute()
114 .right(right)
115 .bottom(bottom)
116 .w(px(MINI_WIDTH))
117 .h(px(MINI_HEIGHT))
118 .overflow_hidden()
119 .rounded(px(WINDOW_RADIUS))
120 .bg(theme::surface())
121 .border_2()
122 .border_color(border)
123 .text_color(theme::text())
124 .shadow(theme::flyout_shadow())
125 .cursor_pointer()
126 .on_click(move |_, _, cx| {
127 open_app.update(cx, |state, cx| state.show_call(true, cx));
128 })
129 .child(speaker_layer(state, model, now))
130 .child(div().absolute().top(px(8.)).left(px(8.)).child(top_left))
131 .children(
132 speaker_name
133 .map(|name| h_flex().absolute().bottom(px(6.)).left(px(8.)).child(name)),
134 )
135 .children(if sharing {
136 Some(stop_sharing_pill(&self.app).into_any_element())
137 } else {
138 self_view(state, model, now)
139 })
140 .child(controls_row(
141 &self.app,
142 model,
143 ControlIds {
144 mute: "call-mini-mute",
145 back: "call-mini-back",
146 leave: "call-mini-leave",
147 },
148 "call-mini",
149 move |cx| back_app.update(cx, |state, cx| state.show_call(true, cx)),
150 ))
151 .into_any_element()
152 }
153}
crates/app/src/views/call_mini_window.rs +5 −8
@@ -104,11 +104,7 @@ fn speaker_video(
104 104 .flatten()
105 105 }
106 106
107 pub(super) fn speaker_name_chip(
108 state: &AppState,
109 model: &CallModel,
110 now: Instant,
111 ) -> Option<Div> {
107 pub(super) fn speaker_name_chip(state: &AppState, model: &CallModel, now: Instant) -> Option<Div> {
112 108 let tile = speaker_tile(model)?;
113 109 speaker_video(state, model, tile, now)?;
114 110 Some(chip(tile.name.clone()))
@@ -272,9 +268,10 @@ impl Render for MiniWindowView {
272 268 .left(px(8.))
273 269 .child(chip(status)),
274 270 )
275 .children(speaker_name.map(|name| {
276 div().absolute().bottom(px(6.)).left(px(8.)).child(name)
277 }))
271 .children(
272 speaker_name
273 .map(|name| div().absolute().bottom(px(6.)).left(px(8.)).child(name)),
274 )
278 275 .children(self_view(state, model, now)),
279 276 )
280 277 .child(
@@ -104,11 +104,7 @@ fn speaker_video(
104 .flatten()
104 .flatten()
105}
105}
106
106
107pub(super) fn speaker_name_chip(
107pub(super) fn speaker_name_chip(state: &AppState, model: &CallModel, now: Instant) -> Option<Div> {
108 state: &AppState,
109 model: &CallModel,
110 now: Instant,
111) -> Option<Div> {
112 let tile = speaker_tile(model)?;
108 let tile = speaker_tile(model)?;
113 speaker_video(state, model, tile, now)?;
109 speaker_video(state, model, tile, now)?;
114 Some(chip(tile.name.clone()))
110 Some(chip(tile.name.clone()))
@@ -272,9 +268,10 @@ impl Render for MiniWindowView {
272 .left(px(8.))
268 .left(px(8.))
273 .child(chip(status)),
269 .child(chip(status)),
274 )
270 )
275 .children(speaker_name.map(|name| {
271 .children(
276 div().absolute().bottom(px(6.)).left(px(8.)).child(name)
272 speaker_name
277 }))
273 .map(|name| div().absolute().bottom(px(6.)).left(px(8.)).child(name)),
274 )
278 .children(self_view(state, model, now)),
275 .children(self_view(state, model, now)),
279 )
276 )
280 .child(
277 .child(
crates/app/src/views/call_notice.rs +1 −5
@@ -158,11 +158,7 @@ fn transcript_chip(index: usize, transcript: RowAction) -> Stateful<Div> {
158 158 .text_size(px(TEXT_SIZE))
159 159 .font_weight(FontWeight::SEMIBOLD)
160 160 .text_color(theme::text())
161 .child(symbol(
162 "description",
163 ICON_SIZE,
164 theme::accent_text(),
165 ))
161 .child(symbol("description", ICON_SIZE, theme::accent_text()))
166 162 .child("Transcript")
167 163 }
168 164
@@ -158,11 +158,7 @@ fn transcript_chip(index: usize, transcript: RowAction) -> Stateful<Div> {
158 .text_size(px(TEXT_SIZE))
158 .text_size(px(TEXT_SIZE))
159 .font_weight(FontWeight::SEMIBOLD)
159 .font_weight(FontWeight::SEMIBOLD)
160 .text_color(theme::text())
160 .text_color(theme::text())
161 .child(symbol(
161 .child(symbol("description", ICON_SIZE, theme::accent_text()))
162 "description",
163 ICON_SIZE,
164 theme::accent_text(),
165 ))
166 .child("Transcript")
162 .child("Transcript")
167}
163}
168
164
crates/app/src/views/call_organizer.rs +50 −19
@@ -13,9 +13,7 @@ use gpui_kit::*;
13 13
14 14 use super::avatar::person_avatar;
15 15 use super::call_control_fold::{Foldable, FoldedControls, folded_items};
16 use super::call_extras::{
17 CameraMenu, background_items, effect_items, open_transfer_picker,
18 };
16 use super::call_extras::{CameraMenu, background_items, effect_items, open_transfer_picker};
19 17 use super::call_record::{record_items, transcript_and_settings_items};
20 18 use super::call_toolbar::{split_chevron, tool_face, tool_trigger};
21 19 use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
@@ -45,7 +43,11 @@ fn dark_text() -> Hsla {
45 43 hsla(0., 0., 0.08, 1.)
46 44 }
47 45
48 pub(super) fn pill(id: impl Into<ElementId>, label: impl Into<SharedString>, filled: bool) -> Stateful<Div> {
46 pub(super) fn pill(
47 id: impl Into<ElementId>,
48 label: impl Into<SharedString>,
49 filled: bool,
50 ) -> Stateful<Div> {
49 51 let (background, foreground) = if filled {
50 52 (dark_text(), theme::white())
51 53 } else {
@@ -259,7 +261,11 @@ pub fn tile_menu(
259 261 let fitted = model.is_fitted(mri);
260 262 popup = popup.item(
261 263 PopupMenuItem::new(if fitted { "Fill frame" } else { "Fit to frame" })
262 .icon(if fitted { IconName::Expand } else { IconName::Shrink })
264 .icon(if fitted {
265 IconName::Expand
266 } else {
267 IconName::Shrink
268 })
263 269 .on_click(move |_, _, cx| {
264 270 fit_app.update(cx, |state, cx| state.toggle_call_fit(&fit_mri, cx))
265 271 }),
@@ -329,11 +335,13 @@ fn modality_item(
329 335 (Modality::Camera, true) => ("Disable camera", IconName::VideoOff),
330 336 (Modality::Camera, false) => ("Allow camera", IconName::Video),
331 337 };
332 PopupMenuItem::new(label).icon(glyph).on_click(move |_, _, cx| {
333 app.update(cx, |state, cx| {
334 state.set_call_attendee_modality(mri.clone(), modality, !allowed, cx)
338 PopupMenuItem::new(label)
339 .icon(glyph)
340 .on_click(move |_, _, cx| {
341 app.update(cx, |state, cx| {
342 state.set_call_attendee_modality(mri.clone(), modality, !allowed, cx)
343 })
335 344 })
336 })
337 345 }
338 346
339 347 fn restriction_items(
@@ -345,15 +353,35 @@ fn restriction_items(
345 353 let presenter = model.tile_role(mri) == Some(MeetingRole::Presenter);
346 354 let (role_app, role_mri) = (app.clone(), mri.to_owned());
347 355 popup
348 .item(modality_item(app, mri, Modality::Mic, model.attendee_allowed(mri, Modality::Mic)))
349 .item(modality_item(app, mri, Modality::Camera, model.attendee_allowed(mri, Modality::Camera)))
356 .item(modality_item(
357 app,
358 mri,
359 Modality::Mic,
360 model.attendee_allowed(mri, Modality::Mic),
361 ))
362 .item(modality_item(
363 app,
364 mri,
365 Modality::Camera,
366 model.attendee_allowed(mri, Modality::Camera),
367 ))
350 368 .item(
351 PopupMenuItem::new(if presenter { "Make attendee" } else { "Make presenter" })
352 .icon(IconName::Users)
353 .on_click(move |_, _, cx| {
354 let role = if presenter { MeetingRole::Attendee } else { MeetingRole::Presenter };
355 role_app.update(cx, |state, cx| state.set_call_role(role_mri.clone(), role, cx))
356 }),
369 PopupMenuItem::new(if presenter {
370 "Make attendee"
371 } else {
372 "Make presenter"
373 })
374 .icon(IconName::Users)
375 .on_click(move |_, _, cx| {
376 let role = if presenter {
377 MeetingRole::Attendee
378 } else {
379 MeetingRole::Presenter
380 };
381 role_app.update(cx, |state, cx| {
382 state.set_call_role(role_mri.clone(), role, cx)
383 })
384 }),
357 385 )
358 386 }
359 387
@@ -439,7 +467,9 @@ pub fn more_button(
439 467 ) -> Option<AnyElement> {
440 468 if !matches!(
441 469 model.kind,
442 crate::call::CallKind::Meeting | crate::call::CallKind::Direct | crate::call::CallKind::Group
470 crate::call::CallKind::Meeting
471 | crate::call::CallKind::Direct
472 | crate::call::CallKind::Group
443 473 ) {
444 474 return None;
445 475 }
@@ -721,7 +751,8 @@ pub fn render_focus_stage(
721 751 let (picture_size, picture) = match image {
722 752 Some(image) => {
723 753 let pixels = image.size(0);
724 let (width, height) = contain_size(size, (pixels.width.0 as f32, pixels.height.0 as f32));
754 let (width, height) =
755 contain_size(size, (pixels.width.0 as f32, pixels.height.0 as f32));
725 756 let picture = img(ImageSource::Render(image))
726 757 .size_full()
727 758 .object_fit(ObjectFit::Fill)
@@ -13,9 +13,7 @@ use gpui_kit::*;
13
13
14use super::avatar::person_avatar;
14use super::avatar::person_avatar;
15use super::call_control_fold::{Foldable, FoldedControls, folded_items};
15use super::call_control_fold::{Foldable, FoldedControls, folded_items};
16use super::call_extras::{
16use super::call_extras::{CameraMenu, background_items, effect_items, open_transfer_picker};
17 CameraMenu, background_items, effect_items, open_transfer_picker,
18};
19use super::call_record::{record_items, transcript_and_settings_items};
17use super::call_record::{record_items, transcript_and_settings_items};
20use super::call_toolbar::{split_chevron, tool_face, tool_trigger};
18use super::call_toolbar::{split_chevron, tool_face, tool_trigger};
21use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
19use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
@@ -45,7 +43,11 @@ fn dark_text() -> Hsla {
45 hsla(0., 0., 0.08, 1.)
43 hsla(0., 0., 0.08, 1.)
46}
44}
47
45
48pub(super) fn pill(id: impl Into<ElementId>, label: impl Into<SharedString>, filled: bool) -> Stateful<Div> {
46pub(super) fn pill(
47 id: impl Into<ElementId>,
48 label: impl Into<SharedString>,
49 filled: bool,
50) -> Stateful<Div> {
49 let (background, foreground) = if filled {
51 let (background, foreground) = if filled {
50 (dark_text(), theme::white())
52 (dark_text(), theme::white())
51 } else {
53 } else {
@@ -259,7 +261,11 @@ pub fn tile_menu(
259 let fitted = model.is_fitted(mri);
261 let fitted = model.is_fitted(mri);
260 popup = popup.item(
262 popup = popup.item(
261 PopupMenuItem::new(if fitted { "Fill frame" } else { "Fit to frame" })
263 PopupMenuItem::new(if fitted { "Fill frame" } else { "Fit to frame" })
262 .icon(if fitted { IconName::Expand } else { IconName::Shrink })
264 .icon(if fitted {
265 IconName::Expand
266 } else {
267 IconName::Shrink
268 })
263 .on_click(move |_, _, cx| {
269 .on_click(move |_, _, cx| {
264 fit_app.update(cx, |state, cx| state.toggle_call_fit(&fit_mri, cx))
270 fit_app.update(cx, |state, cx| state.toggle_call_fit(&fit_mri, cx))
265 }),
271 }),
@@ -329,11 +335,13 @@ fn modality_item(
329 (Modality::Camera, true) => ("Disable camera", IconName::VideoOff),
335 (Modality::Camera, true) => ("Disable camera", IconName::VideoOff),
330 (Modality::Camera, false) => ("Allow camera", IconName::Video),
336 (Modality::Camera, false) => ("Allow camera", IconName::Video),
331 };
337 };
332 PopupMenuItem::new(label).icon(glyph).on_click(move |_, _, cx| {
338 PopupMenuItem::new(label)
333 app.update(cx, |state, cx| {
339 .icon(glyph)
334 state.set_call_attendee_modality(mri.clone(), modality, !allowed, cx)
340 .on_click(move |_, _, cx| {
341 app.update(cx, |state, cx| {
342 state.set_call_attendee_modality(mri.clone(), modality, !allowed, cx)
343 })
335 })
344 })
336 })
337}
345}
338
346
339fn restriction_items(
347fn restriction_items(
@@ -345,15 +353,35 @@ fn restriction_items(
345 let presenter = model.tile_role(mri) == Some(MeetingRole::Presenter);
353 let presenter = model.tile_role(mri) == Some(MeetingRole::Presenter);
346 let (role_app, role_mri) = (app.clone(), mri.to_owned());
354 let (role_app, role_mri) = (app.clone(), mri.to_owned());
347 popup
355 popup
348 .item(modality_item(app, mri, Modality::Mic, model.attendee_allowed(mri, Modality::Mic)))
356 .item(modality_item(
349 .item(modality_item(app, mri, Modality::Camera, model.attendee_allowed(mri, Modality::Camera)))
357 app,
358 mri,
359 Modality::Mic,
360 model.attendee_allowed(mri, Modality::Mic),
361 ))
362 .item(modality_item(
363 app,
364 mri,
365 Modality::Camera,
366 model.attendee_allowed(mri, Modality::Camera),
367 ))
350 .item(
368 .item(
351 PopupMenuItem::new(if presenter { "Make attendee" } else { "Make presenter" })
369 PopupMenuItem::new(if presenter {
352 .icon(IconName::Users)
370 "Make attendee"
353 .on_click(move |_, _, cx| {
371 } else {
354 let role = if presenter { MeetingRole::Attendee } else { MeetingRole::Presenter };
372 "Make presenter"
355 role_app.update(cx, |state, cx| state.set_call_role(role_mri.clone(), role, cx))
373 })
356 }),
374 .icon(IconName::Users)
375 .on_click(move |_, _, cx| {
376 let role = if presenter {
377 MeetingRole::Attendee
378 } else {
379 MeetingRole::Presenter
380 };
381 role_app.update(cx, |state, cx| {
382 state.set_call_role(role_mri.clone(), role, cx)
383 })
384 }),
357 )
385 )
358}
386}
359
387
@@ -439,7 +467,9 @@ pub fn more_button(
439) -> Option<AnyElement> {
467) -> Option<AnyElement> {
440 if !matches!(
468 if !matches!(
441 model.kind,
469 model.kind,
442 crate::call::CallKind::Meeting | crate::call::CallKind::Direct | crate::call::CallKind::Group
470 crate::call::CallKind::Meeting
471 | crate::call::CallKind::Direct
472 | crate::call::CallKind::Group
443 ) {
473 ) {
444 return None;
474 return None;
445 }
475 }
@@ -721,7 +751,8 @@ pub fn render_focus_stage(
721 let (picture_size, picture) = match image {
751 let (picture_size, picture) = match image {
722 Some(image) => {
752 Some(image) => {
723 let pixels = image.size(0);
753 let pixels = image.size(0);
724 let (width, height) = contain_size(size, (pixels.width.0 as f32, pixels.height.0 as f32));
754 let (width, height) =
755 contain_size(size, (pixels.width.0 as f32, pixels.height.0 as f32));
725 let picture = img(ImageSource::Render(image))
756 let picture = img(ImageSource::Render(image))
726 .size_full()
757 .size_full()
727 .object_fit(ObjectFit::Fill)
758 .object_fit(ObjectFit::Fill)
crates/app/src/views/call_people.rs +216 −88
@@ -1,5 +1,5 @@
1 use gpui_kit::component::scroll::ScrollableElement as _;
2 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 3 use gpui_kit::component::{
4 4 Sizable as _,
5 5 button::{Button, ButtonVariants as _},
@@ -15,10 +15,9 @@ use gpui_kit::*;
15 15 use super::avatar::person_avatar;
16 16 use super::call_extras::open_invite_picker;
17 17 use super::call_organizer::{pill, tile_menu};
18 use super::call_toolbar::tool_face;
19 use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH};
20 use super::widgets::{Corner, corner_badge, count_badge, icon};
18 use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH, round_control};
21 19 use super::scroll_edge::with_top_edge;
20 use super::widgets::{Corner, corner_badge, count_badge, icon};
22 21 use crate::app_state::AppState;
23 22 use crate::call::{
24 23 ActiveCall, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,
@@ -46,10 +45,20 @@ fn dark_text() -> Hsla {
46 45
47 46 pub fn people_button(app: &Entity<AppState>, open: bool, raised_hands: usize) -> Stateful<Div> {
48 47 let app = app.clone();
49 tool_face("call-people", IconName::Users, "People", open)
48 let (background, foreground) = if open {
49 (theme::accent(), theme::on_accent())
50 } else {
51 (theme::surface_raised(), theme::text())
52 };
53 round_control("call-people", IconName::Users, background, foreground)
50 54 .relative()
51 55 .tooltip(move |window, cx| {
52 Tooltip::new(if open { "Close the people list" } else { "Show people" }).build(window, cx)
56 Tooltip::new(if open {
57 "Close the people list"
58 } else {
59 "Show people"
60 })
61 .build(window, cx)
53 62 })
54 63 .when(raised_hands > 0, |button| {
55 64 button.child(
@@ -100,8 +109,9 @@ pub fn lock_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme
100 109 .font_weight(FontWeight::SEMIBOLD)
101 110 .child("The meeting is locked. Nobody new can join.")
102 111 .child(
103 pill("call-lock-unlock", "Unlock", false)
104 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_lock(false, cx))),
112 pill("call-lock-unlock", "Unlock", false).on_click(move |_, _, cx| {
113 app.update(cx, |state, cx| state.set_call_lock(false, cx))
114 }),
105 115 )
106 116 .into_any_element(),
107 117 )
@@ -113,8 +123,13 @@ fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
113 123 return popup;
114 124 }
115 125 let capability = model.capability;
116 let (mute_app, lock_app, mic_app, camera_app, options_app) =
117 (app.clone(), app.clone(), app.clone(), app.clone(), app.clone());
126 let (mute_app, lock_app, mic_app, camera_app, options_app) = (
127 app.clone(),
128 app.clone(),
129 app.clone(),
130 app.clone(),
131 app.clone(),
132 );
118 133 popup
119 134 .item(
120 135 PopupMenuItem::new("Mute all")
@@ -122,11 +137,19 @@ fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
122 137 .on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
123 138 )
124 139 .item(
125 PopupMenuItem::new(if capability.locked { "Unlock meeting" } else { "Lock meeting" })
126 .icon(if capability.locked { IconName::LockOpen } else { IconName::Lock })
127 .on_click(move |_, _, cx| {
128 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
129 }),
140 PopupMenuItem::new(if capability.locked {
141 "Unlock meeting"
142 } else {
143 "Lock meeting"
144 })
145 .icon(if capability.locked {
146 IconName::LockOpen
147 } else {
148 IconName::Lock
149 })
150 .on_click(move |_, _, cx| {
151 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
152 }),
130 153 )
131 154 .item(
132 155 PopupMenuItem::new(if capability.attendee_mic_off {
@@ -230,7 +253,9 @@ fn panel_header(app: &Entity<AppState>, model: &CallModel, count: usize) -> Div
230 253 .hover(|button| button.bg(theme::row_hover()))
231 254 .tooltip(|window, cx| Tooltip::new("Close the people list").build(window, cx))
232 255 .child(icon(IconName::Close, 14., theme::text_muted()))
233 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.toggle_call_people(cx))),
256 .on_click(move |_, _, cx| {
257 close_app.update(cx, |state, cx| state.toggle_call_people(cx))
258 }),
234 259 )
235 260 }
236 261
@@ -293,19 +318,27 @@ fn person_row(
293 318 row: &PersonRow,
294 319 ) -> AnyElement {
295 320 let group = SharedString::from(format!("call-people-{section}-{}", row.mri));
296 let user_id = row
297 .user_id
298 .clone()
299 .or_else(|| {
300 row.own
301 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
302 .flatten()
303 });
304 let subtitle = if row.ringing { Some("Ringing") } else { row.label };
305 let (more_app, more_model, more_mri, more_name) =
306 (app.clone(), model.clone(), row.mri.clone(), row.name.clone());
321 let user_id = row.user_id.clone().or_else(|| {
322 row.own
323 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
324 .flatten()
325 });
326 let subtitle = if row.ringing {
327 Some("Ringing")
328 } else {
329 row.label
330 };
331 let (more_app, more_model, more_mri, more_name) = (
332 app.clone(),
333 model.clone(),
334 row.mri.clone(),
335 row.name.clone(),
336 );
307 337 h_flex()
308 .id(SharedString::from(format!("call-people-row-{section}-{}", row.mri)))
338 .id(SharedString::from(format!(
339 "call-people-row-{section}-{}",
340 row.mri
341 )))
309 342 .group(group.clone())
310 343 .w_full()
311 344 .h(px(ROW_HEIGHT))
@@ -314,7 +347,12 @@ fn person_row(
314 347 .gap(px(8.))
315 348 .items_center()
316 349 .hover(|row| row.bg(theme::row_hover()))
317 .child(person_avatar(&state.directory, user_id.as_deref(), &row.name, AVATAR_SIZE))
350 .child(person_avatar(
351 &state.directory,
352 user_id.as_deref(),
353 &row.name,
354 AVATAR_SIZE,
355 ))
318 356 .child(
319 357 v_flex()
320 358 .flex_1()
@@ -354,16 +392,30 @@ fn person_row(
354 392 .xsmall()
355 393 .size(px(MORE_SIZE))
356 394 .tooltip("More")
357 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
358 tile_menu(popup, &more_app, &more_model, &more_mri, &more_name, false)
359 }),
395 .dropdown_menu_with_anchor(
396 Anchor::TopRight,
397 move |popup, _, _| {
398 tile_menu(
399 popup,
400 &more_app,
401 &more_model,
402 &more_mri,
403 &more_name,
404 false,
405 )
406 },
407 ),
360 408 )
361 409 }),
362 410 )
363 411 .into_any_element()
364 412 }
365 413
366 fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSections) -> Option<Div> {
414 fn lobby_section(
415 app: &Entity<AppState>,
416 state: &AppState,
417 sections: &PeopleSections,
418 ) -> Option<Div> {
367 419 if sections.lobby.is_empty() {
368 420 return None;
369 421 }
@@ -372,24 +424,37 @@ fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSect
372 424 .label("Admit all")
373 425 .ghost()
374 426 .xsmall()
375 .on_click(move |_, _, cx| admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx)))
427 .on_click(move |_, _, cx| {
428 admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx))
429 })
376 430 .into_any_element();
377 431 Some(
378 432 v_flex()
379 433 .w_full()
380 .child(section_header(format!("Waiting in lobby ({})", sections.lobby.len()), Some(action)))
434 .child(section_header(
435 format!("Waiting in lobby ({})", sections.lobby.len()),
436 Some(action),
437 ))
381 438 .children(sections.lobby.iter().map(|guest| {
382 439 let (admit_app, deny_app) = (app.clone(), app.clone());
383 440 let (admit_mri, deny_mri) = (guest.mri.clone(), guest.mri.clone());
384 441 h_flex()
385 .id(SharedString::from(format!("call-people-lobby-{}", guest.mri)))
442 .id(SharedString::from(format!(
443 "call-people-lobby-{}",
444 guest.mri
445 )))
386 446 .w_full()
387 447 .h(px(ROW_HEIGHT))
388 448 .flex_none()
389 449 .px(px(20.))
390 450 .gap(px(8.))
391 451 .items_center()
392 .child(person_avatar(&state.directory, guest.user_id.as_deref(), &guest.name, AVATAR_SIZE))
452 .child(person_avatar(
453 &state.directory,
454 guest.user_id.as_deref(),
455 &guest.name,
456 AVATAR_SIZE,
457 ))
393 458 .child(
394 459 div()
395 460 .flex_1()
@@ -400,27 +465,40 @@ fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSect
400 465 .child(truncated(&guest.name, NAME_LIMIT)),
401 466 )
402 467 .child(
403 Button::new(SharedString::from(format!("call-people-admit-{}", guest.mri)))
404 .label("Admit")
405 .xsmall()
406 .on_click(move |_, _, cx| {
407 admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))
408 }),
468 Button::new(SharedString::from(format!(
469 "call-people-admit-{}",
470 guest.mri
471 )))
472 .label("Admit")
473 .xsmall()
474 .on_click(move |_, _, cx| {
475 admit_app.update(cx, |state, cx| {
476 state.admit_call_guest(admit_mri.clone(), cx)
477 })
478 }),
409 479 )
410 480 .child(
411 Button::new(SharedString::from(format!("call-people-deny-{}", guest.mri)))
412 .label("Deny")
413 .ghost()
414 .xsmall()
415 .on_click(move |_, _, cx| {
416 deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
417 }),
481 Button::new(SharedString::from(format!(
482 "call-people-deny-{}",
483 guest.mri
484 )))
485 .label("Deny")
486 .ghost()
487 .xsmall()
488 .on_click(move |_, _, cx| {
489 deny_app
490 .update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
491 }),
418 492 )
419 493 })),
420 494 )
421 495 }
422 496
423 pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
497 pub fn people_panel(
498 app: &Entity<AppState>,
499 state: &AppState,
500 call: &ActiveCall,
501 ) -> Option<AnyElement> {
424 502 call.people_open.then_some(())?;
425 503 let model = &call.model;
426 504 let sections = people_sections(model);
@@ -441,21 +519,37 @@ pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall)
441 519 .overflow_y_scrollbar()
442 520 .track_scroll(&call.people_scroll)
443 521 .pb(px(12.))
444 .children(model.can_admit().then(|| lobby_section(app, state, &sections)).flatten())
522 .children(
523 model
524 .can_admit()
525 .then(|| lobby_section(app, state, &sections))
526 .flatten(),
527 )
445 528 .when(!sections.hands.is_empty(), |list| {
446 list.child(section_header(format!("Raised hands ({})", sections.hands.len()), lower_all))
447 .children(
448 sections
449 .hands
450 .iter()
451 .map(|row| person_row(app, state, model, "hands", row)),
452 )
529 list.child(section_header(
530 format!("Raised hands ({})", sections.hands.len()),
531 lower_all,
532 ))
533 .children(
534 sections
535 .hands
536 .iter()
537 .map(|row| person_row(app, state, model, "hands", row)),
538 )
453 539 })
454 540 .children(sections.groups.iter().map(|group| {
455 541 v_flex()
456 542 .w_full()
457 .child(section_header(format!("{} ({})", group.title, group.rows.len()), None))
458 .children(group.rows.iter().map(|row| person_row(app, state, model, "group", row)))
543 .child(section_header(
544 format!("{} ({})", group.title, group.rows.len()),
545 None,
546 ))
547 .children(
548 group
549 .rows
550 .iter()
551 .map(|row| person_row(app, state, model, "group", row)),
552 )
459 553 }));
460 554 Some(
461 555 v_flex()
@@ -469,7 +563,11 @@ pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall)
469 563 .overflow_hidden()
470 564 .bg(theme::surface())
471 565 .child(panel_header(app, model, sections.count))
472 .child(with_top_edge(body, &call.people_scroll, PEOPLE_SCROLL_DIVIDER))
566 .child(with_top_edge(
567 body,
568 &call.people_scroll,
569 PEOPLE_SCROLL_DIVIDER,
570 ))
473 571 .into_any_element(),
474 572 )
475 573 }
@@ -502,13 +600,15 @@ fn choice_dropdown(
502 600 }
503 601 for (wire, label) in choices {
504 602 let app = app.clone();
505 popup = popup.item(PopupMenuItem::new(*label).checked(*wire == current).on_click(
506 move |_, _, cx| {
507 app.update(cx, |state, cx| {
508 state.edit_meeting_options(|options| edit(options, wire), cx)
509 })
510 },
511 ));
603 popup = popup.item(
604 PopupMenuItem::new(*label)
605 .checked(*wire == current)
606 .on_click(move |_, _, cx| {
607 app.update(cx, |state, cx| {
608 state.edit_meeting_options(|options| edit(options, wire), cx)
609 })
610 }),
611 );
512 612 }
513 613 popup
514 614 })
@@ -551,41 +651,66 @@ fn options_fields(app: &Entity<AppState>, options: &MeetingOptions) -> Div {
551 651 .gap(px(6.))
552 652 .child(option_row(
553 653 "Who can bypass the lobby",
554 choice_dropdown("options-bypass", app, &BYPASS_CHOICES, &options.bypass_lobby, |options, value| {
555 options.bypass_lobby = value.to_owned()
556 }),
654 choice_dropdown(
655 "options-bypass",
656 app,
657 &BYPASS_CHOICES,
658 &options.bypass_lobby,
659 |options, value| options.bypass_lobby = value.to_owned(),
660 ),
557 661 ))
558 662 .child(option_row(
559 663 "Who can present",
560 choice_dropdown("options-present", app, &PRESENTER_CHOICES, &options.presenters, |options, value| {
561 options.presenters = value.to_owned()
562 }),
664 choice_dropdown(
665 "options-present",
666 app,
667 &PRESENTER_CHOICES,
668 &options.presenters,
669 |options, value| options.presenters = value.to_owned(),
670 ),
563 671 ))
564 672 .child(option_row(
565 673 "Allow mic for attendees",
566 switch_field("options-mic", app, options.attendee_mic, |options, on| options.attendee_mic = on),
674 switch_field("options-mic", app, options.attendee_mic, |options, on| {
675 options.attendee_mic = on
676 }),
567 677 ))
568 678 .child(option_row(
569 679 "Allow camera for attendees",
570 switch_field("options-camera", app, options.attendee_camera, |options, on| {
571 options.attendee_camera = on
572 }),
680 switch_field(
681 "options-camera",
682 app,
683 options.attendee_camera,
684 |options, on| options.attendee_camera = on,
685 ),
573 686 ))
574 687 .child(option_row(
575 688 "Meeting chat",
576 choice_dropdown("options-chat", app, &CHAT_CHOICES, &options.meeting_chat, |options, value| {
577 options.meeting_chat = value.to_owned()
578 }),
689 choice_dropdown(
690 "options-chat",
691 app,
692 &CHAT_CHOICES,
693 &options.meeting_chat,
694 |options, value| options.meeting_chat = value.to_owned(),
695 ),
579 696 ))
580 697 .child(option_row(
581 698 "Allow reactions",
582 switch_field("options-reactions", app, options.reactions, |options, on| options.reactions = on),
699 switch_field(
700 "options-reactions",
701 app,
702 options.reactions,
703 |options, on| options.reactions = on,
704 ),
583 705 ))
584 706 .child(option_row(
585 707 "Record automatically",
586 switch_field("options-record", app, options.record_automatically, |options, on| {
587 options.record_automatically = on
588 }),
708 switch_field(
709 "options-record",
710 app,
711 options.record_automatically,
712 |options, on| options.record_automatically = on,
713 ),
589 714 ))
590 715 }
591 716
@@ -642,7 +767,9 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl
642 767 .size_full()
643 768 .bg(black().opacity(DIALOG_BACKDROP))
644 769 .occlude()
645 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.close_meeting_options(cx))),
770 .on_click(move |_, _, cx| {
771 close_app.update(cx, |state, cx| state.close_meeting_options(cx))
772 }),
646 773 )
647 774 .child(
648 775 v_flex()
@@ -672,7 +799,8 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl
672 799 .label("Cancel")
673 800 .ghost()
674 801 .on_click(move |_, _, cx| {
675 cancel_app.update(cx, |state, cx| state.close_meeting_options(cx))
802 cancel_app
803 .update(cx, |state, cx| state.close_meeting_options(cx))
676 804 }),
677 805 )
678 806 .child(save),
@@ -1,5 +1,5 @@
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::component::{
3use gpui_kit::component::{
4 Sizable as _,
4 Sizable as _,
5 button::{Button, ButtonVariants as _},
5 button::{Button, ButtonVariants as _},
@@ -15,10 +15,9 @@ use gpui_kit::*;
15use super::avatar::person_avatar;
15use super::avatar::person_avatar;
16use super::call_extras::open_invite_picker;
16use super::call_extras::open_invite_picker;
17use super::call_organizer::{pill, tile_menu};
17use super::call_organizer::{pill, tile_menu};
18use super::call_toolbar::tool_face;
18use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH, round_control};
19use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH};
20use super::widgets::{Corner, corner_badge, count_badge, icon};
21use super::scroll_edge::with_top_edge;
19use super::scroll_edge::with_top_edge;
20use super::widgets::{Corner, corner_badge, count_badge, icon};
22use crate::app_state::AppState;
21use crate::app_state::AppState;
23use crate::call::{
22use crate::call::{
24 ActiveCall, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,
23 ActiveCall, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,
@@ -46,10 +45,20 @@ fn dark_text() -> Hsla {
46
45
47pub fn people_button(app: &Entity<AppState>, open: bool, raised_hands: usize) -> Stateful<Div> {
46pub fn people_button(app: &Entity<AppState>, open: bool, raised_hands: usize) -> Stateful<Div> {
48 let app = app.clone();
47 let app = app.clone();
49 tool_face("call-people", IconName::Users, "People", open)
48 let (background, foreground) = if open {
49 (theme::accent(), theme::on_accent())
50 } else {
51 (theme::surface_raised(), theme::text())
52 };
53 round_control("call-people", IconName::Users, background, foreground)
50 .relative()
54 .relative()
51 .tooltip(move |window, cx| {
55 .tooltip(move |window, cx| {
52 Tooltip::new(if open { "Close the people list" } else { "Show people" }).build(window, cx)
56 Tooltip::new(if open {
57 "Close the people list"
58 } else {
59 "Show people"
60 })
61 .build(window, cx)
53 })
62 })
54 .when(raised_hands > 0, |button| {
63 .when(raised_hands > 0, |button| {
55 button.child(
64 button.child(
@@ -100,8 +109,9 @@ pub fn lock_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme
100 .font_weight(FontWeight::SEMIBOLD)
109 .font_weight(FontWeight::SEMIBOLD)
101 .child("The meeting is locked. Nobody new can join.")
110 .child("The meeting is locked. Nobody new can join.")
102 .child(
111 .child(
103 pill("call-lock-unlock", "Unlock", false)
112 pill("call-lock-unlock", "Unlock", false).on_click(move |_, _, cx| {
104 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_lock(false, cx))),
113 app.update(cx, |state, cx| state.set_call_lock(false, cx))
114 }),
105 )
115 )
106 .into_any_element(),
116 .into_any_element(),
107 )
117 )
@@ -113,8 +123,13 @@ fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
113 return popup;
123 return popup;
114 }
124 }
115 let capability = model.capability;
125 let capability = model.capability;
116 let (mute_app, lock_app, mic_app, camera_app, options_app) =
126 let (mute_app, lock_app, mic_app, camera_app, options_app) = (
117 (app.clone(), app.clone(), app.clone(), app.clone(), app.clone());
127 app.clone(),
128 app.clone(),
129 app.clone(),
130 app.clone(),
131 app.clone(),
132 );
118 popup
133 popup
119 .item(
134 .item(
120 PopupMenuItem::new("Mute all")
135 PopupMenuItem::new("Mute all")
@@ -122,11 +137,19 @@ fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
122 .on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
137 .on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
123 )
138 )
124 .item(
139 .item(
125 PopupMenuItem::new(if capability.locked { "Unlock meeting" } else { "Lock meeting" })
140 PopupMenuItem::new(if capability.locked {
126 .icon(if capability.locked { IconName::LockOpen } else { IconName::Lock })
141 "Unlock meeting"
127 .on_click(move |_, _, cx| {
142 } else {
128 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
143 "Lock meeting"
129 }),
144 })
145 .icon(if capability.locked {
146 IconName::LockOpen
147 } else {
148 IconName::Lock
149 })
150 .on_click(move |_, _, cx| {
151 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
152 }),
130 )
153 )
131 .item(
154 .item(
132 PopupMenuItem::new(if capability.attendee_mic_off {
155 PopupMenuItem::new(if capability.attendee_mic_off {
@@ -230,7 +253,9 @@ fn panel_header(app: &Entity<AppState>, model: &CallModel, count: usize) -> Div
230 .hover(|button| button.bg(theme::row_hover()))
253 .hover(|button| button.bg(theme::row_hover()))
231 .tooltip(|window, cx| Tooltip::new("Close the people list").build(window, cx))
254 .tooltip(|window, cx| Tooltip::new("Close the people list").build(window, cx))
232 .child(icon(IconName::Close, 14., theme::text_muted()))
255 .child(icon(IconName::Close, 14., theme::text_muted()))
233 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.toggle_call_people(cx))),
256 .on_click(move |_, _, cx| {
257 close_app.update(cx, |state, cx| state.toggle_call_people(cx))
258 }),
234 )
259 )
235}
260}
236
261
@@ -293,19 +318,27 @@ fn person_row(
293 row: &PersonRow,
318 row: &PersonRow,
294) -> AnyElement {
319) -> AnyElement {
295 let group = SharedString::from(format!("call-people-{section}-{}", row.mri));
320 let group = SharedString::from(format!("call-people-{section}-{}", row.mri));
296 let user_id = row
321 let user_id = row.user_id.clone().or_else(|| {
297 .user_id
322 row.own
298 .clone()
323 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
299 .or_else(|| {
324 .flatten()
300 row.own
325 });
301 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
326 let subtitle = if row.ringing {
302 .flatten()
327 Some("Ringing")
303 });
328 } else {
304 let subtitle = if row.ringing { Some("Ringing") } else { row.label };
329 row.label
305 let (more_app, more_model, more_mri, more_name) =
330 };
306 (app.clone(), model.clone(), row.mri.clone(), row.name.clone());
331 let (more_app, more_model, more_mri, more_name) = (
332 app.clone(),
333 model.clone(),
334 row.mri.clone(),
335 row.name.clone(),
336 );
307 h_flex()
337 h_flex()
308 .id(SharedString::from(format!("call-people-row-{section}-{}", row.mri)))
338 .id(SharedString::from(format!(
339 "call-people-row-{section}-{}",
340 row.mri
341 )))
309 .group(group.clone())
342 .group(group.clone())
310 .w_full()
343 .w_full()
311 .h(px(ROW_HEIGHT))
344 .h(px(ROW_HEIGHT))
@@ -314,7 +347,12 @@ fn person_row(
314 .gap(px(8.))
347 .gap(px(8.))
315 .items_center()
348 .items_center()
316 .hover(|row| row.bg(theme::row_hover()))
349 .hover(|row| row.bg(theme::row_hover()))
317 .child(person_avatar(&state.directory, user_id.as_deref(), &row.name, AVATAR_SIZE))
350 .child(person_avatar(
351 &state.directory,
352 user_id.as_deref(),
353 &row.name,
354 AVATAR_SIZE,
355 ))
318 .child(
356 .child(
319 v_flex()
357 v_flex()
320 .flex_1()
358 .flex_1()
@@ -354,16 +392,30 @@ fn person_row(
354 .xsmall()
392 .xsmall()
355 .size(px(MORE_SIZE))
393 .size(px(MORE_SIZE))
356 .tooltip("More")
394 .tooltip("More")
357 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
395 .dropdown_menu_with_anchor(
358 tile_menu(popup, &more_app, &more_model, &more_mri, &more_name, false)
396 Anchor::TopRight,
359 }),
397 move |popup, _, _| {
398 tile_menu(
399 popup,
400 &more_app,
401 &more_model,
402 &more_mri,
403 &more_name,
404 false,
405 )
406 },
407 ),
360 )
408 )
361 }),
409 }),
362 )
410 )
363 .into_any_element()
411 .into_any_element()
364}
412}
365
413
366fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSections) -> Option<Div> {
414fn lobby_section(
415 app: &Entity<AppState>,
416 state: &AppState,
417 sections: &PeopleSections,
418) -> Option<Div> {
367 if sections.lobby.is_empty() {
419 if sections.lobby.is_empty() {
368 return None;
420 return None;
369 }
421 }
@@ -372,24 +424,37 @@ fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSect
372 .label("Admit all")
424 .label("Admit all")
373 .ghost()
425 .ghost()
374 .xsmall()
426 .xsmall()
375 .on_click(move |_, _, cx| admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx)))
427 .on_click(move |_, _, cx| {
428 admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx))
429 })
376 .into_any_element();
430 .into_any_element();
377 Some(
431 Some(
378 v_flex()
432 v_flex()
379 .w_full()
433 .w_full()
380 .child(section_header(format!("Waiting in lobby ({})", sections.lobby.len()), Some(action)))
434 .child(section_header(
435 format!("Waiting in lobby ({})", sections.lobby.len()),
436 Some(action),
437 ))
381 .children(sections.lobby.iter().map(|guest| {
438 .children(sections.lobby.iter().map(|guest| {
382 let (admit_app, deny_app) = (app.clone(), app.clone());
439 let (admit_app, deny_app) = (app.clone(), app.clone());
383 let (admit_mri, deny_mri) = (guest.mri.clone(), guest.mri.clone());
440 let (admit_mri, deny_mri) = (guest.mri.clone(), guest.mri.clone());
384 h_flex()
441 h_flex()
385 .id(SharedString::from(format!("call-people-lobby-{}", guest.mri)))
442 .id(SharedString::from(format!(
443 "call-people-lobby-{}",
444 guest.mri
445 )))
386 .w_full()
446 .w_full()
387 .h(px(ROW_HEIGHT))
447 .h(px(ROW_HEIGHT))
388 .flex_none()
448 .flex_none()
389 .px(px(20.))
449 .px(px(20.))
390 .gap(px(8.))
450 .gap(px(8.))
391 .items_center()
451 .items_center()
392 .child(person_avatar(&state.directory, guest.user_id.as_deref(), &guest.name, AVATAR_SIZE))
452 .child(person_avatar(
453 &state.directory,
454 guest.user_id.as_deref(),
455 &guest.name,
456 AVATAR_SIZE,
457 ))
393 .child(
458 .child(
394 div()
459 div()
395 .flex_1()
460 .flex_1()
@@ -400,27 +465,40 @@ fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSect
400 .child(truncated(&guest.name, NAME_LIMIT)),
465 .child(truncated(&guest.name, NAME_LIMIT)),
401 )
466 )
402 .child(
467 .child(
403 Button::new(SharedString::from(format!("call-people-admit-{}", guest.mri)))
468 Button::new(SharedString::from(format!(
404 .label("Admit")
469 "call-people-admit-{}",
405 .xsmall()
470 guest.mri
406 .on_click(move |_, _, cx| {
471 )))
407 admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))
472 .label("Admit")
408 }),
473 .xsmall()
474 .on_click(move |_, _, cx| {
475 admit_app.update(cx, |state, cx| {
476 state.admit_call_guest(admit_mri.clone(), cx)
477 })
478 }),
409 )
479 )
410 .child(
480 .child(
411 Button::new(SharedString::from(format!("call-people-deny-{}", guest.mri)))
481 Button::new(SharedString::from(format!(
412 .label("Deny")
482 "call-people-deny-{}",
413 .ghost()
483 guest.mri
414 .xsmall()
484 )))
415 .on_click(move |_, _, cx| {
485 .label("Deny")
416 deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
486 .ghost()
417 }),
487 .xsmall()
488 .on_click(move |_, _, cx| {
489 deny_app
490 .update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
491 }),
418 )
492 )
419 })),
493 })),
420 )
494 )
421}
495}
422
496
423pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
497pub fn people_panel(
498 app: &Entity<AppState>,
499 state: &AppState,
500 call: &ActiveCall,
501) -> Option<AnyElement> {
424 call.people_open.then_some(())?;
502 call.people_open.then_some(())?;
425 let model = &call.model;
503 let model = &call.model;
426 let sections = people_sections(model);
504 let sections = people_sections(model);
@@ -441,21 +519,37 @@ pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall)
441 .overflow_y_scrollbar()
519 .overflow_y_scrollbar()
442 .track_scroll(&call.people_scroll)
520 .track_scroll(&call.people_scroll)
443 .pb(px(12.))
521 .pb(px(12.))
444 .children(model.can_admit().then(|| lobby_section(app, state, &sections)).flatten())
522 .children(
523 model
524 .can_admit()
525 .then(|| lobby_section(app, state, &sections))
526 .flatten(),
527 )
445 .when(!sections.hands.is_empty(), |list| {
528 .when(!sections.hands.is_empty(), |list| {
446 list.child(section_header(format!("Raised hands ({})", sections.hands.len()), lower_all))
529 list.child(section_header(
447 .children(
530 format!("Raised hands ({})", sections.hands.len()),
448 sections
531 lower_all,
449 .hands
532 ))
450 .iter()
533 .children(
451 .map(|row| person_row(app, state, model, "hands", row)),
534 sections
452 )
535 .hands
536 .iter()
537 .map(|row| person_row(app, state, model, "hands", row)),
538 )
453 })
539 })
454 .children(sections.groups.iter().map(|group| {
540 .children(sections.groups.iter().map(|group| {
455 v_flex()
541 v_flex()
456 .w_full()
542 .w_full()
457 .child(section_header(format!("{} ({})", group.title, group.rows.len()), None))
543 .child(section_header(
458 .children(group.rows.iter().map(|row| person_row(app, state, model, "group", row)))
544 format!("{} ({})", group.title, group.rows.len()),
545 None,
546 ))
547 .children(
548 group
549 .rows
550 .iter()
551 .map(|row| person_row(app, state, model, "group", row)),
552 )
459 }));
553 }));
460 Some(
554 Some(
461 v_flex()
555 v_flex()
@@ -469,7 +563,11 @@ pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall)
469 .overflow_hidden()
563 .overflow_hidden()
470 .bg(theme::surface())
564 .bg(theme::surface())
471 .child(panel_header(app, model, sections.count))
565 .child(panel_header(app, model, sections.count))
472 .child(with_top_edge(body, &call.people_scroll, PEOPLE_SCROLL_DIVIDER))
566 .child(with_top_edge(
567 body,
568 &call.people_scroll,
569 PEOPLE_SCROLL_DIVIDER,
570 ))
473 .into_any_element(),
571 .into_any_element(),
474 )
572 )
475}
573}
@@ -502,13 +600,15 @@ fn choice_dropdown(
502 }
600 }
503 for (wire, label) in choices {
601 for (wire, label) in choices {
504 let app = app.clone();
602 let app = app.clone();
505 popup = popup.item(PopupMenuItem::new(*label).checked(*wire == current).on_click(
603 popup = popup.item(
506 move |_, _, cx| {
604 PopupMenuItem::new(*label)
507 app.update(cx, |state, cx| {
605 .checked(*wire == current)
508 state.edit_meeting_options(|options| edit(options, wire), cx)
606 .on_click(move |_, _, cx| {
509 })
607 app.update(cx, |state, cx| {
510 },
608 state.edit_meeting_options(|options| edit(options, wire), cx)
511 ));
609 })
610 }),
611 );
512 }
612 }
513 popup
613 popup
514 })
614 })
@@ -551,41 +651,66 @@ fn options_fields(app: &Entity<AppState>, options: &MeetingOptions) -> Div {
551 .gap(px(6.))
651 .gap(px(6.))
552 .child(option_row(
652 .child(option_row(
553 "Who can bypass the lobby",
653 "Who can bypass the lobby",
554 choice_dropdown("options-bypass", app, &BYPASS_CHOICES, &options.bypass_lobby, |options, value| {
654 choice_dropdown(
555 options.bypass_lobby = value.to_owned()
655 "options-bypass",
556 }),
656 app,
657 &BYPASS_CHOICES,
658 &options.bypass_lobby,
659 |options, value| options.bypass_lobby = value.to_owned(),
660 ),
557 ))
661 ))
558 .child(option_row(
662 .child(option_row(
559 "Who can present",
663 "Who can present",
560 choice_dropdown("options-present", app, &PRESENTER_CHOICES, &options.presenters, |options, value| {
664 choice_dropdown(
561 options.presenters = value.to_owned()
665 "options-present",
562 }),
666 app,
667 &PRESENTER_CHOICES,
668 &options.presenters,
669 |options, value| options.presenters = value.to_owned(),
670 ),
563 ))
671 ))
564 .child(option_row(
672 .child(option_row(
565 "Allow mic for attendees",
673 "Allow mic for attendees",
566 switch_field("options-mic", app, options.attendee_mic, |options, on| options.attendee_mic = on),
674 switch_field("options-mic", app, options.attendee_mic, |options, on| {
675 options.attendee_mic = on
676 }),
567 ))
677 ))
568 .child(option_row(
678 .child(option_row(
569 "Allow camera for attendees",
679 "Allow camera for attendees",
570 switch_field("options-camera", app, options.attendee_camera, |options, on| {
680 switch_field(
571 options.attendee_camera = on
681 "options-camera",
572 }),
682 app,
683 options.attendee_camera,
684 |options, on| options.attendee_camera = on,
685 ),
573 ))
686 ))
574 .child(option_row(
687 .child(option_row(
575 "Meeting chat",
688 "Meeting chat",
576 choice_dropdown("options-chat", app, &CHAT_CHOICES, &options.meeting_chat, |options, value| {
689 choice_dropdown(
577 options.meeting_chat = value.to_owned()
690 "options-chat",
578 }),
691 app,
692 &CHAT_CHOICES,
693 &options.meeting_chat,
694 |options, value| options.meeting_chat = value.to_owned(),
695 ),
579 ))
696 ))
580 .child(option_row(
697 .child(option_row(
581 "Allow reactions",
698 "Allow reactions",
582 switch_field("options-reactions", app, options.reactions, |options, on| options.reactions = on),
699 switch_field(
700 "options-reactions",
701 app,
702 options.reactions,
703 |options, on| options.reactions = on,
704 ),
583 ))
705 ))
584 .child(option_row(
706 .child(option_row(
585 "Record automatically",
707 "Record automatically",
586 switch_field("options-record", app, options.record_automatically, |options, on| {
708 switch_field(
587 options.record_automatically = on
709 "options-record",
588 }),
710 app,
711 options.record_automatically,
712 |options, on| options.record_automatically = on,
713 ),
589 ))
714 ))
590}
715}
591
716
@@ -642,7 +767,9 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl
642 .size_full()
767 .size_full()
643 .bg(black().opacity(DIALOG_BACKDROP))
768 .bg(black().opacity(DIALOG_BACKDROP))
644 .occlude()
769 .occlude()
645 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.close_meeting_options(cx))),
770 .on_click(move |_, _, cx| {
771 close_app.update(cx, |state, cx| state.close_meeting_options(cx))
772 }),
646 )
773 )
647 .child(
774 .child(
648 v_flex()
775 v_flex()
@@ -672,7 +799,8 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl
672 .label("Cancel")
799 .label("Cancel")
673 .ghost()
800 .ghost()
674 .on_click(move |_, _, cx| {
801 .on_click(move |_, _, cx| {
675 cancel_app.update(cx, |state, cx| state.close_meeting_options(cx))
802 cancel_app
803 .update(cx, |state, cx| state.close_meeting_options(cx))
676 }),
804 }),
677 )
805 )
678 .child(save),
806 .child(save),
crates/app/src/views/call_record.rs +15 −4
@@ -154,7 +154,9 @@ fn choice_chip(
154 154 .bg(background)
155 155 .text_color(foreground)
156 156 .text_size(px(13.))
157 .when(!selected, |chip| chip.hover(|chip| chip.bg(theme::row_hover())))
157 .when(!selected, |chip| {
158 chip.hover(|chip| chip.bg(theme::row_hover()))
159 })
158 160 .cursor_pointer()
159 161 .child(label.to_owned())
160 162 .on_click(move |_, _, cx| on_click(cx))
@@ -181,7 +183,10 @@ pub fn open_captions_settings(app: &Entity<AppState>, window: &mut Window, cx: &
181 183 .call
182 184 .as_ref()
183 185 .and_then(|call| call.model.caption_language.clone());
184 let (size, position) = (state.call_view.caption_size, state.call_view.caption_position);
186 let (size, position) = (
187 state.call_view.caption_size,
188 state.call_view.caption_position,
189 );
185 190 let languages = SPOKEN_LANGUAGES
186 191 .iter()
187 192 .map(|(tag, label)| {
@@ -191,7 +196,11 @@ pub fn open_captions_settings(app: &Entity<AppState>, window: &mut Window, cx: &
191 196 format!("captions-language-{tag}"),
192 197 label,
193 198 language.as_deref() == Some(tag),
194 move |cx| app.update(cx, |state, cx| state.choose_call_caption_language(chosen, cx)),
199 move |cx| {
200 app.update(cx, |state, cx| {
201 state.choose_call_caption_language(chosen, cx)
202 })
203 },
195 204 )
196 205 })
197 206 .collect();
@@ -217,7 +226,9 @@ pub fn open_captions_settings(app: &Entity<AppState>, window: &mut Window, cx: &
217 226 format!("captions-position-{}", choice.meta()),
218 227 choice.label(),
219 228 position == choice,
220 move |cx| app.update(cx, |state, cx| state.set_call_caption_position(choice, cx)),
229 move |cx| {
230 app.update(cx, |state, cx| state.set_call_caption_position(choice, cx))
231 },
221 232 )
222 233 })
223 234 .collect();
@@ -154,7 +154,9 @@ fn choice_chip(
154 .bg(background)
154 .bg(background)
155 .text_color(foreground)
155 .text_color(foreground)
156 .text_size(px(13.))
156 .text_size(px(13.))
157 .when(!selected, |chip| chip.hover(|chip| chip.bg(theme::row_hover())))
157 .when(!selected, |chip| {
158 chip.hover(|chip| chip.bg(theme::row_hover()))
159 })
158 .cursor_pointer()
160 .cursor_pointer()
159 .child(label.to_owned())
161 .child(label.to_owned())
160 .on_click(move |_, _, cx| on_click(cx))
162 .on_click(move |_, _, cx| on_click(cx))
@@ -181,7 +183,10 @@ pub fn open_captions_settings(app: &Entity<AppState>, window: &mut Window, cx: &
181 .call
183 .call
182 .as_ref()
184 .as_ref()
183 .and_then(|call| call.model.caption_language.clone());
185 .and_then(|call| call.model.caption_language.clone());
184 let (size, position) = (state.call_view.caption_size, state.call_view.caption_position);
186 let (size, position) = (
187 state.call_view.caption_size,
188 state.call_view.caption_position,
189 );
185 let languages = SPOKEN_LANGUAGES
190 let languages = SPOKEN_LANGUAGES
186 .iter()
191 .iter()
187 .map(|(tag, label)| {
192 .map(|(tag, label)| {
@@ -191,7 +196,11 @@ pub fn open_captions_settings(app: &Entity<AppState>, window: &mut Window, cx: &
191 format!("captions-language-{tag}"),
196 format!("captions-language-{tag}"),
192 label,
197 label,
193 language.as_deref() == Some(tag),
198 language.as_deref() == Some(tag),
194 move |cx| app.update(cx, |state, cx| state.choose_call_caption_language(chosen, cx)),
199 move |cx| {
200 app.update(cx, |state, cx| {
201 state.choose_call_caption_language(chosen, cx)
202 })
203 },
195 )
204 )
196 })
205 })
197 .collect();
206 .collect();
@@ -217,7 +226,9 @@ pub fn open_captions_settings(app: &Entity<AppState>, window: &mut Window, cx: &
217 format!("captions-position-{}", choice.meta()),
226 format!("captions-position-{}", choice.meta()),
218 choice.label(),
227 choice.label(),
219 position == choice,
228 position == choice,
220 move |cx| app.update(cx, |state, cx| state.set_call_caption_position(choice, cx)),
229 move |cx| {
230 app.update(cx, |state, cx| state.set_call_caption_position(choice, cx))
231 },
221 )
232 )
222 })
233 })
223 .collect();
234 .collect();
crates/app/src/views/call_stage.rs +52 −2
@@ -141,6 +141,36 @@ fn zoom_chip(app: &Entity<AppState>, stage: &ShareStage) -> Option<AnyElement> {
141 141 )
142 142 }
143 143
144 fn pop_out_button(app: &Entity<AppState>) -> AnyElement {
145 let app = app.clone();
146 div()
147 .absolute()
148 .bottom(px(LABEL_OFFSET))
149 .right(px(LABEL_OFFSET))
150 .child(
151 h_flex()
152 .id("call-stage-pop-out")
153 .h(px(CHIP_HEIGHT))
154 .px(px(12.))
155 .gap(px(8.))
156 .items_center()
157 .rounded_full()
158 .bg(hsla(0., 0., 0., LABEL_BACKGROUND))
159 .text_color(theme::white())
160 .text_size(px(13.))
161 .font_weight(FontWeight::SEMIBOLD)
162 .cursor_pointer()
163 .hover(|chip| chip.opacity(0.85))
164 .child(icon(IconName::ExternalLink, 15., theme::white()))
165 .child(POP_OUT_TOOLTIP)
166 .on_click(move |_, _, cx| {
167 cx.stop_propagation();
168 app.update(cx, |state, cx| state.pop_out_stage(cx));
169 }),
170 )
171 .into_any_element()
172 }
173
144 174 pub fn popped_placeholder(app: &Entity<AppState>) -> AnyElement {
145 175 let app = app.clone();
146 176 v_flex()
@@ -228,11 +258,15 @@ pub fn render_stage(
228 258 cx.stop_propagation();
229 259 })
230 260 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
231 down_app.update(cx, |state, cx| state.begin_share_pan(position(event.position), cx));
261 down_app.update(cx, |state, cx| {
262 state.begin_share_pan(position(event.position), cx)
263 });
232 264 })
233 265 .on_mouse_move(move |event, _, cx| {
234 266 if event.pressed_button == Some(MouseButton::Left) {
235 move_app.update(cx, |state, cx| state.pan_share_to(position(event.position), cx));
267 move_app.update(cx, |state, cx| {
268 state.pan_share_to(position(event.position), cx)
269 });
236 270 }
237 271 })
238 272 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
@@ -250,6 +284,9 @@ pub fn render_stage(
250 284 .child(picture(image, share_stage))
251 285 .child(label_chip(label))
252 286 .children(zoom_chip(app, share_stage))
287 .when(mode == StageMode::Docked, |stage| {
288 stage.child(pop_out_button(app))
289 })
253 290 .when(mode == StageMode::Fullscreen, |stage| {
254 291 stage.child(
255 292 div()
@@ -293,3 +330,16 @@ pub fn render_stage_overlay(app: &Entity<AppState>, state: &AppState) -> Option<
293 330 .into_any_element(),
294 331 )
295 332 }
333
334 pub fn render_call_overlay(view: AnyElement) -> AnyElement {
335 v_flex()
336 .id("call-fullscreen-overlay")
337 .occlude()
338 .absolute()
339 .top_0()
340 .left_0()
341 .size_full()
342 .bg(theme::background())
343 .child(view)
344 .into_any_element()
345 }
@@ -141,6 +141,36 @@ fn zoom_chip(app: &Entity<AppState>, stage: &ShareStage) -> Option<AnyElement> {
141 )
141 )
142}
142}
143
143
144fn pop_out_button(app: &Entity<AppState>) -> AnyElement {
145 let app = app.clone();
146 div()
147 .absolute()
148 .bottom(px(LABEL_OFFSET))
149 .right(px(LABEL_OFFSET))
150 .child(
151 h_flex()
152 .id("call-stage-pop-out")
153 .h(px(CHIP_HEIGHT))
154 .px(px(12.))
155 .gap(px(8.))
156 .items_center()
157 .rounded_full()
158 .bg(hsla(0., 0., 0., LABEL_BACKGROUND))
159 .text_color(theme::white())
160 .text_size(px(13.))
161 .font_weight(FontWeight::SEMIBOLD)
162 .cursor_pointer()
163 .hover(|chip| chip.opacity(0.85))
164 .child(icon(IconName::ExternalLink, 15., theme::white()))
165 .child(POP_OUT_TOOLTIP)
166 .on_click(move |_, _, cx| {
167 cx.stop_propagation();
168 app.update(cx, |state, cx| state.pop_out_stage(cx));
169 }),
170 )
171 .into_any_element()
172}
173
144pub fn popped_placeholder(app: &Entity<AppState>) -> AnyElement {
174pub fn popped_placeholder(app: &Entity<AppState>) -> AnyElement {
145 let app = app.clone();
175 let app = app.clone();
146 v_flex()
176 v_flex()
@@ -228,11 +258,15 @@ pub fn render_stage(
228 cx.stop_propagation();
258 cx.stop_propagation();
229 })
259 })
230 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
260 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
231 down_app.update(cx, |state, cx| state.begin_share_pan(position(event.position), cx));
261 down_app.update(cx, |state, cx| {
262 state.begin_share_pan(position(event.position), cx)
263 });
232 })
264 })
233 .on_mouse_move(move |event, _, cx| {
265 .on_mouse_move(move |event, _, cx| {
234 if event.pressed_button == Some(MouseButton::Left) {
266 if event.pressed_button == Some(MouseButton::Left) {
235 move_app.update(cx, |state, cx| state.pan_share_to(position(event.position), cx));
267 move_app.update(cx, |state, cx| {
268 state.pan_share_to(position(event.position), cx)
269 });
236 }
270 }
237 })
271 })
238 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
272 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
@@ -250,6 +284,9 @@ pub fn render_stage(
250 .child(picture(image, share_stage))
284 .child(picture(image, share_stage))
251 .child(label_chip(label))
285 .child(label_chip(label))
252 .children(zoom_chip(app, share_stage))
286 .children(zoom_chip(app, share_stage))
287 .when(mode == StageMode::Docked, |stage| {
288 stage.child(pop_out_button(app))
289 })
253 .when(mode == StageMode::Fullscreen, |stage| {
290 .when(mode == StageMode::Fullscreen, |stage| {
254 stage.child(
291 stage.child(
255 div()
292 div()
@@ -293,3 +330,16 @@ pub fn render_stage_overlay(app: &Entity<AppState>, state: &AppState) -> Option<
293 .into_any_element(),
330 .into_any_element(),
294 )
331 )
295}
332}
333
334pub fn render_call_overlay(view: AnyElement) -> AnyElement {
335 v_flex()
336 .id("call-fullscreen-overlay")
337 .occlude()
338 .absolute()
339 .top_0()
340 .left_0()
341 .size_full()
342 .bg(theme::background())
343 .child(view)
344 .into_any_element()
345}
crates/app/src/views/call_transcript.rs +4 −2
@@ -1,5 +1,5 @@
1 use gpui_kit::component::scroll::ScrollableElement as _;
2 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 3 use gpui_kit::component::{
4 4 h_flex,
5 5 input::{Input, InputEvent, InputState},
@@ -135,7 +135,9 @@ impl Render for TranscriptPanel {
135 135 .into_any_element()
136 136 })
137 137 .collect();
138 let hint = rows.is_empty().then_some(if empty { EMPTY_TEXT } else { NO_MATCH_TEXT });
138 let hint = rows
139 .is_empty()
140 .then_some(if empty { EMPTY_TEXT } else { NO_MATCH_TEXT });
139 141 let app = self.app.clone();
140 142 let search = h_flex()
141 143 .h(px(SEARCH_HEIGHT))
@@ -1,5 +1,5 @@
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::component::{
3use gpui_kit::component::{
4 h_flex,
4 h_flex,
5 input::{Input, InputEvent, InputState},
5 input::{Input, InputEvent, InputState},
@@ -135,7 +135,9 @@ impl Render for TranscriptPanel {
135 .into_any_element()
135 .into_any_element()
136 })
136 })
137 .collect();
137 .collect();
138 let hint = rows.is_empty().then_some(if empty { EMPTY_TEXT } else { NO_MATCH_TEXT });
138 let hint = rows
139 .is_empty()
140 .then_some(if empty { EMPTY_TEXT } else { NO_MATCH_TEXT });
139 let app = self.app.clone();
141 let app = self.app.clone();
140 let search = h_flex()
142 let search = h_flex()
141 .h(px(SEARCH_HEIGHT))
143 .h(px(SEARCH_HEIGHT))
crates/app/src/views/call_view.rs +211 −202
@@ -16,9 +16,8 @@ use gpui_kit::prelude::FluentBuilder as _;
16 16 use gpui_kit::*;
17 17
18 18 use super::avatar::person_avatar;
19 use super::call_control_fold::{Foldable, FoldedControls, fixed_controls_width, folded_for_width, in_more_menu};
20 use super::call_toolbar::{
21 GROUP_GAP, LEAVE_HEIGHT, group_divider, SPLIT_CHEVRON_WIDTH, TOOL_GAP, tool_face, tool_trigger, split_chevron,
19 use super::call_control_fold::{
20 CONTROL_GAP, CONTROLS_PADDING, Foldable, FoldedControls, fixed_controls_width, folded_for_width,
22 21 };
23 22 use super::call_extras::{
24 23 CameraMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
@@ -26,22 +25,22 @@ use super::call_extras::{
26 25 };
27 26 use super::call_health::{health_banner, health_indicator};
28 27 use super::call_layouts::stage_region;
29 use crate::call::measured_stage;
30 28 use super::call_organizer::{
31 camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner,
29 camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,
32 30 more_button, pin_chip, spotlight_chip, with_tile_menu,
33 31 };
34 32 use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
35 use super::call_stage::{POP_OUT_TOOLTIP, StageMode, popped_placeholder, render_stage};
33 use super::call_stage::{StageMode, popped_placeholder, render_stage};
36 34 use super::call_view_menu::view_button;
37 use app_ui_kit::layout::ISLAND_GAP;
38 35 use super::widgets::{Corner, corner_badge, count_badge, icon};
39 36 use crate::app_state::AppState;
40 37 use crate::call::REACTION_SHOWN;
41 38 use crate::call::TileSize;
39 use crate::call::measured_stage;
42 40 use crate::call::{ActiveCall, CallKind, CallModel, Tile, TileState};
43 41 use crate::rows::reaction_glyph as chat_reaction_glyph;
44 42 use crate::theme;
43 use app_ui_kit::layout::ISLAND_GAP;
45 44
46 45 const HEADER_HEIGHT: f32 = 60.;
47 46 const RING_WIDTH: f32 = 3.;
@@ -73,8 +72,7 @@ const THUMBNAIL_ICON: f32 = 22.;
73 72 pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
74 73 pub(super) const CHAT_PANEL_WIDTH: f32 = 320.;
75 74 pub(super) const OVERLAY_BELOW: f32 = 720.;
76 const HEADER_END_PADDING: f32 = 8.;
77 const LEAVE_RADIUS: f32 = 6.;
75 const CONTROLS_HEIGHT: f32 = 2. * 16. + CONTROL_SIZE;
78 76 const CHAT_HEADER_HEIGHT: f32 = 48.;
79 77 const REACTION_RISE: f32 = 24.;
80 78 const REACTION_FADE_FROM: f32 = 0.75;
@@ -251,9 +249,23 @@ struct NamePlate {
251 249
252 250 fn name_plate_metrics(size: TileSize) -> NamePlate {
253 251 if size.height < COMPACT_PLATE_BELOW {
254 NamePlate { inset: 4., padding_x: 6., padding_y: 2., radius: 4., text_size: 11., max_width_share: 0.6 }
252 NamePlate {
253 inset: 4.,
254 padding_x: 6.,
255 padding_y: 2.,
256 radius: 4.,
257 text_size: 11.,
258 max_width_share: 0.6,
259 }
255 260 } else {
256 NamePlate { inset: 8., padding_x: 8., padding_y: 4., radius: 6., text_size: 12., max_width_share: 1. }
261 NamePlate {
262 inset: 8.,
263 padding_x: 8.,
264 padding_y: 4.,
265 radius: 6.,
266 text_size: 12.,
267 max_width_share: 1.,
268 }
257 269 }
258 270 }
259 271
@@ -263,7 +275,9 @@ fn name_plate(size: TileSize, name: &str) -> Div {
263 275 .absolute()
264 276 .left(px(plate.inset))
265 277 .bottom(px(plate.inset))
266 .max_w(px(((size.width - 3. * plate.inset) * plate.max_width_share).max(0.)))
278 .max_w(px(((size.width - 3. * plate.inset)
279 * plate.max_width_share)
280 .max(0.)))
267 281 .truncate()
268 282 .px(px(plate.padding_x))
269 283 .py(px(plate.padding_y))
@@ -385,19 +399,7 @@ pub fn mute_button(
385 399 } else {
386 400 (IconName::Mic, theme::surface_raised(), theme::text())
387 401 };
388 mic_action(round_control(id, glyph, background, foreground).size(px(size)), app, model)
389 }
390
391 fn toolbar_mic(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
392 let glyph = if model.muted {
393 IconName::MicOff
394 } else {
395 IconName::Mic
396 };
397 mic_action(tool_face("call-mute", glyph, "Mic", false), app, model)
398 }
399
400 fn mic_action(button: Stateful<Div>, app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
402 let button = round_control(id, glyph, background, foreground).size(px(size));
401 403 if !model.can_unmute() {
402 404 let hint = if model.audio_off {
403 405 AUDIO_OFF_HINT
@@ -430,8 +432,8 @@ pub fn leave_button(
430 432 let app = app.clone();
431 433 h_flex()
432 434 .id(id)
433 .h(px(if compact { 28. } else { LEAVE_HEIGHT }))
434 .px(px(if compact { 10. } else { 14. }))
435 .h(px(if compact { 28. } else { CONTROL_SIZE }))
436 .px(px(if compact { 10. } else { 20. }))
435 437 .gap(px(8.))
436 438 .flex_none()
437 439 .items_center()
@@ -439,13 +441,13 @@ pub fn leave_button(
439 441 .rounded_full()
440 442 .bg(theme::red())
441 443 .text_color(theme::white())
442 .text_size(px(if compact { 12. } else { 13. }))
444 .text_size(px(if compact { 12. } else { 14. }))
443 445 .font_weight(FontWeight::SEMIBOLD)
444 446 .cursor_pointer()
445 447 .hover(|button| button.opacity(0.85))
446 448 .child(icon(
447 449 IconName::PhoneOff,
448 if compact { 14. } else { 16. },
450 if compact { 14. } else { 18. },
449 451 theme::white(),
450 452 ))
451 453 .child(label)
@@ -455,7 +457,11 @@ pub fn leave_button(
455 457 })
456 458 }
457 459
458 fn share_stage_element(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
460 fn share_stage_element(
461 app: &Entity<AppState>,
462 state: &AppState,
463 call: &ActiveCall,
464 ) -> Option<AnyElement> {
459 465 if call.share_stage.popped && call.model.screen_sharer.is_some() {
460 466 return Some(popped_placeholder(app));
461 467 }
@@ -468,19 +474,7 @@ pub(super) fn camera_button(app: &Entity<AppState>, model: &CallModel) -> Statef
468 474 } else {
469 475 (IconName::VideoOff, theme::surface_raised(), theme::text())
470 476 };
471 camera_action(round_control("call-camera", glyph, background, foreground), app, model)
472 }
473
474 fn toolbar_camera(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
475 let glyph = if model.camera_on {
476 IconName::Video
477 } else {
478 IconName::VideoOff
479 };
480 camera_action(tool_face("call-camera", glyph, "Camera", false), app, model)
481 }
482
483 fn camera_action(button: Stateful<Div>, app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
477 let button = round_control("call-camera", glyph, background, foreground);
484 478 if !model.can_use_camera() {
485 479 return button
486 480 .opacity(DISABLED_OPACITY)
@@ -550,7 +544,9 @@ fn standout_switch_item(app: &Entity<AppState>, standout: bool, camera_on: bool)
550 544 })
551 545 })
552 546 .disabled(!camera_on)
553 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx)))
547 .on_click(move |_, _, cx| {
548 app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx))
549 })
554 550 }
555 551
556 552 fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
@@ -643,7 +639,9 @@ fn share_items(
643 639 let app = app.clone();
644 640 popup = popup.item(
645 641 share_source_item(label, thumbnail, IconName::Monitor, SCREEN_THUMBNAIL).on_click(
646 move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),
642 move |_, _, cx| {
643 app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))
644 },
647 645 ),
648 646 );
649 647 }
@@ -661,7 +659,9 @@ fn share_items(
661 659 let app = app.clone();
662 660 popup = popup.item(
663 661 share_source_item(label, thumbnail, IconName::AppWindow, WINDOW_THUMBNAIL).on_click(
664 move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),
662 move |_, _, cx| {
663 app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))
664 },
665 665 ),
666 666 );
667 667 }
@@ -716,7 +716,12 @@ fn share_button(
716 716 ) -> AnyElement {
717 717 if model.local_share.is_some() {
718 718 let app = app.clone();
719 return tool_face("call-share-stop", IconName::ScreenShareOff, "Stop", true)
719 return round_control(
720 "call-share-stop",
721 IconName::ScreenShareOff,
722 theme::accent(),
723 theme::on_accent(),
724 )
720 725 .tooltip(|window, cx| Tooltip::new("Stop sharing").build(window, cx))
721 726 .on_click(move |_, _, cx| {
722 727 cx.stop_propagation();
@@ -724,7 +729,12 @@ fn share_button(
724 729 })
725 730 .into_any_element();
726 731 }
727 let face = tool_face("call-share-face", IconName::ScreenShare, "Share", false);
732 let face = round_control(
733 "call-share-face",
734 IconName::ScreenShare,
735 theme::surface_raised(),
736 theme::text(),
737 );
728 738 if !model.can_share() {
729 739 return face
730 740 .opacity(DISABLED_OPACITY)
@@ -735,8 +745,13 @@ fn share_button(
735 745 let app = app.clone();
736 746 let open_app = app.clone();
737 747 let model = model.clone();
738 tool_trigger("call-share", face)
739 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
748 Button::new("call-share")
749 .ghost()
750 .p_0()
751 .size(px(CONTROL_SIZE))
752 .rounded_full()
753 .child(face)
754 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
740 755 share_items(popup, &app, &model, options)
741 756 })
742 757 .open(menu_open)
@@ -809,7 +824,12 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
809 824
810 825 fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div> {
811 826 let app = app.clone();
812 tool_face("call-chat", IconName::MessageCircle, "Chat", open)
827 let (background, foreground) = if open {
828 (theme::accent(), theme::on_accent())
829 } else {
830 (theme::surface_raised(), theme::text())
831 };
832 round_control("call-chat", IconName::MessageCircle, background, foreground)
813 833 .relative()
814 834 .tooltip(move |window, cx| {
815 835 Tooltip::new(if open {
@@ -825,9 +845,41 @@ fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div>
825 845 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))
826 846 }
827 847
828 fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
848 fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
829 849 let raised = model.own_hand.is_some();
830 let face = tool_face("call-reactions-face", IconName::FaceSlightlySmiling, "React", raised);
850 let background = if raised {
851 theme::accent()
852 } else {
853 theme::surface_raised()
854 };
855 let foreground = if raised {
856 theme::on_accent()
857 } else {
858 theme::text()
859 };
860 let button = control_shell("call-hand", background).child(icon(
861 IconName::Hand,
862 CONTROL_ICON,
863 foreground,
864 ));
865 let tooltip = if raised { "Lower hand" } else { "Raise hand" };
866 let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));
867 if !model.can_react() {
868 return button.opacity(DISABLED_OPACITY).cursor_default();
869 }
870 let app = app.clone();
871 button.on_click(move |_, _, cx| {
872 cx.stop_propagation();
873 app.update(cx, |state, cx| state.toggle_call_hand(cx));
874 })
875 }
876
877 fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
878 let face = control_shell("call-reactions-face", theme::surface_raised()).child(icon(
879 IconName::FaceSlightlySmiling,
880 CONTROL_ICON,
881 theme::text(),
882 ));
831 883 if !model.can_react() {
832 884 return face
833 885 .opacity(DISABLED_OPACITY)
@@ -836,14 +888,19 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
836 888 }
837 889 let app = app.clone();
838 890 Popover::new("call-reactions-popover")
839 .anchor(Anchor::TopRight)
840 .offset(px(6.))
841 .trigger(tool_trigger("call-reactions", face))
891 .anchor(Anchor::BottomLeft)
892 .offset(px(10.))
893 .trigger(
894 Button::new("call-reactions")
895 .ghost()
896 .p_0()
897 .size(px(CONTROL_SIZE))
898 .rounded_full()
899 .child(face),
900 )
842 901 .content(move |_, _, cx| {
843 902 let popover = cx.entity().downgrade();
844 let hand_app = app.clone();
845 let hand_popover = popover.clone();
846 let reactions = h_flex()
903 h_flex()
847 904 .id("call-reactions-row")
848 905 .gap(px(4.))
849 906 .children(Reaction::ALL.into_iter().map(|reaction| {
@@ -861,64 +918,18 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
861 918 .hover(|cell| cell.bg(theme::border_strong()))
862 919 .child(reaction_glyph(&reaction))
863 920 .on_click(move |_, window, cx| {
864 app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx));
921 app.update(cx, |state, cx| {
922 state.send_call_reaction(reaction.clone(), cx)
923 });
865 924 popover
866 925 .update(cx, |state, cx| state.dismiss(window, cx))
867 926 .ok();
868 927 })
869 }));
870 v_flex()
871 .gap(px(6.))
872 .child(reactions)
873 .child(
874 h_flex()
875 .id("call-hand")
876 .h(px(36.))
877 .px(px(10.))
878 .gap(px(8.))
879 .items_center()
880 .rounded(px(8.))
881 .cursor_pointer()
882 .when(raised, |row| row.bg(theme::accent_soft()))
883 .hover(|row| row.bg(theme::border_strong()))
884 .child(icon(IconName::Hand, 18., if raised { theme::accent_text() } else { theme::text() }))
885 .child(div().text_size(px(13.)).child(if raised { "Lower hand" } else { "Raise hand" }))
886 .on_click(move |_, window, cx| {
887 hand_app.update(cx, |state, cx| state.toggle_call_hand(cx));
888 hand_popover
889 .update(cx, |state, cx| state.dismiss(window, cx))
890 .ok();
891 }),
892 )
928 }))
893 929 })
894 930 .into_any_element()
895 931 }
896 932
897 fn pop_out_tool(app: &Entity<AppState>) -> Stateful<Div> {
898 let app = app.clone();
899 tool_face("call-pop-out", IconName::ExternalLink, POP_OUT_TOOLTIP, false)
900 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.pop_out_stage(cx)))
901 }
902
903 fn shows_pop_out(call: &ActiveCall) -> bool {
904 call.model.screen_sharer.is_some() && !call.share_stage.popped
905 }
906
907 fn leave_group(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
908 let leave = leave_button(app, model, "call-leave", false)
909 .rounded(px(LEAVE_RADIUS))
910 .debug_selector(|| "shell/islands/main/call-header/leave".into());
911 if !has_leave_menu(model) {
912 return leave.into_any_element();
913 }
914 h_flex()
915 .flex_none()
916 .gap(px(1.))
917 .child(leave.rounded_r(px(0.)))
918 .child(leave_menu(app, model))
919 .into_any_element()
920 }
921
922 933 fn has_leave_menu(model: &CallModel) -> bool {
923 934 model.kind == CallKind::Meeting
924 935 && (model.can_end_meeting || (model.can_lower_hands() && model.any_hand_raised()))
@@ -932,23 +943,15 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
932 943 Button::new("call-leave-menu")
933 944 .ghost()
934 945 .p_0()
935 .w(px(SPLIT_CHEVRON_WIDTH + 4.))
936 .h(px(LEAVE_HEIGHT))
937 .rounded_r(px(LEAVE_RADIUS))
938 .child(
939 div()
940 .id("call-leave-menu-face")
941 .size_full()
942 .flex()
943 .items_center()
944 .justify_center()
945 .rounded_r(px(LEAVE_RADIUS))
946 .bg(theme::red())
947 .cursor_pointer()
948 .hover(|face| face.opacity(0.85))
949 .child(icon(IconName::ChevronDown, 12., theme::white())),
950 )
951 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
946 .size(px(CONTROL_SIZE))
947 .rounded_full()
948 .child(round_control(
949 "call-leave-menu-face",
950 IconName::ChevronUp,
951 theme::surface_raised(),
952 theme::text(),
953 ))
954 .dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
952 955 let end_app = end_app.clone();
953 956 let lower_app = lower_app.clone();
954 957 let popup = popup.min_w(px(MENU_WIDTH));
@@ -1057,11 +1060,15 @@ fn devices_menu(
1057 1060 popup
1058 1061 }
1059 1062
1060 fn mic_menu_button(app: &Entity<AppState>, model: &CallModel, mic: MicSettings) -> impl IntoElement {
1063 fn mic_menu_button(
1064 app: &Entity<AppState>,
1065 model: &CallModel,
1066 mic: MicSettings,
1067 ) -> impl IntoElement {
1061 1068 let app = app.clone();
1062 1069 let model = model.clone();
1063 split_chevron("call-mic-menu", "call-mic-menu-face")
1064 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
1070 chevron_button("call-mic-menu", "call-mic-menu-face")
1071 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
1065 1072 devices_menu(popup, &app, &model, mic)
1066 1073 })
1067 1074 }
@@ -1180,7 +1187,9 @@ pub(super) fn plain_own_tile(
1180 1187 let extras = TileExtras {
1181 1188 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1182 1189 own: true,
1183 reaction: model.own_chip(now).map(|chip| (chip.reaction.clone(), chip.serial)),
1190 reaction: model
1191 .own_chip(now)
1192 .map(|chip| (chip.reaction.clone(), chip.serial)),
1184 1193 spotlight: model.own_spotlight.is_some(),
1185 1194 pinned: model.is_pinned(own_mri),
1186 1195 fitted: false,
@@ -1235,9 +1244,9 @@ fn folded_controls(state: &AppState, call: &ActiveCall, fullscreen: bool) -> Fol
1235 1244 if !has_more {
1236 1245 return FoldedControls::default();
1237 1246 }
1238 let mut present = Vec::new();
1247 let mut present = vec![Foldable::View];
1239 1248 if model.has_reaction_controls() {
1240 present.push(Foldable::Reactions);
1249 present.extend([Foldable::Reactions, Foldable::RaiseHand]);
1241 1250 }
1242 1251 if model.kind != CallKind::Test {
1243 1252 present.push(Foldable::People);
@@ -1245,14 +1254,9 @@ fn folded_controls(state: &AppState, call: &ActiveCall, fullscreen: bool) -> Fol
1245 1254 if call.chat_thread().is_some() {
1246 1255 present.push(Foldable::Chat);
1247 1256 }
1248 let fixed = fixed_controls_width(
1249 model.can_use_camera(),
1250 has_more,
1251 has_leave_menu(model),
1252 shows_pop_out(call),
1253 );
1257 let fixed = fixed_controls_width(model.can_use_camera(), has_more, has_leave_menu(model));
1254 1258 FoldedControls {
1255 items: in_more_menu(folded_for_width(measured_stage(call).0, fixed, &present)),
1259 items: folded_for_width(measured_stage(call).0, fixed, &present),
1256 1260 fullscreen,
1257 1261 people_open: call.people_open,
1258 1262 chat_open: call.chat_open,
@@ -1275,14 +1279,7 @@ pub fn render_call_view(
1275 1279 .w_full()
1276 1280 .h(px(HEADER_HEIGHT))
1277 1281 .flex_none()
1278 .pl(px(20.))
1279 .pr(px(HEADER_END_PADDING))
1280 .gap(px(12.))
1281 .items_center();
1282 let title_group = h_flex()
1283 .flex_1()
1284 .flex_basis(px(0.))
1285 .min_w_0()
1282 .px(px(20.))
1286 1283 .gap(px(12.))
1287 1284 .items_center()
1288 1285 .child(icon(IconName::Phone, 18., theme::accent_text()))
@@ -1304,59 +1301,40 @@ pub fn render_call_view(
1304 1301 .children(health_indicator(model))
1305 1302 .children(recording_chip(model))
1306 1303 .children(lock_chip(model))
1307 .children(room_chip(model));
1308 let end_group = h_flex()
1309 .flex_1()
1310 .flex_basis(px(0.))
1311 .min_w_0()
1312 .justify_end()
1313 .gap(px(GROUP_GAP))
1314 .items_center()
1315 .children(return_button(app, model))
1316 .child(leave_group(app, model));
1304 .children(room_chip(model))
1305 .child(div().flex_1())
1306 .children(return_button(app, model));
1317 1307
1318 1308 let hold = hold_panel(app, model);
1319 1309 let share_stage = share_stage_element(app, state, call);
1320 1310 let region = stage_region(app, state, call, now, hold, share_stage);
1321 1311
1322 1312 let folded = folded_controls(state, call, fullscreen);
1323 let panels_and_reactions = h_flex()
1324 .gap(px(TOOL_GAP))
1325 .items_center()
1326 .when(
1327 model.has_reaction_controls() && !folded.folds(Foldable::Reactions),
1328 |row| row.child(reactions_button(app, model)),
1329 )
1330 .when(
1331 call.chat_thread().is_some() && !folded.folds(Foldable::Chat),
1332 |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())),
1333 )
1334 .when(
1335 model.kind != CallKind::Test && !folded.folds(Foldable::People),
1336 |row| row.child(people_button(app, call.people_open, model.raised_hands())),
1337 );
1338 let stage_and_more = h_flex()
1339 .gap(px(TOOL_GAP))
1340 .items_center()
1341 .when(shows_pop_out(call), |row| row.child(pop_out_tool(app)))
1342 .when(!folded.folds(Foldable::View), |row| {
1343 row.child(view_button(app, model, fullscreen))
1344 })
1345 .children(more_button(app, model, &folded));
1346 let devices = h_flex()
1347 .gap(px(TOOL_GAP))
1313 let controls = h_flex()
1314 .w_full()
1315 .flex_none()
1316 .py(px(16.))
1317 .px(px(CONTROLS_PADDING))
1318 .gap(px(CONTROL_GAP))
1348 1319 .items_center()
1320 .justify_center()
1349 1321 .child(
1350 1322 h_flex()
1351 .debug_selector(|| "shell/islands/main/call-header/controls/mic".into())
1323 .debug_selector(|| "shell/islands/main/call-controls/mic".into())
1324 .h(px(CONTROL_SIZE))
1352 1325 .items_center()
1353 .child(toolbar_mic(app, model))
1326 .rounded_full()
1327 .bg(theme::surface_raised())
1328 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
1354 1329 .child(mic_menu_button(app, model, state.call_mic)),
1355 1330 )
1356 1331 .child(
1357 1332 h_flex()
1333 .h(px(CONTROL_SIZE))
1358 1334 .items_center()
1359 .child(toolbar_camera(app, model))
1335 .rounded_full()
1336 .bg(theme::surface_raised())
1337 .child(camera_button(app, model))
1360 1338 .children(camera_menu_button(app, model, CameraMenu::of(state))),
1361 1339 )
1362 1340 .child(share_button(
@@ -1364,18 +1342,34 @@ pub fn render_call_view(
1364 1342 model,
1365 1343 ShareOptions::of(state),
1366 1344 call.share_menu_open,
1367 ));
1368 let controls = h_flex()
1369 .debug_selector(|| "shell/islands/main/call-header/controls".into())
1370 .flex_none()
1371 .gap(px(GROUP_GAP))
1372 .items_center()
1373 .child(devices)
1374 .child(group_divider())
1375 .child(panels_and_reactions)
1376 .child(group_divider())
1377 .child(stage_and_more);
1378 let header = header.child(title_group).child(controls).child(end_group);
1345 ))
1346 .when(
1347 model.has_reaction_controls() && !folded.folds(Foldable::RaiseHand),
1348 |row| row.child(hand_button(app, model)),
1349 )
1350 .when(
1351 model.has_reaction_controls() && !folded.folds(Foldable::Reactions),
1352 |row| row.child(reactions_button(app, model)),
1353 )
1354 .when(!folded.folds(Foldable::View), |row| {
1355 row.child(view_button(app, model, fullscreen))
1356 })
1357 .children(more_button(app, model, &folded))
1358 .when(
1359 model.kind != CallKind::Test && !folded.folds(Foldable::People),
1360 |row| row.child(people_button(app, call.people_open, model.raised_hands())),
1361 )
1362 .when(
1363 call.chat_thread().is_some() && !folded.folds(Foldable::Chat),
1364 |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())),
1365 )
1366 .child(
1367 leave_button(app, model, "call-leave", false)
1368 .debug_selector(|| "shell/islands/main/call-controls/leave".into()),
1369 )
1370 .when(has_leave_menu(model), |row| {
1371 row.child(leave_menu(app, model))
1372 });
1379 1373
1380 1374 let top = v_flex()
1381 1375 .w_full()
@@ -1406,10 +1400,14 @@ pub fn render_call_view(
1406 1400 column.child(fullscreen_chrome("call-chrome-top", app, top))
1407 1401 })
1408 1402 .child(region)
1403 .when(chrome_visible, |column| {
1404 column.child(fullscreen_chrome("call-chrome-bottom", app, controls))
1405 })
1409 1406 } else {
1410 1407 base.rounded(px(10.))
1411 1408 .child(top.debug_selector(|| "shell/islands/main/call-header".into()))
1412 1409 .child(region)
1410 .child(controls.debug_selector(|| "shell/islands/main/call-controls".into()))
1413 1411 }
1414 1412 .children(captions_overlay(model, now))
1415 1413 .children(captions_hint_chip(model))
@@ -1455,9 +1453,9 @@ fn side_panels(panels: Vec<AnyElement>, island_width: f32) -> Vec<AnyElement> {
1455 1453 vec![
1456 1454 h_flex()
1457 1455 .absolute()
1458 .top(px(HEADER_HEIGHT))
1456 .top_0()
1459 1457 .right_0()
1460 .bottom_0()
1458 .bottom(px(CONTROLS_HEIGHT))
1461 1459 .gap(px(ISLAND_GAP))
1462 1460 .w(px(panels_width.min(island_width)))
1463 1461 .children(panels)
@@ -1545,10 +1543,21 @@ mod tests {
1545 1543
1546 1544 #[test]
1547 1545 fn small_strip_tiles_get_a_compact_name_plate() {
1548 let strip = name_plate_metrics(TileSize { width: 216., height: 121.5, avatar: 48. });
1549 assert_eq!((strip.text_size, strip.inset, strip.padding_y), (11., 4., 2.));
1546 let strip = name_plate_metrics(TileSize {
1547 width: 216.,
1548 height: 121.5,
1549 avatar: 48.,
1550 });
1551 assert_eq!(
1552 (strip.text_size, strip.inset, strip.padding_y),
1553 (11., 4., 2.)
1554 );
1550 1555 assert!(strip.max_width_share < 1.);
1551 let stage = name_plate_metrics(TileSize { width: 640., height: 360., avatar: 96. });
1556 let stage = name_plate_metrics(TileSize {
1557 width: 640.,
1558 height: 360.,
1559 avatar: 96.,
1560 });
1552 1561 assert_eq!((stage.text_size, stage.inset), (12., 8.));
1553 1562 }
1554 1563 }
@@ -16,9 +16,8 @@ use gpui_kit::prelude::FluentBuilder as _;
16use gpui_kit::*;
16use gpui_kit::*;
17
17
18use super::avatar::person_avatar;
18use super::avatar::person_avatar;
19use super::call_control_fold::{Foldable, FoldedControls, fixed_controls_width, folded_for_width, in_more_menu};
19use super::call_control_fold::{
20use super::call_toolbar::{
20 CONTROL_GAP, CONTROLS_PADDING, Foldable, FoldedControls, fixed_controls_width, folded_for_width,
21 GROUP_GAP, LEAVE_HEIGHT, group_divider, SPLIT_CHEVRON_WIDTH, TOOL_GAP, tool_face, tool_trigger, split_chevron,
22};
21};
23use super::call_extras::{
22use super::call_extras::{
24 CameraMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
23 CameraMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
@@ -26,22 +25,22 @@ use super::call_extras::{
26};
25};
27use super::call_health::{health_banner, health_indicator};
26use super::call_health::{health_banner, health_indicator};
28use super::call_layouts::stage_region;
27use super::call_layouts::stage_region;
29use crate::call::measured_stage;
30use super::call_organizer::{
28use super::call_organizer::{
31 camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner,
29 camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,
32 more_button, pin_chip, spotlight_chip, with_tile_menu,
30 more_button, pin_chip, spotlight_chip, with_tile_menu,
33};
31};
34use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
32use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
35use super::call_stage::{POP_OUT_TOOLTIP, StageMode, popped_placeholder, render_stage};
33use super::call_stage::{StageMode, popped_placeholder, render_stage};
36use super::call_view_menu::view_button;
34use super::call_view_menu::view_button;
37use app_ui_kit::layout::ISLAND_GAP;
38use super::widgets::{Corner, corner_badge, count_badge, icon};
35use super::widgets::{Corner, corner_badge, count_badge, icon};
39use crate::app_state::AppState;
36use crate::app_state::AppState;
40use crate::call::REACTION_SHOWN;
37use crate::call::REACTION_SHOWN;
41use crate::call::TileSize;
38use crate::call::TileSize;
39use crate::call::measured_stage;
42use crate::call::{ActiveCall, CallKind, CallModel, Tile, TileState};
40use crate::call::{ActiveCall, CallKind, CallModel, Tile, TileState};
43use crate::rows::reaction_glyph as chat_reaction_glyph;
41use crate::rows::reaction_glyph as chat_reaction_glyph;
44use crate::theme;
42use crate::theme;
43use app_ui_kit::layout::ISLAND_GAP;
45
44
46const HEADER_HEIGHT: f32 = 60.;
45const HEADER_HEIGHT: f32 = 60.;
47const RING_WIDTH: f32 = 3.;
46const RING_WIDTH: f32 = 3.;
@@ -73,8 +72,7 @@ const THUMBNAIL_ICON: f32 = 22.;
73pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
72pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
74pub(super) const CHAT_PANEL_WIDTH: f32 = 320.;
73pub(super) const CHAT_PANEL_WIDTH: f32 = 320.;
75pub(super) const OVERLAY_BELOW: f32 = 720.;
74pub(super) const OVERLAY_BELOW: f32 = 720.;
76const HEADER_END_PADDING: f32 = 8.;
75const CONTROLS_HEIGHT: f32 = 2. * 16. + CONTROL_SIZE;
77const LEAVE_RADIUS: f32 = 6.;
78const CHAT_HEADER_HEIGHT: f32 = 48.;
76const CHAT_HEADER_HEIGHT: f32 = 48.;
79const REACTION_RISE: f32 = 24.;
77const REACTION_RISE: f32 = 24.;
80const REACTION_FADE_FROM: f32 = 0.75;
78const REACTION_FADE_FROM: f32 = 0.75;
@@ -251,9 +249,23 @@ struct NamePlate {
251
249
252fn name_plate_metrics(size: TileSize) -> NamePlate {
250fn name_plate_metrics(size: TileSize) -> NamePlate {
253 if size.height < COMPACT_PLATE_BELOW {
251 if size.height < COMPACT_PLATE_BELOW {
254 NamePlate { inset: 4., padding_x: 6., padding_y: 2., radius: 4., text_size: 11., max_width_share: 0.6 }
252 NamePlate {
253 inset: 4.,
254 padding_x: 6.,
255 padding_y: 2.,
256 radius: 4.,
257 text_size: 11.,
258 max_width_share: 0.6,
259 }
255 } else {
260 } else {
256 NamePlate { inset: 8., padding_x: 8., padding_y: 4., radius: 6., text_size: 12., max_width_share: 1. }
261 NamePlate {
262 inset: 8.,
263 padding_x: 8.,
264 padding_y: 4.,
265 radius: 6.,
266 text_size: 12.,
267 max_width_share: 1.,
268 }
257 }
269 }
258}
270}
259
271
@@ -263,7 +275,9 @@ fn name_plate(size: TileSize, name: &str) -> Div {
263 .absolute()
275 .absolute()
264 .left(px(plate.inset))
276 .left(px(plate.inset))
265 .bottom(px(plate.inset))
277 .bottom(px(plate.inset))
266 .max_w(px(((size.width - 3. * plate.inset) * plate.max_width_share).max(0.)))
278 .max_w(px(((size.width - 3. * plate.inset)
279 * plate.max_width_share)
280 .max(0.)))
267 .truncate()
281 .truncate()
268 .px(px(plate.padding_x))
282 .px(px(plate.padding_x))
269 .py(px(plate.padding_y))
283 .py(px(plate.padding_y))
@@ -385,19 +399,7 @@ pub fn mute_button(
385 } else {
399 } else {
386 (IconName::Mic, theme::surface_raised(), theme::text())
400 (IconName::Mic, theme::surface_raised(), theme::text())
387 };
401 };
388 mic_action(round_control(id, glyph, background, foreground).size(px(size)), app, model)
402 let button = round_control(id, glyph, background, foreground).size(px(size));
389}
390
391fn toolbar_mic(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
392 let glyph = if model.muted {
393 IconName::MicOff
394 } else {
395 IconName::Mic
396 };
397 mic_action(tool_face("call-mute", glyph, "Mic", false), app, model)
398}
399
400fn mic_action(button: Stateful<Div>, app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
401 if !model.can_unmute() {
403 if !model.can_unmute() {
402 let hint = if model.audio_off {
404 let hint = if model.audio_off {
403 AUDIO_OFF_HINT
405 AUDIO_OFF_HINT
@@ -430,8 +432,8 @@ pub fn leave_button(
430 let app = app.clone();
432 let app = app.clone();
431 h_flex()
433 h_flex()
432 .id(id)
434 .id(id)
433 .h(px(if compact { 28. } else { LEAVE_HEIGHT }))
435 .h(px(if compact { 28. } else { CONTROL_SIZE }))
434 .px(px(if compact { 10. } else { 14. }))
436 .px(px(if compact { 10. } else { 20. }))
435 .gap(px(8.))
437 .gap(px(8.))
436 .flex_none()
438 .flex_none()
437 .items_center()
439 .items_center()
@@ -439,13 +441,13 @@ pub fn leave_button(
439 .rounded_full()
441 .rounded_full()
440 .bg(theme::red())
442 .bg(theme::red())
441 .text_color(theme::white())
443 .text_color(theme::white())
442 .text_size(px(if compact { 12. } else { 13. }))
444 .text_size(px(if compact { 12. } else { 14. }))
443 .font_weight(FontWeight::SEMIBOLD)
445 .font_weight(FontWeight::SEMIBOLD)
444 .cursor_pointer()
446 .cursor_pointer()
445 .hover(|button| button.opacity(0.85))
447 .hover(|button| button.opacity(0.85))
446 .child(icon(
448 .child(icon(
447 IconName::PhoneOff,
449 IconName::PhoneOff,
448 if compact { 14. } else { 16. },
450 if compact { 14. } else { 18. },
449 theme::white(),
451 theme::white(),
450 ))
452 ))
451 .child(label)
453 .child(label)
@@ -455,7 +457,11 @@ pub fn leave_button(
455 })
457 })
456}
458}
457
459
458fn share_stage_element(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
460fn share_stage_element(
461 app: &Entity<AppState>,
462 state: &AppState,
463 call: &ActiveCall,
464) -> Option<AnyElement> {
459 if call.share_stage.popped && call.model.screen_sharer.is_some() {
465 if call.share_stage.popped && call.model.screen_sharer.is_some() {
460 return Some(popped_placeholder(app));
466 return Some(popped_placeholder(app));
461 }
467 }
@@ -468,19 +474,7 @@ pub(super) fn camera_button(app: &Entity<AppState>, model: &CallModel) -> Statef
468 } else {
474 } else {
469 (IconName::VideoOff, theme::surface_raised(), theme::text())
475 (IconName::VideoOff, theme::surface_raised(), theme::text())
470 };
476 };
471 camera_action(round_control("call-camera", glyph, background, foreground), app, model)
477 let button = round_control("call-camera", glyph, background, foreground);
472}
473
474fn toolbar_camera(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
475 let glyph = if model.camera_on {
476 IconName::Video
477 } else {
478 IconName::VideoOff
479 };
480 camera_action(tool_face("call-camera", glyph, "Camera", false), app, model)
481}
482
483fn camera_action(button: Stateful<Div>, app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
484 if !model.can_use_camera() {
478 if !model.can_use_camera() {
485 return button
479 return button
486 .opacity(DISABLED_OPACITY)
480 .opacity(DISABLED_OPACITY)
@@ -550,7 +544,9 @@ fn standout_switch_item(app: &Entity<AppState>, standout: bool, camera_on: bool)
550 })
544 })
551 })
545 })
552 .disabled(!camera_on)
546 .disabled(!camera_on)
553 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx)))
547 .on_click(move |_, _, cx| {
548 app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx))
549 })
554}
550}
555
551
556fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
552fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
@@ -643,7 +639,9 @@ fn share_items(
643 let app = app.clone();
639 let app = app.clone();
644 popup = popup.item(
640 popup = popup.item(
645 share_source_item(label, thumbnail, IconName::Monitor, SCREEN_THUMBNAIL).on_click(
641 share_source_item(label, thumbnail, IconName::Monitor, SCREEN_THUMBNAIL).on_click(
646 move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),
642 move |_, _, cx| {
643 app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))
644 },
647 ),
645 ),
648 );
646 );
649 }
647 }
@@ -661,7 +659,9 @@ fn share_items(
661 let app = app.clone();
659 let app = app.clone();
662 popup = popup.item(
660 popup = popup.item(
663 share_source_item(label, thumbnail, IconName::AppWindow, WINDOW_THUMBNAIL).on_click(
661 share_source_item(label, thumbnail, IconName::AppWindow, WINDOW_THUMBNAIL).on_click(
664 move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),
662 move |_, _, cx| {
663 app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))
664 },
665 ),
665 ),
666 );
666 );
667 }
667 }
@@ -716,7 +716,12 @@ fn share_button(
716) -> AnyElement {
716) -> AnyElement {
717 if model.local_share.is_some() {
717 if model.local_share.is_some() {
718 let app = app.clone();
718 let app = app.clone();
719 return tool_face("call-share-stop", IconName::ScreenShareOff, "Stop", true)
719 return round_control(
720 "call-share-stop",
721 IconName::ScreenShareOff,
722 theme::accent(),
723 theme::on_accent(),
724 )
720 .tooltip(|window, cx| Tooltip::new("Stop sharing").build(window, cx))
725 .tooltip(|window, cx| Tooltip::new("Stop sharing").build(window, cx))
721 .on_click(move |_, _, cx| {
726 .on_click(move |_, _, cx| {
722 cx.stop_propagation();
727 cx.stop_propagation();
@@ -724,7 +729,12 @@ fn share_button(
724 })
729 })
725 .into_any_element();
730 .into_any_element();
726 }
731 }
727 let face = tool_face("call-share-face", IconName::ScreenShare, "Share", false);
732 let face = round_control(
733 "call-share-face",
734 IconName::ScreenShare,
735 theme::surface_raised(),
736 theme::text(),
737 );
728 if !model.can_share() {
738 if !model.can_share() {
729 return face
739 return face
730 .opacity(DISABLED_OPACITY)
740 .opacity(DISABLED_OPACITY)
@@ -735,8 +745,13 @@ fn share_button(
735 let app = app.clone();
745 let app = app.clone();
736 let open_app = app.clone();
746 let open_app = app.clone();
737 let model = model.clone();
747 let model = model.clone();
738 tool_trigger("call-share", face)
748 Button::new("call-share")
739 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
749 .ghost()
750 .p_0()
751 .size(px(CONTROL_SIZE))
752 .rounded_full()
753 .child(face)
754 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
740 share_items(popup, &app, &model, options)
755 share_items(popup, &app, &model, options)
741 })
756 })
742 .open(menu_open)
757 .open(menu_open)
@@ -809,7 +824,12 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
809
824
810fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div> {
825fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div> {
811 let app = app.clone();
826 let app = app.clone();
812 tool_face("call-chat", IconName::MessageCircle, "Chat", open)
827 let (background, foreground) = if open {
828 (theme::accent(), theme::on_accent())
829 } else {
830 (theme::surface_raised(), theme::text())
831 };
832 round_control("call-chat", IconName::MessageCircle, background, foreground)
813 .relative()
833 .relative()
814 .tooltip(move |window, cx| {
834 .tooltip(move |window, cx| {
815 Tooltip::new(if open {
835 Tooltip::new(if open {
@@ -825,9 +845,41 @@ fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div>
825 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))
845 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))
826}
846}
827
847
828fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
848fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
829 let raised = model.own_hand.is_some();
849 let raised = model.own_hand.is_some();
830 let face = tool_face("call-reactions-face", IconName::FaceSlightlySmiling, "React", raised);
850 let background = if raised {
851 theme::accent()
852 } else {
853 theme::surface_raised()
854 };
855 let foreground = if raised {
856 theme::on_accent()
857 } else {
858 theme::text()
859 };
860 let button = control_shell("call-hand", background).child(icon(
861 IconName::Hand,
862 CONTROL_ICON,
863 foreground,
864 ));
865 let tooltip = if raised { "Lower hand" } else { "Raise hand" };
866 let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));
867 if !model.can_react() {
868 return button.opacity(DISABLED_OPACITY).cursor_default();
869 }
870 let app = app.clone();
871 button.on_click(move |_, _, cx| {
872 cx.stop_propagation();
873 app.update(cx, |state, cx| state.toggle_call_hand(cx));
874 })
875}
876
877fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
878 let face = control_shell("call-reactions-face", theme::surface_raised()).child(icon(
879 IconName::FaceSlightlySmiling,
880 CONTROL_ICON,
881 theme::text(),
882 ));
831 if !model.can_react() {
883 if !model.can_react() {
832 return face
884 return face
833 .opacity(DISABLED_OPACITY)
885 .opacity(DISABLED_OPACITY)
@@ -836,14 +888,19 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
836 }
888 }
837 let app = app.clone();
889 let app = app.clone();
838 Popover::new("call-reactions-popover")
890 Popover::new("call-reactions-popover")
839 .anchor(Anchor::TopRight)
891 .anchor(Anchor::BottomLeft)
840 .offset(px(6.))
892 .offset(px(10.))
841 .trigger(tool_trigger("call-reactions", face))
893 .trigger(
894 Button::new("call-reactions")
895 .ghost()
896 .p_0()
897 .size(px(CONTROL_SIZE))
898 .rounded_full()
899 .child(face),
900 )
842 .content(move |_, _, cx| {
901 .content(move |_, _, cx| {
843 let popover = cx.entity().downgrade();
902 let popover = cx.entity().downgrade();
844 let hand_app = app.clone();
903 h_flex()
845 let hand_popover = popover.clone();
846 let reactions = h_flex()
847 .id("call-reactions-row")
904 .id("call-reactions-row")
848 .gap(px(4.))
905 .gap(px(4.))
849 .children(Reaction::ALL.into_iter().map(|reaction| {
906 .children(Reaction::ALL.into_iter().map(|reaction| {
@@ -861,64 +918,18 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
861 .hover(|cell| cell.bg(theme::border_strong()))
918 .hover(|cell| cell.bg(theme::border_strong()))
862 .child(reaction_glyph(&reaction))
919 .child(reaction_glyph(&reaction))
863 .on_click(move |_, window, cx| {
920 .on_click(move |_, window, cx| {
864 app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx));
921 app.update(cx, |state, cx| {
922 state.send_call_reaction(reaction.clone(), cx)
923 });
865 popover
924 popover
866 .update(cx, |state, cx| state.dismiss(window, cx))
925 .update(cx, |state, cx| state.dismiss(window, cx))
867 .ok();
926 .ok();
868 })
927 })
869 }));
928 }))
870 v_flex()
871 .gap(px(6.))
872 .child(reactions)
873 .child(
874 h_flex()
875 .id("call-hand")
876 .h(px(36.))
877 .px(px(10.))
878 .gap(px(8.))
879 .items_center()
880 .rounded(px(8.))
881 .cursor_pointer()
882 .when(raised, |row| row.bg(theme::accent_soft()))
883 .hover(|row| row.bg(theme::border_strong()))
884 .child(icon(IconName::Hand, 18., if raised { theme::accent_text() } else { theme::text() }))
885 .child(div().text_size(px(13.)).child(if raised { "Lower hand" } else { "Raise hand" }))
886 .on_click(move |_, window, cx| {
887 hand_app.update(cx, |state, cx| state.toggle_call_hand(cx));
888 hand_popover
889 .update(cx, |state, cx| state.dismiss(window, cx))
890 .ok();
891 }),
892 )
893 })
929 })
894 .into_any_element()
930 .into_any_element()
895}
931}
896
932
897fn pop_out_tool(app: &Entity<AppState>) -> Stateful<Div> {
898 let app = app.clone();
899 tool_face("call-pop-out", IconName::ExternalLink, POP_OUT_TOOLTIP, false)
900 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.pop_out_stage(cx)))
901}
902
903fn shows_pop_out(call: &ActiveCall) -> bool {
904 call.model.screen_sharer.is_some() && !call.share_stage.popped
905}
906
907fn leave_group(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
908 let leave = leave_button(app, model, "call-leave", false)
909 .rounded(px(LEAVE_RADIUS))
910 .debug_selector(|| "shell/islands/main/call-header/leave".into());
911 if !has_leave_menu(model) {
912 return leave.into_any_element();
913 }
914 h_flex()
915 .flex_none()
916 .gap(px(1.))
917 .child(leave.rounded_r(px(0.)))
918 .child(leave_menu(app, model))
919 .into_any_element()
920}
921
922fn has_leave_menu(model: &CallModel) -> bool {
933fn has_leave_menu(model: &CallModel) -> bool {
923 model.kind == CallKind::Meeting
934 model.kind == CallKind::Meeting
924 && (model.can_end_meeting || (model.can_lower_hands() && model.any_hand_raised()))
935 && (model.can_end_meeting || (model.can_lower_hands() && model.any_hand_raised()))
@@ -932,23 +943,15 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
932 Button::new("call-leave-menu")
943 Button::new("call-leave-menu")
933 .ghost()
944 .ghost()
934 .p_0()
945 .p_0()
935 .w(px(SPLIT_CHEVRON_WIDTH + 4.))
946 .size(px(CONTROL_SIZE))
936 .h(px(LEAVE_HEIGHT))
947 .rounded_full()
937 .rounded_r(px(LEAVE_RADIUS))
948 .child(round_control(
938 .child(
949 "call-leave-menu-face",
939 div()
950 IconName::ChevronUp,
940 .id("call-leave-menu-face")
951 theme::surface_raised(),
941 .size_full()
952 theme::text(),
942 .flex()
953 ))
943 .items_center()
954 .dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
944 .justify_center()
945 .rounded_r(px(LEAVE_RADIUS))
946 .bg(theme::red())
947 .cursor_pointer()
948 .hover(|face| face.opacity(0.85))
949 .child(icon(IconName::ChevronDown, 12., theme::white())),
950 )
951 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
952 let end_app = end_app.clone();
955 let end_app = end_app.clone();
953 let lower_app = lower_app.clone();
956 let lower_app = lower_app.clone();
954 let popup = popup.min_w(px(MENU_WIDTH));
957 let popup = popup.min_w(px(MENU_WIDTH));
@@ -1057,11 +1060,15 @@ fn devices_menu(
1057 popup
1060 popup
1058}
1061}
1059
1062
1060fn mic_menu_button(app: &Entity<AppState>, model: &CallModel, mic: MicSettings) -> impl IntoElement {
1063fn mic_menu_button(
1064 app: &Entity<AppState>,
1065 model: &CallModel,
1066 mic: MicSettings,
1067) -> impl IntoElement {
1061 let app = app.clone();
1068 let app = app.clone();
1062 let model = model.clone();
1069 let model = model.clone();
1063 split_chevron("call-mic-menu", "call-mic-menu-face")
1070 chevron_button("call-mic-menu", "call-mic-menu-face")
1064 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
1071 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
1065 devices_menu(popup, &app, &model, mic)
1072 devices_menu(popup, &app, &model, mic)
1066 })
1073 })
1067}
1074}
@@ -1180,7 +1187,9 @@ pub(super) fn plain_own_tile(
1180 let extras = TileExtras {
1187 let extras = TileExtras {
1181 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1188 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1182 own: true,
1189 own: true,
1183 reaction: model.own_chip(now).map(|chip| (chip.reaction.clone(), chip.serial)),
1190 reaction: model
1191 .own_chip(now)
1192 .map(|chip| (chip.reaction.clone(), chip.serial)),
1184 spotlight: model.own_spotlight.is_some(),
1193 spotlight: model.own_spotlight.is_some(),
1185 pinned: model.is_pinned(own_mri),
1194 pinned: model.is_pinned(own_mri),
1186 fitted: false,
1195 fitted: false,
@@ -1235,9 +1244,9 @@ fn folded_controls(state: &AppState, call: &ActiveCall, fullscreen: bool) -> Fol
1235 if !has_more {
1244 if !has_more {
1236 return FoldedControls::default();
1245 return FoldedControls::default();
1237 }
1246 }
1238 let mut present = Vec::new();
1247 let mut present = vec![Foldable::View];
1239 if model.has_reaction_controls() {
1248 if model.has_reaction_controls() {
1240 present.push(Foldable::Reactions);
1249 present.extend([Foldable::Reactions, Foldable::RaiseHand]);
1241 }
1250 }
1242 if model.kind != CallKind::Test {
1251 if model.kind != CallKind::Test {
1243 present.push(Foldable::People);
1252 present.push(Foldable::People);
@@ -1245,14 +1254,9 @@ fn folded_controls(state: &AppState, call: &ActiveCall, fullscreen: bool) -> Fol
1245 if call.chat_thread().is_some() {
1254 if call.chat_thread().is_some() {
1246 present.push(Foldable::Chat);
1255 present.push(Foldable::Chat);
1247 }
1256 }
1248 let fixed = fixed_controls_width(
1257 let fixed = fixed_controls_width(model.can_use_camera(), has_more, has_leave_menu(model));
1249 model.can_use_camera(),
1250 has_more,
1251 has_leave_menu(model),
1252 shows_pop_out(call),
1253 );
1254 FoldedControls {
1258 FoldedControls {
1255 items: in_more_menu(folded_for_width(measured_stage(call).0, fixed, &present)),
1259 items: folded_for_width(measured_stage(call).0, fixed, &present),
1256 fullscreen,
1260 fullscreen,
1257 people_open: call.people_open,
1261 people_open: call.people_open,
1258 chat_open: call.chat_open,
1262 chat_open: call.chat_open,
@@ -1275,14 +1279,7 @@ pub fn render_call_view(
1275 .w_full()
1279 .w_full()
1276 .h(px(HEADER_HEIGHT))
1280 .h(px(HEADER_HEIGHT))
1277 .flex_none()
1281 .flex_none()
1278 .pl(px(20.))
1282 .px(px(20.))
1279 .pr(px(HEADER_END_PADDING))
1280 .gap(px(12.))
1281 .items_center();
1282 let title_group = h_flex()
1283 .flex_1()
1284 .flex_basis(px(0.))
1285 .min_w_0()
1286 .gap(px(12.))
1283 .gap(px(12.))
1287 .items_center()
1284 .items_center()
1288 .child(icon(IconName::Phone, 18., theme::accent_text()))
1285 .child(icon(IconName::Phone, 18., theme::accent_text()))
@@ -1304,59 +1301,40 @@ pub fn render_call_view(
1304 .children(health_indicator(model))
1301 .children(health_indicator(model))
1305 .children(recording_chip(model))
1302 .children(recording_chip(model))
1306 .children(lock_chip(model))
1303 .children(lock_chip(model))
1307 .children(room_chip(model));
1304 .children(room_chip(model))
1308 let end_group = h_flex()
1305 .child(div().flex_1())
1309 .flex_1()
1306 .children(return_button(app, model));
1310 .flex_basis(px(0.))
1311 .min_w_0()
1312 .justify_end()
1313 .gap(px(GROUP_GAP))
1314 .items_center()
1315 .children(return_button(app, model))
1316 .child(leave_group(app, model));
1317
1307
1318 let hold = hold_panel(app, model);
1308 let hold = hold_panel(app, model);
1319 let share_stage = share_stage_element(app, state, call);
1309 let share_stage = share_stage_element(app, state, call);
1320 let region = stage_region(app, state, call, now, hold, share_stage);
1310 let region = stage_region(app, state, call, now, hold, share_stage);
1321
1311
1322 let folded = folded_controls(state, call, fullscreen);
1312 let folded = folded_controls(state, call, fullscreen);
1323 let panels_and_reactions = h_flex()
1313 let controls = h_flex()
1324 .gap(px(TOOL_GAP))
1314 .w_full()
1325 .items_center()
1315 .flex_none()
1326 .when(
1316 .py(px(16.))
1327 model.has_reaction_controls() && !folded.folds(Foldable::Reactions),
1317 .px(px(CONTROLS_PADDING))
1328 |row| row.child(reactions_button(app, model)),
1318 .gap(px(CONTROL_GAP))
1329 )
1330 .when(
1331 call.chat_thread().is_some() && !folded.folds(Foldable::Chat),
1332 |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())),
1333 )
1334 .when(
1335 model.kind != CallKind::Test && !folded.folds(Foldable::People),
1336 |row| row.child(people_button(app, call.people_open, model.raised_hands())),
1337 );
1338 let stage_and_more = h_flex()
1339 .gap(px(TOOL_GAP))
1340 .items_center()
1341 .when(shows_pop_out(call), |row| row.child(pop_out_tool(app)))
1342 .when(!folded.folds(Foldable::View), |row| {
1343 row.child(view_button(app, model, fullscreen))
1344 })
1345 .children(more_button(app, model, &folded));
1346 let devices = h_flex()
1347 .gap(px(TOOL_GAP))
1348 .items_center()
1319 .items_center()
1320 .justify_center()
1349 .child(
1321 .child(
1350 h_flex()
1322 h_flex()
1351 .debug_selector(|| "shell/islands/main/call-header/controls/mic".into())
1323 .debug_selector(|| "shell/islands/main/call-controls/mic".into())
1324 .h(px(CONTROL_SIZE))
1352 .items_center()
1325 .items_center()
1353 .child(toolbar_mic(app, model))
1326 .rounded_full()
1327 .bg(theme::surface_raised())
1328 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
1354 .child(mic_menu_button(app, model, state.call_mic)),
1329 .child(mic_menu_button(app, model, state.call_mic)),
1355 )
1330 )
1356 .child(
1331 .child(
1357 h_flex()
1332 h_flex()
1333 .h(px(CONTROL_SIZE))
1358 .items_center()
1334 .items_center()
1359 .child(toolbar_camera(app, model))
1335 .rounded_full()
1336 .bg(theme::surface_raised())
1337 .child(camera_button(app, model))
1360 .children(camera_menu_button(app, model, CameraMenu::of(state))),
1338 .children(camera_menu_button(app, model, CameraMenu::of(state))),
1361 )
1339 )
1362 .child(share_button(
1340 .child(share_button(
@@ -1364,18 +1342,34 @@ pub fn render_call_view(
1364 model,
1342 model,
1365 ShareOptions::of(state),
1343 ShareOptions::of(state),
1366 call.share_menu_open,
1344 call.share_menu_open,
1367 ));
1345 ))
1368 let controls = h_flex()
1346 .when(
1369 .debug_selector(|| "shell/islands/main/call-header/controls".into())
1347 model.has_reaction_controls() && !folded.folds(Foldable::RaiseHand),
1370 .flex_none()
1348 |row| row.child(hand_button(app, model)),
1371 .gap(px(GROUP_GAP))
1349 )
1372 .items_center()
1350 .when(
1373 .child(devices)
1351 model.has_reaction_controls() && !folded.folds(Foldable::Reactions),
1374 .child(group_divider())
1352 |row| row.child(reactions_button(app, model)),
1375 .child(panels_and_reactions)
1353 )
1376 .child(group_divider())
1354 .when(!folded.folds(Foldable::View), |row| {
1377 .child(stage_and_more);
1355 row.child(view_button(app, model, fullscreen))
1378 let header = header.child(title_group).child(controls).child(end_group);
1356 })
1357 .children(more_button(app, model, &folded))
1358 .when(
1359 model.kind != CallKind::Test && !folded.folds(Foldable::People),
1360 |row| row.child(people_button(app, call.people_open, model.raised_hands())),
1361 )
1362 .when(
1363 call.chat_thread().is_some() && !folded.folds(Foldable::Chat),
1364 |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())),
1365 )
1366 .child(
1367 leave_button(app, model, "call-leave", false)
1368 .debug_selector(|| "shell/islands/main/call-controls/leave".into()),
1369 )
1370 .when(has_leave_menu(model), |row| {
1371 row.child(leave_menu(app, model))
1372 });
1379
1373
1380 let top = v_flex()
1374 let top = v_flex()
1381 .w_full()
1375 .w_full()
@@ -1406,10 +1400,14 @@ pub fn render_call_view(
1406 column.child(fullscreen_chrome("call-chrome-top", app, top))
1400 column.child(fullscreen_chrome("call-chrome-top", app, top))
1407 })
1401 })
1408 .child(region)
1402 .child(region)
1403 .when(chrome_visible, |column| {
1404 column.child(fullscreen_chrome("call-chrome-bottom", app, controls))
1405 })
1409 } else {
1406 } else {
1410 base.rounded(px(10.))
1407 base.rounded(px(10.))
1411 .child(top.debug_selector(|| "shell/islands/main/call-header".into()))
1408 .child(top.debug_selector(|| "shell/islands/main/call-header".into()))
1412 .child(region)
1409 .child(region)
1410 .child(controls.debug_selector(|| "shell/islands/main/call-controls".into()))
1413 }
1411 }
1414 .children(captions_overlay(model, now))
1412 .children(captions_overlay(model, now))
1415 .children(captions_hint_chip(model))
1413 .children(captions_hint_chip(model))
@@ -1455,9 +1453,9 @@ fn side_panels(panels: Vec<AnyElement>, island_width: f32) -> Vec<AnyElement> {
1455 vec![
1453 vec![
1456 h_flex()
1454 h_flex()
1457 .absolute()
1455 .absolute()
1458 .top(px(HEADER_HEIGHT))
1456 .top_0()
1459 .right_0()
1457 .right_0()
1460 .bottom_0()
1458 .bottom(px(CONTROLS_HEIGHT))
1461 .gap(px(ISLAND_GAP))
1459 .gap(px(ISLAND_GAP))
1462 .w(px(panels_width.min(island_width)))
1460 .w(px(panels_width.min(island_width)))
1463 .children(panels)
1461 .children(panels)
@@ -1545,10 +1543,21 @@ mod tests {
1545
1543
1546 #[test]
1544 #[test]
1547 fn small_strip_tiles_get_a_compact_name_plate() {
1545 fn small_strip_tiles_get_a_compact_name_plate() {
1548 let strip = name_plate_metrics(TileSize { width: 216., height: 121.5, avatar: 48. });
1546 let strip = name_plate_metrics(TileSize {
1549 assert_eq!((strip.text_size, strip.inset, strip.padding_y), (11., 4., 2.));
1547 width: 216.,
1548 height: 121.5,
1549 avatar: 48.,
1550 });
1551 assert_eq!(
1552 (strip.text_size, strip.inset, strip.padding_y),
1553 (11., 4., 2.)
1554 );
1550 assert!(strip.max_width_share < 1.);
1555 assert!(strip.max_width_share < 1.);
1551 let stage = name_plate_metrics(TileSize { width: 640., height: 360., avatar: 96. });
1556 let stage = name_plate_metrics(TileSize {
1557 width: 640.,
1558 height: 360.,
1559 avatar: 96.,
1560 });
1552 assert_eq!((stage.text_size, stage.inset), (12., 8.));
1561 assert_eq!((stage.text_size, stage.inset), (12., 8.));
1553 }
1562 }
1554}
1563}
crates/app/src/views/calls_page.rs +13 −8
@@ -184,7 +184,10 @@ fn history_filters(state: &Entity<AppState>, current: HistoryFilter) -> AnyEleme
184 184 let selected = filter == current;
185 185 let state = state.clone();
186 186 div()
187 .id(SharedString::from(format!("calls-filter-{}", filter.label())))
187 .id(SharedString::from(format!(
188 "calls-filter-{}",
189 filter.label()
190 )))
188 191 .h(px(24.))
189 192 .px(px(10.))
190 193 .flex()
@@ -206,7 +209,11 @@ fn history_filters(state: &Entity<AppState>, current: HistoryFilter) -> AnyEleme
206 209 state.update(cx, |state, cx| state.set_call_history_filter(filter, cx))
207 210 })
208 211 });
209 h_flex().gap(px(6.)).items_center().children(pills).into_any_element()
212 h_flex()
213 .gap(px(6.))
214 .items_center()
215 .children(pills)
216 .into_any_element()
210 217 }
211 218
212 219 fn empty_row(text: &'static str) -> AnyElement {
@@ -409,9 +416,9 @@ impl CallsPage {
409 416 .child(
410 417 Button::new("speed-dial-empty-add")
411 418 .label(ADD_LABEL)
412 .on_click(cx.listener(|this, _, window, cx| {
413 this.open_speed_dial_add(window, cx)
414 })),
419 .on_click(
420 cx.listener(|this, _, window, cx| this.open_speed_dial_add(window, cx)),
421 ),
415 422 )
416 423 }
417 424
@@ -423,9 +430,7 @@ impl CallsPage {
423 430 .map(|entry| speed_dial_row(&self.app, entry, &state.directory))
424 431 .collect::<Vec<_>>();
425 432 let body = if self.adding_speed_dial {
426 div()
427 .p(px(PAGE_PADDING))
428 .child(self.speed_dial_adder(cx))
433 div().p(px(PAGE_PADDING)).child(self.speed_dial_adder(cx))
429 434 } else if rows.is_empty() {
430 435 self.speed_dial_empty(cx)
431 436 } else {
@@ -184,7 +184,10 @@ fn history_filters(state: &Entity<AppState>, current: HistoryFilter) -> AnyEleme
184 let selected = filter == current;
184 let selected = filter == current;
185 let state = state.clone();
185 let state = state.clone();
186 div()
186 div()
187 .id(SharedString::from(format!("calls-filter-{}", filter.label())))
187 .id(SharedString::from(format!(
188 "calls-filter-{}",
189 filter.label()
190 )))
188 .h(px(24.))
191 .h(px(24.))
189 .px(px(10.))
192 .px(px(10.))
190 .flex()
193 .flex()
@@ -206,7 +209,11 @@ fn history_filters(state: &Entity<AppState>, current: HistoryFilter) -> AnyEleme
206 state.update(cx, |state, cx| state.set_call_history_filter(filter, cx))
209 state.update(cx, |state, cx| state.set_call_history_filter(filter, cx))
207 })
210 })
208 });
211 });
209 h_flex().gap(px(6.)).items_center().children(pills).into_any_element()
212 h_flex()
213 .gap(px(6.))
214 .items_center()
215 .children(pills)
216 .into_any_element()
210}
217}
211
218
212fn empty_row(text: &'static str) -> AnyElement {
219fn empty_row(text: &'static str) -> AnyElement {
@@ -409,9 +416,9 @@ impl CallsPage {
409 .child(
416 .child(
410 Button::new("speed-dial-empty-add")
417 Button::new("speed-dial-empty-add")
411 .label(ADD_LABEL)
418 .label(ADD_LABEL)
412 .on_click(cx.listener(|this, _, window, cx| {
419 .on_click(
413 this.open_speed_dial_add(window, cx)
420 cx.listener(|this, _, window, cx| this.open_speed_dial_add(window, cx)),
414 })),
421 ),
415 )
422 )
416 }
423 }
417
424
@@ -423,9 +430,7 @@ impl CallsPage {
423 .map(|entry| speed_dial_row(&self.app, entry, &state.directory))
430 .map(|entry| speed_dial_row(&self.app, entry, &state.directory))
424 .collect::<Vec<_>>();
431 .collect::<Vec<_>>();
425 let body = if self.adding_speed_dial {
432 let body = if self.adding_speed_dial {
426 div()
433 div().p(px(PAGE_PADDING)).child(self.speed_dial_adder(cx))
427 .p(px(PAGE_PADDING))
428 .child(self.speed_dial_adder(cx))
429 } else if rows.is_empty() {
434 } else if rows.is_empty() {
430 self.speed_dial_empty(cx)
435 self.speed_dial_empty(cx)
431 } else {
436 } else {
crates/app/src/views/card_input_tests.rs +2 −7
@@ -8,9 +8,9 @@ use serde_json::json;
8 8 use store::Store;
9 9 use teams_core::AdaptiveCard;
10 10
11 use crate::card_inputs::InputField;
12 11 use crate::app_state::{AppHandle, AppState, Mode};
13 12 use crate::card_actions::CardTask;
13 use crate::card_inputs::InputField;
14 14 use crate::card_state::{CardScope, Surface};
15 15 use crate::views::adaptive_card::card_view;
16 16
@@ -129,12 +129,7 @@ fn error_of(cx: &mut VisualTestContext, app: &Entity<AppState>, key: &str) -> Op
129 129 cx.update(|_, cx| app.read(cx).cards.input_error(key).map(str::to_owned))
130 130 }
131 131
132 fn type_name(
133 cx: &mut VisualTestContext,
134 app: &Entity<AppState>,
135 scope: &CardScope,
136 text: &str,
137 ) {
132 fn type_name(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope, text: &str) {
138 133 focus_name_field(cx, app, scope);
139 134 cx.simulate_input(text);
140 135 }
@@ -8,9 +8,9 @@ use serde_json::json;
8use store::Store;
8use store::Store;
9use teams_core::AdaptiveCard;
9use teams_core::AdaptiveCard;
10
10
11use crate::card_inputs::InputField;
12use crate::app_state::{AppHandle, AppState, Mode};
11use crate::app_state::{AppHandle, AppState, Mode};
13use crate::card_actions::CardTask;
12use crate::card_actions::CardTask;
13use crate::card_inputs::InputField;
14use crate::card_state::{CardScope, Surface};
14use crate::card_state::{CardScope, Surface};
15use crate::views::adaptive_card::card_view;
15use crate::views::adaptive_card::card_view;
16
16
@@ -129,12 +129,7 @@ fn error_of(cx: &mut VisualTestContext, app: &Entity<AppState>, key: &str) -> Op
129 cx.update(|_, cx| app.read(cx).cards.input_error(key).map(str::to_owned))
129 cx.update(|_, cx| app.read(cx).cards.input_error(key).map(str::to_owned))
130}
130}
131
131
132fn type_name(
132fn type_name(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope, text: &str) {
133 cx: &mut VisualTestContext,
134 app: &Entity<AppState>,
135 scope: &CardScope,
136 text: &str,
137) {
138 focus_name_field(cx, app, scope);
133 focus_name_field(cx, app, scope);
139 cx.simulate_input(text);
134 cx.simulate_input(text);
140}
135}
crates/app/src/views/chat_members.rs +7 −3
@@ -1,4 +1,3 @@
1 use gpui_kit::component::scroll::ScrollableElement as _;
2 1 use gpui_kit::assets::IconName;
3 2 use gpui_kit::component::button::{Button, ButtonVariants as _};
4 3 use gpui_kit::component::dialog::DialogFooter;
@@ -7,14 +6,15 @@ use gpui_kit::component::fluent::{
7 6 MENU_ITEM_PADDING_X, MENU_LIST_PADDING,
8 7 };
9 8 use gpui_kit::component::popover::{Popover, PopoverState};
9 use gpui_kit::component::scroll::ScrollableElement as _;
10 10 use gpui_kit::component::{Sizable as _, WindowExt as _, h_flex, v_flex};
11 11 use gpui_kit::prelude::FluentBuilder as _;
12 12 use gpui_kit::*;
13 13
14 14 use super::add_people_dialog::open_add_people;
15 15 use super::avatar::{person_avatar, with_presence};
16 use super::profile_card::opens_profile;
17 16 use super::chat_menu::confirm_leave;
17 use super::profile_card::opens_profile;
18 18 use super::widgets::icon;
19 19 use crate::app_state::AppState;
20 20 use crate::chat_actions::TITLE_LIMIT;
@@ -268,7 +268,11 @@ fn action_row(id: &'static str, icon_name: IconName, label: &'static str) -> Sta
268 268 .flex()
269 269 .items_center()
270 270 .justify_center()
271 .child(icon(icon_name, f32::from(MENU_ICON_GLYPH), theme::text_soft())),
271 .child(icon(
272 icon_name,
273 f32::from(MENU_ICON_GLYPH),
274 theme::text_soft(),
275 )),
272 276 )
273 277 .child(label)
274 278 }
@@ -1,4 +1,3 @@
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
3use gpui_kit::component::button::{Button, ButtonVariants as _};
2use gpui_kit::component::button::{Button, ButtonVariants as _};
4use gpui_kit::component::dialog::DialogFooter;
3use gpui_kit::component::dialog::DialogFooter;
@@ -7,14 +6,15 @@ use gpui_kit::component::fluent::{
7 MENU_ITEM_PADDING_X, MENU_LIST_PADDING,
6 MENU_ITEM_PADDING_X, MENU_LIST_PADDING,
8};
7};
9use gpui_kit::component::popover::{Popover, PopoverState};
8use gpui_kit::component::popover::{Popover, PopoverState};
9use gpui_kit::component::scroll::ScrollableElement as _;
10use gpui_kit::component::{Sizable as _, WindowExt as _, h_flex, v_flex};
10use gpui_kit::component::{Sizable as _, WindowExt as _, h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
12use gpui_kit::*;
13
13
14use super::add_people_dialog::open_add_people;
14use super::add_people_dialog::open_add_people;
15use super::avatar::{person_avatar, with_presence};
15use super::avatar::{person_avatar, with_presence};
16use super::profile_card::opens_profile;
17use super::chat_menu::confirm_leave;
16use super::chat_menu::confirm_leave;
17use super::profile_card::opens_profile;
18use super::widgets::icon;
18use super::widgets::icon;
19use crate::app_state::AppState;
19use crate::app_state::AppState;
20use crate::chat_actions::TITLE_LIMIT;
20use crate::chat_actions::TITLE_LIMIT;
@@ -268,7 +268,11 @@ fn action_row(id: &'static str, icon_name: IconName, label: &'static str) -> Sta
268 .flex()
268 .flex()
269 .items_center()
269 .items_center()
270 .justify_center()
270 .justify_center()
271 .child(icon(icon_name, f32::from(MENU_ICON_GLYPH), theme::text_soft())),
271 .child(icon(
272 icon_name,
273 f32::from(MENU_ICON_GLYPH),
274 theme::text_soft(),
275 )),
272 )
276 )
273 .child(label)
277 .child(label)
274}
278}
crates/app/src/views/chat_menu.rs +5 −2
@@ -1,8 +1,8 @@
1 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::WindowExt as _;
2 3 use gpui_kit::component::button::{Button, ButtonVariants as _};
3 4 use gpui_kit::component::dialog::DialogFooter;
4 5 use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
5 use gpui_kit::component::WindowExt as _;
6 6 use gpui_kit::*;
7 7 use teams_core::{ChatNotificationMode, DesktopNotifications, chat_link, is_notes_chat};
8 8
@@ -165,7 +165,10 @@ pub(crate) fn chat_menu(
165 165 .flatten();
166 166 if let Some(partner) = partner {
167 167 let follow_state = context.state.clone();
168 let follow = !context.state.read(cx).is_presence_followed(&partner.user_id);
168 let follow = !context
169 .state
170 .read(cx)
171 .is_presence_followed(&partner.user_id);
169 172 popup = popup.item(
170 173 PopupMenuItem::new(if follow {
171 174 NOTIFY_WHEN_AVAILABLE
@@ -1,8 +1,8 @@
1use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::WindowExt as _;
2use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::dialog::DialogFooter;
4use gpui_kit::component::dialog::DialogFooter;
4use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
5use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
5use gpui_kit::component::WindowExt as _;
6use gpui_kit::*;
6use gpui_kit::*;
7use teams_core::{ChatNotificationMode, DesktopNotifications, chat_link, is_notes_chat};
7use teams_core::{ChatNotificationMode, DesktopNotifications, chat_link, is_notes_chat};
8
8
@@ -165,7 +165,10 @@ pub(crate) fn chat_menu(
165 .flatten();
165 .flatten();
166 if let Some(partner) = partner {
166 if let Some(partner) = partner {
167 let follow_state = context.state.clone();
167 let follow_state = context.state.clone();
168 let follow = !context.state.read(cx).is_presence_followed(&partner.user_id);
168 let follow = !context
169 .state
170 .read(cx)
171 .is_presence_followed(&partner.user_id);
169 popup = popup.item(
172 popup = popup.item(
170 PopupMenuItem::new(if follow {
173 PopupMenuItem::new(if follow {
171 NOTIFY_WHEN_AVAILABLE
174 NOTIFY_WHEN_AVAILABLE
crates/app/src/views/chat_pop_out.rs +2 −6
@@ -39,8 +39,7 @@ impl ChatPopOutView {
39 39 true
40 40 });
41 41 let selection = Selection::Chat(chat_id);
42 let conversation =
43 cx.new(|cx| ConversationView::popped_out(app, selection, window, cx));
42 let conversation = cx.new(|cx| ConversationView::popped_out(app, selection, window, cx));
44 43 ChatPopOutView { conversation }
45 44 }
46 45 }
@@ -86,10 +85,7 @@ pub fn pop_out_chat(app: &Entity<AppState>, chat_id: &str, cx: &mut App) {
86 85 size(px(CHAT_WINDOW_SIZE.0), px(CHAT_WINDOW_SIZE.1)),
87 86 cx,
88 87 ))),
89 window_min_size: Some(size(
90 px(CHAT_WINDOW_MIN_SIZE.0),
91 px(CHAT_WINDOW_MIN_SIZE.1),
92 )),
88 window_min_size: Some(size(px(CHAT_WINDOW_MIN_SIZE.0), px(CHAT_WINDOW_MIN_SIZE.1))),
93 89 titlebar: Some(TitlebarOptions {
94 90 title: Some(title.into()),
95 91 ..Default::default()
@@ -39,8 +39,7 @@ impl ChatPopOutView {
39 true
39 true
40 });
40 });
41 let selection = Selection::Chat(chat_id);
41 let selection = Selection::Chat(chat_id);
42 let conversation =
42 let conversation = cx.new(|cx| ConversationView::popped_out(app, selection, window, cx));
43 cx.new(|cx| ConversationView::popped_out(app, selection, window, cx));
44 ChatPopOutView { conversation }
43 ChatPopOutView { conversation }
45 }
44 }
46}
45}
@@ -86,10 +85,7 @@ pub fn pop_out_chat(app: &Entity<AppState>, chat_id: &str, cx: &mut App) {
86 size(px(CHAT_WINDOW_SIZE.0), px(CHAT_WINDOW_SIZE.1)),
85 size(px(CHAT_WINDOW_SIZE.0), px(CHAT_WINDOW_SIZE.1)),
87 cx,
86 cx,
88 ))),
87 ))),
89 window_min_size: Some(size(
88 window_min_size: Some(size(px(CHAT_WINDOW_MIN_SIZE.0), px(CHAT_WINDOW_MIN_SIZE.1))),
90 px(CHAT_WINDOW_MIN_SIZE.0),
91 px(CHAT_WINDOW_MIN_SIZE.1),
92 )),
93 titlebar: Some(TitlebarOptions {
89 titlebar: Some(TitlebarOptions {
94 title: Some(title.into()),
90 title: Some(title.into()),
95 ..Default::default()
91 ..Default::default()
crates/app/src/views/composer.rs +26 −11
@@ -31,9 +31,9 @@ use teams_core::{
31 31 reverse_edits,
32 32 };
33 33
34 pub(crate) mod delivery;
35 34 mod attach_menu;
36 35 mod cloud_picker;
36 pub(crate) mod delivery;
37 37 mod drafts;
38 38 mod format_menus;
39 39 pub(crate) mod plus_menu;
@@ -52,8 +52,8 @@ mod table;
52 52 use super::actions::{
53 53 COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLastMessage,
54 54 EditLink, InsertTableColumnLeft, InsertTableColumnRight, InsertTableLine, InsertTableRowAbove,
55 InsertTableRowBelow, OpenSwitcher, PastePlainText, RemoveTableLine, ScheduleSend,
56 SetHeading1, SetHeading2, SetHeading3, SetParagraph, ToggleBold, ToggleCode, ToggleCodeBlock,
55 InsertTableRowBelow, OpenSwitcher, PastePlainText, RemoveTableLine, ScheduleSend, SetHeading1,
56 SetHeading2, SetHeading3, SetParagraph, ToggleBold, ToggleCode, ToggleCodeBlock,
57 57 ToggleFormatBar, ToggleItalic, ToggleQuote, ToggleStrike, ToggleSubscript, ToggleSuperscript,
58 58 ToggleUnderline,
59 59 };
@@ -2718,7 +2718,11 @@ impl Composer {
2718 2718 }
2719 2719
2720 2720 fn format_bar_fit(&self) -> format_toolbar::BarFit {
2721 let toggle_width = if self.post_layout() { COMPOSER_BUTTON_SIZE } else { 0. };
2721 let toggle_width = if self.post_layout() {
2722 COMPOSER_BUTTON_SIZE
2723 } else {
2724 0.
2725 };
2722 2726 let available = self.composer_bounds.get().map_or(f32::INFINITY, |bounds| {
2723 2727 f32::from(bounds.size.width) - 2. * (COMPOSER_BUTTON_INSET + 1.) - toggle_width
2724 2728 });
@@ -3034,7 +3038,11 @@ impl Render for Composer {
3034 3038 .is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH);
3035 3039 let mut send = Some(send);
3036 3040 let (row_actions, stacked_actions, post_footer) = if post_layout {
3037 (None, None, Some(self.render_post_footer(actions, can_send, cx)))
3041 (
3042 None,
3043 None,
3044 Some(self.render_post_footer(actions, can_send, cx)),
3045 )
3038 3046 } else if stacked {
3039 3047 (None, Some((actions, send.take())), None)
3040 3048 } else {
@@ -3215,9 +3223,9 @@ impl Render for Composer {
3215 3223 .on_action(cx.listener(|this, _: &ToggleFormatBar, window, cx| {
3216 3224 this.toggle_format_bar(window, cx)
3217 3225 }))
3218 .on_action(cx.listener(|_, _: &EditLastMessage, _, cx| {
3219 cx.emit(ComposerEvent::EditLast)
3220 }))
3226 .on_action(
3227 cx.listener(|_, _: &EditLastMessage, _, cx| cx.emit(ComposerEvent::EditLast)),
3228 )
3221 3229 .on_action(cx.listener(|this, _: &InsertTableLine, window, cx| {
3222 3230 this.open_table_menu(TableLineMenu::Insert, window, cx);
3223 3231 }))
@@ -3471,7 +3479,8 @@ impl Render for Composer {
3471 3479 if this.slash_popup.is_some() {
3472 3480 this.slash_dismissed = true;
3473 3481 }
3474 if this.popup.is_some() || this.emoji_popup.is_some() || this.slash_popup.is_some() {
3482 if this.popup.is_some() || this.emoji_popup.is_some() || this.slash_popup.is_some()
3483 {
3475 3484 this.close_popup();
3476 3485 cx.notify();
3477 3486 cx.stop_propagation();
@@ -4705,7 +4714,10 @@ mod tests {
4705 4714 typist.press("enter");
4706 4715 typist.type_text("b");
4707 4716 typist.press("up end delete");
4708 assert_eq!(typist.outgoing().html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>");
4717 assert_eq!(
4718 typist.outgoing().html(),
4719 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>"
4720 );
4709 4721 }
4710 4722
4711 4723 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
@@ -4869,7 +4881,10 @@ mod tests {
4869 4881 .update(|cx| composer.read(cx).paste_hint.is_none())
4870 4882 );
4871 4883 let outgoing = typist.outgoing();
4872 assert_eq!(outgoing.html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>");
4884 assert_eq!(
4885 outgoing.html(),
4886 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>"
4887 );
4873 4888 }
4874 4889
4875 4890 #[gpui_kit::test]
@@ -31,9 +31,9 @@ use teams_core::{
31 reverse_edits,
31 reverse_edits,
32};
32};
33
33
34pub(crate) mod delivery;
35mod attach_menu;
34mod attach_menu;
36mod cloud_picker;
35mod cloud_picker;
36pub(crate) mod delivery;
37mod drafts;
37mod drafts;
38mod format_menus;
38mod format_menus;
39pub(crate) mod plus_menu;
39pub(crate) mod plus_menu;
@@ -52,8 +52,8 @@ mod table;
52use super::actions::{
52use super::actions::{
53 COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLastMessage,
53 COMPOSER_KEY_CONTEXT, DeleteTable, DeleteTableColumn, DeleteTableRow, EditLastMessage,
54 EditLink, InsertTableColumnLeft, InsertTableColumnRight, InsertTableLine, InsertTableRowAbove,
54 EditLink, InsertTableColumnLeft, InsertTableColumnRight, InsertTableLine, InsertTableRowAbove,
55 InsertTableRowBelow, OpenSwitcher, PastePlainText, RemoveTableLine, ScheduleSend,
55 InsertTableRowBelow, OpenSwitcher, PastePlainText, RemoveTableLine, ScheduleSend, SetHeading1,
56 SetHeading1, SetHeading2, SetHeading3, SetParagraph, ToggleBold, ToggleCode, ToggleCodeBlock,
56 SetHeading2, SetHeading3, SetParagraph, ToggleBold, ToggleCode, ToggleCodeBlock,
57 ToggleFormatBar, ToggleItalic, ToggleQuote, ToggleStrike, ToggleSubscript, ToggleSuperscript,
57 ToggleFormatBar, ToggleItalic, ToggleQuote, ToggleStrike, ToggleSubscript, ToggleSuperscript,
58 ToggleUnderline,
58 ToggleUnderline,
59};
59};
@@ -2718,7 +2718,11 @@ impl Composer {
2718 }
2718 }
2719
2719
2720 fn format_bar_fit(&self) -> format_toolbar::BarFit {
2720 fn format_bar_fit(&self) -> format_toolbar::BarFit {
2721 let toggle_width = if self.post_layout() { COMPOSER_BUTTON_SIZE } else { 0. };
2721 let toggle_width = if self.post_layout() {
2722 COMPOSER_BUTTON_SIZE
2723 } else {
2724 0.
2725 };
2722 let available = self.composer_bounds.get().map_or(f32::INFINITY, |bounds| {
2726 let available = self.composer_bounds.get().map_or(f32::INFINITY, |bounds| {
2723 f32::from(bounds.size.width) - 2. * (COMPOSER_BUTTON_INSET + 1.) - toggle_width
2727 f32::from(bounds.size.width) - 2. * (COMPOSER_BUTTON_INSET + 1.) - toggle_width
2724 });
2728 });
@@ -3034,7 +3038,11 @@ impl Render for Composer {
3034 .is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH);
3038 .is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH);
3035 let mut send = Some(send);
3039 let mut send = Some(send);
3036 let (row_actions, stacked_actions, post_footer) = if post_layout {
3040 let (row_actions, stacked_actions, post_footer) = if post_layout {
3037 (None, None, Some(self.render_post_footer(actions, can_send, cx)))
3041 (
3042 None,
3043 None,
3044 Some(self.render_post_footer(actions, can_send, cx)),
3045 )
3038 } else if stacked {
3046 } else if stacked {
3039 (None, Some((actions, send.take())), None)
3047 (None, Some((actions, send.take())), None)
3040 } else {
3048 } else {
@@ -3215,9 +3223,9 @@ impl Render for Composer {
3215 .on_action(cx.listener(|this, _: &ToggleFormatBar, window, cx| {
3223 .on_action(cx.listener(|this, _: &ToggleFormatBar, window, cx| {
3216 this.toggle_format_bar(window, cx)
3224 this.toggle_format_bar(window, cx)
3217 }))
3225 }))
3218 .on_action(cx.listener(|_, _: &EditLastMessage, _, cx| {
3226 .on_action(
3219 cx.emit(ComposerEvent::EditLast)
3227 cx.listener(|_, _: &EditLastMessage, _, cx| cx.emit(ComposerEvent::EditLast)),
3220 }))
3228 )
3221 .on_action(cx.listener(|this, _: &InsertTableLine, window, cx| {
3229 .on_action(cx.listener(|this, _: &InsertTableLine, window, cx| {
3222 this.open_table_menu(TableLineMenu::Insert, window, cx);
3230 this.open_table_menu(TableLineMenu::Insert, window, cx);
3223 }))
3231 }))
@@ -3471,7 +3479,8 @@ impl Render for Composer {
3471 if this.slash_popup.is_some() {
3479 if this.slash_popup.is_some() {
3472 this.slash_dismissed = true;
3480 this.slash_dismissed = true;
3473 }
3481 }
3474 if this.popup.is_some() || this.emoji_popup.is_some() || this.slash_popup.is_some() {
3482 if this.popup.is_some() || this.emoji_popup.is_some() || this.slash_popup.is_some()
3483 {
3475 this.close_popup();
3484 this.close_popup();
3476 cx.notify();
3485 cx.notify();
3477 cx.stop_propagation();
3486 cx.stop_propagation();
@@ -4705,7 +4714,10 @@ mod tests {
4705 typist.press("enter");
4714 typist.press("enter");
4706 typist.type_text("b");
4715 typist.type_text("b");
4707 typist.press("up end delete");
4716 typist.press("up end delete");
4708 assert_eq!(typist.outgoing().html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>");
4717 assert_eq!(
4718 typist.outgoing().html(),
4719 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>"
4720 );
4709 }
4721 }
4710
4722
4711 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4723 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
@@ -4869,7 +4881,10 @@ mod tests {
4869 .update(|cx| composer.read(cx).paste_hint.is_none())
4881 .update(|cx| composer.read(cx).paste_hint.is_none())
4870 );
4882 );
4871 let outgoing = typist.outgoing();
4883 let outgoing = typist.outgoing();
4872 assert_eq!(outgoing.html(), "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>");
4884 assert_eq!(
4885 outgoing.html(),
4886 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>"
4887 );
4873 }
4888 }
4874
4889
4875 #[gpui_kit::test]
4890 #[gpui_kit::test]
crates/app/src/views/composer/attach_menu.rs +102 −43
@@ -92,16 +92,16 @@ fn demo_files() -> Vec<CloudFile> {
92 92 ("Architecture review.pdf", 860_000, 2 * DAY),
93 93 ("Budget 2027.xlsx", 74_000, 9 * DAY),
94 94 ]
95 .into_iter()
96 .map(|(name, size, age)| CloudFile {
97 name: name.to_owned(),
98 size,
99 web_url: format!("https://example.com/demo/{name}"),
100 drive_id: None,
101 item_id: None,
102 last_opened: Some(now - chrono::Duration::seconds(age)),
103 })
104 .collect()
95 .into_iter()
96 .map(|(name, size, age)| CloudFile {
97 name: name.to_owned(),
98 size,
99 web_url: format!("https://contoso.sharepoint.com/demo/{name}"),
100 drive_id: None,
101 item_id: None,
102 last_opened: Some(now - chrono::Duration::seconds(age)),
103 })
104 .collect()
105 105 }
106 106
107 107 impl Composer {
@@ -123,7 +123,11 @@ impl Composer {
123 123 .child(symbol(
124 124 "attach_file",
125 125 COMPOSER_ICON_SIZE,
126 if open { theme::accent_text() } else { theme::text_muted() },
126 if open {
127 theme::accent_text()
128 } else {
129 theme::text_muted()
130 },
127 131 ))
128 132 .on_mouse_down(MouseButton::Left, |_, window, cx| {
129 133 window.prevent_default();
@@ -145,7 +149,11 @@ impl Composer {
145 149 cx.notify();
146 150 }
147 151
148 pub(super) fn close_attach_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
152 pub(super) fn close_attach_menu(
153 &mut self,
154 window: &mut Window,
155 cx: &mut Context<Self>,
156 ) -> bool {
149 157 if !self.attach_menu.open {
150 158 return false;
151 159 }
@@ -161,17 +169,22 @@ impl Composer {
161 169 true
162 170 }
163 171
164 fn attach_search_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
172 fn attach_search_input(
173 &mut self,
174 window: &mut Window,
175 cx: &mut Context<Self>,
176 ) -> Entity<InputState> {
165 177 if let Some(input) = &self.attach_menu.search_input {
166 178 return input.clone();
167 179 }
168 180 let input = cx.new(|cx| InputState::new(window, cx).placeholder(SEARCH_PLACEHOLDER));
169 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, _, cx| {
170 if matches!(event, InputEvent::Change) {
171 let text = input.read(cx).value().trim().to_owned();
172 this.search_cloud_files(text, cx);
173 }
174 });
181 let subscription =
182 cx.subscribe_in(&input, window, |this, input, event: &InputEvent, _, cx| {
183 if matches!(event, InputEvent::Change) {
184 let text = input.read(cx).value().trim().to_owned();
185 this.search_cloud_files(text, cx);
186 }
187 });
175 188 self.attach_menu.search_input = Some(input.clone());
176 189 self.attach_menu._search_events = Some(subscription);
177 190 input
@@ -197,7 +210,9 @@ impl Composer {
197 210 _ => Listing::Failed,
198 211 };
199 212 this.update(cx, |this, cx| {
200 if !matches!(listing, Listing::Failed) || !matches!(this.attach_menu.recent, Listing::Ready(_)) {
213 if !matches!(listing, Listing::Failed)
214 || !matches!(this.attach_menu.recent, Listing::Ready(_))
215 {
201 216 this.attach_menu.recent = listing;
202 217 }
203 218 cx.notify();
@@ -230,11 +245,18 @@ impl Composer {
230 245 let Some(engine) = state.engine.clone() else {
231 246 return;
232 247 };
233 let search_session = self.attach_menu.search_session.get_or_insert_with(SearchSession::new).clone();
248 let search_session = self
249 .attach_menu
250 .search_session
251 .get_or_insert_with(SearchSession::new)
252 .clone();
234 253 self.attach_menu.found = Some(Listing::Loading);
235 254 self.attach_menu.search_task = Some(cx.spawn(async move |this, cx| {
236 255 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
237 let receiver = runtime::spawn(async move { engine.search_cloud_files(&search_session, &text).await });
256 let receiver =
257 runtime::spawn(
258 async move { engine.search_cloud_files(&search_session, &text).await },
259 );
238 260 let listing = match receiver.await {
239 261 Ok(Ok(files)) => Listing::Ready(files),
240 262 _ => Listing::Failed,
@@ -264,12 +286,16 @@ impl Composer {
264 286 cx.notify();
265 287 return;
266 288 }
267 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id.clone()) else {
289 let (Some(engine), Some(conversation_id)) =
290 (state.engine.clone(), self.conversation_id.clone())
291 else {
268 292 return;
269 293 };
270 294 let task_file = file.clone();
271 295 let receiver =
272 runtime::spawn(async move { engine.attach_cloud_file(&conversation_id, &task_file).await });
296 runtime::spawn(
297 async move { engine.attach_cloud_file(&conversation_id, &task_file).await },
298 );
273 299 cx.spawn(async move |this, cx| {
274 300 let attached = receiver.await;
275 301 this.update(cx, |this, cx| {
@@ -278,7 +304,9 @@ impl Composer {
278 304 this.tray.add_cloud_file(file.name, file.size, reference);
279 305 this.schedule_draft_save(cx);
280 306 }
281 _ => this.tray.set_notice(format!("{ATTACH_FAILED} {}.", file.name)),
307 _ => this
308 .tray
309 .set_notice(format!("{ATTACH_FAILED} {}.", file.name)),
282 310 }
283 311 cx.notify();
284 312 })
@@ -291,18 +319,22 @@ impl Composer {
291 319 self.close_attach_menu(window, cx);
292 320 let app = self.app.clone();
293 321 let picker = cx.new(|cx| CloudPicker::new(app, cx));
294 let subscription = cx.subscribe_in(&picker, window, |this, _, event: &CloudPickerEvent, window, cx| {
295 let files = match event {
296 CloudPickerEvent::Attach(files) => files.clone(),
297 CloudPickerEvent::Close => Vec::new(),
298 };
299 this.cloud_picker = None;
300 for file in files {
301 this.attach_cloud_file(file, window, cx);
302 }
303 this.focus(window, cx);
304 cx.notify();
305 });
322 let subscription = cx.subscribe_in(
323 &picker,
324 window,
325 |this, _, event: &CloudPickerEvent, window, cx| {
326 let files = match event {
327 CloudPickerEvent::Attach(files) => files.clone(),
328 CloudPickerEvent::Close => Vec::new(),
329 };
330 this.cloud_picker = None;
331 for file in files {
332 this.attach_cloud_file(file, window, cx);
333 }
334 this.focus(window, cx);
335 cx.notify();
336 },
337 );
306 338 picker.read(cx).focus_handle(cx).focus(window, cx);
307 339 self.cloud_picker = Some((picker, subscription));
308 340 cx.notify();
@@ -323,7 +355,12 @@ impl Composer {
323 355 .rounded(px(6.))
324 356 .bg(theme::surface_raised())
325 357 .child(symbol("search", 16., theme::text_muted()))
326 .child(div().flex_1().min_w_0().child(Input::new(&input).appearance(false).bordered(false)))
358 .child(
359 div()
360 .flex_1()
361 .min_w_0()
362 .child(Input::new(&input).appearance(false).bordered(false)),
363 )
327 364 });
328 365 let (title, listing) = match &self.attach_menu.found {
329 366 Some(found) => (RESULTS_TITLE, found),
@@ -334,7 +371,11 @@ impl Composer {
334 371 Listing::Loading => vec![self.menu_note(LOADING)],
335 372 Listing::Failed => vec![self.menu_note(FAILED)],
336 373 Listing::Ready(files) if files.is_empty() => {
337 vec![self.menu_note(if self.attach_menu.found.is_some() { NO_RESULTS } else { NO_RECENT })]
374 vec![self.menu_note(if self.attach_menu.found.is_some() {
375 NO_RESULTS
376 } else {
377 NO_RECENT
378 })]
338 379 }
339 380 Listing::Ready(files) => files
340 381 .iter()
@@ -353,7 +394,12 @@ impl Composer {
353 394 .cursor_pointer()
354 395 .hover(|row| row.bg(theme::popup_hover()))
355 396 .child(symbol("cloud", 16., theme::text_soft()))
356 .child(div().text_size(px(13.)).text_color(theme::text()).child(ATTACH_CLOUD_LABEL))
397 .child(
398 div()
399 .text_size(px(13.))
400 .text_color(theme::text())
401 .child(ATTACH_CLOUD_LABEL),
402 )
357 403 .on_click(cx.listener(|this, _, window, cx| this.open_cloud_picker(window, cx)));
358 404 let upload = h_flex()
359 405 .id("composer-attach-upload")
@@ -366,7 +412,12 @@ impl Composer {
366 412 .cursor_pointer()
367 413 .hover(|row| row.bg(theme::popup_hover()))
368 414 .child(symbol("upload", 16., theme::text_soft()))
369 .child(div().text_size(px(13.)).text_color(theme::text()).child(UPLOAD_LABEL))
415 .child(
416 div()
417 .text_size(px(13.))
418 .text_color(theme::text())
419 .child(UPLOAD_LABEL),
420 )
370 421 .on_click(cx.listener(|this, _, window, cx| {
371 422 this.close_attach_menu(window, cx);
372 423 this.open_picker(window, cx);
@@ -423,7 +474,13 @@ impl Composer {
423 474 .into_any_element()
424 475 }
425 476
426 fn cloud_file_row(&self, index: usize, file: &CloudFile, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
477 fn cloud_file_row(
478 &self,
479 index: usize,
480 file: &CloudFile,
481 now: DateTime<Utc>,
482 cx: &mut Context<Self>,
483 ) -> Stateful<Div> {
427 484 let picked = file.clone();
428 485 h_flex()
429 486 .id(("composer-attach-file", index))
@@ -455,7 +512,9 @@ impl Composer {
455 512 .child(opened_label(opened, now))
456 513 })),
457 514 )
458 .on_click(cx.listener(move |this, _, window, cx| this.attach_cloud_file(picked.clone(), window, cx)))
515 .on_click(cx.listener(move |this, _, window, cx| {
516 this.attach_cloud_file(picked.clone(), window, cx)
517 }))
459 518 }
460 519 }
461 520
@@ -92,16 +92,16 @@ fn demo_files() -> Vec<CloudFile> {
92 ("Architecture review.pdf", 860_000, 2 * DAY),
92 ("Architecture review.pdf", 860_000, 2 * DAY),
93 ("Budget 2027.xlsx", 74_000, 9 * DAY),
93 ("Budget 2027.xlsx", 74_000, 9 * DAY),
94 ]
94 ]
95 .into_iter()
95 .into_iter()
96 .map(|(name, size, age)| CloudFile {
96 .map(|(name, size, age)| CloudFile {
97 name: name.to_owned(),
97 name: name.to_owned(),
98 size,
98 size,
99 web_url: format!("https://example.com/demo/{name}"),
99 web_url: format!("https://contoso.sharepoint.com/demo/{name}"),
100 drive_id: None,
100 drive_id: None,
101 item_id: None,
101 item_id: None,
102 last_opened: Some(now - chrono::Duration::seconds(age)),
102 last_opened: Some(now - chrono::Duration::seconds(age)),
103 })
103 })
104 .collect()
104 .collect()
105}
105}
106
106
107impl Composer {
107impl Composer {
@@ -123,7 +123,11 @@ impl Composer {
123 .child(symbol(
123 .child(symbol(
124 "attach_file",
124 "attach_file",
125 COMPOSER_ICON_SIZE,
125 COMPOSER_ICON_SIZE,
126 if open { theme::accent_text() } else { theme::text_muted() },
126 if open {
127 theme::accent_text()
128 } else {
129 theme::text_muted()
130 },
127 ))
131 ))
128 .on_mouse_down(MouseButton::Left, |_, window, cx| {
132 .on_mouse_down(MouseButton::Left, |_, window, cx| {
129 window.prevent_default();
133 window.prevent_default();
@@ -145,7 +149,11 @@ impl Composer {
145 cx.notify();
149 cx.notify();
146 }
150 }
147
151
148 pub(super) fn close_attach_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
152 pub(super) fn close_attach_menu(
153 &mut self,
154 window: &mut Window,
155 cx: &mut Context<Self>,
156 ) -> bool {
149 if !self.attach_menu.open {
157 if !self.attach_menu.open {
150 return false;
158 return false;
151 }
159 }
@@ -161,17 +169,22 @@ impl Composer {
161 true
169 true
162 }
170 }
163
171
164 fn attach_search_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
172 fn attach_search_input(
173 &mut self,
174 window: &mut Window,
175 cx: &mut Context<Self>,
176 ) -> Entity<InputState> {
165 if let Some(input) = &self.attach_menu.search_input {
177 if let Some(input) = &self.attach_menu.search_input {
166 return input.clone();
178 return input.clone();
167 }
179 }
168 let input = cx.new(|cx| InputState::new(window, cx).placeholder(SEARCH_PLACEHOLDER));
180 let input = cx.new(|cx| InputState::new(window, cx).placeholder(SEARCH_PLACEHOLDER));
169 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, _, cx| {
181 let subscription =
170 if matches!(event, InputEvent::Change) {
182 cx.subscribe_in(&input, window, |this, input, event: &InputEvent, _, cx| {
171 let text = input.read(cx).value().trim().to_owned();
183 if matches!(event, InputEvent::Change) {
172 this.search_cloud_files(text, cx);
184 let text = input.read(cx).value().trim().to_owned();
173 }
185 this.search_cloud_files(text, cx);
174 });
186 }
187 });
175 self.attach_menu.search_input = Some(input.clone());
188 self.attach_menu.search_input = Some(input.clone());
176 self.attach_menu._search_events = Some(subscription);
189 self.attach_menu._search_events = Some(subscription);
177 input
190 input
@@ -197,7 +210,9 @@ impl Composer {
197 _ => Listing::Failed,
210 _ => Listing::Failed,
198 };
211 };
199 this.update(cx, |this, cx| {
212 this.update(cx, |this, cx| {
200 if !matches!(listing, Listing::Failed) || !matches!(this.attach_menu.recent, Listing::Ready(_)) {
213 if !matches!(listing, Listing::Failed)
214 || !matches!(this.attach_menu.recent, Listing::Ready(_))
215 {
201 this.attach_menu.recent = listing;
216 this.attach_menu.recent = listing;
202 }
217 }
203 cx.notify();
218 cx.notify();
@@ -230,11 +245,18 @@ impl Composer {
230 let Some(engine) = state.engine.clone() else {
245 let Some(engine) = state.engine.clone() else {
231 return;
246 return;
232 };
247 };
233 let search_session = self.attach_menu.search_session.get_or_insert_with(SearchSession::new).clone();
248 let search_session = self
249 .attach_menu
250 .search_session
251 .get_or_insert_with(SearchSession::new)
252 .clone();
234 self.attach_menu.found = Some(Listing::Loading);
253 self.attach_menu.found = Some(Listing::Loading);
235 self.attach_menu.search_task = Some(cx.spawn(async move |this, cx| {
254 self.attach_menu.search_task = Some(cx.spawn(async move |this, cx| {
236 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
255 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
237 let receiver = runtime::spawn(async move { engine.search_cloud_files(&search_session, &text).await });
256 let receiver =
257 runtime::spawn(
258 async move { engine.search_cloud_files(&search_session, &text).await },
259 );
238 let listing = match receiver.await {
260 let listing = match receiver.await {
239 Ok(Ok(files)) => Listing::Ready(files),
261 Ok(Ok(files)) => Listing::Ready(files),
240 _ => Listing::Failed,
262 _ => Listing::Failed,
@@ -264,12 +286,16 @@ impl Composer {
264 cx.notify();
286 cx.notify();
265 return;
287 return;
266 }
288 }
267 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id.clone()) else {
289 let (Some(engine), Some(conversation_id)) =
290 (state.engine.clone(), self.conversation_id.clone())
291 else {
268 return;
292 return;
269 };
293 };
270 let task_file = file.clone();
294 let task_file = file.clone();
271 let receiver =
295 let receiver =
272 runtime::spawn(async move { engine.attach_cloud_file(&conversation_id, &task_file).await });
296 runtime::spawn(
297 async move { engine.attach_cloud_file(&conversation_id, &task_file).await },
298 );
273 cx.spawn(async move |this, cx| {
299 cx.spawn(async move |this, cx| {
274 let attached = receiver.await;
300 let attached = receiver.await;
275 this.update(cx, |this, cx| {
301 this.update(cx, |this, cx| {
@@ -278,7 +304,9 @@ impl Composer {
278 this.tray.add_cloud_file(file.name, file.size, reference);
304 this.tray.add_cloud_file(file.name, file.size, reference);
279 this.schedule_draft_save(cx);
305 this.schedule_draft_save(cx);
280 }
306 }
281 _ => this.tray.set_notice(format!("{ATTACH_FAILED} {}.", file.name)),
307 _ => this
308 .tray
309 .set_notice(format!("{ATTACH_FAILED} {}.", file.name)),
282 }
310 }
283 cx.notify();
311 cx.notify();
284 })
312 })
@@ -291,18 +319,22 @@ impl Composer {
291 self.close_attach_menu(window, cx);
319 self.close_attach_menu(window, cx);
292 let app = self.app.clone();
320 let app = self.app.clone();
293 let picker = cx.new(|cx| CloudPicker::new(app, cx));
321 let picker = cx.new(|cx| CloudPicker::new(app, cx));
294 let subscription = cx.subscribe_in(&picker, window, |this, _, event: &CloudPickerEvent, window, cx| {
322 let subscription = cx.subscribe_in(
295 let files = match event {
323 &picker,
296 CloudPickerEvent::Attach(files) => files.clone(),
324 window,
297 CloudPickerEvent::Close => Vec::new(),
325 |this, _, event: &CloudPickerEvent, window, cx| {
298 };
326 let files = match event {
299 this.cloud_picker = None;
327 CloudPickerEvent::Attach(files) => files.clone(),
300 for file in files {
328 CloudPickerEvent::Close => Vec::new(),
301 this.attach_cloud_file(file, window, cx);
329 };
302 }
330 this.cloud_picker = None;
303 this.focus(window, cx);
331 for file in files {
304 cx.notify();
332 this.attach_cloud_file(file, window, cx);
305 });
333 }
334 this.focus(window, cx);
335 cx.notify();
336 },
337 );
306 picker.read(cx).focus_handle(cx).focus(window, cx);
338 picker.read(cx).focus_handle(cx).focus(window, cx);
307 self.cloud_picker = Some((picker, subscription));
339 self.cloud_picker = Some((picker, subscription));
308 cx.notify();
340 cx.notify();
@@ -323,7 +355,12 @@ impl Composer {
323 .rounded(px(6.))
355 .rounded(px(6.))
324 .bg(theme::surface_raised())
356 .bg(theme::surface_raised())
325 .child(symbol("search", 16., theme::text_muted()))
357 .child(symbol("search", 16., theme::text_muted()))
326 .child(div().flex_1().min_w_0().child(Input::new(&input).appearance(false).bordered(false)))
358 .child(
359 div()
360 .flex_1()
361 .min_w_0()
362 .child(Input::new(&input).appearance(false).bordered(false)),
363 )
327 });
364 });
328 let (title, listing) = match &self.attach_menu.found {
365 let (title, listing) = match &self.attach_menu.found {
329 Some(found) => (RESULTS_TITLE, found),
366 Some(found) => (RESULTS_TITLE, found),
@@ -334,7 +371,11 @@ impl Composer {
334 Listing::Loading => vec![self.menu_note(LOADING)],
371 Listing::Loading => vec![self.menu_note(LOADING)],
335 Listing::Failed => vec![self.menu_note(FAILED)],
372 Listing::Failed => vec![self.menu_note(FAILED)],
336 Listing::Ready(files) if files.is_empty() => {
373 Listing::Ready(files) if files.is_empty() => {
337 vec![self.menu_note(if self.attach_menu.found.is_some() { NO_RESULTS } else { NO_RECENT })]
374 vec![self.menu_note(if self.attach_menu.found.is_some() {
375 NO_RESULTS
376 } else {
377 NO_RECENT
378 })]
338 }
379 }
339 Listing::Ready(files) => files
380 Listing::Ready(files) => files
340 .iter()
381 .iter()
@@ -353,7 +394,12 @@ impl Composer {
353 .cursor_pointer()
394 .cursor_pointer()
354 .hover(|row| row.bg(theme::popup_hover()))
395 .hover(|row| row.bg(theme::popup_hover()))
355 .child(symbol("cloud", 16., theme::text_soft()))
396 .child(symbol("cloud", 16., theme::text_soft()))
356 .child(div().text_size(px(13.)).text_color(theme::text()).child(ATTACH_CLOUD_LABEL))
397 .child(
398 div()
399 .text_size(px(13.))
400 .text_color(theme::text())
401 .child(ATTACH_CLOUD_LABEL),
402 )
357 .on_click(cx.listener(|this, _, window, cx| this.open_cloud_picker(window, cx)));
403 .on_click(cx.listener(|this, _, window, cx| this.open_cloud_picker(window, cx)));
358 let upload = h_flex()
404 let upload = h_flex()
359 .id("composer-attach-upload")
405 .id("composer-attach-upload")
@@ -366,7 +412,12 @@ impl Composer {
366 .cursor_pointer()
412 .cursor_pointer()
367 .hover(|row| row.bg(theme::popup_hover()))
413 .hover(|row| row.bg(theme::popup_hover()))
368 .child(symbol("upload", 16., theme::text_soft()))
414 .child(symbol("upload", 16., theme::text_soft()))
369 .child(div().text_size(px(13.)).text_color(theme::text()).child(UPLOAD_LABEL))
415 .child(
416 div()
417 .text_size(px(13.))
418 .text_color(theme::text())
419 .child(UPLOAD_LABEL),
420 )
370 .on_click(cx.listener(|this, _, window, cx| {
421 .on_click(cx.listener(|this, _, window, cx| {
371 this.close_attach_menu(window, cx);
422 this.close_attach_menu(window, cx);
372 this.open_picker(window, cx);
423 this.open_picker(window, cx);
@@ -423,7 +474,13 @@ impl Composer {
423 .into_any_element()
474 .into_any_element()
424 }
475 }
425
476
426 fn cloud_file_row(&self, index: usize, file: &CloudFile, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
477 fn cloud_file_row(
478 &self,
479 index: usize,
480 file: &CloudFile,
481 now: DateTime<Utc>,
482 cx: &mut Context<Self>,
483 ) -> Stateful<Div> {
427 let picked = file.clone();
484 let picked = file.clone();
428 h_flex()
485 h_flex()
429 .id(("composer-attach-file", index))
486 .id(("composer-attach-file", index))
@@ -455,7 +512,9 @@ impl Composer {
455 .child(opened_label(opened, now))
512 .child(opened_label(opened, now))
456 })),
513 })),
457 )
514 )
458 .on_click(cx.listener(move |this, _, window, cx| this.attach_cloud_file(picked.clone(), window, cx)))
515 .on_click(cx.listener(move |this, _, window, cx| {
516 this.attach_cloud_file(picked.clone(), window, cx)
517 }))
459 }
518 }
460}
519}
461
520
crates/app/src/views/composer/cloud_picker.rs +192 −47
@@ -165,7 +165,11 @@ impl CloudPicker {
165 165 self.rows = Rows::Loading;
166 166 cx.notify();
167 167 if self.app.read(cx).mode.demo {
168 self.rows = Rows::Ready(if place == Place::Home { demo_rows() } else { Vec::new() });
168 self.rows = Rows::Ready(if place == Place::Home {
169 demo_rows()
170 } else {
171 Vec::new()
172 });
169 173 return;
170 174 }
171 175 let Some(engine) = self.app.read(cx).engine.clone() else {
@@ -178,7 +182,15 @@ impl CloudPicker {
178 182 };
179 183 let receiver = runtime::spawn(async move {
180 184 match place {
181 Place::Home => Ok((None, engine.picker_recent().await?.into_iter().filter_map(recent_row).collect())),
185 Place::Home => Ok((
186 None,
187 engine
188 .picker_recent()
189 .await?
190 .into_iter()
191 .filter_map(recent_row)
192 .collect(),
193 )),
182 194 Place::Shared => Ok((None, engine.picker_shared().await?)),
183 195 Place::MyFiles | Place::Site(_) => {
184 196 let root = engine.picker_root(site.as_deref()).await?;
@@ -188,7 +200,8 @@ impl CloudPicker {
188 200 }
189 201 });
190 202 cx.spawn(async move |this, cx| {
191 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> = receiver.await.ok();
203 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> =
204 receiver.await.ok();
192 205 this.update(cx, |this, cx| {
193 206 if this.generation != generation {
194 207 return;
@@ -196,7 +209,10 @@ impl CloudPicker {
196 209 match result {
197 210 Some(Ok((root, entries))) => {
198 211 if let Some(folder) = root {
199 this.crumbs.push(Crumb { name: this.root_name(), folder });
212 this.crumbs.push(Crumb {
213 name: this.root_name(),
214 folder,
215 });
200 216 }
201 217 this.rows = Rows::Ready(entries);
202 218 }
@@ -217,7 +233,10 @@ impl CloudPicker {
217 233 }
218 234
219 235 fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {
220 self.crumbs.push(Crumb { name, folder: folder.clone() });
236 self.crumbs.push(Crumb {
237 name,
238 folder: folder.clone(),
239 });
221 240 self.list_folder(folder, cx);
222 241 }
223 242
@@ -260,7 +279,11 @@ impl CloudPicker {
260 279 self.open_folder(entry.name.clone(), entry.folder(), cx);
261 280 return;
262 281 }
263 match self.selected.iter().position(|picked| picked.id == entry.id) {
282 match self
283 .selected
284 .iter()
285 .position(|picked| picked.id == entry.id)
286 {
264 287 Some(index) => {
265 288 self.selected.remove(index);
266 289 }
@@ -270,7 +293,11 @@ impl CloudPicker {
270 293 }
271 294
272 295 fn attach(&mut self, cx: &mut Context<Self>) {
273 let files = self.selected.iter().map(CloudFile::from).collect::<Vec<_>>();
296 let files = self
297 .selected
298 .iter()
299 .map(CloudFile::from)
300 .collect::<Vec<_>>();
274 301 if !files.is_empty() {
275 302 cx.emit(CloudPickerEvent::Attach(files));
276 303 }
@@ -280,11 +307,21 @@ impl CloudPicker {
280 307 match self.place {
281 308 Place::Home => "Home".into(),
282 309 Place::Shared => "Shared with you".into(),
283 Place::MyFiles | Place::Site(_) => self.crumbs.last().map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
310 Place::MyFiles | Place::Site(_) => self
311 .crumbs
312 .last()
313 .map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
284 314 }
285 315 }
286 316
287 fn nav_row(&self, id: impl Into<ElementId>, glyph: &'static str, label: String, place: Place, cx: &mut Context<Self>) -> Stateful<Div> {
317 fn nav_row(
318 &self,
319 id: impl Into<ElementId>,
320 glyph: &'static str,
321 label: String,
322 place: Place,
323 cx: &mut Context<Self>,
324 ) -> Stateful<Div> {
288 325 let active = self.place == place;
289 326 h_flex()
290 327 .id(id)
@@ -296,10 +333,24 @@ impl CloudPicker {
296 333 .rounded(px(6.))
297 334 .cursor_pointer()
298 335 .text_size(px(13.))
299 .text_color(if active { theme::text_strong() } else { theme::text() })
300 .when(active, |row| row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD))
336 .text_color(if active {
337 theme::text_strong()
338 } else {
339 theme::text()
340 })
341 .when(active, |row| {
342 row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD)
343 })
301 344 .hover(|row| row.bg(theme::row_hover()))
302 .child(symbol(glyph, 18., if active { theme::accent_text() } else { theme::text_soft() }))
345 .child(symbol(
346 glyph,
347 18.,
348 if active {
349 theme::accent_text()
350 } else {
351 theme::text_soft()
352 },
353 ))
303 354 .child(div().flex_1().min_w_0().truncate().child(label))
304 355 .on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))
305 356 }
@@ -317,7 +368,13 @@ impl CloudPicker {
317 368 };
318 369 let mut sites = Vec::with_capacity(self.sites.len());
319 370 for (index, site) in self.sites.iter().enumerate() {
320 sites.push(self.nav_row(("cloud-picker-site", index), "domain", site.name.clone(), Place::Site(index), cx));
371 sites.push(self.nav_row(
372 ("cloud-picker-site", index),
373 "domain",
374 site.name.clone(),
375 Place::Site(index),
376 cx,
377 ));
321 378 }
322 379 v_flex()
323 380 .w(px(NAV_WIDTH))
@@ -335,11 +392,29 @@ impl CloudPicker {
335 392 .child("OneDrive"),
336 393 )
337 394 .child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))
338 .child(self.nav_row("cloud-picker-mine", "folder", "My files".into(), Place::MyFiles, cx))
339 .child(self.nav_row("cloud-picker-shared", "group", "Shared".into(), Place::Shared, cx))
395 .child(self.nav_row(
396 "cloud-picker-mine",
397 "folder",
398 "My files".into(),
399 Place::MyFiles,
400 cx,
401 ))
402 .child(self.nav_row(
403 "cloud-picker-shared",
404 "group",
405 "Shared".into(),
406 Place::Shared,
407 cx,
408 ))
340 409 .when(!self.sites.is_empty(), |nav| {
341 nav.child(section("Quick access"))
342 .child(v_flex().id("cloud-picker-sites").flex_1().min_h_0().overflow_y_scrollbar().children(sites))
410 nav.child(section("Quick access")).child(
411 v_flex()
412 .id("cloud-picker-sites")
413 .flex_1()
414 .min_h_0()
415 .overflow_y_scrollbar()
416 .children(sites),
417 )
343 418 })
344 419 }
345 420
@@ -356,10 +431,21 @@ impl CloudPicker {
356 431 .id(("cloud-picker-crumb", depth))
357 432 .truncate()
358 433 .text_size(px(if current { 20. } else { 14. }))
359 .font_weight(if current { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
360 .text_color(if current { theme::text_strong() } else { theme::text_soft() })
434 .font_weight(if current {
435 FontWeight::SEMIBOLD
436 } else {
437 FontWeight::NORMAL
438 })
439 .text_color(if current {
440 theme::text_strong()
441 } else {
442 theme::text_soft()
443 })
361 444 .when(!current, |crumb| {
362 crumb.cursor_pointer().hover(|crumb| crumb.text_color(theme::text())).on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
445 crumb
446 .cursor_pointer()
447 .hover(|crumb| crumb.text_color(theme::text()))
448 .on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
363 449 })
364 450 .child(crumb.name.clone()),
365 451 );
@@ -376,12 +462,21 @@ impl CloudPicker {
376 462 self.breadcrumb(cx)
377 463 } else {
378 464 h_flex().child(
379 div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme::text_strong()).child(self.title()),
465 div()
466 .text_size(px(20.))
467 .font_weight(FontWeight::SEMIBOLD)
468 .text_color(theme::text_strong())
469 .child(self.title()),
380 470 )
381 471 };
382 472 v_flex()
383 473 .gap(px(2.))
384 .children(site.map(|name| div().text_size(px(13.)).text_color(theme::text_soft()).child(name)))
474 .children(site.map(|name| {
475 div()
476 .text_size(px(13.))
477 .text_color(theme::text_soft())
478 .child(name)
479 }))
385 480 .child(title)
386 481 }
387 482
@@ -406,12 +501,20 @@ impl CloudPicker {
406 501
407 502 fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {
408 503 match (self.place, entry.modified_at) {
409 (Place::Home, Some(opened)) => opened_ago(opened, now).unwrap_or_else(|| modified_text(entry)),
504 (Place::Home, Some(opened)) => {
505 opened_ago(opened, now).unwrap_or_else(|| modified_text(entry))
506 }
410 507 _ => modified_text(entry),
411 508 }
412 509 }
413 510
414 fn row(&self, index: usize, entry: &DriveEntry, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
511 fn row(
512 &self,
513 index: usize,
514 entry: &DriveEntry,
515 now: DateTime<Utc>,
516 cx: &mut Context<Self>,
517 ) -> Stateful<Div> {
415 518 let picked = self.selected.iter().any(|selected| selected.id == entry.id);
416 519 let folder = entry.is_folder();
417 520 let clicked = entry.clone();
@@ -429,11 +532,9 @@ impl CloudPicker {
429 532 .text_color(theme::text_soft())
430 533 .when(picked, |row| row.bg(theme::selection()))
431 534 .hover(|row| row.bg(theme::row_hover()))
432 .child(
433 div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
434 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
435 }),
436 )
535 .child(div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
536 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
537 }))
437 538 .child(
438 539 h_flex()
439 540 .flex_1()
@@ -441,25 +542,49 @@ impl CloudPicker {
441 542 .gap(px(10.))
442 543 .items_center()
443 544 .child(entry_badge(entry))
444 .child(div().truncate().text_color(theme::text()).child(entry.name.clone())),
545 .child(
546 div()
547 .truncate()
548 .text_color(theme::text())
549 .child(entry.name.clone()),
550 ),
551 )
552 .child(
553 div()
554 .w(px(WHEN_WIDTH))
555 .flex_none()
556 .truncate()
557 .child(self.when_text(entry, now)),
558 )
559 .child(
560 div()
561 .w(px(WHO_WIDTH))
562 .flex_none()
563 .truncate()
564 .child(entry.modified_by.clone().unwrap_or_default()),
445 565 )
446 .child(div().w(px(WHEN_WIDTH)).flex_none().truncate().child(self.when_text(entry, now)))
447 .child(div().w(px(WHO_WIDTH)).flex_none().truncate().child(entry.modified_by.clone().unwrap_or_default()))
448 566 .on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))
449 567 }
450 568
451 569 fn table(&self, cx: &mut Context<Self>) -> AnyElement {
452 570 let note = |text: &'static str| {
453 div().p(px(16.)).text_size(px(13.)).text_color(theme::text_soft()).child(text).into_any_element()
571 div()
572 .p(px(16.))
573 .text_size(px(13.))
574 .text_color(theme::text_soft())
575 .child(text)
576 .into_any_element()
454 577 };
455 578 let now = Utc::now();
456 579 let body: Vec<AnyElement> = match &self.rows {
457 580 Rows::Loading => vec![note("Loading ...")],
458 581 Rows::Failed => vec![note("Couldn't load files.")],
459 582 Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],
460 Rows::Ready(entries) => {
461 entries.iter().enumerate().map(|(index, entry)| self.row(index, entry, now, cx).into_any_element()).collect()
462 }
583 Rows::Ready(entries) => entries
584 .iter()
585 .enumerate()
586 .map(|(index, entry)| self.row(index, entry, now, cx).into_any_element())
587 .collect(),
463 588 };
464 589 v_flex()
465 590 .flex_1()
@@ -468,7 +593,14 @@ impl CloudPicker {
468 593 .bg(theme::surface_raised())
469 594 .overflow_hidden()
470 595 .child(self.column_header())
471 .child(v_flex().id("cloud-picker-rows").flex_1().min_h_0().overflow_y_scrollbar().children(body))
596 .child(
597 v_flex()
598 .id("cloud-picker-rows")
599 .flex_1()
600 .min_h_0()
601 .overflow_y_scrollbar()
602 .children(body),
603 )
472 604 .into_any_element()
473 605 }
474 606 }
@@ -510,11 +642,9 @@ impl Render for CloudPicker {
510 642 .disabled(!can_attach)
511 643 .on_click(cx.listener(|this, _, _, cx| this.attach(cx))),
512 644 )
513 .child(
514 Button::new("cloud-picker-cancel")
515 .label("Cancel")
516 .on_click(cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close))),
517 ),
645 .child(Button::new("cloud-picker-cancel").label("Cancel").on_click(
646 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
647 )),
518 648 ),
519 649 );
520 650 deferred(
@@ -534,7 +664,10 @@ impl Render for CloudPicker {
534 664 cx.emit(CloudPickerEvent::Close);
535 665 }
536 666 }))
537 .on_mouse_down(MouseButton::Left, cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)))
667 .on_mouse_down(
668 MouseButton::Left,
669 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
670 )
538 671 .child(panel),
539 672 ),
540 673 )
@@ -551,15 +684,27 @@ mod tests {
551 684 #[test]
552 685 fn home_shows_hours_ago_like_the_onedrive_picker() {
553 686 let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();
554 assert_eq!(opened_ago(now - chrono::Duration::hours(9), now).as_deref(), Some("9h ago"));
555 assert_eq!(opened_ago(now - chrono::Duration::minutes(5), now).as_deref(), Some("5m ago"));
687 assert_eq!(
688 opened_ago(now - chrono::Duration::hours(9), now).as_deref(),
689 Some("9h ago")
690 );
691 assert_eq!(
692 opened_ago(now - chrono::Duration::minutes(5), now).as_deref(),
693 Some("5m ago")
694 );
556 695 assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);
557 696 }
558 697
559 698 #[test]
560 699 fn each_place_has_the_picker_columns() {
561 700 assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);
562 assert_eq!(Place::Shared.columns(), ["Name", "Date shared", "Shared by"]);
563 assert_eq!(Place::Site(0).columns(), ["Name", "Modified", "Modified By"]);
701 assert_eq!(
702 Place::Shared.columns(),
703 ["Name", "Date shared", "Shared by"]
704 );
705 assert_eq!(
706 Place::Site(0).columns(),
707 ["Name", "Modified", "Modified By"]
708 );
564 709 }
565 710 }
@@ -165,7 +165,11 @@ impl CloudPicker {
165 self.rows = Rows::Loading;
165 self.rows = Rows::Loading;
166 cx.notify();
166 cx.notify();
167 if self.app.read(cx).mode.demo {
167 if self.app.read(cx).mode.demo {
168 self.rows = Rows::Ready(if place == Place::Home { demo_rows() } else { Vec::new() });
168 self.rows = Rows::Ready(if place == Place::Home {
169 demo_rows()
170 } else {
171 Vec::new()
172 });
169 return;
173 return;
170 }
174 }
171 let Some(engine) = self.app.read(cx).engine.clone() else {
175 let Some(engine) = self.app.read(cx).engine.clone() else {
@@ -178,7 +182,15 @@ impl CloudPicker {
178 };
182 };
179 let receiver = runtime::spawn(async move {
183 let receiver = runtime::spawn(async move {
180 match place {
184 match place {
181 Place::Home => Ok((None, engine.picker_recent().await?.into_iter().filter_map(recent_row).collect())),
185 Place::Home => Ok((
186 None,
187 engine
188 .picker_recent()
189 .await?
190 .into_iter()
191 .filter_map(recent_row)
192 .collect(),
193 )),
182 Place::Shared => Ok((None, engine.picker_shared().await?)),
194 Place::Shared => Ok((None, engine.picker_shared().await?)),
183 Place::MyFiles | Place::Site(_) => {
195 Place::MyFiles | Place::Site(_) => {
184 let root = engine.picker_root(site.as_deref()).await?;
196 let root = engine.picker_root(site.as_deref()).await?;
@@ -188,7 +200,8 @@ impl CloudPicker {
188 }
200 }
189 });
201 });
190 cx.spawn(async move |this, cx| {
202 cx.spawn(async move |this, cx| {
191 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> = receiver.await.ok();
203 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> =
204 receiver.await.ok();
192 this.update(cx, |this, cx| {
205 this.update(cx, |this, cx| {
193 if this.generation != generation {
206 if this.generation != generation {
194 return;
207 return;
@@ -196,7 +209,10 @@ impl CloudPicker {
196 match result {
209 match result {
197 Some(Ok((root, entries))) => {
210 Some(Ok((root, entries))) => {
198 if let Some(folder) = root {
211 if let Some(folder) = root {
199 this.crumbs.push(Crumb { name: this.root_name(), folder });
212 this.crumbs.push(Crumb {
213 name: this.root_name(),
214 folder,
215 });
200 }
216 }
201 this.rows = Rows::Ready(entries);
217 this.rows = Rows::Ready(entries);
202 }
218 }
@@ -217,7 +233,10 @@ impl CloudPicker {
217 }
233 }
218
234
219 fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {
235 fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {
220 self.crumbs.push(Crumb { name, folder: folder.clone() });
236 self.crumbs.push(Crumb {
237 name,
238 folder: folder.clone(),
239 });
221 self.list_folder(folder, cx);
240 self.list_folder(folder, cx);
222 }
241 }
223
242
@@ -260,7 +279,11 @@ impl CloudPicker {
260 self.open_folder(entry.name.clone(), entry.folder(), cx);
279 self.open_folder(entry.name.clone(), entry.folder(), cx);
261 return;
280 return;
262 }
281 }
263 match self.selected.iter().position(|picked| picked.id == entry.id) {
282 match self
283 .selected
284 .iter()
285 .position(|picked| picked.id == entry.id)
286 {
264 Some(index) => {
287 Some(index) => {
265 self.selected.remove(index);
288 self.selected.remove(index);
266 }
289 }
@@ -270,7 +293,11 @@ impl CloudPicker {
270 }
293 }
271
294
272 fn attach(&mut self, cx: &mut Context<Self>) {
295 fn attach(&mut self, cx: &mut Context<Self>) {
273 let files = self.selected.iter().map(CloudFile::from).collect::<Vec<_>>();
296 let files = self
297 .selected
298 .iter()
299 .map(CloudFile::from)
300 .collect::<Vec<_>>();
274 if !files.is_empty() {
301 if !files.is_empty() {
275 cx.emit(CloudPickerEvent::Attach(files));
302 cx.emit(CloudPickerEvent::Attach(files));
276 }
303 }
@@ -280,11 +307,21 @@ impl CloudPicker {
280 match self.place {
307 match self.place {
281 Place::Home => "Home".into(),
308 Place::Home => "Home".into(),
282 Place::Shared => "Shared with you".into(),
309 Place::Shared => "Shared with you".into(),
283 Place::MyFiles | Place::Site(_) => self.crumbs.last().map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
310 Place::MyFiles | Place::Site(_) => self
311 .crumbs
312 .last()
313 .map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
284 }
314 }
285 }
315 }
286
316
287 fn nav_row(&self, id: impl Into<ElementId>, glyph: &'static str, label: String, place: Place, cx: &mut Context<Self>) -> Stateful<Div> {
317 fn nav_row(
318 &self,
319 id: impl Into<ElementId>,
320 glyph: &'static str,
321 label: String,
322 place: Place,
323 cx: &mut Context<Self>,
324 ) -> Stateful<Div> {
288 let active = self.place == place;
325 let active = self.place == place;
289 h_flex()
326 h_flex()
290 .id(id)
327 .id(id)
@@ -296,10 +333,24 @@ impl CloudPicker {
296 .rounded(px(6.))
333 .rounded(px(6.))
297 .cursor_pointer()
334 .cursor_pointer()
298 .text_size(px(13.))
335 .text_size(px(13.))
299 .text_color(if active { theme::text_strong() } else { theme::text() })
336 .text_color(if active {
300 .when(active, |row| row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD))
337 theme::text_strong()
338 } else {
339 theme::text()
340 })
341 .when(active, |row| {
342 row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD)
343 })
301 .hover(|row| row.bg(theme::row_hover()))
344 .hover(|row| row.bg(theme::row_hover()))
302 .child(symbol(glyph, 18., if active { theme::accent_text() } else { theme::text_soft() }))
345 .child(symbol(
346 glyph,
347 18.,
348 if active {
349 theme::accent_text()
350 } else {
351 theme::text_soft()
352 },
353 ))
303 .child(div().flex_1().min_w_0().truncate().child(label))
354 .child(div().flex_1().min_w_0().truncate().child(label))
304 .on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))
355 .on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))
305 }
356 }
@@ -317,7 +368,13 @@ impl CloudPicker {
317 };
368 };
318 let mut sites = Vec::with_capacity(self.sites.len());
369 let mut sites = Vec::with_capacity(self.sites.len());
319 for (index, site) in self.sites.iter().enumerate() {
370 for (index, site) in self.sites.iter().enumerate() {
320 sites.push(self.nav_row(("cloud-picker-site", index), "domain", site.name.clone(), Place::Site(index), cx));
371 sites.push(self.nav_row(
372 ("cloud-picker-site", index),
373 "domain",
374 site.name.clone(),
375 Place::Site(index),
376 cx,
377 ));
321 }
378 }
322 v_flex()
379 v_flex()
323 .w(px(NAV_WIDTH))
380 .w(px(NAV_WIDTH))
@@ -335,11 +392,29 @@ impl CloudPicker {
335 .child("OneDrive"),
392 .child("OneDrive"),
336 )
393 )
337 .child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))
394 .child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))
338 .child(self.nav_row("cloud-picker-mine", "folder", "My files".into(), Place::MyFiles, cx))
395 .child(self.nav_row(
339 .child(self.nav_row("cloud-picker-shared", "group", "Shared".into(), Place::Shared, cx))
396 "cloud-picker-mine",
397 "folder",
398 "My files".into(),
399 Place::MyFiles,
400 cx,
401 ))
402 .child(self.nav_row(
403 "cloud-picker-shared",
404 "group",
405 "Shared".into(),
406 Place::Shared,
407 cx,
408 ))
340 .when(!self.sites.is_empty(), |nav| {
409 .when(!self.sites.is_empty(), |nav| {
341 nav.child(section("Quick access"))
410 nav.child(section("Quick access")).child(
342 .child(v_flex().id("cloud-picker-sites").flex_1().min_h_0().overflow_y_scrollbar().children(sites))
411 v_flex()
412 .id("cloud-picker-sites")
413 .flex_1()
414 .min_h_0()
415 .overflow_y_scrollbar()
416 .children(sites),
417 )
343 })
418 })
344 }
419 }
345
420
@@ -356,10 +431,21 @@ impl CloudPicker {
356 .id(("cloud-picker-crumb", depth))
431 .id(("cloud-picker-crumb", depth))
357 .truncate()
432 .truncate()
358 .text_size(px(if current { 20. } else { 14. }))
433 .text_size(px(if current { 20. } else { 14. }))
359 .font_weight(if current { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
434 .font_weight(if current {
360 .text_color(if current { theme::text_strong() } else { theme::text_soft() })
435 FontWeight::SEMIBOLD
436 } else {
437 FontWeight::NORMAL
438 })
439 .text_color(if current {
440 theme::text_strong()
441 } else {
442 theme::text_soft()
443 })
361 .when(!current, |crumb| {
444 .when(!current, |crumb| {
362 crumb.cursor_pointer().hover(|crumb| crumb.text_color(theme::text())).on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
445 crumb
446 .cursor_pointer()
447 .hover(|crumb| crumb.text_color(theme::text()))
448 .on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
363 })
449 })
364 .child(crumb.name.clone()),
450 .child(crumb.name.clone()),
365 );
451 );
@@ -376,12 +462,21 @@ impl CloudPicker {
376 self.breadcrumb(cx)
462 self.breadcrumb(cx)
377 } else {
463 } else {
378 h_flex().child(
464 h_flex().child(
379 div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme::text_strong()).child(self.title()),
465 div()
466 .text_size(px(20.))
467 .font_weight(FontWeight::SEMIBOLD)
468 .text_color(theme::text_strong())
469 .child(self.title()),
380 )
470 )
381 };
471 };
382 v_flex()
472 v_flex()
383 .gap(px(2.))
473 .gap(px(2.))
384 .children(site.map(|name| div().text_size(px(13.)).text_color(theme::text_soft()).child(name)))
474 .children(site.map(|name| {
475 div()
476 .text_size(px(13.))
477 .text_color(theme::text_soft())
478 .child(name)
479 }))
385 .child(title)
480 .child(title)
386 }
481 }
387
482
@@ -406,12 +501,20 @@ impl CloudPicker {
406
501
407 fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {
502 fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {
408 match (self.place, entry.modified_at) {
503 match (self.place, entry.modified_at) {
409 (Place::Home, Some(opened)) => opened_ago(opened, now).unwrap_or_else(|| modified_text(entry)),
504 (Place::Home, Some(opened)) => {
505 opened_ago(opened, now).unwrap_or_else(|| modified_text(entry))
506 }
410 _ => modified_text(entry),
507 _ => modified_text(entry),
411 }
508 }
412 }
509 }
413
510
414 fn row(&self, index: usize, entry: &DriveEntry, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
511 fn row(
512 &self,
513 index: usize,
514 entry: &DriveEntry,
515 now: DateTime<Utc>,
516 cx: &mut Context<Self>,
517 ) -> Stateful<Div> {
415 let picked = self.selected.iter().any(|selected| selected.id == entry.id);
518 let picked = self.selected.iter().any(|selected| selected.id == entry.id);
416 let folder = entry.is_folder();
519 let folder = entry.is_folder();
417 let clicked = entry.clone();
520 let clicked = entry.clone();
@@ -429,11 +532,9 @@ impl CloudPicker {
429 .text_color(theme::text_soft())
532 .text_color(theme::text_soft())
430 .when(picked, |row| row.bg(theme::selection()))
533 .when(picked, |row| row.bg(theme::selection()))
431 .hover(|row| row.bg(theme::row_hover()))
534 .hover(|row| row.bg(theme::row_hover()))
432 .child(
535 .child(div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
433 div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
536 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
434 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
537 }))
435 }),
436 )
437 .child(
538 .child(
438 h_flex()
539 h_flex()
439 .flex_1()
540 .flex_1()
@@ -441,25 +542,49 @@ impl CloudPicker {
441 .gap(px(10.))
542 .gap(px(10.))
442 .items_center()
543 .items_center()
443 .child(entry_badge(entry))
544 .child(entry_badge(entry))
444 .child(div().truncate().text_color(theme::text()).child(entry.name.clone())),
545 .child(
546 div()
547 .truncate()
548 .text_color(theme::text())
549 .child(entry.name.clone()),
550 ),
551 )
552 .child(
553 div()
554 .w(px(WHEN_WIDTH))
555 .flex_none()
556 .truncate()
557 .child(self.when_text(entry, now)),
558 )
559 .child(
560 div()
561 .w(px(WHO_WIDTH))
562 .flex_none()
563 .truncate()
564 .child(entry.modified_by.clone().unwrap_or_default()),
445 )
565 )
446 .child(div().w(px(WHEN_WIDTH)).flex_none().truncate().child(self.when_text(entry, now)))
447 .child(div().w(px(WHO_WIDTH)).flex_none().truncate().child(entry.modified_by.clone().unwrap_or_default()))
448 .on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))
566 .on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))
449 }
567 }
450
568
451 fn table(&self, cx: &mut Context<Self>) -> AnyElement {
569 fn table(&self, cx: &mut Context<Self>) -> AnyElement {
452 let note = |text: &'static str| {
570 let note = |text: &'static str| {
453 div().p(px(16.)).text_size(px(13.)).text_color(theme::text_soft()).child(text).into_any_element()
571 div()
572 .p(px(16.))
573 .text_size(px(13.))
574 .text_color(theme::text_soft())
575 .child(text)
576 .into_any_element()
454 };
577 };
455 let now = Utc::now();
578 let now = Utc::now();
456 let body: Vec<AnyElement> = match &self.rows {
579 let body: Vec<AnyElement> = match &self.rows {
457 Rows::Loading => vec![note("Loading ...")],
580 Rows::Loading => vec![note("Loading ...")],
458 Rows::Failed => vec![note("Couldn't load files.")],
581 Rows::Failed => vec![note("Couldn't load files.")],
459 Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],
582 Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],
460 Rows::Ready(entries) => {
583 Rows::Ready(entries) => entries
461 entries.iter().enumerate().map(|(index, entry)| self.row(index, entry, now, cx).into_any_element()).collect()
584 .iter()
462 }
585 .enumerate()
586 .map(|(index, entry)| self.row(index, entry, now, cx).into_any_element())
587 .collect(),
463 };
588 };
464 v_flex()
589 v_flex()
465 .flex_1()
590 .flex_1()
@@ -468,7 +593,14 @@ impl CloudPicker {
468 .bg(theme::surface_raised())
593 .bg(theme::surface_raised())
469 .overflow_hidden()
594 .overflow_hidden()
470 .child(self.column_header())
595 .child(self.column_header())
471 .child(v_flex().id("cloud-picker-rows").flex_1().min_h_0().overflow_y_scrollbar().children(body))
596 .child(
597 v_flex()
598 .id("cloud-picker-rows")
599 .flex_1()
600 .min_h_0()
601 .overflow_y_scrollbar()
602 .children(body),
603 )
472 .into_any_element()
604 .into_any_element()
473 }
605 }
474}
606}
@@ -510,11 +642,9 @@ impl Render for CloudPicker {
510 .disabled(!can_attach)
642 .disabled(!can_attach)
511 .on_click(cx.listener(|this, _, _, cx| this.attach(cx))),
643 .on_click(cx.listener(|this, _, _, cx| this.attach(cx))),
512 )
644 )
513 .child(
645 .child(Button::new("cloud-picker-cancel").label("Cancel").on_click(
514 Button::new("cloud-picker-cancel")
646 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
515 .label("Cancel")
647 )),
516 .on_click(cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close))),
517 ),
518 ),
648 ),
519 );
649 );
520 deferred(
650 deferred(
@@ -534,7 +664,10 @@ impl Render for CloudPicker {
534 cx.emit(CloudPickerEvent::Close);
664 cx.emit(CloudPickerEvent::Close);
535 }
665 }
536 }))
666 }))
537 .on_mouse_down(MouseButton::Left, cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)))
667 .on_mouse_down(
668 MouseButton::Left,
669 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
670 )
538 .child(panel),
671 .child(panel),
539 ),
672 ),
540 )
673 )
@@ -551,15 +684,27 @@ mod tests {
551 #[test]
684 #[test]
552 fn home_shows_hours_ago_like_the_onedrive_picker() {
685 fn home_shows_hours_ago_like_the_onedrive_picker() {
553 let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();
686 let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();
554 assert_eq!(opened_ago(now - chrono::Duration::hours(9), now).as_deref(), Some("9h ago"));
687 assert_eq!(
555 assert_eq!(opened_ago(now - chrono::Duration::minutes(5), now).as_deref(), Some("5m ago"));
688 opened_ago(now - chrono::Duration::hours(9), now).as_deref(),
689 Some("9h ago")
690 );
691 assert_eq!(
692 opened_ago(now - chrono::Duration::minutes(5), now).as_deref(),
693 Some("5m ago")
694 );
556 assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);
695 assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);
557 }
696 }
558
697
559 #[test]
698 #[test]
560 fn each_place_has_the_picker_columns() {
699 fn each_place_has_the_picker_columns() {
561 assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);
700 assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);
562 assert_eq!(Place::Shared.columns(), ["Name", "Date shared", "Shared by"]);
701 assert_eq!(
563 assert_eq!(Place::Site(0).columns(), ["Name", "Modified", "Modified By"]);
702 Place::Shared.columns(),
703 ["Name", "Date shared", "Shared by"]
704 );
705 assert_eq!(
706 Place::Site(0).columns(),
707 ["Name", "Modified", "Modified By"]
708 );
564 }
709 }
565}
710}
crates/app/src/views/composer/delivery.rs +2 −2
@@ -9,8 +9,8 @@ use store::MessageImportance;
9 9
10 10 use super::{COMPOSER_BUTTON_INSET, COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
11 11 use crate::delivery_options::{
12 DeliveryOption, URGENT_TOO_MANY_MEMBERS, UrgentAvailability,
13 allowed_importance, delivery_options, urgent_banner,
12 DeliveryOption, URGENT_TOO_MANY_MEMBERS, UrgentAvailability, allowed_importance,
13 delivery_options, urgent_banner,
14 14 };
15 15 use crate::importance::importance_label;
16 16 use crate::theme::{self, ElevatedSurface as _};
@@ -9,8 +9,8 @@ use store::MessageImportance;
9
9
10use super::{COMPOSER_BUTTON_INSET, COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
10use super::{COMPOSER_BUTTON_INSET, COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
11use crate::delivery_options::{
11use crate::delivery_options::{
12 DeliveryOption, URGENT_TOO_MANY_MEMBERS, UrgentAvailability,
12 DeliveryOption, URGENT_TOO_MANY_MEMBERS, UrgentAvailability, allowed_importance,
13 allowed_importance, delivery_options, urgent_banner,
13 delivery_options, urgent_banner,
14};
14};
15use crate::importance::importance_label;
15use crate::importance::importance_label;
16use crate::theme::{self, ElevatedSurface as _};
16use crate::theme::{self, ElevatedSurface as _};
crates/app/src/views/composer/format_menus.rs +98 −44
@@ -35,25 +35,73 @@ pub(super) struct Swatch {
35 35
36 36 /// Teams' font colour palette (`categoryColors`, shades in the compose bundle).
37 37 pub(super) const FONT_COLORS: [Swatch; 8] = [
38 Swatch { name: "Red", color: 0xB6424C },
39 Swatch { name: "Tuscan orange", color: 0xCD5937 },
40 Swatch { name: "Sunglow", color: 0xFDC030 },
41 Swatch { name: "Pear", color: 0xBDCB4C },
42 Swatch { name: "Eucalyptus", color: 0x2B9B62 },
43 Swatch { name: "Faded jade", color: 0x37797B },
44 Swatch { name: "Fun blue", color: 0x1E53A3 },
45 Swatch { name: "Tyrian purple", color: 0xA5397A },
38 Swatch {
39 name: "Red",
40 color: 0xB6424C,
41 },
42 Swatch {
43 name: "Tuscan orange",
44 color: 0xCD5937,
45 },
46 Swatch {
47 name: "Sunglow",
48 color: 0xFDC030,
49 },
50 Swatch {
51 name: "Pear",
52 color: 0xBDCB4C,
53 },
54 Swatch {
55 name: "Eucalyptus",
56 color: 0x2B9B62,
57 },
58 Swatch {
59 name: "Faded jade",
60 color: 0x37797B,
61 },
62 Swatch {
63 name: "Fun blue",
64 color: 0x1E53A3,
65 },
66 Swatch {
67 name: "Tyrian purple",
68 color: 0xA5397A,
69 },
46 70 ];
47 71
48 72 pub(super) const HIGHLIGHT_COLORS: [Swatch; 8] = [
49 Swatch { name: "Kobi red", color: 0xDF9299 },
50 Swatch { name: "Rose bud", color: 0xF4A593 },
51 Swatch { name: "Goldenrod", color: 0xFDD472 },
52 Swatch { name: "Primrose", color: 0xE5F18F },
53 Swatch { name: "Mantis", color: 0x82CDA8 },
54 Swatch { name: "Regent St. blue", color: 0x9DD9DB },
55 Swatch { name: "Periwinkle grey", color: 0xC7D4E8 },
56 Swatch { name: "Pale rose", color: 0xEBD3E1 },
73 Swatch {
74 name: "Kobi red",
75 color: 0xDF9299,
76 },
77 Swatch {
78 name: "Rose bud",
79 color: 0xF4A593,
80 },
81 Swatch {
82 name: "Goldenrod",
83 color: 0xFDD472,
84 },
85 Swatch {
86 name: "Primrose",
87 color: 0xE5F18F,
88 },
89 Swatch {
90 name: "Mantis",
91 color: 0x82CDA8,
92 },
93 Swatch {
94 name: "Regent St. blue",
95 color: 0x9DD9DB,
96 },
97 Swatch {
98 name: "Periwinkle grey",
99 color: 0xC7D4E8,
100 },
101 Swatch {
102 name: "Pale rose",
103 color: 0xEBD3E1,
104 },
57 105 ];
58 106
59 107 pub(super) const PARAGRAPH_STYLES: [(Option<u8>, &str); 4] = [
@@ -312,30 +360,34 @@ impl Composer {
312 360 fn render_color_picker(&self, popup: FormatPopup, cx: &mut Context<Self>) -> Div {
313 361 let current = self.current_color(popup, cx);
314 362 let rows = popup.palette().chunks(SWATCH_COLUMNS).map(|row| {
315 h_flex().gap(px(SWATCH_GAP)).children(row.iter().map(|swatch| {
316 let color = swatch.color;
317 let name = swatch.name;
318 let selected = current == Some(color);
319 swallow_mouse_down(
320 div()
321 .id(ElementId::Name(format!("swatch-{popup:?}-{color:06x}").into()))
322 .size(px(SWATCH))
323 .rounded(px(SWATCH / 2.))
324 .bg(rgb(color))
325 .cursor_pointer()
326 .border_2()
327 .border_color(if selected {
328 theme::text()
329 } else {
330 transparent_black()
331 })
332 .hover(|swatch| swatch.opacity(0.85))
333 .tooltip(move |window, cx| Tooltip::new(name).build(window, cx)),
334 )
335 .on_click(cx.listener(move |this, _, window, cx| {
336 this.apply_color(popup, Some(color), window, cx)
363 h_flex()
364 .gap(px(SWATCH_GAP))
365 .children(row.iter().map(|swatch| {
366 let color = swatch.color;
367 let name = swatch.name;
368 let selected = current == Some(color);
369 swallow_mouse_down(
370 div()
371 .id(ElementId::Name(
372 format!("swatch-{popup:?}-{color:06x}").into(),
373 ))
374 .size(px(SWATCH))
375 .rounded(px(SWATCH / 2.))
376 .bg(rgb(color))
377 .cursor_pointer()
378 .border_2()
379 .border_color(if selected {
380 theme::text()
381 } else {
382 transparent_black()
383 })
384 .hover(|swatch| swatch.opacity(0.85))
385 .tooltip(move |window, cx| Tooltip::new(name).build(window, cx)),
386 )
387 .on_click(cx.listener(move |this, _, window, cx| {
388 this.apply_color(popup, Some(color), window, cx)
389 }))
337 390 }))
338 }))
339 391 });
340 392 let clear = swallow_mouse_down(
341 393 div()
@@ -350,9 +402,7 @@ impl Composer {
350 402 .cursor_pointer()
351 403 .hover(|row| row.bg(theme::popup_hover())),
352 404 )
353 .on_click(cx.listener(move |this, _, window, cx| {
354 this.apply_color(popup, None, window, cx)
355 }))
405 .on_click(cx.listener(move |this, _, window, cx| this.apply_color(popup, None, window, cx)))
356 406 .child(popup.clear_label());
357 407 v_flex()
358 408 .p(px(POPUP_PADDING))
@@ -365,7 +415,8 @@ impl Composer {
365 415 let selection = self.selection(cx);
366 416 let rows = FONT_SIZES.iter().map(|(size, button, label)| {
367 417 let size = *size;
368 let current = size.is_some() && self.format_state(*button, &selection) == FormatState::On;
418 let current =
419 size.is_some() && self.format_state(*button, &selection) == FormatState::On;
369 420 swallow_mouse_down(
370 421 div()
371 422 .id(ElementId::Name(format!("font-size-{label}").into()))
@@ -427,7 +478,10 @@ mod tests {
427 478
428 479 #[test]
429 480 fn font_sizes_read_like_teams() {
430 assert_eq!(FONT_SIZES.map(|(_, _, label)| label), ["Large", "Medium", "Small"]);
481 assert_eq!(
482 FONT_SIZES.map(|(_, _, label)| label),
483 ["Large", "Medium", "Small"]
484 );
431 485 assert_eq!(
432 486 FONT_SIZES.map(|(size, _, _)| size),
433 487 [Some(SizeStep::Large), None, Some(SizeStep::Small)]
@@ -35,25 +35,73 @@ pub(super) struct Swatch {
35
35
36/// Teams' font colour palette (`categoryColors`, shades in the compose bundle).
36/// Teams' font colour palette (`categoryColors`, shades in the compose bundle).
37pub(super) const FONT_COLORS: [Swatch; 8] = [
37pub(super) const FONT_COLORS: [Swatch; 8] = [
38 Swatch { name: "Red", color: 0xB6424C },
38 Swatch {
39 Swatch { name: "Tuscan orange", color: 0xCD5937 },
39 name: "Red",
40 Swatch { name: "Sunglow", color: 0xFDC030 },
40 color: 0xB6424C,
41 Swatch { name: "Pear", color: 0xBDCB4C },
41 },
42 Swatch { name: "Eucalyptus", color: 0x2B9B62 },
42 Swatch {
43 Swatch { name: "Faded jade", color: 0x37797B },
43 name: "Tuscan orange",
44 Swatch { name: "Fun blue", color: 0x1E53A3 },
44 color: 0xCD5937,
45 Swatch { name: "Tyrian purple", color: 0xA5397A },
45 },
46 Swatch {
47 name: "Sunglow",
48 color: 0xFDC030,
49 },
50 Swatch {
51 name: "Pear",
52 color: 0xBDCB4C,
53 },
54 Swatch {
55 name: "Eucalyptus",
56 color: 0x2B9B62,
57 },
58 Swatch {
59 name: "Faded jade",
60 color: 0x37797B,
61 },
62 Swatch {
63 name: "Fun blue",
64 color: 0x1E53A3,
65 },
66 Swatch {
67 name: "Tyrian purple",
68 color: 0xA5397A,
69 },
46];
70];
47
71
48pub(super) const HIGHLIGHT_COLORS: [Swatch; 8] = [
72pub(super) const HIGHLIGHT_COLORS: [Swatch; 8] = [
49 Swatch { name: "Kobi red", color: 0xDF9299 },
73 Swatch {
50 Swatch { name: "Rose bud", color: 0xF4A593 },
74 name: "Kobi red",
51 Swatch { name: "Goldenrod", color: 0xFDD472 },
75 color: 0xDF9299,
52 Swatch { name: "Primrose", color: 0xE5F18F },
76 },
53 Swatch { name: "Mantis", color: 0x82CDA8 },
77 Swatch {
54 Swatch { name: "Regent St. blue", color: 0x9DD9DB },
78 name: "Rose bud",
55 Swatch { name: "Periwinkle grey", color: 0xC7D4E8 },
79 color: 0xF4A593,
56 Swatch { name: "Pale rose", color: 0xEBD3E1 },
80 },
81 Swatch {
82 name: "Goldenrod",
83 color: 0xFDD472,
84 },
85 Swatch {
86 name: "Primrose",
87 color: 0xE5F18F,
88 },
89 Swatch {
90 name: "Mantis",
91 color: 0x82CDA8,
92 },
93 Swatch {
94 name: "Regent St. blue",
95 color: 0x9DD9DB,
96 },
97 Swatch {
98 name: "Periwinkle grey",
99 color: 0xC7D4E8,
100 },
101 Swatch {
102 name: "Pale rose",
103 color: 0xEBD3E1,
104 },
57];
105];
58
106
59pub(super) const PARAGRAPH_STYLES: [(Option<u8>, &str); 4] = [
107pub(super) const PARAGRAPH_STYLES: [(Option<u8>, &str); 4] = [
@@ -312,30 +360,34 @@ impl Composer {
312 fn render_color_picker(&self, popup: FormatPopup, cx: &mut Context<Self>) -> Div {
360 fn render_color_picker(&self, popup: FormatPopup, cx: &mut Context<Self>) -> Div {
313 let current = self.current_color(popup, cx);
361 let current = self.current_color(popup, cx);
314 let rows = popup.palette().chunks(SWATCH_COLUMNS).map(|row| {
362 let rows = popup.palette().chunks(SWATCH_COLUMNS).map(|row| {
315 h_flex().gap(px(SWATCH_GAP)).children(row.iter().map(|swatch| {
363 h_flex()
316 let color = swatch.color;
364 .gap(px(SWATCH_GAP))
317 let name = swatch.name;
365 .children(row.iter().map(|swatch| {
318 let selected = current == Some(color);
366 let color = swatch.color;
319 swallow_mouse_down(
367 let name = swatch.name;
320 div()
368 let selected = current == Some(color);
321 .id(ElementId::Name(format!("swatch-{popup:?}-{color:06x}").into()))
369 swallow_mouse_down(
322 .size(px(SWATCH))
370 div()
323 .rounded(px(SWATCH / 2.))
371 .id(ElementId::Name(
324 .bg(rgb(color))
372 format!("swatch-{popup:?}-{color:06x}").into(),
325 .cursor_pointer()
373 ))
326 .border_2()
374 .size(px(SWATCH))
327 .border_color(if selected {
375 .rounded(px(SWATCH / 2.))
328 theme::text()
376 .bg(rgb(color))
329 } else {
377 .cursor_pointer()
330 transparent_black()
378 .border_2()
331 })
379 .border_color(if selected {
332 .hover(|swatch| swatch.opacity(0.85))
380 theme::text()
333 .tooltip(move |window, cx| Tooltip::new(name).build(window, cx)),
381 } else {
334 )
382 transparent_black()
335 .on_click(cx.listener(move |this, _, window, cx| {
383 })
336 this.apply_color(popup, Some(color), window, cx)
384 .hover(|swatch| swatch.opacity(0.85))
385 .tooltip(move |window, cx| Tooltip::new(name).build(window, cx)),
386 )
387 .on_click(cx.listener(move |this, _, window, cx| {
388 this.apply_color(popup, Some(color), window, cx)
389 }))
337 }))
390 }))
338 }))
339 });
391 });
340 let clear = swallow_mouse_down(
392 let clear = swallow_mouse_down(
341 div()
393 div()
@@ -350,9 +402,7 @@ impl Composer {
350 .cursor_pointer()
402 .cursor_pointer()
351 .hover(|row| row.bg(theme::popup_hover())),
403 .hover(|row| row.bg(theme::popup_hover())),
352 )
404 )
353 .on_click(cx.listener(move |this, _, window, cx| {
405 .on_click(cx.listener(move |this, _, window, cx| this.apply_color(popup, None, window, cx)))
354 this.apply_color(popup, None, window, cx)
355 }))
356 .child(popup.clear_label());
406 .child(popup.clear_label());
357 v_flex()
407 v_flex()
358 .p(px(POPUP_PADDING))
408 .p(px(POPUP_PADDING))
@@ -365,7 +415,8 @@ impl Composer {
365 let selection = self.selection(cx);
415 let selection = self.selection(cx);
366 let rows = FONT_SIZES.iter().map(|(size, button, label)| {
416 let rows = FONT_SIZES.iter().map(|(size, button, label)| {
367 let size = *size;
417 let size = *size;
368 let current = size.is_some() && self.format_state(*button, &selection) == FormatState::On;
418 let current =
419 size.is_some() && self.format_state(*button, &selection) == FormatState::On;
369 swallow_mouse_down(
420 swallow_mouse_down(
370 div()
421 div()
371 .id(ElementId::Name(format!("font-size-{label}").into()))
422 .id(ElementId::Name(format!("font-size-{label}").into()))
@@ -427,7 +478,10 @@ mod tests {
427
478
428 #[test]
479 #[test]
429 fn font_sizes_read_like_teams() {
480 fn font_sizes_read_like_teams() {
430 assert_eq!(FONT_SIZES.map(|(_, _, label)| label), ["Large", "Medium", "Small"]);
481 assert_eq!(
482 FONT_SIZES.map(|(_, _, label)| label),
483 ["Large", "Medium", "Small"]
484 );
431 assert_eq!(
485 assert_eq!(
432 FONT_SIZES.map(|(size, _, _)| size),
486 FONT_SIZES.map(|(size, _, _)| size),
433 [Some(SizeStep::Large), None, Some(SizeStep::Small)]
487 [Some(SizeStep::Large), None, Some(SizeStep::Small)]
crates/app/src/views/composer/plus_menu.rs +3 −3
@@ -161,9 +161,9 @@ impl Composer {
161 161 .text_color(theme::text())
162 162 .child(action.label()),
163 163 )
164 .on_click(cx.listener(move |this, _, window, cx| {
165 this.run_plus_action(action, window, cx)
166 }))
164 .on_click(
165 cx.listener(move |this, _, window, cx| this.run_plus_action(action, window, cx)),
166 )
167 167 }
168 168
169 169 fn run_plus_action(&mut self, action: PlusAction, window: &mut Window, cx: &mut Context<Self>) {
@@ -161,9 +161,9 @@ impl Composer {
161 .text_color(theme::text())
161 .text_color(theme::text())
162 .child(action.label()),
162 .child(action.label()),
163 )
163 )
164 .on_click(cx.listener(move |this, _, window, cx| {
164 .on_click(
165 this.run_plus_action(action, window, cx)
165 cx.listener(move |this, _, window, cx| this.run_plus_action(action, window, cx)),
166 }))
166 )
167 }
167 }
168
168
169 fn run_plus_action(&mut self, action: PlusAction, window: &mut Window, cx: &mut Context<Self>) {
169 fn run_plus_action(&mut self, action: PlusAction, window: &mut Window, cx: &mut Context<Self>) {
crates/app/src/views/composer/rewrite.rs +164 −39
@@ -10,13 +10,15 @@ use teams_core::{ComposeAction, ComposeAdjustment, Draft, OBJECT_MARK, TABLE_MAR
10 10
11 11 use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
12 12 use crate::runtime;
13 use app_ui_kit::spinner::spinner;
14 13 use crate::theme::{self, ElevatedSurface as _};
15 14 use crate::views::widgets::symbol;
15 use app_ui_kit::spinner::spinner;
16 16
17 17 pub const REWRITE_BUTTON_TAG: &str = "composer/actions/copilot";
18 18 pub const REWRITE_PANEL_TAG: &str = "composer/copilot";
19 19 const BUTTON_LABEL: &str = "Write with Copilot";
20 const REWRITE_SYSTEM: &str = "You rewrite a Teams chat draft. Reply with only the new message text. Keep the meaning. Do not add a preamble.";
21 const SWITCH_HINT: &str = "Choose another model under Settings > Agents, Write with.";
20 22 const CLOSE_LABEL: &str = "Close";
21 23 const ADJUST_LABEL: &str = "Adjust";
22 24 const CUSTOM_LABEL: &str = "Customised";
@@ -26,7 +28,8 @@ const DISCLAIMER: &str = "AI-generated content may be incorrect";
26 28 const WORKING: &str = "Copilot is writing ...";
27 29 const FAILED: &str = "Copilot could not rewrite this:";
28 30 const EMPTY_DRAFT: &str = "Type a message first, then let Copilot rewrite it.";
29 const TEXT_ONLY: &str = "Copilot rewrites text only. Move images and tables out of the message first.";
31 const TEXT_ONLY: &str =
32 "Copilot rewrites text only. Move images and tables out of the message first.";
30 33 const BUTTON_ICON: &str = "auto_fix_high";
31 34 const PANEL_WIDTH: f32 = 600.;
32 35 const PANEL_PADDING: f32 = 16.;
@@ -78,11 +81,17 @@ impl Composer {
78 81 fn rewrite_available(&self, cx: &App) -> bool {
79 82 let state = self.app.read(cx);
80 83 self.editing.is_none()
81 && (state.mode.demo || state.engine.is_some())
84 && (state.mode.demo || local_writer(cx).is_some() || state.engine.is_some())
82 85 && self
83 86 .conversation_id
84 87 .as_deref()
85 .is_some_and(|conversation_id| state.sidebar.chats.iter().any(|chat| chat.id == conversation_id))
88 .is_some_and(|conversation_id| {
89 state
90 .sidebar
91 .chats
92 .iter()
93 .any(|chat| chat.id == conversation_id)
94 })
86 95 }
87 96
88 97 pub(super) fn render_rewrite_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
@@ -107,11 +116,20 @@ impl Composer {
107 116 .cursor_pointer()
108 117 .when(open, |button| button.bg(theme::popup_hover()))
109 118 .hover(|button| button.bg(theme::popup_hover()))
110 .popup_trigger_tooltip_text(open, BUTTON_LABEL)
119 .popup_trigger_tooltip_text(
120 open,
121 local_writer(cx)
122 .map(|profile| format!("Rewrite with {}", profile.name))
123 .unwrap_or_else(|| BUTTON_LABEL.to_owned()),
124 )
111 125 .child(symbol(
112 126 BUTTON_ICON,
113 127 COMPOSER_ICON_SIZE,
114 if open { theme::accent_text() } else { theme::text_muted() },
128 if open {
129 theme::accent_text()
130 } else {
131 theme::text_muted()
132 },
115 133 ))
116 134 .on_mouse_down(MouseButton::Left, |_, window, cx| {
117 135 window.prevent_default();
@@ -166,10 +184,34 @@ impl Composer {
166 184 });
167 185 cx.notify();
168 186 let user_html = draft.to_html();
169 let receiver = (!demo)
170 .then_some(engine)
171 .flatten()
172 .map(|engine| runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await }));
187 let plain = draft.plain_text();
188 if !demo && let Some(profile) = local_writer(cx) {
189 let instruction = rewrite_instruction(&action, &plain);
190 let receiver = runtime::spawn(async move {
191 agents::complete_text(&profile, REWRITE_SYSTEM, &instruction).await
192 });
193 cx.spawn(async move |this, cx| {
194 let answer = match receiver.await {
195 Ok(Ok(text)) => RewriteAnswer::Ready(Draft::from_markdown(&text)),
196 Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
197 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
198 };
199 this.update(cx, |this, cx| {
200 if this.rewrite.generation == generation
201 && let Some(result) = this.rewrite.result.as_mut()
202 {
203 result.answer = answer;
204 cx.notify();
205 }
206 })
207 .ok();
208 })
209 .detach();
210 return;
211 }
212 let receiver = (!demo).then_some(engine).flatten().map(|engine| {
213 runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await })
214 });
173 215 let demo_answer = demo_rewrite(&draft.plain_text());
174 216 cx.spawn(async move |this, cx| {
175 217 let answer = match receiver {
@@ -178,9 +220,13 @@ impl Composer {
178 220 RewriteAnswer::Ready(Draft::from_markdown(&demo_answer))
179 221 }
180 222 Some(receiver) => match receiver.await {
181 Ok(Ok(html)) => RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed()),
182 Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
183 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
223 Ok(Ok(html)) => {
224 RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed())
225 }
226 Ok(Err(error)) => {
227 RewriteAnswer::Failed(format!("{FAILED} {error} {SWITCH_HINT}"))
228 }
229 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error} {SWITCH_HINT}")),
184 230 },
185 231 };
186 232 this.update(cx, |this, cx| {
@@ -197,12 +243,19 @@ impl Composer {
197 243 }
198 244
199 245 fn replace_with_rewrite(&mut self, window: &mut Window, cx: &mut Context<Self>) {
200 let Some(RewriteAnswer::Ready(draft)) = self.rewrite.result.as_ref().map(|result| &result.answer) else {
246 let Some(RewriteAnswer::Ready(draft)) =
247 self.rewrite.result.as_ref().map(|result| &result.answer)
248 else {
201 249 return;
202 250 };
203 251 let draft = draft.clone();
204 252 self.close_rewrite();
205 self.load_draft(draft.clone(), InputContent::new(draft.text().to_owned()), window, cx);
253 self.load_draft(
254 draft.clone(),
255 InputContent::new(draft.text().to_owned()),
256 window,
257 cx,
258 );
206 259 self.mention_inputs.clear();
207 260 self.schedule_draft_save(cx);
208 261 self.focus(window, cx);
@@ -214,16 +267,20 @@ impl Composer {
214 267 self.rewrite.custom_open = true;
215 268 if self.rewrite.custom_input.is_none() {
216 269 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CUSTOM_PLACEHOLDER));
217 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
218 if matches!(event, InputEvent::PressEnter { .. }) {
219 let prompt = input.read(cx).value().trim().to_owned();
220 if !prompt.is_empty() {
221 input.update(cx, |input, cx| input.set_value("", window, cx));
222 this.rewrite.custom_open = false;
223 this.request_rewrite(ComposeAction::Custom(prompt), cx);
270 let subscription = cx.subscribe_in(
271 &input,
272 window,
273 |this, input, event: &InputEvent, window, cx| {
274 if matches!(event, InputEvent::PressEnter { .. }) {
275 let prompt = input.read(cx).value().trim().to_owned();
276 if !prompt.is_empty() {
277 input.update(cx, |input, cx| input.set_value("", window, cx));
278 this.rewrite.custom_open = false;
279 this.request_rewrite(ComposeAction::Custom(prompt), cx);
280 }
224 281 }
225 }
226 });
282 },
283 );
227 284 self.rewrite.custom_input = Some(input);
228 285 self.rewrite._custom_events = Some(subscription);
229 286 }
@@ -307,7 +364,12 @@ impl Composer {
307 364 )
308 365 }
309 366
310 fn chip(id: &'static str, icon: &'static str, label: &'static str, busy: bool) -> Stateful<Div> {
367 fn chip(
368 id: &'static str,
369 icon: &'static str,
370 label: &'static str,
371 busy: bool,
372 ) -> Stateful<Div> {
311 373 h_flex()
312 374 .id(id)
313 375 .h(px(CHIP_HEIGHT))
@@ -322,20 +384,33 @@ impl Composer {
322 384 .child(symbol(icon, CHIP_ICON, theme::text_soft()))
323 385 .child(label)
324 386 .when(busy, |chip| chip.opacity(0.5))
325 .when(!busy, |chip| chip.cursor_pointer().hover(|chip| chip.bg(theme::popup_hover())))
387 .when(!busy, |chip| {
388 chip.cursor_pointer()
389 .hover(|chip| chip.bg(theme::popup_hover()))
390 })
326 391 }
327 392
328 393 fn choice_chip(&self, choice: Choice, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
329 394 let (id, icon, action) = match choice {
330 Choice::Rewrite => ("composer-copilot-rewrite", BUTTON_ICON, ComposeAction::Rewrite),
331 Choice::Proofread => ("composer-copilot-proofread", "spellcheck", ComposeAction::Proofread),
395 Choice::Rewrite => (
396 "composer-copilot-rewrite",
397 BUTTON_ICON,
398 ComposeAction::Rewrite,
399 ),
400 Choice::Proofread => (
401 "composer-copilot-proofread",
402 "spellcheck",
403 ComposeAction::Proofread,
404 ),
332 405 };
333 406 let label = match choice {
334 407 Choice::Rewrite => "Rewrite",
335 408 Choice::Proofread => "Proofread",
336 409 };
337 410 Self::chip(id, icon, label, busy).when(!busy, |chip| {
338 chip.on_click(cx.listener(move |this, _, _, cx| this.request_rewrite(action.clone(), cx)))
411 chip.on_click(
412 cx.listener(move |this, _, _, cx| this.request_rewrite(action.clone(), cx)),
413 )
339 414 })
340 415 }
341 416
@@ -372,9 +447,9 @@ impl Composer {
372 447 let custom = item("composer-copilot-custom", CUSTOM_LABEL)
373 448 .on_click(cx.listener(|this, _, window, cx| this.open_custom(window, cx)));
374 449 let adjustments = ComposeAdjustment::ALL.into_iter().map(|adjustment| {
375 item(adjustment.label(), adjustment.label()).on_click(cx.listener(move |this, _, _, cx| {
376 this.request_rewrite(ComposeAction::Adjust(adjustment), cx)
377 }))
450 item(adjustment.label(), adjustment.label()).on_click(cx.listener(
451 move |this, _, _, cx| this.request_rewrite(ComposeAction::Adjust(adjustment), cx),
452 ))
378 453 });
379 454 Some(
380 455 v_flex()
@@ -419,13 +494,26 @@ impl Composer {
419 494 .gap(px(8.))
420 495 .items_center()
421 496 .child(spinner(16.))
422 .child(div().text_size(px(14.)).text_color(theme::text_soft()).child(WORKING)),
497 .child(
498 div()
499 .text_size(px(14.))
500 .text_color(theme::text_soft())
501 .child(WORKING),
502 ),
503 ),
504 RewriteAnswer::Failed(reason) => card.child(
505 div()
506 .text_size(px(14.))
507 .text_color(theme::text_soft())
508 .child(reason.clone()),
423 509 ),
424 RewriteAnswer::Failed(reason) => {
425 card.child(div().text_size(px(14.)).text_color(theme::text_soft()).child(reason.clone()))
426 }
427 510 RewriteAnswer::Ready(draft) => card
428 .child(div().text_size(px(14.)).text_color(theme::text()).child(draft.plain_text()))
511 .child(
512 div()
513 .text_size(px(14.))
514 .text_color(theme::text())
515 .child(draft.plain_text()),
516 )
429 517 .child(
430 518 h_flex()
431 519 .w_full()
@@ -446,14 +534,51 @@ impl Composer {
446 534 .cursor_pointer()
447 535 .hover(|button| button.opacity(0.85))
448 536 .child(REPLACE_LABEL)
449 .on_click(cx.listener(|this, _, window, cx| this.replace_with_rewrite(window, cx))),
537 .on_click(cx.listener(|this, _, window, cx| {
538 this.replace_with_rewrite(window, cx)
539 })),
450 540 )
451 .child(div().text_size(px(11.)).text_color(theme::text_muted()).child(DISCLAIMER)),
541 .child(
542 div()
543 .text_size(px(11.))
544 .text_color(theme::text_muted())
545 .child(DISCLAIMER),
546 ),
452 547 ),
453 548 })
454 549 }
455 550 }
456 551
552 fn local_writer(cx: &App) -> Option<agents::AgentProfile> {
553 let runs = crate::agents::runs_handle(cx)?;
554 let settings = runs.read(cx).settings();
555 if settings.write_with.is_empty() {
556 return None;
557 }
558 settings
559 .agents
560 .iter()
561 .find(|agent| agent.id == settings.write_with && agent.is_chat())
562 .cloned()
563 }
564
565 fn rewrite_instruction(action: &ComposeAction, draft: &str) -> String {
566 let ask = match action {
567 ComposeAction::Rewrite => "Rewrite it so it is clearer.",
568 ComposeAction::Proofread => "Proofread it. Fix spelling and grammar.",
569 ComposeAction::Adjust(adjustment) => match adjustment {
570 ComposeAdjustment::Concise => "Make it shorter.",
571 ComposeAdjustment::Longer => "Make it a bit longer.",
572 ComposeAdjustment::Casual => "Make it more casual.",
573 ComposeAdjustment::Professional => "Make it more professional.",
574 ComposeAdjustment::Confident => "Make it more confident.",
575 ComposeAdjustment::Enthusiastic => "Make it more enthusiastic.",
576 },
577 ComposeAction::Custom(prompt) => prompt.as_str(),
578 };
579 format!("{ask}\n\n{draft}")
580 }
581
457 582 fn demo_rewrite(text: &str) -> String {
458 583 let trimmed = text.trim().trim_end_matches(['.', '!', '?']);
459 584 let mut characters = trimmed.chars();
@@ -10,13 +10,15 @@ use teams_core::{ComposeAction, ComposeAdjustment, Draft, OBJECT_MARK, TABLE_MAR
10
10
11use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
11use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
12use crate::runtime;
12use crate::runtime;
13use app_ui_kit::spinner::spinner;
14use crate::theme::{self, ElevatedSurface as _};
13use crate::theme::{self, ElevatedSurface as _};
15use crate::views::widgets::symbol;
14use crate::views::widgets::symbol;
15use app_ui_kit::spinner::spinner;
16
16
17pub const REWRITE_BUTTON_TAG: &str = "composer/actions/copilot";
17pub const REWRITE_BUTTON_TAG: &str = "composer/actions/copilot";
18pub const REWRITE_PANEL_TAG: &str = "composer/copilot";
18pub const REWRITE_PANEL_TAG: &str = "composer/copilot";
19const BUTTON_LABEL: &str = "Write with Copilot";
19const BUTTON_LABEL: &str = "Write with Copilot";
20const REWRITE_SYSTEM: &str = "You rewrite a Teams chat draft. Reply with only the new message text. Keep the meaning. Do not add a preamble.";
21const SWITCH_HINT: &str = "Choose another model under Settings > Agents, Write with.";
20const CLOSE_LABEL: &str = "Close";
22const CLOSE_LABEL: &str = "Close";
21const ADJUST_LABEL: &str = "Adjust";
23const ADJUST_LABEL: &str = "Adjust";
22const CUSTOM_LABEL: &str = "Customised";
24const CUSTOM_LABEL: &str = "Customised";
@@ -26,7 +28,8 @@ const DISCLAIMER: &str = "AI-generated content may be incorrect";
26const WORKING: &str = "Copilot is writing ...";
28const WORKING: &str = "Copilot is writing ...";
27const FAILED: &str = "Copilot could not rewrite this:";
29const FAILED: &str = "Copilot could not rewrite this:";
28const EMPTY_DRAFT: &str = "Type a message first, then let Copilot rewrite it.";
30const EMPTY_DRAFT: &str = "Type a message first, then let Copilot rewrite it.";
29const TEXT_ONLY: &str = "Copilot rewrites text only. Move images and tables out of the message first.";
31const TEXT_ONLY: &str =
32 "Copilot rewrites text only. Move images and tables out of the message first.";
30const BUTTON_ICON: &str = "auto_fix_high";
33const BUTTON_ICON: &str = "auto_fix_high";
31const PANEL_WIDTH: f32 = 600.;
34const PANEL_WIDTH: f32 = 600.;
32const PANEL_PADDING: f32 = 16.;
35const PANEL_PADDING: f32 = 16.;
@@ -78,11 +81,17 @@ impl Composer {
78 fn rewrite_available(&self, cx: &App) -> bool {
81 fn rewrite_available(&self, cx: &App) -> bool {
79 let state = self.app.read(cx);
82 let state = self.app.read(cx);
80 self.editing.is_none()
83 self.editing.is_none()
81 && (state.mode.demo || state.engine.is_some())
84 && (state.mode.demo || local_writer(cx).is_some() || state.engine.is_some())
82 && self
85 && self
83 .conversation_id
86 .conversation_id
84 .as_deref()
87 .as_deref()
85 .is_some_and(|conversation_id| state.sidebar.chats.iter().any(|chat| chat.id == conversation_id))
88 .is_some_and(|conversation_id| {
89 state
90 .sidebar
91 .chats
92 .iter()
93 .any(|chat| chat.id == conversation_id)
94 })
86 }
95 }
87
96
88 pub(super) fn render_rewrite_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
97 pub(super) fn render_rewrite_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
@@ -107,11 +116,20 @@ impl Composer {
107 .cursor_pointer()
116 .cursor_pointer()
108 .when(open, |button| button.bg(theme::popup_hover()))
117 .when(open, |button| button.bg(theme::popup_hover()))
109 .hover(|button| button.bg(theme::popup_hover()))
118 .hover(|button| button.bg(theme::popup_hover()))
110 .popup_trigger_tooltip_text(open, BUTTON_LABEL)
119 .popup_trigger_tooltip_text(
120 open,
121 local_writer(cx)
122 .map(|profile| format!("Rewrite with {}", profile.name))
123 .unwrap_or_else(|| BUTTON_LABEL.to_owned()),
124 )
111 .child(symbol(
125 .child(symbol(
112 BUTTON_ICON,
126 BUTTON_ICON,
113 COMPOSER_ICON_SIZE,
127 COMPOSER_ICON_SIZE,
114 if open { theme::accent_text() } else { theme::text_muted() },
128 if open {
129 theme::accent_text()
130 } else {
131 theme::text_muted()
132 },
115 ))
133 ))
116 .on_mouse_down(MouseButton::Left, |_, window, cx| {
134 .on_mouse_down(MouseButton::Left, |_, window, cx| {
117 window.prevent_default();
135 window.prevent_default();
@@ -166,10 +184,34 @@ impl Composer {
166 });
184 });
167 cx.notify();
185 cx.notify();
168 let user_html = draft.to_html();
186 let user_html = draft.to_html();
169 let receiver = (!demo)
187 let plain = draft.plain_text();
170 .then_some(engine)
188 if !demo && let Some(profile) = local_writer(cx) {
171 .flatten()
189 let instruction = rewrite_instruction(&action, &plain);
172 .map(|engine| runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await }));
190 let receiver = runtime::spawn(async move {
191 agents::complete_text(&profile, REWRITE_SYSTEM, &instruction).await
192 });
193 cx.spawn(async move |this, cx| {
194 let answer = match receiver.await {
195 Ok(Ok(text)) => RewriteAnswer::Ready(Draft::from_markdown(&text)),
196 Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
197 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
198 };
199 this.update(cx, |this, cx| {
200 if this.rewrite.generation == generation
201 && let Some(result) = this.rewrite.result.as_mut()
202 {
203 result.answer = answer;
204 cx.notify();
205 }
206 })
207 .ok();
208 })
209 .detach();
210 return;
211 }
212 let receiver = (!demo).then_some(engine).flatten().map(|engine| {
213 runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await })
214 });
173 let demo_answer = demo_rewrite(&draft.plain_text());
215 let demo_answer = demo_rewrite(&draft.plain_text());
174 cx.spawn(async move |this, cx| {
216 cx.spawn(async move |this, cx| {
175 let answer = match receiver {
217 let answer = match receiver {
@@ -178,9 +220,13 @@ impl Composer {
178 RewriteAnswer::Ready(Draft::from_markdown(&demo_answer))
220 RewriteAnswer::Ready(Draft::from_markdown(&demo_answer))
179 }
221 }
180 Some(receiver) => match receiver.await {
222 Some(receiver) => match receiver.await {
181 Ok(Ok(html)) => RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed()),
223 Ok(Ok(html)) => {
182 Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
224 RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed())
183 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
225 }
226 Ok(Err(error)) => {
227 RewriteAnswer::Failed(format!("{FAILED} {error} {SWITCH_HINT}"))
228 }
229 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error} {SWITCH_HINT}")),
184 },
230 },
185 };
231 };
186 this.update(cx, |this, cx| {
232 this.update(cx, |this, cx| {
@@ -197,12 +243,19 @@ impl Composer {
197 }
243 }
198
244
199 fn replace_with_rewrite(&mut self, window: &mut Window, cx: &mut Context<Self>) {
245 fn replace_with_rewrite(&mut self, window: &mut Window, cx: &mut Context<Self>) {
200 let Some(RewriteAnswer::Ready(draft)) = self.rewrite.result.as_ref().map(|result| &result.answer) else {
246 let Some(RewriteAnswer::Ready(draft)) =
247 self.rewrite.result.as_ref().map(|result| &result.answer)
248 else {
201 return;
249 return;
202 };
250 };
203 let draft = draft.clone();
251 let draft = draft.clone();
204 self.close_rewrite();
252 self.close_rewrite();
205 self.load_draft(draft.clone(), InputContent::new(draft.text().to_owned()), window, cx);
253 self.load_draft(
254 draft.clone(),
255 InputContent::new(draft.text().to_owned()),
256 window,
257 cx,
258 );
206 self.mention_inputs.clear();
259 self.mention_inputs.clear();
207 self.schedule_draft_save(cx);
260 self.schedule_draft_save(cx);
208 self.focus(window, cx);
261 self.focus(window, cx);
@@ -214,16 +267,20 @@ impl Composer {
214 self.rewrite.custom_open = true;
267 self.rewrite.custom_open = true;
215 if self.rewrite.custom_input.is_none() {
268 if self.rewrite.custom_input.is_none() {
216 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CUSTOM_PLACEHOLDER));
269 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CUSTOM_PLACEHOLDER));
217 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
270 let subscription = cx.subscribe_in(
218 if matches!(event, InputEvent::PressEnter { .. }) {
271 &input,
219 let prompt = input.read(cx).value().trim().to_owned();
272 window,
220 if !prompt.is_empty() {
273 |this, input, event: &InputEvent, window, cx| {
221 input.update(cx, |input, cx| input.set_value("", window, cx));
274 if matches!(event, InputEvent::PressEnter { .. }) {
222 this.rewrite.custom_open = false;
275 let prompt = input.read(cx).value().trim().to_owned();
223 this.request_rewrite(ComposeAction::Custom(prompt), cx);
276 if !prompt.is_empty() {
277 input.update(cx, |input, cx| input.set_value("", window, cx));
278 this.rewrite.custom_open = false;
279 this.request_rewrite(ComposeAction::Custom(prompt), cx);
280 }
224 }
281 }
225 }
282 },
226 });
283 );
227 self.rewrite.custom_input = Some(input);
284 self.rewrite.custom_input = Some(input);
228 self.rewrite._custom_events = Some(subscription);
285 self.rewrite._custom_events = Some(subscription);
229 }
286 }
@@ -307,7 +364,12 @@ impl Composer {
307 )
364 )
308 }
365 }
309
366
310 fn chip(id: &'static str, icon: &'static str, label: &'static str, busy: bool) -> Stateful<Div> {
367 fn chip(
368 id: &'static str,
369 icon: &'static str,
370 label: &'static str,
371 busy: bool,
372 ) -> Stateful<Div> {
311 h_flex()
373 h_flex()
312 .id(id)
374 .id(id)
313 .h(px(CHIP_HEIGHT))
375 .h(px(CHIP_HEIGHT))
@@ -322,20 +384,33 @@ impl Composer {
322 .child(symbol(icon, CHIP_ICON, theme::text_soft()))
384 .child(symbol(icon, CHIP_ICON, theme::text_soft()))
323 .child(label)
385 .child(label)
324 .when(busy, |chip| chip.opacity(0.5))
386 .when(busy, |chip| chip.opacity(0.5))
325 .when(!busy, |chip| chip.cursor_pointer().hover(|chip| chip.bg(theme::popup_hover())))
387 .when(!busy, |chip| {
388 chip.cursor_pointer()
389 .hover(|chip| chip.bg(theme::popup_hover()))
390 })
326 }
391 }
327
392
328 fn choice_chip(&self, choice: Choice, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
393 fn choice_chip(&self, choice: Choice, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
329 let (id, icon, action) = match choice {
394 let (id, icon, action) = match choice {
330 Choice::Rewrite => ("composer-copilot-rewrite", BUTTON_ICON, ComposeAction::Rewrite),
395 Choice::Rewrite => (
331 Choice::Proofread => ("composer-copilot-proofread", "spellcheck", ComposeAction::Proofread),
396 "composer-copilot-rewrite",
397 BUTTON_ICON,
398 ComposeAction::Rewrite,
399 ),
400 Choice::Proofread => (
401 "composer-copilot-proofread",
402 "spellcheck",
403 ComposeAction::Proofread,
404 ),
332 };
405 };
333 let label = match choice {
406 let label = match choice {
334 Choice::Rewrite => "Rewrite",
407 Choice::Rewrite => "Rewrite",
335 Choice::Proofread => "Proofread",
408 Choice::Proofread => "Proofread",
336 };
409 };
337 Self::chip(id, icon, label, busy).when(!busy, |chip| {
410 Self::chip(id, icon, label, busy).when(!busy, |chip| {
338 chip.on_click(cx.listener(move |this, _, _, cx| this.request_rewrite(action.clone(), cx)))
411 chip.on_click(
412 cx.listener(move |this, _, _, cx| this.request_rewrite(action.clone(), cx)),
413 )
339 })
414 })
340 }
415 }
341
416
@@ -372,9 +447,9 @@ impl Composer {
372 let custom = item("composer-copilot-custom", CUSTOM_LABEL)
447 let custom = item("composer-copilot-custom", CUSTOM_LABEL)
373 .on_click(cx.listener(|this, _, window, cx| this.open_custom(window, cx)));
448 .on_click(cx.listener(|this, _, window, cx| this.open_custom(window, cx)));
374 let adjustments = ComposeAdjustment::ALL.into_iter().map(|adjustment| {
449 let adjustments = ComposeAdjustment::ALL.into_iter().map(|adjustment| {
375 item(adjustment.label(), adjustment.label()).on_click(cx.listener(move |this, _, _, cx| {
450 item(adjustment.label(), adjustment.label()).on_click(cx.listener(
376 this.request_rewrite(ComposeAction::Adjust(adjustment), cx)
451 move |this, _, _, cx| this.request_rewrite(ComposeAction::Adjust(adjustment), cx),
377 }))
452 ))
378 });
453 });
379 Some(
454 Some(
380 v_flex()
455 v_flex()
@@ -419,13 +494,26 @@ impl Composer {
419 .gap(px(8.))
494 .gap(px(8.))
420 .items_center()
495 .items_center()
421 .child(spinner(16.))
496 .child(spinner(16.))
422 .child(div().text_size(px(14.)).text_color(theme::text_soft()).child(WORKING)),
497 .child(
498 div()
499 .text_size(px(14.))
500 .text_color(theme::text_soft())
501 .child(WORKING),
502 ),
503 ),
504 RewriteAnswer::Failed(reason) => card.child(
505 div()
506 .text_size(px(14.))
507 .text_color(theme::text_soft())
508 .child(reason.clone()),
423 ),
509 ),
424 RewriteAnswer::Failed(reason) => {
425 card.child(div().text_size(px(14.)).text_color(theme::text_soft()).child(reason.clone()))
426 }
427 RewriteAnswer::Ready(draft) => card
510 RewriteAnswer::Ready(draft) => card
428 .child(div().text_size(px(14.)).text_color(theme::text()).child(draft.plain_text()))
511 .child(
512 div()
513 .text_size(px(14.))
514 .text_color(theme::text())
515 .child(draft.plain_text()),
516 )
429 .child(
517 .child(
430 h_flex()
518 h_flex()
431 .w_full()
519 .w_full()
@@ -446,14 +534,51 @@ impl Composer {
446 .cursor_pointer()
534 .cursor_pointer()
447 .hover(|button| button.opacity(0.85))
535 .hover(|button| button.opacity(0.85))
448 .child(REPLACE_LABEL)
536 .child(REPLACE_LABEL)
449 .on_click(cx.listener(|this, _, window, cx| this.replace_with_rewrite(window, cx))),
537 .on_click(cx.listener(|this, _, window, cx| {
538 this.replace_with_rewrite(window, cx)
539 })),
450 )
540 )
451 .child(div().text_size(px(11.)).text_color(theme::text_muted()).child(DISCLAIMER)),
541 .child(
542 div()
543 .text_size(px(11.))
544 .text_color(theme::text_muted())
545 .child(DISCLAIMER),
546 ),
452 ),
547 ),
453 })
548 })
454 }
549 }
455}
550}
456
551
552fn local_writer(cx: &App) -> Option<agents::AgentProfile> {
553 let runs = crate::agents::runs_handle(cx)?;
554 let settings = runs.read(cx).settings();
555 if settings.write_with.is_empty() {
556 return None;
557 }
558 settings
559 .agents
560 .iter()
561 .find(|agent| agent.id == settings.write_with && agent.is_chat())
562 .cloned()
563}
564
565fn rewrite_instruction(action: &ComposeAction, draft: &str) -> String {
566 let ask = match action {
567 ComposeAction::Rewrite => "Rewrite it so it is clearer.",
568 ComposeAction::Proofread => "Proofread it. Fix spelling and grammar.",
569 ComposeAction::Adjust(adjustment) => match adjustment {
570 ComposeAdjustment::Concise => "Make it shorter.",
571 ComposeAdjustment::Longer => "Make it a bit longer.",
572 ComposeAdjustment::Casual => "Make it more casual.",
573 ComposeAdjustment::Professional => "Make it more professional.",
574 ComposeAdjustment::Confident => "Make it more confident.",
575 ComposeAdjustment::Enthusiastic => "Make it more enthusiastic.",
576 },
577 ComposeAction::Custom(prompt) => prompt.as_str(),
578 };
579 format!("{ask}\n\n{draft}")
580}
581
457fn demo_rewrite(text: &str) -> String {
582fn demo_rewrite(text: &str) -> String {
458 let trimmed = text.trim().trim_end_matches(['.', '!', '?']);
583 let trimmed = text.trim().trim_end_matches(['.', '!', '?']);
459 let mut characters = trimmed.chars();
584 let mut characters = trimmed.chars();
crates/app/src/views/composer/rule.rs +4 −1
@@ -54,7 +54,10 @@ impl Composer {
54 54 let token = token(self.table_counter);
55 55 self.input.update(cx, |state, cx| {
56 56 let selection = state.selected_range();
57 if state.replace_range_with_token(line, token, window, cx).is_ok() {
57 if state
58 .replace_range_with_token(line, token, window, cx)
59 .is_ok()
60 {
58 61 state.set_selected_range(selection, cx);
59 62 }
60 63 });
@@ -54,7 +54,10 @@ impl Composer {
54 let token = token(self.table_counter);
54 let token = token(self.table_counter);
55 self.input.update(cx, |state, cx| {
55 self.input.update(cx, |state, cx| {
56 let selection = state.selected_range();
56 let selection = state.selected_range();
57 if state.replace_range_with_token(line, token, window, cx).is_ok() {
57 if state
58 .replace_range_with_token(line, token, window, cx)
59 .is_ok()
60 {
58 state.set_selected_range(selection, cx);
61 state.set_selected_range(selection, cx);
59 }
62 }
60 });
63 });
crates/app/src/views/composer/slash.rs +17 −8
@@ -10,8 +10,8 @@ use teams_core::{ForcedAvailability, ForcedKind};
10 10 use super::Composer;
11 11 use crate::theme::{self, ElevatedSurface as _};
12 12 use crate::views::actions::OpenSwitcher;
13 use crate::views::shortcuts::{OpenSettings, ShowShortcuts};
14 13 use crate::views::chat_menu::confirm_leave;
14 use crate::views::shortcuts::{OpenSettings, ShowShortcuts};
15 15
16 16 const GROUP_KIND: &str = "group";
17 17 const WIDTH: f32 = 380.;
@@ -86,9 +86,7 @@ impl SlashCommand {
86 86 SlashCommand::Presence(ForcedKind::Away) => "Set your status to away",
87 87 SlashCommand::Presence(ForcedKind::BeRightBack) => "Set your status to be right back",
88 88 SlashCommand::Presence(ForcedKind::Busy) => "Set your status to busy",
89 SlashCommand::Presence(ForcedKind::DoNotDisturb) => {
90 "Set your status to do not disturb"
91 }
89 SlashCommand::Presence(ForcedKind::DoNotDisturb) => "Set your status to do not disturb",
92 90 SlashCommand::Presence(ForcedKind::Offline) => "Set your status to offline",
93 91 SlashCommand::ResetPresence => "Reset your presence status",
94 92 SlashCommand::Goto => "Go right to a chat or channel",
@@ -451,7 +449,10 @@ mod tests {
451 449
452 450 #[test]
453 451 fn the_list_is_sorted_by_name_like_teams() {
454 let names: Vec<&str> = matching("", chat()).iter().map(|command| command.name()).collect();
452 let names: Vec<&str> = matching("", chat())
453 .iter()
454 .map(|command| command.name())
455 .collect();
455 456 let mut sorted = names.clone();
456 457 sorted.sort_unstable();
457 458 assert_eq!(names, sorted);
@@ -476,14 +477,22 @@ mod tests {
476 477 muted: true,
477 478 notes: false,
478 479 };
479 let names: Vec<&str> = matching("", group_muted).iter().map(|command| command.name()).collect();
480 assert!(names.contains(&"leavechat") && names.contains(&"unmute") && !names.contains(&"mute"));
480 let names: Vec<&str> = matching("", group_muted)
481 .iter()
482 .map(|command| command.name())
483 .collect();
484 assert!(
485 names.contains(&"leavechat") && names.contains(&"unmute") && !names.contains(&"mute")
486 );
481 487 let notes = SlashContext {
482 488 chat: true,
483 489 notes: true,
484 490 ..SlashContext::default()
485 491 };
486 let names: Vec<&str> = matching("", notes).iter().map(|command| command.name()).collect();
492 let names: Vec<&str> = matching("", notes)
493 .iter()
494 .map(|command| command.name())
495 .collect();
487 496 assert!(!names.contains(&"mute") && !names.contains(&"schedulemessage"));
488 497 let channel: Vec<&str> = matching("", SlashContext::default())
489 498 .iter()
@@ -10,8 +10,8 @@ use teams_core::{ForcedAvailability, ForcedKind};
10use super::Composer;
10use super::Composer;
11use crate::theme::{self, ElevatedSurface as _};
11use crate::theme::{self, ElevatedSurface as _};
12use crate::views::actions::OpenSwitcher;
12use crate::views::actions::OpenSwitcher;
13use crate::views::shortcuts::{OpenSettings, ShowShortcuts};
14use crate::views::chat_menu::confirm_leave;
13use crate::views::chat_menu::confirm_leave;
14use crate::views::shortcuts::{OpenSettings, ShowShortcuts};
15
15
16const GROUP_KIND: &str = "group";
16const GROUP_KIND: &str = "group";
17const WIDTH: f32 = 380.;
17const WIDTH: f32 = 380.;
@@ -86,9 +86,7 @@ impl SlashCommand {
86 SlashCommand::Presence(ForcedKind::Away) => "Set your status to away",
86 SlashCommand::Presence(ForcedKind::Away) => "Set your status to away",
87 SlashCommand::Presence(ForcedKind::BeRightBack) => "Set your status to be right back",
87 SlashCommand::Presence(ForcedKind::BeRightBack) => "Set your status to be right back",
88 SlashCommand::Presence(ForcedKind::Busy) => "Set your status to busy",
88 SlashCommand::Presence(ForcedKind::Busy) => "Set your status to busy",
89 SlashCommand::Presence(ForcedKind::DoNotDisturb) => {
89 SlashCommand::Presence(ForcedKind::DoNotDisturb) => "Set your status to do not disturb",
90 "Set your status to do not disturb"
91 }
92 SlashCommand::Presence(ForcedKind::Offline) => "Set your status to offline",
90 SlashCommand::Presence(ForcedKind::Offline) => "Set your status to offline",
93 SlashCommand::ResetPresence => "Reset your presence status",
91 SlashCommand::ResetPresence => "Reset your presence status",
94 SlashCommand::Goto => "Go right to a chat or channel",
92 SlashCommand::Goto => "Go right to a chat or channel",
@@ -451,7 +449,10 @@ mod tests {
451
449
452 #[test]
450 #[test]
453 fn the_list_is_sorted_by_name_like_teams() {
451 fn the_list_is_sorted_by_name_like_teams() {
454 let names: Vec<&str> = matching("", chat()).iter().map(|command| command.name()).collect();
452 let names: Vec<&str> = matching("", chat())
453 .iter()
454 .map(|command| command.name())
455 .collect();
455 let mut sorted = names.clone();
456 let mut sorted = names.clone();
456 sorted.sort_unstable();
457 sorted.sort_unstable();
457 assert_eq!(names, sorted);
458 assert_eq!(names, sorted);
@@ -476,14 +477,22 @@ mod tests {
476 muted: true,
477 muted: true,
477 notes: false,
478 notes: false,
478 };
479 };
479 let names: Vec<&str> = matching("", group_muted).iter().map(|command| command.name()).collect();
480 let names: Vec<&str> = matching("", group_muted)
480 assert!(names.contains(&"leavechat") && names.contains(&"unmute") && !names.contains(&"mute"));
481 .iter()
482 .map(|command| command.name())
483 .collect();
484 assert!(
485 names.contains(&"leavechat") && names.contains(&"unmute") && !names.contains(&"mute")
486 );
481 let notes = SlashContext {
487 let notes = SlashContext {
482 chat: true,
488 chat: true,
483 notes: true,
489 notes: true,
484 ..SlashContext::default()
490 ..SlashContext::default()
485 };
491 };
486 let names: Vec<&str> = matching("", notes).iter().map(|command| command.name()).collect();
492 let names: Vec<&str> = matching("", notes)
493 .iter()
494 .map(|command| command.name())
495 .collect();
487 assert!(!names.contains(&"mute") && !names.contains(&"schedulemessage"));
496 assert!(!names.contains(&"mute") && !names.contains(&"schedulemessage"));
488 let channel: Vec<&str> = matching("", SlashContext::default())
497 let channel: Vec<&str> = matching("", SlashContext::default())
489 .iter()
498 .iter()
crates/app/src/views/conversation.rs +148 −245
@@ -1,5 +1,5 @@
1 1 use std::cell::{Cell, RefCell};
2 use std::collections::{HashMap, HashSet, VecDeque};
2 use std::collections::{HashMap, HashSet};
3 3 use std::path::{Path, PathBuf};
4 4 use std::rc::Rc;
5 5 use std::time::{Duration, Instant};
@@ -36,8 +36,6 @@ mod forward_select;
36 36 pub use forward_select::{
37 37 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
38 38 };
39 mod absence;
40 mod appear_tracker;
41 39 mod jump;
42 40 mod notes_space;
43 41 mod pins;
@@ -61,7 +59,6 @@ use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPrevi
61 59 use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
62 60 use super::group_name::{GroupNameSlot, group_name_button};
63 61 use super::message_actions::{Action, DelegateEntry, MessageMenu};
64 use super::message_context_menu::OpenContextMenu;
65 62 use super::message_row::{
66 63 AVATAR_GAP, AVATAR_SIZE, JUMP_HIGHLIGHT_PERIOD, render_message_row, render_skeleton_row,
67 64 };
@@ -93,7 +90,7 @@ use crate::people::{local_names, resolve_names};
93 90 use crate::reaction_model::UNKNOWN_REACTOR;
94 91 use crate::read_state::{ReadTrigger, missed_before_fetch, plan_read};
95 92 use crate::rows::{
96 Delivery, LocalImage, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
93 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
97 94 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
98 95 forward_sender_ids, has_own_reaction, message_draft, message_text, own_reaction_glyph,
99 96 place_local_rows, placeholder_rows, reaction_glyph, reply_excerpt, set_own_reaction,
@@ -116,7 +113,6 @@ pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
116 113 pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
117 114 pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
118 115 pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed";
119 const SENT_PREVIEWS_KEPT: usize = 16;
120 116 const POSTED_WITHOUT_BANNER: &str = "Posted, but Teams did not take the banner.";
121 117 const QUIET_RETRY_DELAYS: [Duration; 3] = [
122 118 Duration::from_secs(2),
@@ -146,13 +142,7 @@ const SLOW_AFTER: Duration = Duration::from_secs(8);
146 142 const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
147 143 const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
148 144 const PROGRESS_BAR_WIDTH: f32 = 0.35;
149 const TYPING_BUBBLE_HEIGHT: f32 = 28.;
150 const TYPING_BUBBLE_PADDING: f32 = 12.;
151 const TYPING_SIDE_INSET: f32 = 20.;
152 const COMPOSER_TOP_GAP: f32 = 16.;
153 const TYPING_TOP_GAP: f32 = 16.;
154 const TYPING_BOTTOM_GAP: f32 = 8.;
155 pub const TYPING_TAG: &str = "shell/islands/main/typing";
145 const TYPING_LINE_HEIGHT: f32 = 22.;
156 146 const TYPING_DOT_SIZE: f32 = 5.;
157 147 const TYPING_DOT_COUNT: usize = 3;
158 148 const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
@@ -245,13 +235,11 @@ pub struct ConversationView {
245 235 saving_edits: HashSet<String>,
246 236 pending_counter: usize,
247 237 pending_outgoing: HashMap<String, Outgoing>,
248 sent_previews: VecDeque<(String, Vec<LocalImage>)>,
249 238 pending_reactions: PendingReactions,
250 239 downloads: Downloads,
251 240 hovered_message: Option<String>,
252 241 toolbar_hovered: Option<String>,
253 context_menu: Option<OpenContextMenu>,
254 context_serial: u64,
242 toolbar_opened: Option<String>,
255 243 timeline_bounds: TimelineBounds,
256 244 header_width: Rc<Cell<f32>>,
257 245 toolbar_pinned: Option<String>,
@@ -289,7 +277,6 @@ pub struct ConversationView {
289 277 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
290 278 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
291 279 receipt_fade: receipt_fade::ReceiptFade,
292 appear_tracker: appear_tracker::AppearTracker,
293 280 find_panel: Option<Entity<FindPanel>>,
294 281 find_subscription: Option<Subscription>,
295 282 group_name: GroupNameSlot,
@@ -516,6 +503,10 @@ impl ConversationView {
516 503 Self::build(app, None, window, cx)
517 504 }
518 505
506 pub fn timeline_bounds(&self) -> TimelineBounds {
507 self.timeline_bounds.clone()
508 }
509
519 510 pub fn pinned_to(
520 511 app: Entity<AppState>,
521 512 selection: Selection,
@@ -565,7 +556,6 @@ impl ConversationView {
565 556 cx.observe_keystrokes(|this, event, _, cx| {
566 557 if event.keystroke.key == "escape" {
567 558 this.close_reaction_details(cx);
568 this.close_context_menu(false, cx);
569 559 }
570 560 }),
571 561 ];
@@ -600,13 +590,11 @@ impl ConversationView {
600 590 saving_edits: HashSet::new(),
601 591 pending_counter: 0,
602 592 pending_outgoing: HashMap::new(),
603 sent_previews: VecDeque::new(),
604 593 pending_reactions: HashMap::new(),
605 594 downloads: Downloads::default(),
606 595 hovered_message: None,
607 596 toolbar_hovered: None,
608 context_menu: None,
609 context_serial: 0,
597 toolbar_opened: None,
610 598 timeline_bounds: TimelineBounds::default(),
611 599 header_width: Rc::default(),
612 600 toolbar_pinned: None,
@@ -644,7 +632,6 @@ impl ConversationView {
644 632 agent_runs: Rc::new(RefCell::new(HashMap::new())),
645 633 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
646 634 receipt_fade: receipt_fade::ReceiptFade::default(),
647 appear_tracker: appear_tracker::AppearTracker::default(),
648 635 find_panel: None,
649 636 find_subscription: None,
650 637 _subscriptions: subscriptions,
@@ -661,11 +648,6 @@ impl ConversationView {
661 648 }
662 649
663 650 #[cfg_attr(not(windows), allow(dead_code))]
664 pub fn opening_title(&self) -> Option<String> {
665 let loading = self.rows.borrow().iter().any(|row| matches!(row, Row::Skeleton(_)));
666 self.current.as_ref().filter(|_| loading).map(|current| current.title.clone())
667 }
668
669 651 pub fn send_in_flight(&self) -> bool {
670 652 self.pending
671 653 .iter()
@@ -880,10 +862,7 @@ impl ConversationView {
880 862 }
881 863 }
882 864
883 fn render_typing_line(&self, cx: &App) -> Option<AnyElement> {
884 if self.in_feed() {
885 return None;
886 }
865 fn render_typing_line(&self, cx: &App) -> impl IntoElement {
887 866 let app = self.app.read(cx);
888 867 let faces = self
889 868 .current
@@ -891,17 +870,18 @@ impl ConversationView {
891 870 .filter(|_| !self.draft_active)
892 871 .map(|current| app.typing.faces(current.selection.conversation_id()))
893 872 .unwrap_or_default();
894 if faces.is_empty() {
895 return None;
896 }
897 873 let tooltip_text = typing_tooltip(
898 874 &faces
899 875 .iter()
900 876 .map(|face| face.name.clone())
901 877 .collect::<Vec<_>>(),
902 878 );
879 let flat = matches!(
880 self.current.as_ref().map(|current| &current.mode),
881 Some(ViewMode::Flat)
882 );
903 883 let faces_element = match faces.as_slice() {
904 [face] => person_avatar(
884 [face] if flat => person_avatar(
905 885 &app.directory,
906 886 face.user_id.as_deref(),
907 887 &face.name,
@@ -909,33 +889,27 @@ impl ConversationView {
909 889 ),
910 890 _ => member_stack(&app.directory, &faces, faces.len(), true).into_any_element(),
911 891 };
912 Some(
913 h_flex()
914 .debug_selector(|| TYPING_TAG.into())
915 .h(px(TYPING_BUBBLE_HEIGHT))
916 .px(px(TYPING_SIDE_INSET))
917 .gap(px(AVATAR_GAP))
918 .items_center()
919 .child(
892 h_flex()
893 .h(px(if flat {
894 AVATAR_SIZE + 4.
895 } else {
896 TYPING_LINE_HEIGHT
897 }))
898 .flex_none()
899 .px(px(20.))
900 .gap(px(if flat { AVATAR_GAP } else { 6. }))
901 .items_center()
902 .when(!faces.is_empty(), |line| {
903 line.child(
920 904 div()
921 905 .id("typing-faces")
922 .flex_none()
923 906 .tooltip(move |window, cx| {
924 907 Tooltip::new(tooltip_text.clone()).build(window, cx)
925 908 })
926 909 .child(faces_element),
927 910 )
928 .child(
929 h_flex()
930 .h_full()
931 .px(px(TYPING_BUBBLE_PADDING))
932 .items_center()
933 .rounded_full()
934 .bg(theme::surface_raised())
935 .child(typing_dots()),
936 )
937 .into_any_element(),
938 )
911 .child(typing_dots())
912 })
939 913 }
940 914
941 915 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
@@ -962,7 +936,6 @@ impl ConversationView {
962 936 crate::inline_video::stop(cx);
963 937 self.toolbar_pinned = None;
964 938 self.toolbar_suppressed = None;
965 self.context_menu = None;
966 939 self.agent_layouts.clear();
967 940 self.agent_runs.borrow_mut().clear();
968 941 self.reaction_proposals.borrow_mut().clear();
@@ -1042,9 +1015,8 @@ impl ConversationView {
1042 1015 self.hovered_message = None;
1043 1016 self.sync_generation += 1;
1044 1017 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
1045 self.composer.update(cx, |composer, cx| {
1046 composer.set_conversation("", window, cx)
1047 });
1018 self.composer
1019 .update(cx, |composer, cx| composer.set_conversation("", window, cx));
1048 1020 self.on_draft_changed(window, cx);
1049 1021 self.rebuild(true, cx);
1050 1022 }
@@ -1288,11 +1260,7 @@ impl ConversationView {
1288 1260 if refresh_replies {
1289 1261 self.refresh_thread(row_key.clone(), cx);
1290 1262 }
1291 let shown_alone = self
1292 .rows
1293 .borrow()
1294 .iter()
1295 .any(|row| row.key() == message_id);
1263 let shown_alone = self.rows.borrow().iter().any(|row| row.key() == message_id);
1296 1264 if shown_alone {
1297 1265 self.reveal_row(message_id.to_owned(), message_id.to_owned(), cx);
1298 1266 return;
@@ -1314,7 +1282,8 @@ impl ConversationView {
1314 1282 }
1315 1283 self.fetched_jump = Some(message_id.to_owned());
1316 1284 let conversation_id = current.selection.conversation_id().to_owned();
1317 let (task_conversation_id, task_message_id) = (conversation_id.clone(), message_id.to_owned());
1285 let (task_conversation_id, task_message_id) =
1286 (conversation_id.clone(), message_id.to_owned());
1318 1287 let receiver = runtime::spawn(async move {
1319 1288 engine
1320 1289 .open_post(&task_conversation_id, &task_message_id)
@@ -1358,9 +1327,10 @@ impl ConversationView {
1358 1327 if self.conversation_id().as_deref() != Some(conversation_id) {
1359 1328 return;
1360 1329 }
1361 let still_waiting = self.current.as_ref().is_some_and(|current| {
1362 current.mode == ViewMode::Thread(message_id.to_owned())
1363 });
1330 let still_waiting = self
1331 .current
1332 .as_ref()
1333 .is_some_and(|current| current.mode == ViewMode::Thread(message_id.to_owned()));
1364 1334 match result {
1365 1335 Ok(Ok(Some(post))) if still_waiting => {
1366 1336 self.jump_to_post(conversation_id, message_id, !post.replies_loaded, cx)
@@ -1646,11 +1616,9 @@ impl ConversationView {
1646 1616 let app = self.app.read(cx);
1647 1617 let (user_id, member_name, notes) = match &current.selection {
1648 1618 Selection::Chat(chat_id)
1649 if app
1650 .sidebar
1651 .chats
1652 .iter()
1653 .any(|chat| &chat.id == chat_id && chat.kind.eq_ignore_ascii_case("meeting")) =>
1619 if app.sidebar.chats.iter().any(|chat| {
1620 &chat.id == chat_id && chat.kind.eq_ignore_ascii_case("meeting")
1621 }) =>
1654 1622 {
1655 1623 return None;
1656 1624 }
@@ -1790,11 +1758,9 @@ impl ConversationView {
1790 1758 current.loaded_count = records.len();
1791 1759 }
1792 1760 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1793 let placeholders = records.is_empty()
1794 && (loading_post || current.sync.messages && thread_root.is_none());
1761 let placeholders =
1762 records.is_empty() && (loading_post || current.sync.messages && thread_root.is_none());
1795 1763 let in_feed = current.mode == ViewMode::ThreadList;
1796 let appear_scope = format!("{conversation_id}/{:?}", current.mode);
1797 let appear_live = !placeholders && !in_feed && window.is_none() && !current.sync.messages;
1798 1764 let mut rows = match &current.mode {
1799 1765 _ if placeholders => {
1800 1766 current.has_older = false;
@@ -1851,9 +1817,6 @@ impl ConversationView {
1851 1817 {
1852 1818 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
1853 1819 message.receipt_label = receipt_labels.get(&message.key).cloned();
1854 if let Some((_, previews)) = self.sent_previews.iter().find(|(key, _)| key == &message.key) {
1855 message.sent_previews = previews.clone();
1856 }
1857 1820 }
1858 1821 }
1859 1822 if let Some(read_until) = posts_new_after.filter(|_| in_feed) {
@@ -1873,7 +1836,6 @@ impl ConversationView {
1873 1836 }
1874 1837 }
1875 1838 assign_series(&mut rows);
1876 self.track_appearing(&rows, &appear_scope, appear_live, reset);
1877 1839 self.apply_rows(rows, reset, cx);
1878 1840 if self.is_detached() {
1879 1841 self.scroller
@@ -2201,7 +2163,11 @@ impl ConversationView {
2201 2163 for receipt in receipts.values_mut() {
2202 2164 *receipt = shown_receipt(&settings, *receipt);
2203 2165 }
2204 labels.retain(|key, _| receipts.get(key).is_some_and(|receipt| *receipt != Receipt::Hidden));
2166 labels.retain(|key, _| {
2167 receipts
2168 .get(key)
2169 .is_some_and(|receipt| *receipt != Receipt::Hidden)
2170 });
2205 2171 (receipts, labels)
2206 2172 }
2207 2173
@@ -2227,7 +2193,11 @@ impl ConversationView {
2227 2193 let labels = receipts
2228 2194 .iter()
2229 2195 .map(|(key, receipt)| {
2230 let label = if *receipt == Receipt::Read { "Seen" } else { "Sent" };
2196 let label = if *receipt == Receipt::Read {
2197 "Seen"
2198 } else {
2199 "Sent"
2200 };
2231 2201 (key.clone(), label.to_owned())
2232 2202 })
2233 2203 .collect();
@@ -2263,29 +2233,6 @@ impl ConversationView {
2263 2233 .apply(&conversation_id, settled, receipts, Instant::now())
2264 2234 }
2265 2235
2266 fn track_appearing(&mut self, rows: &[Row], scope: &str, live: bool, reset: bool) {
2267 let sending: HashSet<&str> = self.pending.iter().map(|row| row.key.as_str()).collect();
2268 let candidates: Vec<appear_tracker::Candidate> = rows
2269 .iter()
2270 .filter_map(|row| match row {
2271 Row::Message(message) => Some(appear_tracker::Candidate {
2272 key: &message.key,
2273 own: message.own,
2274 origin: if sending.contains(message.key.as_str()) {
2275 appear_tracker::Origin::Sending
2276 } else if message.key.starts_with(SCHEDULED_KEY_PREFIX) {
2277 appear_tracker::Origin::Scheduled
2278 } else {
2279 appear_tracker::Origin::Server
2280 },
2281 }),
2282 _ => None,
2283 })
2284 .collect();
2285 self.appear_tracker
2286 .apply(scope, live, reset, &candidates, Instant::now());
2287 }
2288
2289 2236 fn schedule_fade_end(&mut self, cx: &mut Context<Self>) {
2290 2237 cx.spawn(async move |this, cx| {
2291 2238 cx.background_executor()
@@ -2325,6 +2272,9 @@ impl ConversationView {
2325 2272 return;
2326 2273 }
2327 2274 let state = self.app.read(cx);
2275 if state.viewing_call() && !self.pinned {
2276 return;
2277 }
2328 2278 let Some(selection) = self.current.as_ref().map(|c| c.selection.clone()) else {
2329 2279 return;
2330 2280 };
@@ -2405,7 +2355,10 @@ impl ConversationView {
2405 2355 current.loading_older = false;
2406 2356 match result {
2407 2357 Ok(Ok(records)) if !records.is_empty() => {
2408 app_base::diagnostics::record(&format!("chat: older page, {} messages", records.len()));
2358 app_base::diagnostics::record(&format!(
2359 "chat: older page, {} messages",
2360 records.len()
2361 ));
2409 2362 current.loaded_limit = current.loaded_count + records.len();
2410 2363 self.older_anchor = self
2411 2364 .rows
@@ -2419,7 +2372,10 @@ impl ConversationView {
2419 2372 current.older_blocked = true;
2420 2373 }
2421 2374 Ok(Err(error)) => {
2422 app_base::diagnostics::record(&format!("chat: older page failed: {}", short_error(&error)));
2375 app_base::diagnostics::record(&format!(
2376 "chat: older page failed: {}",
2377 short_error(&error)
2378 ));
2423 2379 current.older_blocked = true;
2424 2380 self.notice = Some(format!(
2425 2381 "Could not load older messages: {}",
@@ -2575,10 +2531,8 @@ impl ConversationView {
2575 2531 self.notice = None;
2576 2532 self.rebuild(false, cx);
2577 2533 if self.in_feed() {
2578 if thread_root_id.is_none() {
2579 self.scroller
2580 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
2581 }
2534 self.scroller
2535 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
2582 2536 } else {
2583 2537 self.scroller
2584 2538 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
@@ -2874,9 +2828,16 @@ impl ConversationView {
2874 2828 } else if target.as_deref() == Some(key) {
2875 2829 *target = None;
2876 2830 }
2831 if !hovered && matches!(slot, HoverSlot::Row) && self.toolbar_opened.as_deref() == Some(key)
2832 {
2833 self.toolbar_opened = None;
2834 }
2877 2835 if hovered
2878 2836 && matches!(slot, HoverSlot::Row)
2879 && self.toolbar_hovered.as_deref().is_some_and(|toolbar| toolbar != key)
2837 && self
2838 .toolbar_hovered
2839 .as_deref()
2840 .is_some_and(|toolbar| toolbar != key)
2880 2841 {
2881 2842 self.toolbar_hovered = None;
2882 2843 }
@@ -2907,9 +2868,11 @@ impl ConversationView {
2907 2868 }
2908 2869
2909 2870 fn toolbar_visible(&self, key: &str, cx: &App) -> bool {
2910 let row_trigger = (!self.app.read(cx).actions_on_right_click)
2911 .then_some(self.hovered_message.as_deref())
2912 .flatten();
2871 let row_trigger = if self.app.read(cx).actions_on_right_click {
2872 self.toolbar_opened.as_deref()
2873 } else {
2874 self.hovered_message.as_deref()
2875 };
2913 2876 self.toolbar_suppressed.as_deref() != Some(key)
2914 2877 && self
2915 2878 .toolbar_pinned
@@ -2919,24 +2882,9 @@ impl ConversationView {
2919 2882 == Some(key)
2920 2883 }
2921 2884
2922 pub(crate) fn context_menu_for(&self, key: &str) -> Option<OpenContextMenu> {
2923 self.context_menu.clone().filter(|open| open.key == key)
2924 }
2925
2926 fn open_context_menu(&mut self, key: &str, position: Point<Pixels>, cx: &mut Context<Self>) {
2927 self.context_serial += 1;
2928 self.context_menu = Some(OpenContextMenu::new(key, position, self.context_serial));
2929 cx.notify();
2930 }
2931
2932 fn close_context_menu(&mut self, from_outside: bool, cx: &mut Context<Self>) {
2933 let Some(open) = &self.context_menu else {
2934 return;
2935 };
2936 if from_outside && self.toolbar_pinned.as_deref() == Some(open.key.as_str()) {
2937 return;
2938 }
2939 self.context_menu = None;
2885 fn open_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
2886 self.toolbar_opened = Some(key.to_owned());
2887 self.toolbar_suppressed = None;
2940 2888 cx.notify();
2941 2889 }
2942 2890
@@ -3540,9 +3488,6 @@ impl ConversationView {
3540 3488 if matches!(result, Ok(Ok(Delivered::WithoutBanner))) {
3541 3489 self.notice = Some(POSTED_WITHOUT_BANNER.to_owned());
3542 3490 }
3543 if let Ok(Ok(Delivered::Complete { message_id: Some(message_id) })) = &result {
3544 self.keep_sent_previews(key, message_id);
3545 }
3546 3491 let failure = match result {
3547 3492 Ok(Ok(_)) => None,
3548 3493 Ok(Err(error)) => Some(short_error(&error)),
@@ -3568,19 +3513,6 @@ impl ConversationView {
3568 3513 self.rebuild(false, cx);
3569 3514 }
3570 3515
3571 fn keep_sent_previews(&mut self, pending_key: &str, message_id: &str) {
3572 let Some(row) = self.pending.iter().find(|row| row.key == pending_key) else {
3573 return;
3574 };
3575 if row.local_images.is_empty() {
3576 return;
3577 }
3578 self.sent_previews.push_back((message_id.to_owned(), row.local_images.clone()));
3579 if self.sent_previews.len() > SENT_PREVIEWS_KEPT {
3580 self.sent_previews.pop_front();
3581 }
3582 }
3583
3584 3516 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
3585 3517 let target = match self.current.as_ref().map(|current| &current.selection) {
3586 3518 Some(Selection::Chat(_)) => DropTarget::Chat,
@@ -3813,7 +3745,12 @@ impl ConversationView {
3813 3745 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3814 3746 })
3815 3747 {
3816 rename = Some(group_name_button(&self.app, &self.group_name, chat_id, &chat.title));
3748 rename = Some(group_name_button(
3749 &self.app,
3750 &self.group_name,
3751 chat_id,
3752 &chat.title,
3753 ));
3817 3754 }
3818 3755 if chat.title.trim().is_empty() {
3819 3756 names_title = Some(chat_header_actions::group_title(directory, &faces));
@@ -3845,9 +3782,12 @@ impl ConversationView {
3845 3782 .avatar(&teams_core::team_avatar_key(&entry.team.id))
3846 3783 });
3847 3784 lead = Some(team_avatar(photo, name, key, 36., 9.));
3848 if let Some(channel) = team
3849 .and_then(|entry| entry.channels.iter().find(|channel| &channel.id == channel_id))
3850 {
3785 if let Some(channel) = team.and_then(|entry| {
3786 entry
3787 .channels
3788 .iter()
3789 .find(|channel| &channel.id == channel_id)
3790 }) {
3851 3791 header_title = channel.name.clone();
3852 3792 }
3853 3793 }
@@ -3900,7 +3840,12 @@ impl ConversationView {
3900 3840 } else if loading_window {
3901 3841 subline = "Loading message ...".to_owned();
3902 3842 } else if sync.shown_at.is_some() {
3903 subline = if sync.slow { "Taking longer than usual ..." } else { "Loading messages ..." }.to_owned();
3843 subline = if sync.slow {
3844 "Taking longer than usual ..."
3845 } else {
3846 "Loading messages ..."
3847 }
3848 .to_owned();
3904 3849 }
3905 3850 let inline_tabs = tabs.map(|tabs| h_flex().h_full().flex_1().child(tabs));
3906 3851 let overflow = self.header_overflows();
@@ -3961,7 +3906,9 @@ impl ConversationView {
3961 3906 .children(self.chat_find_button(cx))
3962 3907 })
3963 3908 .children(self.channel_find_button(cx))
3964 .when(!overflow, |header| header.children(self.channel_details_button(cx)))
3909 .when(!overflow, |header| {
3910 header.children(self.channel_details_button(cx))
3911 })
3965 3912 .children(self.channel_more_button(cx))
3966 3913 .children(self.chat_more_button(overflow, cx))
3967 3914 .children(self.pop_in_button(current))
@@ -4045,7 +3992,6 @@ impl Render for ConversationView {
4045 3992 agent_runs: self.agent_runs.clone(),
4046 3993 reaction_proposals: self.reaction_proposals.clone(),
4047 3994 forward_selection: forward_selection.clone(),
4048 appearing: self.appear_tracker.entering(Instant::now()),
4049 3995 };
4050 3996 let pin_banner = self
4051 3997 .render_pin_banner(cx)
@@ -4053,15 +3999,6 @@ impl Render for ConversationView {
4053 3999 let timeline_top_inset = pin_banner_inset(pin_banner.is_some());
4054 4000 let comfy = self.app.read(cx).account_chat_settings().message_density
4055 4001 != teams_core::MessageDensity::Compact;
4056 let typing_line = self.render_typing_line(cx);
4057 let typing_offset = {
4058 let scroller = self.scroller.read(cx);
4059 let last_row = scroller.item_count().checked_sub(1);
4060 typing_bottom_offset(
4061 self.timeline_bounds.get(),
4062 last_row.and_then(|index| scroller.item_bounds(index)),
4063 )
4064 };
4065 4002 let scroller = MessageScroller::new(
4066 4003 "messages",
4067 4004 self.scroller.clone(),
@@ -4160,7 +4097,6 @@ impl Render for ConversationView {
4160 4097 },
4161 4098 )
4162 4099 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
4163 .wheel_mask(false)
4164 4100 .jump_button(!in_feed)
4165 4101 .force_jump_button(detached)
4166 4102 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
@@ -4178,13 +4114,7 @@ impl Render for ConversationView {
4178 4114 view.update(cx, |this, cx| this.leave_detached(cx)).ok();
4179 4115 })
4180 4116 })
4181 .with_list_style(StyleRefinement::default().pb(px(if typing_line.is_some() {
4182 TYPING_TOP_GAP + TYPING_BUBBLE_HEIGHT + TYPING_BOTTOM_GAP
4183 } else if in_feed {
4184 0.
4185 } else {
4186 COMPOSER_TOP_GAP
4187 })))
4117 .with_bottom_fade(background)
4188 4118 .with_top_inset(timeline_top_inset);
4189 4119
4190 4120 root = match self.current.as_ref().filter(|_| !drafting) {
@@ -4282,14 +4212,6 @@ impl Render for ConversationView {
4282 4212 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
4283 4213 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
4284 4214 .child(body)
4285 .children(typing_line.map(|line| {
4286 div()
4287 .absolute()
4288 .left_0()
4289 .right_0()
4290 .bottom(px(typing_offset))
4291 .child(runway(line, comfy))
4292 }))
4293 4215 .when(feed_scrolled, |timeline| {
4294 4216 timeline.child(
4295 4217 edge_divider(FEED_EDGE_TAG)
@@ -4301,7 +4223,10 @@ impl Render for ConversationView {
4301 4223 })
4302 4224 .children(pin_banner.map(|banner| pin_banner_overlay(runway(banner, comfy)))),
4303 4225 )
4304 .children(self.render_draft_error(cx).map(|error| runway(error, comfy)))
4226 .children(
4227 self.render_draft_error(cx)
4228 .map(|error| runway(error, comfy)),
4229 )
4305 4230 .when(
4306 4231 !in_feed && !recap_active && !self.shared_active(),
4307 4232 |column| match &forward_selection {
@@ -4311,53 +4236,52 @@ impl Render for ConversationView {
4311 4236 None => column.child(runway(
4312 4237 v_flex()
4313 4238 .w_full()
4314 .children(self.render_absence_notice(cx))
4315 .children(self.render_proposal_card(cx).map(|card| {
4316 div().w_full().pb(px(COMPOSER_TOP_GAP)).child(card)
4317 }))
4239 .child(self.render_typing_line(cx))
4240 .children(self.render_proposal_card(cx))
4318 4241 .child(self.composer.clone()),
4319 4242 comfy,
4320 4243 )),
4321 4244 },
4322 4245 )
4323 4246 .child(self.render_drop_overlay(cx));
4324 let root = root.child(
4325 h_flex()
4326 .relative()
4327 .flex_1()
4328 .min_h_0()
4329 .w_full()
4330 .items_stretch()
4331 .child(content)
4332 .children(channel_details)
4333 .children(find_panel.map(|panel| {
4334 div()
4335 .h_full()
4336 .w(px(FIND_PANEL_WIDTH))
4337 .min_w_0()
4338 .flex_shrink(1.)
4339 .when(find_overlays, |slot| {
4340 slot.absolute().top_0().right_0().bottom_0().max_w_full()
4341 })
4342 .child(panel)
4343 })),
4344 )
4345 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
4346 if this.reaction_details.is_some() {
4347 this.close_reaction_details(cx);
4348 cx.stop_propagation();
4349 }
4350 }))
4351 .on_action(cx.listener(|this, _: &Escape, window, cx| {
4352 if this.draft_active {
4353 if this.draft.read(cx).has_focus(window, cx) {
4354 this.draft.update(cx, |draft, cx| draft.escape(cx));
4247 let root = root
4248 .child(
4249 h_flex()
4250 .relative()
4251 .flex_1()
4252 .min_h_0()
4253 .w_full()
4254 .items_stretch()
4255 .child(content)
4256 .children(channel_details)
4257 .children(find_panel.map(|panel| {
4258 div()
4259 .h_full()
4260 .w(px(FIND_PANEL_WIDTH))
4261 .min_w_0()
4262 .flex_shrink(1.)
4263 .when(find_overlays, |slot| {
4264 slot.absolute().top_0().right_0().bottom_0().max_w_full()
4265 })
4266 .child(panel)
4267 })),
4268 )
4269 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
4270 if this.reaction_details.is_some() {
4271 this.close_reaction_details(cx);
4272 cx.stop_propagation();
4355 4273 }
4356 } else if this.cancel_forward_selection(cx) {
4357 } else if !this.on_escape(window, cx) {
4358 cx.propagate();
4359 }
4360 }));
4274 }))
4275 .on_action(cx.listener(|this, _: &Escape, window, cx| {
4276 if this.draft_active {
4277 if this.draft.read(cx).has_focus(window, cx) {
4278 this.draft.update(cx, |draft, cx| draft.escape(cx));
4279 }
4280 } else if this.cancel_forward_selection(cx) {
4281 } else if !this.on_escape(window, cx) {
4282 cx.propagate();
4283 }
4284 }));
4361 4285 let root = root.child(crate::inline_video::sentinel());
4362 4286 match copilot_island {
4363 4287 Some(island) => h_flex()
@@ -4372,17 +4296,6 @@ impl Render for ConversationView {
4372 4296 }
4373 4297 }
4374 4298
4375 /// Right under the last row like one more message; once that row scrolls below the view it sticks above the composer.
4376 fn typing_bottom_offset(timeline: Option<Bounds<Pixels>>, last_row: Option<Bounds<Pixels>>) -> f32 {
4377 let (Some(timeline), Some(last_row)) = (timeline, last_row) else {
4378 return TYPING_BOTTOM_GAP;
4379 };
4380 let under_last_row = f32::from(timeline.bottom() - last_row.bottom())
4381 - TYPING_TOP_GAP
4382 - TYPING_BUBBLE_HEIGHT;
4383 under_last_row.max(TYPING_BOTTOM_GAP)
4384 }
4385
4386 4299 fn typing_dots() -> impl IntoElement {
4387 4300 h_flex()
4388 4301 .gap(px(3.))
@@ -4478,7 +4391,7 @@ fn runway(content: impl IntoElement, comfy: bool) -> AnyElement {
4478 4391 mod tests {
4479 4392 use std::sync::Arc;
4480 4393
4481 use super::{DropTarget, drop_overlay_text, typing_bottom_offset};
4394 use super::{DropTarget, drop_overlay_text};
4482 4395
4483 4396 use gpui_kit::test::TestWindowExt as _;
4484 4397 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
@@ -4612,14 +4525,4 @@ mod tests {
4612 4525 assert_eq!(state.selection, Some(crate::demo::first_selection()));
4613 4526 });
4614 4527 }
4615
4616 #[test]
4617 fn the_typing_bubble_follows_the_last_row_and_sticks_above_the_composer() {
4618 use gpui_kit::{Bounds, point, px, size};
4619 let timeline = Bounds::new(point(px(0.), px(100.)), size(px(800.), px(600.)));
4620 let row_ending_at = |bottom: f32| Some(Bounds::new(point(px(0.), px(bottom - 50.)), size(px(800.), px(50.))));
4621 assert_eq!(typing_bottom_offset(Some(timeline), row_ending_at(400.)), 256.);
4622 assert_eq!(typing_bottom_offset(Some(timeline), row_ending_at(900.)), 8.);
4623 assert_eq!(typing_bottom_offset(Some(timeline), None), 8.);
4624 }
4625 4528 }
@@ -1,5 +1,5 @@
1use std::cell::{Cell, RefCell};
1use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet, VecDeque};
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
4use std::rc::Rc;
5use std::time::{Duration, Instant};
5use std::time::{Duration, Instant};
@@ -36,8 +36,6 @@ mod forward_select;
36pub use forward_select::{
36pub use forward_select::{
37 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
37 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
38};
38};
39mod absence;
40mod appear_tracker;
41mod jump;
39mod jump;
42mod notes_space;
40mod notes_space;
43mod pins;
41mod pins;
@@ -61,7 +59,6 @@ use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPrevi
61use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
59use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
62use super::group_name::{GroupNameSlot, group_name_button};
60use super::group_name::{GroupNameSlot, group_name_button};
63use super::message_actions::{Action, DelegateEntry, MessageMenu};
61use super::message_actions::{Action, DelegateEntry, MessageMenu};
64use super::message_context_menu::OpenContextMenu;
65use super::message_row::{
62use super::message_row::{
66 AVATAR_GAP, AVATAR_SIZE, JUMP_HIGHLIGHT_PERIOD, render_message_row, render_skeleton_row,
63 AVATAR_GAP, AVATAR_SIZE, JUMP_HIGHLIGHT_PERIOD, render_message_row, render_skeleton_row,
67};
64};
@@ -93,7 +90,7 @@ use crate::people::{local_names, resolve_names};
93use crate::reaction_model::UNKNOWN_REACTOR;
90use crate::reaction_model::UNKNOWN_REACTOR;
94use crate::read_state::{ReadTrigger, missed_before_fetch, plan_read};
91use crate::read_state::{ReadTrigger, missed_before_fetch, plan_read};
95use crate::rows::{
92use crate::rows::{
96 Delivery, LocalImage, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
93 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
97 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
94 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
98 forward_sender_ids, has_own_reaction, message_draft, message_text, own_reaction_glyph,
95 forward_sender_ids, has_own_reaction, message_draft, message_text, own_reaction_glyph,
99 place_local_rows, placeholder_rows, reaction_glyph, reply_excerpt, set_own_reaction,
96 place_local_rows, placeholder_rows, reaction_glyph, reply_excerpt, set_own_reaction,
@@ -116,7 +113,6 @@ pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
116pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
113pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
117pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
114pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
118pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed";
115pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed";
119const SENT_PREVIEWS_KEPT: usize = 16;
120const POSTED_WITHOUT_BANNER: &str = "Posted, but Teams did not take the banner.";
116const POSTED_WITHOUT_BANNER: &str = "Posted, but Teams did not take the banner.";
121const QUIET_RETRY_DELAYS: [Duration; 3] = [
117const QUIET_RETRY_DELAYS: [Duration; 3] = [
122 Duration::from_secs(2),
118 Duration::from_secs(2),
@@ -146,13 +142,7 @@ const SLOW_AFTER: Duration = Duration::from_secs(8);
146const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
142const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
147const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
143const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
148const PROGRESS_BAR_WIDTH: f32 = 0.35;
144const PROGRESS_BAR_WIDTH: f32 = 0.35;
149const TYPING_BUBBLE_HEIGHT: f32 = 28.;
145const TYPING_LINE_HEIGHT: f32 = 22.;
150const TYPING_BUBBLE_PADDING: f32 = 12.;
151const TYPING_SIDE_INSET: f32 = 20.;
152const COMPOSER_TOP_GAP: f32 = 16.;
153const TYPING_TOP_GAP: f32 = 16.;
154const TYPING_BOTTOM_GAP: f32 = 8.;
155pub const TYPING_TAG: &str = "shell/islands/main/typing";
156const TYPING_DOT_SIZE: f32 = 5.;
146const TYPING_DOT_SIZE: f32 = 5.;
157const TYPING_DOT_COUNT: usize = 3;
147const TYPING_DOT_COUNT: usize = 3;
158const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
148const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
@@ -245,13 +235,11 @@ pub struct ConversationView {
245 saving_edits: HashSet<String>,
235 saving_edits: HashSet<String>,
246 pending_counter: usize,
236 pending_counter: usize,
247 pending_outgoing: HashMap<String, Outgoing>,
237 pending_outgoing: HashMap<String, Outgoing>,
248 sent_previews: VecDeque<(String, Vec<LocalImage>)>,
249 pending_reactions: PendingReactions,
238 pending_reactions: PendingReactions,
250 downloads: Downloads,
239 downloads: Downloads,
251 hovered_message: Option<String>,
240 hovered_message: Option<String>,
252 toolbar_hovered: Option<String>,
241 toolbar_hovered: Option<String>,
253 context_menu: Option<OpenContextMenu>,
242 toolbar_opened: Option<String>,
254 context_serial: u64,
255 timeline_bounds: TimelineBounds,
243 timeline_bounds: TimelineBounds,
256 header_width: Rc<Cell<f32>>,
244 header_width: Rc<Cell<f32>>,
257 toolbar_pinned: Option<String>,
245 toolbar_pinned: Option<String>,
@@ -289,7 +277,6 @@ pub struct ConversationView {
289 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
277 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
290 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
278 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
291 receipt_fade: receipt_fade::ReceiptFade,
279 receipt_fade: receipt_fade::ReceiptFade,
292 appear_tracker: appear_tracker::AppearTracker,
293 find_panel: Option<Entity<FindPanel>>,
280 find_panel: Option<Entity<FindPanel>>,
294 find_subscription: Option<Subscription>,
281 find_subscription: Option<Subscription>,
295 group_name: GroupNameSlot,
282 group_name: GroupNameSlot,
@@ -516,6 +503,10 @@ impl ConversationView {
516 Self::build(app, None, window, cx)
503 Self::build(app, None, window, cx)
517 }
504 }
518
505
506 pub fn timeline_bounds(&self) -> TimelineBounds {
507 self.timeline_bounds.clone()
508 }
509
519 pub fn pinned_to(
510 pub fn pinned_to(
520 app: Entity<AppState>,
511 app: Entity<AppState>,
521 selection: Selection,
512 selection: Selection,
@@ -565,7 +556,6 @@ impl ConversationView {
565 cx.observe_keystrokes(|this, event, _, cx| {
556 cx.observe_keystrokes(|this, event, _, cx| {
566 if event.keystroke.key == "escape" {
557 if event.keystroke.key == "escape" {
567 this.close_reaction_details(cx);
558 this.close_reaction_details(cx);
568 this.close_context_menu(false, cx);
569 }
559 }
570 }),
560 }),
571 ];
561 ];
@@ -600,13 +590,11 @@ impl ConversationView {
600 saving_edits: HashSet::new(),
590 saving_edits: HashSet::new(),
601 pending_counter: 0,
591 pending_counter: 0,
602 pending_outgoing: HashMap::new(),
592 pending_outgoing: HashMap::new(),
603 sent_previews: VecDeque::new(),
604 pending_reactions: HashMap::new(),
593 pending_reactions: HashMap::new(),
605 downloads: Downloads::default(),
594 downloads: Downloads::default(),
606 hovered_message: None,
595 hovered_message: None,
607 toolbar_hovered: None,
596 toolbar_hovered: None,
608 context_menu: None,
597 toolbar_opened: None,
609 context_serial: 0,
610 timeline_bounds: TimelineBounds::default(),
598 timeline_bounds: TimelineBounds::default(),
611 header_width: Rc::default(),
599 header_width: Rc::default(),
612 toolbar_pinned: None,
600 toolbar_pinned: None,
@@ -644,7 +632,6 @@ impl ConversationView {
644 agent_runs: Rc::new(RefCell::new(HashMap::new())),
632 agent_runs: Rc::new(RefCell::new(HashMap::new())),
645 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
633 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
646 receipt_fade: receipt_fade::ReceiptFade::default(),
634 receipt_fade: receipt_fade::ReceiptFade::default(),
647 appear_tracker: appear_tracker::AppearTracker::default(),
648 find_panel: None,
635 find_panel: None,
649 find_subscription: None,
636 find_subscription: None,
650 _subscriptions: subscriptions,
637 _subscriptions: subscriptions,
@@ -661,11 +648,6 @@ impl ConversationView {
661 }
648 }
662
649
663 #[cfg_attr(not(windows), allow(dead_code))]
650 #[cfg_attr(not(windows), allow(dead_code))]
664 pub fn opening_title(&self) -> Option<String> {
665 let loading = self.rows.borrow().iter().any(|row| matches!(row, Row::Skeleton(_)));
666 self.current.as_ref().filter(|_| loading).map(|current| current.title.clone())
667 }
668
669 pub fn send_in_flight(&self) -> bool {
651 pub fn send_in_flight(&self) -> bool {
670 self.pending
652 self.pending
671 .iter()
653 .iter()
@@ -880,10 +862,7 @@ impl ConversationView {
880 }
862 }
881 }
863 }
882
864
883 fn render_typing_line(&self, cx: &App) -> Option<AnyElement> {
865 fn render_typing_line(&self, cx: &App) -> impl IntoElement {
884 if self.in_feed() {
885 return None;
886 }
887 let app = self.app.read(cx);
866 let app = self.app.read(cx);
888 let faces = self
867 let faces = self
889 .current
868 .current
@@ -891,17 +870,18 @@ impl ConversationView {
891 .filter(|_| !self.draft_active)
870 .filter(|_| !self.draft_active)
892 .map(|current| app.typing.faces(current.selection.conversation_id()))
871 .map(|current| app.typing.faces(current.selection.conversation_id()))
893 .unwrap_or_default();
872 .unwrap_or_default();
894 if faces.is_empty() {
895 return None;
896 }
897 let tooltip_text = typing_tooltip(
873 let tooltip_text = typing_tooltip(
898 &faces
874 &faces
899 .iter()
875 .iter()
900 .map(|face| face.name.clone())
876 .map(|face| face.name.clone())
901 .collect::<Vec<_>>(),
877 .collect::<Vec<_>>(),
902 );
878 );
879 let flat = matches!(
880 self.current.as_ref().map(|current| &current.mode),
881 Some(ViewMode::Flat)
882 );
903 let faces_element = match faces.as_slice() {
883 let faces_element = match faces.as_slice() {
904 [face] => person_avatar(
884 [face] if flat => person_avatar(
905 &app.directory,
885 &app.directory,
906 face.user_id.as_deref(),
886 face.user_id.as_deref(),
907 &face.name,
887 &face.name,
@@ -909,33 +889,27 @@ impl ConversationView {
909 ),
889 ),
910 _ => member_stack(&app.directory, &faces, faces.len(), true).into_any_element(),
890 _ => member_stack(&app.directory, &faces, faces.len(), true).into_any_element(),
911 };
891 };
912 Some(
892 h_flex()
913 h_flex()
893 .h(px(if flat {
914 .debug_selector(|| TYPING_TAG.into())
894 AVATAR_SIZE + 4.
915 .h(px(TYPING_BUBBLE_HEIGHT))
895 } else {
916 .px(px(TYPING_SIDE_INSET))
896 TYPING_LINE_HEIGHT
917 .gap(px(AVATAR_GAP))
897 }))
918 .items_center()
898 .flex_none()
919 .child(
899 .px(px(20.))
900 .gap(px(if flat { AVATAR_GAP } else { 6. }))
901 .items_center()
902 .when(!faces.is_empty(), |line| {
903 line.child(
920 div()
904 div()
921 .id("typing-faces")
905 .id("typing-faces")
922 .flex_none()
923 .tooltip(move |window, cx| {
906 .tooltip(move |window, cx| {
924 Tooltip::new(tooltip_text.clone()).build(window, cx)
907 Tooltip::new(tooltip_text.clone()).build(window, cx)
925 })
908 })
926 .child(faces_element),
909 .child(faces_element),
927 )
910 )
928 .child(
911 .child(typing_dots())
929 h_flex()
912 })
930 .h_full()
931 .px(px(TYPING_BUBBLE_PADDING))
932 .items_center()
933 .rounded_full()
934 .bg(theme::surface_raised())
935 .child(typing_dots()),
936 )
937 .into_any_element(),
938 )
939 }
913 }
940
914
941 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
915 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
@@ -962,7 +936,6 @@ impl ConversationView {
962 crate::inline_video::stop(cx);
936 crate::inline_video::stop(cx);
963 self.toolbar_pinned = None;
937 self.toolbar_pinned = None;
964 self.toolbar_suppressed = None;
938 self.toolbar_suppressed = None;
965 self.context_menu = None;
966 self.agent_layouts.clear();
939 self.agent_layouts.clear();
967 self.agent_runs.borrow_mut().clear();
940 self.agent_runs.borrow_mut().clear();
968 self.reaction_proposals.borrow_mut().clear();
941 self.reaction_proposals.borrow_mut().clear();
@@ -1042,9 +1015,8 @@ impl ConversationView {
1042 self.hovered_message = None;
1015 self.hovered_message = None;
1043 self.sync_generation += 1;
1016 self.sync_generation += 1;
1044 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
1017 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
1045 self.composer.update(cx, |composer, cx| {
1018 self.composer
1046 composer.set_conversation("", window, cx)
1019 .update(cx, |composer, cx| composer.set_conversation("", window, cx));
1047 });
1048 self.on_draft_changed(window, cx);
1020 self.on_draft_changed(window, cx);
1049 self.rebuild(true, cx);
1021 self.rebuild(true, cx);
1050 }
1022 }
@@ -1288,11 +1260,7 @@ impl ConversationView {
1288 if refresh_replies {
1260 if refresh_replies {
1289 self.refresh_thread(row_key.clone(), cx);
1261 self.refresh_thread(row_key.clone(), cx);
1290 }
1262 }
1291 let shown_alone = self
1263 let shown_alone = self.rows.borrow().iter().any(|row| row.key() == message_id);
1292 .rows
1293 .borrow()
1294 .iter()
1295 .any(|row| row.key() == message_id);
1296 if shown_alone {
1264 if shown_alone {
1297 self.reveal_row(message_id.to_owned(), message_id.to_owned(), cx);
1265 self.reveal_row(message_id.to_owned(), message_id.to_owned(), cx);
1298 return;
1266 return;
@@ -1314,7 +1282,8 @@ impl ConversationView {
1314 }
1282 }
1315 self.fetched_jump = Some(message_id.to_owned());
1283 self.fetched_jump = Some(message_id.to_owned());
1316 let conversation_id = current.selection.conversation_id().to_owned();
1284 let conversation_id = current.selection.conversation_id().to_owned();
1317 let (task_conversation_id, task_message_id) = (conversation_id.clone(), message_id.to_owned());
1285 let (task_conversation_id, task_message_id) =
1286 (conversation_id.clone(), message_id.to_owned());
1318 let receiver = runtime::spawn(async move {
1287 let receiver = runtime::spawn(async move {
1319 engine
1288 engine
1320 .open_post(&task_conversation_id, &task_message_id)
1289 .open_post(&task_conversation_id, &task_message_id)
@@ -1358,9 +1327,10 @@ impl ConversationView {
1358 if self.conversation_id().as_deref() != Some(conversation_id) {
1327 if self.conversation_id().as_deref() != Some(conversation_id) {
1359 return;
1328 return;
1360 }
1329 }
1361 let still_waiting = self.current.as_ref().is_some_and(|current| {
1330 let still_waiting = self
1362 current.mode == ViewMode::Thread(message_id.to_owned())
1331 .current
1363 });
1332 .as_ref()
1333 .is_some_and(|current| current.mode == ViewMode::Thread(message_id.to_owned()));
1364 match result {
1334 match result {
1365 Ok(Ok(Some(post))) if still_waiting => {
1335 Ok(Ok(Some(post))) if still_waiting => {
1366 self.jump_to_post(conversation_id, message_id, !post.replies_loaded, cx)
1336 self.jump_to_post(conversation_id, message_id, !post.replies_loaded, cx)
@@ -1646,11 +1616,9 @@ impl ConversationView {
1646 let app = self.app.read(cx);
1616 let app = self.app.read(cx);
1647 let (user_id, member_name, notes) = match &current.selection {
1617 let (user_id, member_name, notes) = match &current.selection {
1648 Selection::Chat(chat_id)
1618 Selection::Chat(chat_id)
1649 if app
1619 if app.sidebar.chats.iter().any(|chat| {
1650 .sidebar
1620 &chat.id == chat_id && chat.kind.eq_ignore_ascii_case("meeting")
1651 .chats
1621 }) =>
1652 .iter()
1653 .any(|chat| &chat.id == chat_id && chat.kind.eq_ignore_ascii_case("meeting")) =>
1654 {
1622 {
1655 return None;
1623 return None;
1656 }
1624 }
@@ -1790,11 +1758,9 @@ impl ConversationView {
1790 current.loaded_count = records.len();
1758 current.loaded_count = records.len();
1791 }
1759 }
1792 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1760 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1793 let placeholders = records.is_empty()
1761 let placeholders =
1794 && (loading_post || current.sync.messages && thread_root.is_none());
1762 records.is_empty() && (loading_post || current.sync.messages && thread_root.is_none());
1795 let in_feed = current.mode == ViewMode::ThreadList;
1763 let in_feed = current.mode == ViewMode::ThreadList;
1796 let appear_scope = format!("{conversation_id}/{:?}", current.mode);
1797 let appear_live = !placeholders && !in_feed && window.is_none() && !current.sync.messages;
1798 let mut rows = match &current.mode {
1764 let mut rows = match &current.mode {
1799 _ if placeholders => {
1765 _ if placeholders => {
1800 current.has_older = false;
1766 current.has_older = false;
@@ -1851,9 +1817,6 @@ impl ConversationView {
1851 {
1817 {
1852 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
1818 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
1853 message.receipt_label = receipt_labels.get(&message.key).cloned();
1819 message.receipt_label = receipt_labels.get(&message.key).cloned();
1854 if let Some((_, previews)) = self.sent_previews.iter().find(|(key, _)| key == &message.key) {
1855 message.sent_previews = previews.clone();
1856 }
1857 }
1820 }
1858 }
1821 }
1859 if let Some(read_until) = posts_new_after.filter(|_| in_feed) {
1822 if let Some(read_until) = posts_new_after.filter(|_| in_feed) {
@@ -1873,7 +1836,6 @@ impl ConversationView {
1873 }
1836 }
1874 }
1837 }
1875 assign_series(&mut rows);
1838 assign_series(&mut rows);
1876 self.track_appearing(&rows, &appear_scope, appear_live, reset);
1877 self.apply_rows(rows, reset, cx);
1839 self.apply_rows(rows, reset, cx);
1878 if self.is_detached() {
1840 if self.is_detached() {
1879 self.scroller
1841 self.scroller
@@ -2201,7 +2163,11 @@ impl ConversationView {
2201 for receipt in receipts.values_mut() {
2163 for receipt in receipts.values_mut() {
2202 *receipt = shown_receipt(&settings, *receipt);
2164 *receipt = shown_receipt(&settings, *receipt);
2203 }
2165 }
2204 labels.retain(|key, _| receipts.get(key).is_some_and(|receipt| *receipt != Receipt::Hidden));
2166 labels.retain(|key, _| {
2167 receipts
2168 .get(key)
2169 .is_some_and(|receipt| *receipt != Receipt::Hidden)
2170 });
2205 (receipts, labels)
2171 (receipts, labels)
2206 }
2172 }
2207
2173
@@ -2227,7 +2193,11 @@ impl ConversationView {
2227 let labels = receipts
2193 let labels = receipts
2228 .iter()
2194 .iter()
2229 .map(|(key, receipt)| {
2195 .map(|(key, receipt)| {
2230 let label = if *receipt == Receipt::Read { "Seen" } else { "Sent" };
2196 let label = if *receipt == Receipt::Read {
2197 "Seen"
2198 } else {
2199 "Sent"
2200 };
2231 (key.clone(), label.to_owned())
2201 (key.clone(), label.to_owned())
2232 })
2202 })
2233 .collect();
2203 .collect();
@@ -2263,29 +2233,6 @@ impl ConversationView {
2263 .apply(&conversation_id, settled, receipts, Instant::now())
2233 .apply(&conversation_id, settled, receipts, Instant::now())
2264 }
2234 }
2265
2235
2266 fn track_appearing(&mut self, rows: &[Row], scope: &str, live: bool, reset: bool) {
2267 let sending: HashSet<&str> = self.pending.iter().map(|row| row.key.as_str()).collect();
2268 let candidates: Vec<appear_tracker::Candidate> = rows
2269 .iter()
2270 .filter_map(|row| match row {
2271 Row::Message(message) => Some(appear_tracker::Candidate {
2272 key: &message.key,
2273 own: message.own,
2274 origin: if sending.contains(message.key.as_str()) {
2275 appear_tracker::Origin::Sending
2276 } else if message.key.starts_with(SCHEDULED_KEY_PREFIX) {
2277 appear_tracker::Origin::Scheduled
2278 } else {
2279 appear_tracker::Origin::Server
2280 },
2281 }),
2282 _ => None,
2283 })
2284 .collect();
2285 self.appear_tracker
2286 .apply(scope, live, reset, &candidates, Instant::now());
2287 }
2288
2289 fn schedule_fade_end(&mut self, cx: &mut Context<Self>) {
2236 fn schedule_fade_end(&mut self, cx: &mut Context<Self>) {
2290 cx.spawn(async move |this, cx| {
2237 cx.spawn(async move |this, cx| {
2291 cx.background_executor()
2238 cx.background_executor()
@@ -2325,6 +2272,9 @@ impl ConversationView {
2325 return;
2272 return;
2326 }
2273 }
2327 let state = self.app.read(cx);
2274 let state = self.app.read(cx);
2275 if state.viewing_call() && !self.pinned {
2276 return;
2277 }
2328 let Some(selection) = self.current.as_ref().map(|c| c.selection.clone()) else {
2278 let Some(selection) = self.current.as_ref().map(|c| c.selection.clone()) else {
2329 return;
2279 return;
2330 };
2280 };
@@ -2405,7 +2355,10 @@ impl ConversationView {
2405 current.loading_older = false;
2355 current.loading_older = false;
2406 match result {
2356 match result {
2407 Ok(Ok(records)) if !records.is_empty() => {
2357 Ok(Ok(records)) if !records.is_empty() => {
2408 app_base::diagnostics::record(&format!("chat: older page, {} messages", records.len()));
2358 app_base::diagnostics::record(&format!(
2359 "chat: older page, {} messages",
2360 records.len()
2361 ));
2409 current.loaded_limit = current.loaded_count + records.len();
2362 current.loaded_limit = current.loaded_count + records.len();
2410 self.older_anchor = self
2363 self.older_anchor = self
2411 .rows
2364 .rows
@@ -2419,7 +2372,10 @@ impl ConversationView {
2419 current.older_blocked = true;
2372 current.older_blocked = true;
2420 }
2373 }
2421 Ok(Err(error)) => {
2374 Ok(Err(error)) => {
2422 app_base::diagnostics::record(&format!("chat: older page failed: {}", short_error(&error)));
2375 app_base::diagnostics::record(&format!(
2376 "chat: older page failed: {}",
2377 short_error(&error)
2378 ));
2423 current.older_blocked = true;
2379 current.older_blocked = true;
2424 self.notice = Some(format!(
2380 self.notice = Some(format!(
2425 "Could not load older messages: {}",
2381 "Could not load older messages: {}",
@@ -2575,10 +2531,8 @@ impl ConversationView {
2575 self.notice = None;
2531 self.notice = None;
2576 self.rebuild(false, cx);
2532 self.rebuild(false, cx);
2577 if self.in_feed() {
2533 if self.in_feed() {
2578 if thread_root_id.is_none() {
2534 self.scroller
2579 self.scroller
2535 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
2580 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
2581 }
2582 } else {
2536 } else {
2583 self.scroller
2537 self.scroller
2584 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
2538 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
@@ -2874,9 +2828,16 @@ impl ConversationView {
2874 } else if target.as_deref() == Some(key) {
2828 } else if target.as_deref() == Some(key) {
2875 *target = None;
2829 *target = None;
2876 }
2830 }
2831 if !hovered && matches!(slot, HoverSlot::Row) && self.toolbar_opened.as_deref() == Some(key)
2832 {
2833 self.toolbar_opened = None;
2834 }
2877 if hovered
2835 if hovered
2878 && matches!(slot, HoverSlot::Row)
2836 && matches!(slot, HoverSlot::Row)
2879 && self.toolbar_hovered.as_deref().is_some_and(|toolbar| toolbar != key)
2837 && self
2838 .toolbar_hovered
2839 .as_deref()
2840 .is_some_and(|toolbar| toolbar != key)
2880 {
2841 {
2881 self.toolbar_hovered = None;
2842 self.toolbar_hovered = None;
2882 }
2843 }
@@ -2907,9 +2868,11 @@ impl ConversationView {
2907 }
2868 }
2908
2869
2909 fn toolbar_visible(&self, key: &str, cx: &App) -> bool {
2870 fn toolbar_visible(&self, key: &str, cx: &App) -> bool {
2910 let row_trigger = (!self.app.read(cx).actions_on_right_click)
2871 let row_trigger = if self.app.read(cx).actions_on_right_click {
2911 .then_some(self.hovered_message.as_deref())
2872 self.toolbar_opened.as_deref()
2912 .flatten();
2873 } else {
2874 self.hovered_message.as_deref()
2875 };
2913 self.toolbar_suppressed.as_deref() != Some(key)
2876 self.toolbar_suppressed.as_deref() != Some(key)
2914 && self
2877 && self
2915 .toolbar_pinned
2878 .toolbar_pinned
@@ -2919,24 +2882,9 @@ impl ConversationView {
2919 == Some(key)
2882 == Some(key)
2920 }
2883 }
2921
2884
2922 pub(crate) fn context_menu_for(&self, key: &str) -> Option<OpenContextMenu> {
2885 fn open_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
2923 self.context_menu.clone().filter(|open| open.key == key)
2886 self.toolbar_opened = Some(key.to_owned());
2924 }
2887 self.toolbar_suppressed = None;
2925
2926 fn open_context_menu(&mut self, key: &str, position: Point<Pixels>, cx: &mut Context<Self>) {
2927 self.context_serial += 1;
2928 self.context_menu = Some(OpenContextMenu::new(key, position, self.context_serial));
2929 cx.notify();
2930 }
2931
2932 fn close_context_menu(&mut self, from_outside: bool, cx: &mut Context<Self>) {
2933 let Some(open) = &self.context_menu else {
2934 return;
2935 };
2936 if from_outside && self.toolbar_pinned.as_deref() == Some(open.key.as_str()) {
2937 return;
2938 }
2939 self.context_menu = None;
2940 cx.notify();
2888 cx.notify();
2941 }
2889 }
2942
2890
@@ -3540,9 +3488,6 @@ impl ConversationView {
3540 if matches!(result, Ok(Ok(Delivered::WithoutBanner))) {
3488 if matches!(result, Ok(Ok(Delivered::WithoutBanner))) {
3541 self.notice = Some(POSTED_WITHOUT_BANNER.to_owned());
3489 self.notice = Some(POSTED_WITHOUT_BANNER.to_owned());
3542 }
3490 }
3543 if let Ok(Ok(Delivered::Complete { message_id: Some(message_id) })) = &result {
3544 self.keep_sent_previews(key, message_id);
3545 }
3546 let failure = match result {
3491 let failure = match result {
3547 Ok(Ok(_)) => None,
3492 Ok(Ok(_)) => None,
3548 Ok(Err(error)) => Some(short_error(&error)),
3493 Ok(Err(error)) => Some(short_error(&error)),
@@ -3568,19 +3513,6 @@ impl ConversationView {
3568 self.rebuild(false, cx);
3513 self.rebuild(false, cx);
3569 }
3514 }
3570
3515
3571 fn keep_sent_previews(&mut self, pending_key: &str, message_id: &str) {
3572 let Some(row) = self.pending.iter().find(|row| row.key == pending_key) else {
3573 return;
3574 };
3575 if row.local_images.is_empty() {
3576 return;
3577 }
3578 self.sent_previews.push_back((message_id.to_owned(), row.local_images.clone()));
3579 if self.sent_previews.len() > SENT_PREVIEWS_KEPT {
3580 self.sent_previews.pop_front();
3581 }
3582 }
3583
3584 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
3516 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
3585 let target = match self.current.as_ref().map(|current| &current.selection) {
3517 let target = match self.current.as_ref().map(|current| &current.selection) {
3586 Some(Selection::Chat(_)) => DropTarget::Chat,
3518 Some(Selection::Chat(_)) => DropTarget::Chat,
@@ -3813,7 +3745,12 @@ impl ConversationView {
3813 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3745 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3814 })
3746 })
3815 {
3747 {
3816 rename = Some(group_name_button(&self.app, &self.group_name, chat_id, &chat.title));
3748 rename = Some(group_name_button(
3749 &self.app,
3750 &self.group_name,
3751 chat_id,
3752 &chat.title,
3753 ));
3817 }
3754 }
3818 if chat.title.trim().is_empty() {
3755 if chat.title.trim().is_empty() {
3819 names_title = Some(chat_header_actions::group_title(directory, &faces));
3756 names_title = Some(chat_header_actions::group_title(directory, &faces));
@@ -3845,9 +3782,12 @@ impl ConversationView {
3845 .avatar(&teams_core::team_avatar_key(&entry.team.id))
3782 .avatar(&teams_core::team_avatar_key(&entry.team.id))
3846 });
3783 });
3847 lead = Some(team_avatar(photo, name, key, 36., 9.));
3784 lead = Some(team_avatar(photo, name, key, 36., 9.));
3848 if let Some(channel) = team
3785 if let Some(channel) = team.and_then(|entry| {
3849 .and_then(|entry| entry.channels.iter().find(|channel| &channel.id == channel_id))
3786 entry
3850 {
3787 .channels
3788 .iter()
3789 .find(|channel| &channel.id == channel_id)
3790 }) {
3851 header_title = channel.name.clone();
3791 header_title = channel.name.clone();
3852 }
3792 }
3853 }
3793 }
@@ -3900,7 +3840,12 @@ impl ConversationView {
3900 } else if loading_window {
3840 } else if loading_window {
3901 subline = "Loading message ...".to_owned();
3841 subline = "Loading message ...".to_owned();
3902 } else if sync.shown_at.is_some() {
3842 } else if sync.shown_at.is_some() {
3903 subline = if sync.slow { "Taking longer than usual ..." } else { "Loading messages ..." }.to_owned();
3843 subline = if sync.slow {
3844 "Taking longer than usual ..."
3845 } else {
3846 "Loading messages ..."
3847 }
3848 .to_owned();
3904 }
3849 }
3905 let inline_tabs = tabs.map(|tabs| h_flex().h_full().flex_1().child(tabs));
3850 let inline_tabs = tabs.map(|tabs| h_flex().h_full().flex_1().child(tabs));
3906 let overflow = self.header_overflows();
3851 let overflow = self.header_overflows();
@@ -3961,7 +3906,9 @@ impl ConversationView {
3961 .children(self.chat_find_button(cx))
3906 .children(self.chat_find_button(cx))
3962 })
3907 })
3963 .children(self.channel_find_button(cx))
3908 .children(self.channel_find_button(cx))
3964 .when(!overflow, |header| header.children(self.channel_details_button(cx)))
3909 .when(!overflow, |header| {
3910 header.children(self.channel_details_button(cx))
3911 })
3965 .children(self.channel_more_button(cx))
3912 .children(self.channel_more_button(cx))
3966 .children(self.chat_more_button(overflow, cx))
3913 .children(self.chat_more_button(overflow, cx))
3967 .children(self.pop_in_button(current))
3914 .children(self.pop_in_button(current))
@@ -4045,7 +3992,6 @@ impl Render for ConversationView {
4045 agent_runs: self.agent_runs.clone(),
3992 agent_runs: self.agent_runs.clone(),
4046 reaction_proposals: self.reaction_proposals.clone(),
3993 reaction_proposals: self.reaction_proposals.clone(),
4047 forward_selection: forward_selection.clone(),
3994 forward_selection: forward_selection.clone(),
4048 appearing: self.appear_tracker.entering(Instant::now()),
4049 };
3995 };
4050 let pin_banner = self
3996 let pin_banner = self
4051 .render_pin_banner(cx)
3997 .render_pin_banner(cx)
@@ -4053,15 +3999,6 @@ impl Render for ConversationView {
4053 let timeline_top_inset = pin_banner_inset(pin_banner.is_some());
3999 let timeline_top_inset = pin_banner_inset(pin_banner.is_some());
4054 let comfy = self.app.read(cx).account_chat_settings().message_density
4000 let comfy = self.app.read(cx).account_chat_settings().message_density
4055 != teams_core::MessageDensity::Compact;
4001 != teams_core::MessageDensity::Compact;
4056 let typing_line = self.render_typing_line(cx);
4057 let typing_offset = {
4058 let scroller = self.scroller.read(cx);
4059 let last_row = scroller.item_count().checked_sub(1);
4060 typing_bottom_offset(
4061 self.timeline_bounds.get(),
4062 last_row.and_then(|index| scroller.item_bounds(index)),
4063 )
4064 };
4065 let scroller = MessageScroller::new(
4002 let scroller = MessageScroller::new(
4066 "messages",
4003 "messages",
4067 self.scroller.clone(),
4004 self.scroller.clone(),
@@ -4160,7 +4097,6 @@ impl Render for ConversationView {
4160 },
4097 },
4161 )
4098 )
4162 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
4099 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
4163 .wheel_mask(false)
4164 .jump_button(!in_feed)
4100 .jump_button(!in_feed)
4165 .force_jump_button(detached)
4101 .force_jump_button(detached)
4166 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
4102 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
@@ -4178,13 +4114,7 @@ impl Render for ConversationView {
4178 view.update(cx, |this, cx| this.leave_detached(cx)).ok();
4114 view.update(cx, |this, cx| this.leave_detached(cx)).ok();
4179 })
4115 })
4180 })
4116 })
4181 .with_list_style(StyleRefinement::default().pb(px(if typing_line.is_some() {
4117 .with_bottom_fade(background)
4182 TYPING_TOP_GAP + TYPING_BUBBLE_HEIGHT + TYPING_BOTTOM_GAP
4183 } else if in_feed {
4184 0.
4185 } else {
4186 COMPOSER_TOP_GAP
4187 })))
4188 .with_top_inset(timeline_top_inset);
4118 .with_top_inset(timeline_top_inset);
4189
4119
4190 root = match self.current.as_ref().filter(|_| !drafting) {
4120 root = match self.current.as_ref().filter(|_| !drafting) {
@@ -4282,14 +4212,6 @@ impl Render for ConversationView {
4282 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
4212 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
4283 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
4213 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
4284 .child(body)
4214 .child(body)
4285 .children(typing_line.map(|line| {
4286 div()
4287 .absolute()
4288 .left_0()
4289 .right_0()
4290 .bottom(px(typing_offset))
4291 .child(runway(line, comfy))
4292 }))
4293 .when(feed_scrolled, |timeline| {
4215 .when(feed_scrolled, |timeline| {
4294 timeline.child(
4216 timeline.child(
4295 edge_divider(FEED_EDGE_TAG)
4217 edge_divider(FEED_EDGE_TAG)
@@ -4301,7 +4223,10 @@ impl Render for ConversationView {
4301 })
4223 })
4302 .children(pin_banner.map(|banner| pin_banner_overlay(runway(banner, comfy)))),
4224 .children(pin_banner.map(|banner| pin_banner_overlay(runway(banner, comfy)))),
4303 )
4225 )
4304 .children(self.render_draft_error(cx).map(|error| runway(error, comfy)))
4226 .children(
4227 self.render_draft_error(cx)
4228 .map(|error| runway(error, comfy)),
4229 )
4305 .when(
4230 .when(
4306 !in_feed && !recap_active && !self.shared_active(),
4231 !in_feed && !recap_active && !self.shared_active(),
4307 |column| match &forward_selection {
4232 |column| match &forward_selection {
@@ -4311,53 +4236,52 @@ impl Render for ConversationView {
4311 None => column.child(runway(
4236 None => column.child(runway(
4312 v_flex()
4237 v_flex()
4313 .w_full()
4238 .w_full()
4314 .children(self.render_absence_notice(cx))
4239 .child(self.render_typing_line(cx))
4315 .children(self.render_proposal_card(cx).map(|card| {
4240 .children(self.render_proposal_card(cx))
4316 div().w_full().pb(px(COMPOSER_TOP_GAP)).child(card)
4317 }))
4318 .child(self.composer.clone()),
4241 .child(self.composer.clone()),
4319 comfy,
4242 comfy,
4320 )),
4243 )),
4321 },
4244 },
4322 )
4245 )
4323 .child(self.render_drop_overlay(cx));
4246 .child(self.render_drop_overlay(cx));
4324 let root = root.child(
4247 let root = root
4325 h_flex()
4248 .child(
4326 .relative()
4249 h_flex()
4327 .flex_1()
4250 .relative()
4328 .min_h_0()
4251 .flex_1()
4329 .w_full()
4252 .min_h_0()
4330 .items_stretch()
4253 .w_full()
4331 .child(content)
4254 .items_stretch()
4332 .children(channel_details)
4255 .child(content)
4333 .children(find_panel.map(|panel| {
4256 .children(channel_details)
4334 div()
4257 .children(find_panel.map(|panel| {
4335 .h_full()
4258 div()
4336 .w(px(FIND_PANEL_WIDTH))
4259 .h_full()
4337 .min_w_0()
4260 .w(px(FIND_PANEL_WIDTH))
4338 .flex_shrink(1.)
4261 .min_w_0()
4339 .when(find_overlays, |slot| {
4262 .flex_shrink(1.)
4340 slot.absolute().top_0().right_0().bottom_0().max_w_full()
4263 .when(find_overlays, |slot| {
4341 })
4264 slot.absolute().top_0().right_0().bottom_0().max_w_full()
4342 .child(panel)
4265 })
4343 })),
4266 .child(panel)
4344 )
4267 })),
4345 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
4268 )
4346 if this.reaction_details.is_some() {
4269 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
4347 this.close_reaction_details(cx);
4270 if this.reaction_details.is_some() {
4348 cx.stop_propagation();
4271 this.close_reaction_details(cx);
4349 }
4272 cx.stop_propagation();
4350 }))
4351 .on_action(cx.listener(|this, _: &Escape, window, cx| {
4352 if this.draft_active {
4353 if this.draft.read(cx).has_focus(window, cx) {
4354 this.draft.update(cx, |draft, cx| draft.escape(cx));
4355 }
4273 }
4356 } else if this.cancel_forward_selection(cx) {
4274 }))
4357 } else if !this.on_escape(window, cx) {
4275 .on_action(cx.listener(|this, _: &Escape, window, cx| {
4358 cx.propagate();
4276 if this.draft_active {
4359 }
4277 if this.draft.read(cx).has_focus(window, cx) {
4360 }));
4278 this.draft.update(cx, |draft, cx| draft.escape(cx));
4279 }
4280 } else if this.cancel_forward_selection(cx) {
4281 } else if !this.on_escape(window, cx) {
4282 cx.propagate();
4283 }
4284 }));
4361 let root = root.child(crate::inline_video::sentinel());
4285 let root = root.child(crate::inline_video::sentinel());
4362 match copilot_island {
4286 match copilot_island {
4363 Some(island) => h_flex()
4287 Some(island) => h_flex()
@@ -4372,17 +4296,6 @@ impl Render for ConversationView {
4372 }
4296 }
4373}
4297}
4374
4298
4375/// Right under the last row like one more message; once that row scrolls below the view it sticks above the composer.
4376fn typing_bottom_offset(timeline: Option<Bounds<Pixels>>, last_row: Option<Bounds<Pixels>>) -> f32 {
4377 let (Some(timeline), Some(last_row)) = (timeline, last_row) else {
4378 return TYPING_BOTTOM_GAP;
4379 };
4380 let under_last_row = f32::from(timeline.bottom() - last_row.bottom())
4381 - TYPING_TOP_GAP
4382 - TYPING_BUBBLE_HEIGHT;
4383 under_last_row.max(TYPING_BOTTOM_GAP)
4384}
4385
4386fn typing_dots() -> impl IntoElement {
4299fn typing_dots() -> impl IntoElement {
4387 h_flex()
4300 h_flex()
4388 .gap(px(3.))
4301 .gap(px(3.))
@@ -4478,7 +4391,7 @@ fn runway(content: impl IntoElement, comfy: bool) -> AnyElement {
4478mod tests {
4391mod tests {
4479 use std::sync::Arc;
4392 use std::sync::Arc;
4480
4393
4481 use super::{DropTarget, drop_overlay_text, typing_bottom_offset};
4394 use super::{DropTarget, drop_overlay_text};
4482
4395
4483 use gpui_kit::test::TestWindowExt as _;
4396 use gpui_kit::test::TestWindowExt as _;
4484 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
4397 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
@@ -4612,14 +4525,4 @@ mod tests {
4612 assert_eq!(state.selection, Some(crate::demo::first_selection()));
4525 assert_eq!(state.selection, Some(crate::demo::first_selection()));
4613 });
4526 });
4614 }
4527 }
4615
4616 #[test]
4617 fn the_typing_bubble_follows_the_last_row_and_sticks_above_the_composer() {
4618 use gpui_kit::{Bounds, point, px, size};
4619 let timeline = Bounds::new(point(px(0.), px(100.)), size(px(800.), px(600.)));
4620 let row_ending_at = |bottom: f32| Some(Bounds::new(point(px(0.), px(bottom - 50.)), size(px(800.), px(50.))));
4621 assert_eq!(typing_bottom_offset(Some(timeline), row_ending_at(400.)), 256.);
4622 assert_eq!(typing_bottom_offset(Some(timeline), row_ending_at(900.)), 8.);
4623 assert_eq!(typing_bottom_offset(Some(timeline), None), 8.);
4624 }
4625}
4528}
crates/app/src/views/conversation/channel_details.rs +3 −5
@@ -1,7 +1,7 @@
1 1 use chrono::{Local, Offset, Utc};
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 2 use gpui_kit::assets::IconName;
4 3 use gpui_kit::component::button::{Button, ButtonVariants as _};
4 use gpui_kit::component::scroll::ScrollableElement as _;
5 5 use gpui_kit::component::{h_flex, v_flex};
6 6 use gpui_kit::prelude::FluentBuilder as _;
7 7 use gpui_kit::*;
@@ -10,8 +10,8 @@ use teams_core::FileKind;
10 10
11 11 use super::{ChannelPane, ConversationView};
12 12 use crate::app_state::Selection;
13 use crate::find_in_chat::FIND_IN_CHANNEL;
14 13 use crate::channel_files::{SharedContent, SharedItem};
14 use crate::find_in_chat::FIND_IN_CHANNEL;
15 15 use crate::format;
16 16 use crate::rows::reply_excerpt;
17 17 use crate::theme;
@@ -135,9 +135,7 @@ impl ConversationView {
135 135 fn details_conversation_id(&self) -> Option<String> {
136 136 match &self.current.as_ref()?.selection {
137 137 Selection::Channel(channel_id) => Some(channel_id.clone()),
138 Selection::Chat(chat_id) if !self.draft_active && !self.pinned => {
139 Some(chat_id.clone())
140 }
138 Selection::Chat(chat_id) if !self.draft_active && !self.pinned => Some(chat_id.clone()),
141 139 Selection::Chat(_) => None,
142 140 }
143 141 }
@@ -1,7 +1,7 @@
1use chrono::{Local, Offset, Utc};
1use chrono::{Local, Offset, Utc};
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::assets::IconName;
2use gpui_kit::assets::IconName;
4use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::button::{Button, ButtonVariants as _};
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
7use gpui_kit::*;
@@ -10,8 +10,8 @@ use teams_core::FileKind;
10
10
11use super::{ChannelPane, ConversationView};
11use super::{ChannelPane, ConversationView};
12use crate::app_state::Selection;
12use crate::app_state::Selection;
13use crate::find_in_chat::FIND_IN_CHANNEL;
14use crate::channel_files::{SharedContent, SharedItem};
13use crate::channel_files::{SharedContent, SharedItem};
14use crate::find_in_chat::FIND_IN_CHANNEL;
15use crate::format;
15use crate::format;
16use crate::rows::reply_excerpt;
16use crate::rows::reply_excerpt;
17use crate::theme;
17use crate::theme;
@@ -135,9 +135,7 @@ impl ConversationView {
135 fn details_conversation_id(&self) -> Option<String> {
135 fn details_conversation_id(&self) -> Option<String> {
136 match &self.current.as_ref()?.selection {
136 match &self.current.as_ref()?.selection {
137 Selection::Channel(channel_id) => Some(channel_id.clone()),
137 Selection::Channel(channel_id) => Some(channel_id.clone()),
138 Selection::Chat(chat_id) if !self.draft_active && !self.pinned => {
138 Selection::Chat(chat_id) if !self.draft_active && !self.pinned => Some(chat_id.clone()),
139 Some(chat_id.clone())
140 }
141 Selection::Chat(_) => None,
139 Selection::Chat(_) => None,
142 }
140 }
143 }
141 }
crates/app/src/views/conversation/chat_header_actions.rs +16 −5
@@ -12,11 +12,11 @@ use crate::app_state::Selection;
12 12 use crate::data::Directory;
13 13 use crate::find_in_chat::FIND_IN_CHAT;
14 14 use crate::theme;
15 use crate::views::avatar::status_glyph;
15 16 use crate::views::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
16 use crate::views::sidebar::channel_menu;
17 17 use crate::views::composer::plus_menu::chat_invitees;
18 18 use crate::views::new_meeting_dialog::open_new_meeting_with;
19 use crate::views::avatar::status_glyph;
19 use crate::views::sidebar::channel_menu;
20 20 use crate::views::widgets::{icon, menu_icon, symbol};
21 21
22 22 pub const CHAT_HEADER_MORE_TAG: &str = "chat-header-more";
@@ -61,7 +61,12 @@ impl ConversationView {
61 61 .sidebar
62 62 .teams
63 63 .iter()
64 .find(|entry| entry.channels.iter().any(|channel| &channel.id == channel_id))?
64 .find(|entry| {
65 entry
66 .channels
67 .iter()
68 .any(|channel| &channel.id == channel_id)
69 })?
65 70 .channel_notifications(channel_id);
66 71 let (state, channel_id) = (self.app.clone(), channel_id.clone());
67 72 Some(
@@ -88,7 +93,11 @@ impl ConversationView {
88 93 && self.header_chat_id().is_some()
89 94 }
90 95
91 pub(super) fn chat_more_button(&self, overflow: bool, cx: &Context<Self>) -> Option<AnyElement> {
96 pub(super) fn chat_more_button(
97 &self,
98 overflow: bool,
99 cx: &Context<Self>,
100 ) -> Option<AnyElement> {
92 101 let chat_id = self
93 102 .header_chat_id()
94 103 .filter(|_| !self.popped_out && !self.pinned)?;
@@ -157,7 +166,9 @@ fn overflow_items(
157 166 PopupMenuItem::new(details_label)
158 167 .icon(menu_icon(IconName::PanelRight))
159 168 .on_click(move |_, _, cx| {
160 details_view.update(cx, |this, cx| this.toggle_details(cx)).ok();
169 details_view
170 .update(cx, |this, cx| this.toggle_details(cx))
171 .ok();
161 172 }),
162 173 )
163 174 .separator()
@@ -12,11 +12,11 @@ use crate::app_state::Selection;
12use crate::data::Directory;
12use crate::data::Directory;
13use crate::find_in_chat::FIND_IN_CHAT;
13use crate::find_in_chat::FIND_IN_CHAT;
14use crate::theme;
14use crate::theme;
15use crate::views::avatar::status_glyph;
15use crate::views::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
16use crate::views::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
16use crate::views::sidebar::channel_menu;
17use crate::views::composer::plus_menu::chat_invitees;
17use crate::views::composer::plus_menu::chat_invitees;
18use crate::views::new_meeting_dialog::open_new_meeting_with;
18use crate::views::new_meeting_dialog::open_new_meeting_with;
19use crate::views::avatar::status_glyph;
19use crate::views::sidebar::channel_menu;
20use crate::views::widgets::{icon, menu_icon, symbol};
20use crate::views::widgets::{icon, menu_icon, symbol};
21
21
22pub const CHAT_HEADER_MORE_TAG: &str = "chat-header-more";
22pub const CHAT_HEADER_MORE_TAG: &str = "chat-header-more";
@@ -61,7 +61,12 @@ impl ConversationView {
61 .sidebar
61 .sidebar
62 .teams
62 .teams
63 .iter()
63 .iter()
64 .find(|entry| entry.channels.iter().any(|channel| &channel.id == channel_id))?
64 .find(|entry| {
65 entry
66 .channels
67 .iter()
68 .any(|channel| &channel.id == channel_id)
69 })?
65 .channel_notifications(channel_id);
70 .channel_notifications(channel_id);
66 let (state, channel_id) = (self.app.clone(), channel_id.clone());
71 let (state, channel_id) = (self.app.clone(), channel_id.clone());
67 Some(
72 Some(
@@ -88,7 +93,11 @@ impl ConversationView {
88 && self.header_chat_id().is_some()
93 && self.header_chat_id().is_some()
89 }
94 }
90
95
91 pub(super) fn chat_more_button(&self, overflow: bool, cx: &Context<Self>) -> Option<AnyElement> {
96 pub(super) fn chat_more_button(
97 &self,
98 overflow: bool,
99 cx: &Context<Self>,
100 ) -> Option<AnyElement> {
92 let chat_id = self
101 let chat_id = self
93 .header_chat_id()
102 .header_chat_id()
94 .filter(|_| !self.popped_out && !self.pinned)?;
103 .filter(|_| !self.popped_out && !self.pinned)?;
@@ -157,7 +166,9 @@ fn overflow_items(
157 PopupMenuItem::new(details_label)
166 PopupMenuItem::new(details_label)
158 .icon(menu_icon(IconName::PanelRight))
167 .icon(menu_icon(IconName::PanelRight))
159 .on_click(move |_, _, cx| {
168 .on_click(move |_, _, cx| {
160 details_view.update(cx, |this, cx| this.toggle_details(cx)).ok();
169 details_view
170 .update(cx, |this, cx| this.toggle_details(cx))
171 .ok();
161 }),
172 }),
162 )
173 )
163 .separator()
174 .separator()
crates/app/src/views/conversation/copilot.rs +48 −34
@@ -71,7 +71,11 @@ impl ConversationView {
71 71 }
72 72
73 73 pub(super) fn copilot_label(&self) -> &'static str {
74 if self.copilot.open { CLOSE_LABEL } else { OPEN_LABEL }
74 if self.copilot.open {
75 CLOSE_LABEL
76 } else {
77 OPEN_LABEL
78 }
75 79 }
76 80
77 81 pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
@@ -94,15 +98,19 @@ impl ConversationView {
94 98 self.copilot.open = !self.copilot.open;
95 99 if self.copilot.open && self.copilot.input.is_none() {
96 100 let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));
97 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
98 if matches!(event, InputEvent::PressEnter { .. }) {
99 let prompt = input.read(cx).value().trim().to_owned();
100 if !prompt.is_empty() {
101 input.update(cx, |input, cx| input.set_value("", window, cx));
102 this.ask_copilot(prompt, cx);
101 let subscription = cx.subscribe_in(
102 &input,
103 window,
104 |this, input, event: &InputEvent, window, cx| {
105 if matches!(event, InputEvent::PressEnter { .. }) {
106 let prompt = input.read(cx).value().trim().to_owned();
107 if !prompt.is_empty() {
108 input.update(cx, |input, cx| input.set_value("", window, cx));
109 this.ask_copilot(prompt, cx);
110 }
103 111 }
104 }
105 });
112 },
113 );
106 114 self.copilot.input = Some(input);
107 115 self.copilot._input_events = Some(subscription);
108 116 }
@@ -155,8 +163,10 @@ impl ConversationView {
155 163 Ok(Err(error)) => Err(error.to_string()),
156 164 Err(error) => Err(error.to_string()),
157 165 };
158 this.update(cx, |this, cx| this.settle_copilot(generation, index, answer, cx))
159 .ok();
166 this.update(cx, |this, cx| {
167 this.settle_copilot(generation, index, answer, cx)
168 })
169 .ok();
160 170 })
161 171 .detach();
162 172 }
@@ -206,26 +216,28 @@ impl ConversationView {
206 216 .child(Input::new(input).appearance(false).bordered(false))
207 217 });
208 218 let content = if self.copilot.turns.is_empty() {
209 let suggestions = v_flex().w_full().gap(px(8.)).children(
210 SUGGESTIONS.iter().enumerate().map(|(index, prompt)| {
211 div()
212 .id(("copilot-suggestion", index))
213 .w_full()
214 .px(px(12.))
215 .py(px(10.))
216 .rounded(px(CHIP_RADIUS))
217 .bg(theme::surface_raised())
218 .text_size(px(12.))
219 .font_weight(FontWeight::SEMIBOLD)
220 .text_color(theme::text())
221 .cursor_pointer()
222 .hover(|chip| chip.bg(theme::row_hover()))
223 .child(*prompt)
224 .on_click(cx.listener(move |this, _, _, cx| {
225 this.ask_copilot((*prompt).to_owned(), cx)
226 }))
227 }),
228 );
219 let suggestions =
220 v_flex()
221 .w_full()
222 .gap(px(8.))
223 .children(SUGGESTIONS.iter().enumerate().map(|(index, prompt)| {
224 div()
225 .id(("copilot-suggestion", index))
226 .w_full()
227 .px(px(12.))
228 .py(px(10.))
229 .rounded(px(CHIP_RADIUS))
230 .bg(theme::surface_raised())
231 .text_size(px(12.))
232 .font_weight(FontWeight::SEMIBOLD)
233 .text_color(theme::text())
234 .cursor_pointer()
235 .hover(|chip| chip.bg(theme::row_hover()))
236 .child(*prompt)
237 .on_click(cx.listener(move |this, _, _, cx| {
238 this.ask_copilot((*prompt).to_owned(), cx)
239 }))
240 }));
229 241 v_flex()
230 242 .flex_1()
231 243 .min_h_0()
@@ -250,9 +262,11 @@ impl ConversationView {
250 262 .pb(px(PANE_PADDING))
251 263 .gap(px(12.));
252 264 for (index, turn) in self.copilot.turns.iter().enumerate() {
253 body = body
254 .child(prompt_bubble(&turn.prompt))
255 .child(answer_view(index, &turn.answer, cx));
265 body = body.child(prompt_bubble(&turn.prompt)).child(answer_view(
266 index,
267 &turn.answer,
268 cx,
269 ));
256 270 }
257 271 v_flex()
258 272 .flex_1()
@@ -71,7 +71,11 @@ impl ConversationView {
71 }
71 }
72
72
73 pub(super) fn copilot_label(&self) -> &'static str {
73 pub(super) fn copilot_label(&self) -> &'static str {
74 if self.copilot.open { CLOSE_LABEL } else { OPEN_LABEL }
74 if self.copilot.open {
75 CLOSE_LABEL
76 } else {
77 OPEN_LABEL
78 }
75 }
79 }
76
80
77 pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
81 pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
@@ -94,15 +98,19 @@ impl ConversationView {
94 self.copilot.open = !self.copilot.open;
98 self.copilot.open = !self.copilot.open;
95 if self.copilot.open && self.copilot.input.is_none() {
99 if self.copilot.open && self.copilot.input.is_none() {
96 let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));
100 let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));
97 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
101 let subscription = cx.subscribe_in(
98 if matches!(event, InputEvent::PressEnter { .. }) {
102 &input,
99 let prompt = input.read(cx).value().trim().to_owned();
103 window,
100 if !prompt.is_empty() {
104 |this, input, event: &InputEvent, window, cx| {
101 input.update(cx, |input, cx| input.set_value("", window, cx));
105 if matches!(event, InputEvent::PressEnter { .. }) {
102 this.ask_copilot(prompt, cx);
106 let prompt = input.read(cx).value().trim().to_owned();
107 if !prompt.is_empty() {
108 input.update(cx, |input, cx| input.set_value("", window, cx));
109 this.ask_copilot(prompt, cx);
110 }
103 }
111 }
104 }
112 },
105 });
113 );
106 self.copilot.input = Some(input);
114 self.copilot.input = Some(input);
107 self.copilot._input_events = Some(subscription);
115 self.copilot._input_events = Some(subscription);
108 }
116 }
@@ -155,8 +163,10 @@ impl ConversationView {
155 Ok(Err(error)) => Err(error.to_string()),
163 Ok(Err(error)) => Err(error.to_string()),
156 Err(error) => Err(error.to_string()),
164 Err(error) => Err(error.to_string()),
157 };
165 };
158 this.update(cx, |this, cx| this.settle_copilot(generation, index, answer, cx))
166 this.update(cx, |this, cx| {
159 .ok();
167 this.settle_copilot(generation, index, answer, cx)
168 })
169 .ok();
160 })
170 })
161 .detach();
171 .detach();
162 }
172 }
@@ -206,26 +216,28 @@ impl ConversationView {
206 .child(Input::new(input).appearance(false).bordered(false))
216 .child(Input::new(input).appearance(false).bordered(false))
207 });
217 });
208 let content = if self.copilot.turns.is_empty() {
218 let content = if self.copilot.turns.is_empty() {
209 let suggestions = v_flex().w_full().gap(px(8.)).children(
219 let suggestions =
210 SUGGESTIONS.iter().enumerate().map(|(index, prompt)| {
220 v_flex()
211 div()
221 .w_full()
212 .id(("copilot-suggestion", index))
222 .gap(px(8.))
213 .w_full()
223 .children(SUGGESTIONS.iter().enumerate().map(|(index, prompt)| {
214 .px(px(12.))
224 div()
215 .py(px(10.))
225 .id(("copilot-suggestion", index))
216 .rounded(px(CHIP_RADIUS))
226 .w_full()
217 .bg(theme::surface_raised())
227 .px(px(12.))
218 .text_size(px(12.))
228 .py(px(10.))
219 .font_weight(FontWeight::SEMIBOLD)
229 .rounded(px(CHIP_RADIUS))
220 .text_color(theme::text())
230 .bg(theme::surface_raised())
221 .cursor_pointer()
231 .text_size(px(12.))
222 .hover(|chip| chip.bg(theme::row_hover()))
232 .font_weight(FontWeight::SEMIBOLD)
223 .child(*prompt)
233 .text_color(theme::text())
224 .on_click(cx.listener(move |this, _, _, cx| {
234 .cursor_pointer()
225 this.ask_copilot((*prompt).to_owned(), cx)
235 .hover(|chip| chip.bg(theme::row_hover()))
226 }))
236 .child(*prompt)
227 }),
237 .on_click(cx.listener(move |this, _, _, cx| {
228 );
238 this.ask_copilot((*prompt).to_owned(), cx)
239 }))
240 }));
229 v_flex()
241 v_flex()
230 .flex_1()
242 .flex_1()
231 .min_h_0()
243 .min_h_0()
@@ -250,9 +262,11 @@ impl ConversationView {
250 .pb(px(PANE_PADDING))
262 .pb(px(PANE_PADDING))
251 .gap(px(12.));
263 .gap(px(12.));
252 for (index, turn) in self.copilot.turns.iter().enumerate() {
264 for (index, turn) in self.copilot.turns.iter().enumerate() {
253 body = body
265 body = body.child(prompt_bubble(&turn.prompt)).child(answer_view(
254 .child(prompt_bubble(&turn.prompt))
266 index,
255 .child(answer_view(index, &turn.answer, cx));
267 &turn.answer,
268 cx,
269 ));
256 }
270 }
257 v_flex()
271 v_flex()
258 .flex_1()
272 .flex_1()
crates/app/src/views/conversation/feed.rs +16 −14
@@ -31,7 +31,9 @@ pub(super) fn subject_input(
31 31 window: &mut Window,
32 32 cx: &mut Context<ConversationView>,
33 33 ) -> Entity<InputState> {
34 cx.new(|cx| InputState::new(window, cx).placeholder(crate::views::composer::SUBJECT_PLACEHOLDER))
34 cx.new(|cx| {
35 InputState::new(window, cx).placeholder(crate::views::composer::SUBJECT_PLACEHOLDER)
36 })
35 37 }
36 38
37 39 impl ConversationView {
@@ -161,7 +163,11 @@ impl ConversationView {
161 163 let view = cx.entity().downgrade();
162 164 window.on_next_frame(move |_, cx| {
163 165 view.update(cx, |this, cx| {
164 let index = this.rows.borrow().iter().position(|row| row.key() == root_id);
166 let index = this
167 .rows
168 .borrow()
169 .iter()
170 .position(|row| row.key() == root_id);
165 171 if let Some(index) = index {
166 172 this.scroller
167 173 .update(cx, |scroller, cx| scroller.reveal_item_bottom(index, cx));
@@ -287,7 +293,8 @@ impl ConversationView {
287 293 let view = cx.entity().downgrade();
288 294 let announce_view = view.clone();
289 295 let open: PostAction = Box::new(move |window, cx| {
290 view.update(cx, |this, cx| this.open_new_post(window, cx)).ok();
296 view.update(cx, |this, cx| this.open_new_post(window, cx))
297 .ok();
291 298 });
292 299 let announce: PostAction = Box::new(move |window, cx| {
293 300 announce_view
@@ -299,14 +306,9 @@ impl ConversationView {
299 306 .w_full()
300 307 .flex_none()
301 308 .children(proposal_card)
302 .child(
303 div()
304 .w_full()
305 .flex_none()
306 .px(px(20.))
307 .py(px(12.))
308 .child(post_in_channel_card(&self.app.read(cx).directory, open, announce)),
309 )
309 .child(div().w_full().flex_none().px(px(20.)).py(px(12.)).child(
310 post_in_channel_card(&self.app.read(cx).directory, open, announce),
311 ))
310 312 .into_any_element(),
311 313 );
312 314 }
@@ -322,9 +324,9 @@ impl ConversationView {
322 324 .ghost()
323 325 .compact()
324 326 .label("Cancel")
325 .on_click(cx.listener(|this, _, window, cx| {
326 this.cancel_new_post(window, cx)
327 })),
327 .on_click(
328 cx.listener(|this, _, window, cx| this.cancel_new_post(window, cx)),
329 ),
328 330 )
329 331 });
330 332 Some(
@@ -31,7 +31,9 @@ pub(super) fn subject_input(
31 window: &mut Window,
31 window: &mut Window,
32 cx: &mut Context<ConversationView>,
32 cx: &mut Context<ConversationView>,
33) -> Entity<InputState> {
33) -> Entity<InputState> {
34 cx.new(|cx| InputState::new(window, cx).placeholder(crate::views::composer::SUBJECT_PLACEHOLDER))
34 cx.new(|cx| {
35 InputState::new(window, cx).placeholder(crate::views::composer::SUBJECT_PLACEHOLDER)
36 })
35}
37}
36
38
37impl ConversationView {
39impl ConversationView {
@@ -161,7 +163,11 @@ impl ConversationView {
161 let view = cx.entity().downgrade();
163 let view = cx.entity().downgrade();
162 window.on_next_frame(move |_, cx| {
164 window.on_next_frame(move |_, cx| {
163 view.update(cx, |this, cx| {
165 view.update(cx, |this, cx| {
164 let index = this.rows.borrow().iter().position(|row| row.key() == root_id);
166 let index = this
167 .rows
168 .borrow()
169 .iter()
170 .position(|row| row.key() == root_id);
165 if let Some(index) = index {
171 if let Some(index) = index {
166 this.scroller
172 this.scroller
167 .update(cx, |scroller, cx| scroller.reveal_item_bottom(index, cx));
173 .update(cx, |scroller, cx| scroller.reveal_item_bottom(index, cx));
@@ -287,7 +293,8 @@ impl ConversationView {
287 let view = cx.entity().downgrade();
293 let view = cx.entity().downgrade();
288 let announce_view = view.clone();
294 let announce_view = view.clone();
289 let open: PostAction = Box::new(move |window, cx| {
295 let open: PostAction = Box::new(move |window, cx| {
290 view.update(cx, |this, cx| this.open_new_post(window, cx)).ok();
296 view.update(cx, |this, cx| this.open_new_post(window, cx))
297 .ok();
291 });
298 });
292 let announce: PostAction = Box::new(move |window, cx| {
299 let announce: PostAction = Box::new(move |window, cx| {
293 announce_view
300 announce_view
@@ -299,14 +306,9 @@ impl ConversationView {
299 .w_full()
306 .w_full()
300 .flex_none()
307 .flex_none()
301 .children(proposal_card)
308 .children(proposal_card)
302 .child(
309 .child(div().w_full().flex_none().px(px(20.)).py(px(12.)).child(
303 div()
310 post_in_channel_card(&self.app.read(cx).directory, open, announce),
304 .w_full()
311 ))
305 .flex_none()
306 .px(px(20.))
307 .py(px(12.))
308 .child(post_in_channel_card(&self.app.read(cx).directory, open, announce)),
309 )
310 .into_any_element(),
312 .into_any_element(),
311 );
313 );
312 }
314 }
@@ -322,9 +324,9 @@ impl ConversationView {
322 .ghost()
324 .ghost()
323 .compact()
325 .compact()
324 .label("Cancel")
326 .label("Cancel")
325 .on_click(cx.listener(|this, _, window, cx| {
327 .on_click(
326 this.cancel_new_post(window, cx)
328 cx.listener(|this, _, window, cx| this.cancel_new_post(window, cx)),
327 })),
329 ),
328 )
330 )
329 });
331 });
330 Some(
332 Some(
crates/app/src/views/conversation/pins.rs +4 −2
@@ -308,8 +308,10 @@ impl ConversationView {
308 308 }
309 309
310 310 pub(super) fn request_post_follow(&mut self, message_id: &str, cx: &mut Context<Self>) {
311 if let Some(Selection::Channel(channel_id)) =
312 self.current.as_ref().map(|current| current.selection.clone())
311 if let Some(Selection::Channel(channel_id)) = self
312 .current
313 .as_ref()
314 .map(|current| current.selection.clone())
313 315 && self.post_follow(message_id, cx).is_some()
314 316 {
315 317 self.app.update(cx, |state, cx| {
@@ -308,8 +308,10 @@ impl ConversationView {
308 }
308 }
309
309
310 pub(super) fn request_post_follow(&mut self, message_id: &str, cx: &mut Context<Self>) {
310 pub(super) fn request_post_follow(&mut self, message_id: &str, cx: &mut Context<Self>) {
311 if let Some(Selection::Channel(channel_id)) =
311 if let Some(Selection::Channel(channel_id)) = self
312 self.current.as_ref().map(|current| current.selection.clone())
312 .current
313 .as_ref()
314 .map(|current| current.selection.clone())
313 && self.post_follow(message_id, cx).is_some()
315 && self.post_follow(message_id, cx).is_some()
314 {
316 {
315 self.app.update(cx, |state, cx| {
317 self.app.update(cx, |state, cx| {
crates/app/src/views/conversation/recap.rs +23 −10
@@ -8,20 +8,20 @@ use chatsvc::{
8 8 days_until_expiry,
9 9 };
10 10 use chrono::Utc;
11 use gpui_kit::component::WindowExt as _;
11 12 use gpui_kit::component::button::{Button, ButtonVariants as _};
12 13 use gpui_kit::component::dialog::DialogFooter;
13 14 use gpui_kit::component::input::{InputEvent, InputState};
14 use gpui_kit::component::WindowExt as _;
15 15 use gpui_kit::*;
16 16
17 17 use super::ConversationView;
18 18 use crate::app_state::{AppState, Selection};
19 use crate::rows::{MeetingInfo, MeetingSlot};
20 19 use crate::channel_files::SharedContent;
21 20 use crate::demo_recap;
22 21 use crate::downloads::{self, DownloadState};
23 22 use crate::notice::short_error;
24 23 use crate::recap::{DELETE_QUESTION, Load, save_name};
24 use crate::rows::{MeetingInfo, MeetingSlot};
25 25 use crate::runtime;
26 26 use crate::views::channel_tabs::{ChannelPane, render_chat_bar};
27 27 use crate::views::recap_tab::{RecapCommand, RecapDownload, RecapRun, RecapView, render_recap};
@@ -73,7 +73,8 @@ enum SaveEvent {
73 73
74 74 impl ConversationView {
75 75 fn is_meeting_chat(&self, cx: &App) -> bool {
76 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|current| &current.selection)
76 let Some(Selection::Chat(chat_id)) =
77 self.current.as_ref().map(|current| &current.selection)
77 78 else {
78 79 return false;
79 80 };
@@ -445,7 +446,13 @@ impl ConversationView {
445 446 }
446 447
447 448 fn can_delete_recording(&self, cx: &App) -> bool {
448 let my_user_id = self.app.read(cx).directory.me.as_ref().map(|me| me.user_id.as_str());
449 let my_user_id = self
450 .app
451 .read(cx)
452 .directory
453 .me
454 .as_ref()
455 .map(|me| me.user_id.as_str());
449 456 match (self.selected_occurrence(), my_user_id) {
450 457 (Some(occurrence), Some(my_user_id)) => {
451 458 occurrence.organizer_id.as_deref() == Some(my_user_id)
@@ -567,8 +574,10 @@ impl ConversationView {
567 574 let receiver = cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name));
568 575 cx.spawn(async move |this, cx| {
569 576 if let Ok(Ok(Some(target))) = receiver.await {
570 this.update(cx, |this, cx| this.save_to(download, occurrence, target, cx))
571 .ok();
577 this.update(cx, |this, cx| {
578 this.save_to(download, occurrence, target, cx)
579 })
580 .ok();
572 581 }
573 582 })
574 583 .detach();
@@ -594,7 +603,9 @@ impl ConversationView {
594 603 let outcome = std::fs::write(&target, demo_recap::DEMO_FILE_BYTES)
595 604 .map(|_| target)
596 605 .map_err(|error| short_error(&error));
597 self.recap.downloads.insert(download, finished_state(outcome));
606 self.recap
607 .downloads
608 .insert(download, finished_state(outcome));
598 609 return;
599 610 }
600 611 let (Some(engine), Some(details)) = (engine, details) else {
@@ -604,8 +615,8 @@ impl ConversationView {
604 615 return;
605 616 };
606 617 drop(runtime::spawn(async move {
607 let outcome = save_download(&engine, download, &occurrence, &details, target, &sender)
608 .await;
618 let outcome =
619 save_download(&engine, download, &occurrence, &details, target, &sender).await;
609 620 let _ = sender.send(SaveEvent::Finished(outcome));
610 621 }));
611 622 cx.spawn(async move |this, cx| {
@@ -619,7 +630,9 @@ impl ConversationView {
619 630 .insert(download, DownloadState::Saving(percent));
620 631 }
621 632 SaveEvent::Finished(outcome) => {
622 this.recap.downloads.insert(download, finished_state(outcome));
633 this.recap
634 .downloads
635 .insert(download, finished_state(outcome));
623 636 }
624 637 }
625 638 }
@@ -8,20 +8,20 @@ use chatsvc::{
8 days_until_expiry,
8 days_until_expiry,
9};
9};
10use chrono::Utc;
10use chrono::Utc;
11use gpui_kit::component::WindowExt as _;
11use gpui_kit::component::button::{Button, ButtonVariants as _};
12use gpui_kit::component::button::{Button, ButtonVariants as _};
12use gpui_kit::component::dialog::DialogFooter;
13use gpui_kit::component::dialog::DialogFooter;
13use gpui_kit::component::input::{InputEvent, InputState};
14use gpui_kit::component::input::{InputEvent, InputState};
14use gpui_kit::component::WindowExt as _;
15use gpui_kit::*;
15use gpui_kit::*;
16
16
17use super::ConversationView;
17use super::ConversationView;
18use crate::app_state::{AppState, Selection};
18use crate::app_state::{AppState, Selection};
19use crate::rows::{MeetingInfo, MeetingSlot};
20use crate::channel_files::SharedContent;
19use crate::channel_files::SharedContent;
21use crate::demo_recap;
20use crate::demo_recap;
22use crate::downloads::{self, DownloadState};
21use crate::downloads::{self, DownloadState};
23use crate::notice::short_error;
22use crate::notice::short_error;
24use crate::recap::{DELETE_QUESTION, Load, save_name};
23use crate::recap::{DELETE_QUESTION, Load, save_name};
24use crate::rows::{MeetingInfo, MeetingSlot};
25use crate::runtime;
25use crate::runtime;
26use crate::views::channel_tabs::{ChannelPane, render_chat_bar};
26use crate::views::channel_tabs::{ChannelPane, render_chat_bar};
27use crate::views::recap_tab::{RecapCommand, RecapDownload, RecapRun, RecapView, render_recap};
27use crate::views::recap_tab::{RecapCommand, RecapDownload, RecapRun, RecapView, render_recap};
@@ -73,7 +73,8 @@ enum SaveEvent {
73
73
74impl ConversationView {
74impl ConversationView {
75 fn is_meeting_chat(&self, cx: &App) -> bool {
75 fn is_meeting_chat(&self, cx: &App) -> bool {
76 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|current| &current.selection)
76 let Some(Selection::Chat(chat_id)) =
77 self.current.as_ref().map(|current| &current.selection)
77 else {
78 else {
78 return false;
79 return false;
79 };
80 };
@@ -445,7 +446,13 @@ impl ConversationView {
445 }
446 }
446
447
447 fn can_delete_recording(&self, cx: &App) -> bool {
448 fn can_delete_recording(&self, cx: &App) -> bool {
448 let my_user_id = self.app.read(cx).directory.me.as_ref().map(|me| me.user_id.as_str());
449 let my_user_id = self
450 .app
451 .read(cx)
452 .directory
453 .me
454 .as_ref()
455 .map(|me| me.user_id.as_str());
449 match (self.selected_occurrence(), my_user_id) {
456 match (self.selected_occurrence(), my_user_id) {
450 (Some(occurrence), Some(my_user_id)) => {
457 (Some(occurrence), Some(my_user_id)) => {
451 occurrence.organizer_id.as_deref() == Some(my_user_id)
458 occurrence.organizer_id.as_deref() == Some(my_user_id)
@@ -567,8 +574,10 @@ impl ConversationView {
567 let receiver = cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name));
574 let receiver = cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name));
568 cx.spawn(async move |this, cx| {
575 cx.spawn(async move |this, cx| {
569 if let Ok(Ok(Some(target))) = receiver.await {
576 if let Ok(Ok(Some(target))) = receiver.await {
570 this.update(cx, |this, cx| this.save_to(download, occurrence, target, cx))
577 this.update(cx, |this, cx| {
571 .ok();
578 this.save_to(download, occurrence, target, cx)
579 })
580 .ok();
572 }
581 }
573 })
582 })
574 .detach();
583 .detach();
@@ -594,7 +603,9 @@ impl ConversationView {
594 let outcome = std::fs::write(&target, demo_recap::DEMO_FILE_BYTES)
603 let outcome = std::fs::write(&target, demo_recap::DEMO_FILE_BYTES)
595 .map(|_| target)
604 .map(|_| target)
596 .map_err(|error| short_error(&error));
605 .map_err(|error| short_error(&error));
597 self.recap.downloads.insert(download, finished_state(outcome));
606 self.recap
607 .downloads
608 .insert(download, finished_state(outcome));
598 return;
609 return;
599 }
610 }
600 let (Some(engine), Some(details)) = (engine, details) else {
611 let (Some(engine), Some(details)) = (engine, details) else {
@@ -604,8 +615,8 @@ impl ConversationView {
604 return;
615 return;
605 };
616 };
606 drop(runtime::spawn(async move {
617 drop(runtime::spawn(async move {
607 let outcome = save_download(&engine, download, &occurrence, &details, target, &sender)
618 let outcome =
608 .await;
619 save_download(&engine, download, &occurrence, &details, target, &sender).await;
609 let _ = sender.send(SaveEvent::Finished(outcome));
620 let _ = sender.send(SaveEvent::Finished(outcome));
610 }));
621 }));
611 cx.spawn(async move |this, cx| {
622 cx.spawn(async move |this, cx| {
@@ -619,7 +630,9 @@ impl ConversationView {
619 .insert(download, DownloadState::Saving(percent));
630 .insert(download, DownloadState::Saving(percent));
620 }
631 }
621 SaveEvent::Finished(outcome) => {
632 SaveEvent::Finished(outcome) => {
622 this.recap.downloads.insert(download, finished_state(outcome));
633 this.recap
634 .downloads
635 .insert(download, finished_state(outcome));
623 }
636 }
624 }
637 }
625 }
638 }
crates/app/src/views/conversation/scheduled.rs +1 −1
@@ -18,9 +18,9 @@ use crate::scheduled_rows::{
18 18 };
19 19 use crate::views::composer::{EditPreview, Outgoing};
20 20 use crate::views::message_actions::Action;
21 use crate::views::toolbar_placement::HoverChange;
22 21 use crate::views::message_row::{DeliveryActions, RowAction};
23 22 use crate::views::scheduled_toolbar::ScheduledMenu;
23 use crate::views::toolbar_placement::HoverChange;
24 24 use std::sync::Arc;
25 25
26 26 const EXCERPT_CHARS: usize = 140;
@@ -18,9 +18,9 @@ use crate::scheduled_rows::{
18};
18};
19use crate::views::composer::{EditPreview, Outgoing};
19use crate::views::composer::{EditPreview, Outgoing};
20use crate::views::message_actions::Action;
20use crate::views::message_actions::Action;
21use crate::views::toolbar_placement::HoverChange;
22use crate::views::message_row::{DeliveryActions, RowAction};
21use crate::views::message_row::{DeliveryActions, RowAction};
23use crate::views::scheduled_toolbar::ScheduledMenu;
22use crate::views::scheduled_toolbar::ScheduledMenu;
23use crate::views::toolbar_placement::HoverChange;
24use std::sync::Arc;
24use std::sync::Arc;
25
25
26const EXCERPT_CHARS: usize = 140;
26const EXCERPT_CHARS: usize = 140;
crates/app/src/views/conversation/shared.rs +6 −1
@@ -299,7 +299,12 @@ impl ConversationView {
299 299 }
300 300 }
301 301
302 pub(super) fn run_shared(&mut self, command: SharedCommand, window: &mut Window, cx: &mut Context<Self>) {
302 pub(super) fn run_shared(
303 &mut self,
304 command: SharedCommand,
305 window: &mut Window,
306 cx: &mut Context<Self>,
307 ) {
303 308 let conversation_id = self.conversation_id().unwrap_or_default();
304 309 match command {
305 310 SharedCommand::Scope(scope) => {
@@ -299,7 +299,12 @@ impl ConversationView {
299 }
299 }
300 }
300 }
301
301
302 pub(super) fn run_shared(&mut self, command: SharedCommand, window: &mut Window, cx: &mut Context<Self>) {
302 pub(super) fn run_shared(
303 &mut self,
304 command: SharedCommand,
305 window: &mut Window,
306 cx: &mut Context<Self>,
307 ) {
303 let conversation_id = self.conversation_id().unwrap_or_default();
308 let conversation_id = self.conversation_id().unwrap_or_default();
304 match command {
309 match command {
305 SharedCommand::Scope(scope) => {
310 SharedCommand::Scope(scope) => {
crates/app/src/views/customize_reactions.rs +7 −3
@@ -124,9 +124,12 @@ impl CustomizeForm {
124 124 .rounded(px(10.))
125 125 .tooltip(label)
126 126 .map(|button| match &glyph {
127 Some(glyph) => {
128 button.child(div().text_size(px(SLOT_GLYPH_SIZE)).child(glyph.clone()))
129 }
127 Some(glyph) => button.child(
128 div()
129 .text_size(px(SLOT_GLYPH_SIZE))
130 .font_family(theme::EMOJI_FONT_FAMILY)
131 .child(glyph.clone()),
132 ),
130 133 None => button.child(icon(IconName::Plus, 18., theme::text_muted())),
131 134 });
132 135 let (picker, view) = (self.picker.clone(), cx.entity().downgrade());
@@ -196,6 +199,7 @@ impl CustomizeForm {
196 199 .rounded_full()
197 200 .cursor_pointer()
198 201 .text_size(px(TONE_GLYPH_SIZE))
202 .font_family(theme::EMOJI_FONT_FAMILY)
199 203 .when(selected, |choice| choice.bg(theme::reaction_on_own()))
200 204 .when(!selected, |choice| {
201 205 choice.hover(|choice| choice.bg(theme::popup_hover()))
@@ -124,9 +124,12 @@ impl CustomizeForm {
124 .rounded(px(10.))
124 .rounded(px(10.))
125 .tooltip(label)
125 .tooltip(label)
126 .map(|button| match &glyph {
126 .map(|button| match &glyph {
127 Some(glyph) => {
127 Some(glyph) => button.child(
128 button.child(div().text_size(px(SLOT_GLYPH_SIZE)).child(glyph.clone()))
128 div()
129 }
129 .text_size(px(SLOT_GLYPH_SIZE))
130 .font_family(theme::EMOJI_FONT_FAMILY)
131 .child(glyph.clone()),
132 ),
130 None => button.child(icon(IconName::Plus, 18., theme::text_muted())),
133 None => button.child(icon(IconName::Plus, 18., theme::text_muted())),
131 });
134 });
132 let (picker, view) = (self.picker.clone(), cx.entity().downgrade());
135 let (picker, view) = (self.picker.clone(), cx.entity().downgrade());
@@ -196,6 +199,7 @@ impl CustomizeForm {
196 .rounded_full()
199 .rounded_full()
197 .cursor_pointer()
200 .cursor_pointer()
198 .text_size(px(TONE_GLYPH_SIZE))
201 .text_size(px(TONE_GLYPH_SIZE))
202 .font_family(theme::EMOJI_FONT_FAMILY)
199 .when(selected, |choice| choice.bg(theme::reaction_on_own()))
203 .when(selected, |choice| choice.bg(theme::reaction_on_own()))
200 .when(!selected, |choice| {
204 .when(!selected, |choice| {
201 choice.hover(|choice| choice.bg(theme::popup_hover()))
205 choice.hover(|choice| choice.bg(theme::popup_hover()))
crates/app/src/views/find_panel.rs +3 −2
@@ -1,11 +1,11 @@
1 1 use std::time::Duration;
2 2
3 3 use chrono::{Local, NaiveDate, Offset};
4 use gpui_kit::component::scroll::ScrollableElement as _;
5 4 use gpui_kit::assets::IconName;
6 5 use gpui_kit::component::button::{Button, ButtonVariants as _};
7 6 use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
8 7 use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
8 use gpui_kit::component::scroll::ScrollableElement as _;
9 9 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
10 10 use gpui_kit::prelude::FluentBuilder as _;
11 11 use gpui_kit::*;
@@ -521,7 +521,8 @@ impl FindPanel {
521 521 div()
522 522 .text_size(px(13.))
523 523 .text_color(theme::text_soft())
524 .line_clamp(2).text_ellipsis()
524 .line_clamp(2)
525 .text_ellipsis()
525 526 .child(StyledText::new(hit.text.clone()).with_highlights(marks)),
526 527 )
527 528 .on_click(cx.listener(move |panel, _, _, cx| panel.pick(index, cx)))
@@ -1,11 +1,11 @@
1use std::time::Duration;
1use std::time::Duration;
2
2
3use chrono::{Local, NaiveDate, Offset};
3use chrono::{Local, NaiveDate, Offset};
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
6use gpui_kit::component::button::{Button, ButtonVariants as _};
5use gpui_kit::component::button::{Button, ButtonVariants as _};
7use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
6use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
8use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
7use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
8use gpui_kit::component::scroll::ScrollableElement as _;
9use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
9use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
11use gpui_kit::*;
@@ -521,7 +521,8 @@ impl FindPanel {
521 div()
521 div()
522 .text_size(px(13.))
522 .text_size(px(13.))
523 .text_color(theme::text_soft())
523 .text_color(theme::text_soft())
524 .line_clamp(2).text_ellipsis()
524 .line_clamp(2)
525 .text_ellipsis()
525 .child(StyledText::new(hit.text.clone()).with_highlights(marks)),
526 .child(StyledText::new(hit.text.clone()).with_highlights(marks)),
526 )
527 )
527 .on_click(cx.listener(move |panel, _, _, cx| panel.pick(index, cx)))
528 .on_click(cx.listener(move |panel, _, _, cx| panel.pick(index, cx)))
crates/app/src/views/format_toolbar.rs +43 −27
@@ -1,10 +1,10 @@
1 1 use std::rc::Rc;
2 2
3 use gpui_kit::assets::IconName;
3 4 use gpui_kit::component::input::{Input, InputState};
4 5 use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
5 6 use gpui_kit::component::{h_flex, v_flex};
6 7 use gpui_kit::prelude::FluentBuilder as _;
7 use gpui_kit::assets::IconName;
8 8 use gpui_kit::*;
9 9 use teams_core::FormatState;
10 10
@@ -303,13 +303,11 @@ impl FormatButton {
303 303 FormatButton::Numbered => symbol("format_list_numbered", 18., color).into_any_element(),
304 304 FormatButton::Quote => symbol("format_quote", 18., color).into_any_element(),
305 305 FormatButton::Table => symbol("table", 18., color).into_any_element(),
306 FormatButton::TableInsertLine => {
307 symbol("table_chart", 20., color).into_any_element()
308 }
309 FormatButton::TableRemoveLine => {
310 symbol("grid_off", 20., color).into_any_element()
306 FormatButton::TableInsertLine => symbol("table_chart", 20., color).into_any_element(),
307 FormatButton::TableRemoveLine => symbol("grid_off", 20., color).into_any_element(),
308 FormatButton::Highlight => {
309 symbol("format_ink_highlighter", 20., color).into_any_element()
311 310 }
312 FormatButton::Highlight => symbol("format_ink_highlighter", 20., color).into_any_element(),
313 311 FormatButton::FontColor => symbol("format_color_text", 20., color).into_any_element(),
314 312 FormatButton::ParagraphStyle => h_flex()
315 313 .w_full()
@@ -322,20 +320,14 @@ impl FormatButton {
322 320 .child(label.unwrap_or_default())
323 321 .child(icon(IconName::ChevronDown, 12., color))
324 322 .into_any_element(),
325 FormatButton::ClearFormatting => {
326 symbol("format_clear", 20., color).into_any_element()
327 }
323 FormatButton::ClearFormatting => symbol("format_clear", 20., color).into_any_element(),
328 324 FormatButton::Outdent => {
329 325 symbol("format_indent_decrease", 20., color).into_any_element()
330 326 }
331 FormatButton::Indent => {
332 symbol("format_indent_increase", 20., color).into_any_element()
333 }
327 FormatButton::Indent => symbol("format_indent_increase", 20., color).into_any_element(),
334 328 FormatButton::CodeBlock => symbol("code_blocks", 20., color).into_any_element(),
335 329 FormatButton::Rule => symbol("horizontal_rule", 20., color).into_any_element(),
336 FormatButton::FontSize => {
337 symbol("format_size", 20., color).into_any_element()
338 }
330 FormatButton::FontSize => symbol("format_size", 20., color).into_any_element(),
339 331 FormatButton::More => icon(IconName::Ellipsis, 18., color).into_any_element(),
340 332 }
341 333 }
@@ -605,7 +597,9 @@ fn menu_row(
605 597 _ => format.content(color, None),
606 598 };
607 599 div()
608 .id(ElementId::Name(format!("format-overflow-{format:?}").into()))
600 .id(ElementId::Name(
601 format!("format-overflow-{format:?}").into(),
602 ))
609 603 .relative()
610 604 .mx(px(MENU_PADDING))
611 605 .h(px(MENU_ROW_HEIGHT))
@@ -754,12 +748,10 @@ mod tests {
754 748 use gpui_kit::px;
755 749
756 750 use super::{
757 ARROW_MARGIN, BAR_GROUPS, BUTTON, ButtonState, FormatButton, FormatState,
758 SELECTION_GROUPS, bar_width, fit_groups, groups_width, menu_groups, place, toggle_symbol,
759 toggle_tooltip,
751 ARROW_MARGIN, BAR_GROUPS, BUTTON, ButtonState, FormatButton, FormatState, SELECTION_GROUPS,
752 bar_width, fit_groups, groups_width, menu_groups, place, toggle_symbol, toggle_tooltip,
760 753 };
761 754
762
763 755 #[test]
764 756 fn the_bar_centers_over_the_selection() {
765 757 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
@@ -799,7 +791,11 @@ mod tests {
799 791 .iter()
800 792 .all(|group| !group.contains(&FormatButton::Table))
801 793 );
802 assert!(SELECTION_GROUPS.iter().any(|group| group == &[FormatButton::FontSize]));
794 assert!(
795 SELECTION_GROUPS
796 .iter()
797 .any(|group| group == &[FormatButton::FontSize])
798 );
803 799 assert!(bar_width() > 12. * BUTTON);
804 800 }
805 801
@@ -849,10 +845,20 @@ mod tests {
849 845
850 846 #[test]
851 847 fn single_buttons_leave_from_the_end_and_keep_their_groups() {
852 let all: Vec<FormatButton> = BAR_GROUPS.iter().flat_map(|group| group.iter()).copied().collect();
848 let all: Vec<FormatButton> = BAR_GROUPS
849 .iter()
850 .flat_map(|group| group.iter())
851 .copied()
852 .collect();
853 853 let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
854 854 assert_eq!(flat(&fit.overflow), all[all.len() - 2..]);
855 assert_eq!(fit.overflow, vec![vec![FormatButton::TableInsertLine, FormatButton::TableRemoveLine]]);
855 assert_eq!(
856 fit.overflow,
857 vec![vec![
858 FormatButton::TableInsertLine,
859 FormatButton::TableRemoveLine
860 ]]
861 );
856 862 assert_eq!(fit.visible.last(), Some(&vec![FormatButton::Table]));
857 863 let mut both = flat(&fit.visible);
858 864 both.extend(flat(&fit.overflow));
@@ -863,9 +869,17 @@ mod tests {
863 869 fn a_cut_between_groups_leaves_no_empty_group_on_either_side() {
864 870 let two = groups_width(&BAR_GROUPS[..2]);
865 871 let fit = fit_groups(two + 2. + BUTTON, &BAR_GROUPS);
866 assert_eq!(fit.visible, vec![BAR_GROUPS[0].to_vec(), BAR_GROUPS[1].to_vec()]);
872 assert_eq!(
873 fit.visible,
874 vec![BAR_GROUPS[0].to_vec(), BAR_GROUPS[1].to_vec()]
875 );
867 876 assert_eq!(fit.overflow.len(), BAR_GROUPS.len() - 2);
868 assert!(fit.overflow.iter().chain(&fit.visible).all(|group| !group.is_empty()));
877 assert!(
878 fit.overflow
879 .iter()
880 .chain(&fit.visible)
881 .all(|group| !group.is_empty())
882 );
869 883 let fit = fit_groups(two + 2. + BUTTON - 1., &BAR_GROUPS);
870 884 assert_eq!(fit.visible.len(), 2);
871 885 assert_eq!(fit.visible[1], vec![FormatButton::Superscript]);
@@ -876,7 +890,9 @@ mod tests {
876 890 fn outside_a_table_the_menu_drops_the_table_edits_and_their_group() {
877 891 let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
878 892 let outside = |format: FormatButton| match format {
879 FormatButton::TableInsertLine | FormatButton::TableRemoveLine => ButtonState::disabled(),
893 FormatButton::TableInsertLine | FormatButton::TableRemoveLine => {
894 ButtonState::disabled()
895 }
880 896 _ => ButtonState::enabled(FormatState::Off),
881 897 };
882 898 assert!(menu_groups(&fit.overflow, &outside).is_empty());
@@ -1,10 +1,10 @@
1use std::rc::Rc;
1use std::rc::Rc;
2
2
3use gpui_kit::assets::IconName;
3use gpui_kit::component::input::{Input, InputState};
4use gpui_kit::component::input::{Input, InputState};
4use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
5use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::assets::IconName;
8use gpui_kit::*;
8use gpui_kit::*;
9use teams_core::FormatState;
9use teams_core::FormatState;
10
10
@@ -303,13 +303,11 @@ impl FormatButton {
303 FormatButton::Numbered => symbol("format_list_numbered", 18., color).into_any_element(),
303 FormatButton::Numbered => symbol("format_list_numbered", 18., color).into_any_element(),
304 FormatButton::Quote => symbol("format_quote", 18., color).into_any_element(),
304 FormatButton::Quote => symbol("format_quote", 18., color).into_any_element(),
305 FormatButton::Table => symbol("table", 18., color).into_any_element(),
305 FormatButton::Table => symbol("table", 18., color).into_any_element(),
306 FormatButton::TableInsertLine => {
306 FormatButton::TableInsertLine => symbol("table_chart", 20., color).into_any_element(),
307 symbol("table_chart", 20., color).into_any_element()
307 FormatButton::TableRemoveLine => symbol("grid_off", 20., color).into_any_element(),
308 }
308 FormatButton::Highlight => {
309 FormatButton::TableRemoveLine => {
309 symbol("format_ink_highlighter", 20., color).into_any_element()
310 symbol("grid_off", 20., color).into_any_element()
311 }
310 }
312 FormatButton::Highlight => symbol("format_ink_highlighter", 20., color).into_any_element(),
313 FormatButton::FontColor => symbol("format_color_text", 20., color).into_any_element(),
311 FormatButton::FontColor => symbol("format_color_text", 20., color).into_any_element(),
314 FormatButton::ParagraphStyle => h_flex()
312 FormatButton::ParagraphStyle => h_flex()
315 .w_full()
313 .w_full()
@@ -322,20 +320,14 @@ impl FormatButton {
322 .child(label.unwrap_or_default())
320 .child(label.unwrap_or_default())
323 .child(icon(IconName::ChevronDown, 12., color))
321 .child(icon(IconName::ChevronDown, 12., color))
324 .into_any_element(),
322 .into_any_element(),
325 FormatButton::ClearFormatting => {
323 FormatButton::ClearFormatting => symbol("format_clear", 20., color).into_any_element(),
326 symbol("format_clear", 20., color).into_any_element()
327 }
328 FormatButton::Outdent => {
324 FormatButton::Outdent => {
329 symbol("format_indent_decrease", 20., color).into_any_element()
325 symbol("format_indent_decrease", 20., color).into_any_element()
330 }
326 }
331 FormatButton::Indent => {
327 FormatButton::Indent => symbol("format_indent_increase", 20., color).into_any_element(),
332 symbol("format_indent_increase", 20., color).into_any_element()
333 }
334 FormatButton::CodeBlock => symbol("code_blocks", 20., color).into_any_element(),
328 FormatButton::CodeBlock => symbol("code_blocks", 20., color).into_any_element(),
335 FormatButton::Rule => symbol("horizontal_rule", 20., color).into_any_element(),
329 FormatButton::Rule => symbol("horizontal_rule", 20., color).into_any_element(),
336 FormatButton::FontSize => {
330 FormatButton::FontSize => symbol("format_size", 20., color).into_any_element(),
337 symbol("format_size", 20., color).into_any_element()
338 }
339 FormatButton::More => icon(IconName::Ellipsis, 18., color).into_any_element(),
331 FormatButton::More => icon(IconName::Ellipsis, 18., color).into_any_element(),
340 }
332 }
341 }
333 }
@@ -605,7 +597,9 @@ fn menu_row(
605 _ => format.content(color, None),
597 _ => format.content(color, None),
606 };
598 };
607 div()
599 div()
608 .id(ElementId::Name(format!("format-overflow-{format:?}").into()))
600 .id(ElementId::Name(
601 format!("format-overflow-{format:?}").into(),
602 ))
609 .relative()
603 .relative()
610 .mx(px(MENU_PADDING))
604 .mx(px(MENU_PADDING))
611 .h(px(MENU_ROW_HEIGHT))
605 .h(px(MENU_ROW_HEIGHT))
@@ -754,12 +748,10 @@ mod tests {
754 use gpui_kit::px;
748 use gpui_kit::px;
755
749
756 use super::{
750 use super::{
757 ARROW_MARGIN, BAR_GROUPS, BUTTON, ButtonState, FormatButton, FormatState,
751 ARROW_MARGIN, BAR_GROUPS, BUTTON, ButtonState, FormatButton, FormatState, SELECTION_GROUPS,
758 SELECTION_GROUPS, bar_width, fit_groups, groups_width, menu_groups, place, toggle_symbol,
752 bar_width, fit_groups, groups_width, menu_groups, place, toggle_symbol, toggle_tooltip,
759 toggle_tooltip,
760 };
753 };
761
754
762
763 #[test]
755 #[test]
764 fn the_bar_centers_over_the_selection() {
756 fn the_bar_centers_over_the_selection() {
765 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
757 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
@@ -799,7 +791,11 @@ mod tests {
799 .iter()
791 .iter()
800 .all(|group| !group.contains(&FormatButton::Table))
792 .all(|group| !group.contains(&FormatButton::Table))
801 );
793 );
802 assert!(SELECTION_GROUPS.iter().any(|group| group == &[FormatButton::FontSize]));
794 assert!(
795 SELECTION_GROUPS
796 .iter()
797 .any(|group| group == &[FormatButton::FontSize])
798 );
803 assert!(bar_width() > 12. * BUTTON);
799 assert!(bar_width() > 12. * BUTTON);
804 }
800 }
805
801
@@ -849,10 +845,20 @@ mod tests {
849
845
850 #[test]
846 #[test]
851 fn single_buttons_leave_from_the_end_and_keep_their_groups() {
847 fn single_buttons_leave_from_the_end_and_keep_their_groups() {
852 let all: Vec<FormatButton> = BAR_GROUPS.iter().flat_map(|group| group.iter()).copied().collect();
848 let all: Vec<FormatButton> = BAR_GROUPS
849 .iter()
850 .flat_map(|group| group.iter())
851 .copied()
852 .collect();
853 let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
853 let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
854 assert_eq!(flat(&fit.overflow), all[all.len() - 2..]);
854 assert_eq!(flat(&fit.overflow), all[all.len() - 2..]);
855 assert_eq!(fit.overflow, vec![vec![FormatButton::TableInsertLine, FormatButton::TableRemoveLine]]);
855 assert_eq!(
856 fit.overflow,
857 vec![vec![
858 FormatButton::TableInsertLine,
859 FormatButton::TableRemoveLine
860 ]]
861 );
856 assert_eq!(fit.visible.last(), Some(&vec![FormatButton::Table]));
862 assert_eq!(fit.visible.last(), Some(&vec![FormatButton::Table]));
857 let mut both = flat(&fit.visible);
863 let mut both = flat(&fit.visible);
858 both.extend(flat(&fit.overflow));
864 both.extend(flat(&fit.overflow));
@@ -863,9 +869,17 @@ mod tests {
863 fn a_cut_between_groups_leaves_no_empty_group_on_either_side() {
869 fn a_cut_between_groups_leaves_no_empty_group_on_either_side() {
864 let two = groups_width(&BAR_GROUPS[..2]);
870 let two = groups_width(&BAR_GROUPS[..2]);
865 let fit = fit_groups(two + 2. + BUTTON, &BAR_GROUPS);
871 let fit = fit_groups(two + 2. + BUTTON, &BAR_GROUPS);
866 assert_eq!(fit.visible, vec![BAR_GROUPS[0].to_vec(), BAR_GROUPS[1].to_vec()]);
872 assert_eq!(
873 fit.visible,
874 vec![BAR_GROUPS[0].to_vec(), BAR_GROUPS[1].to_vec()]
875 );
867 assert_eq!(fit.overflow.len(), BAR_GROUPS.len() - 2);
876 assert_eq!(fit.overflow.len(), BAR_GROUPS.len() - 2);
868 assert!(fit.overflow.iter().chain(&fit.visible).all(|group| !group.is_empty()));
877 assert!(
878 fit.overflow
879 .iter()
880 .chain(&fit.visible)
881 .all(|group| !group.is_empty())
882 );
869 let fit = fit_groups(two + 2. + BUTTON - 1., &BAR_GROUPS);
883 let fit = fit_groups(two + 2. + BUTTON - 1., &BAR_GROUPS);
870 assert_eq!(fit.visible.len(), 2);
884 assert_eq!(fit.visible.len(), 2);
871 assert_eq!(fit.visible[1], vec![FormatButton::Superscript]);
885 assert_eq!(fit.visible[1], vec![FormatButton::Superscript]);
@@ -876,7 +890,9 @@ mod tests {
876 fn outside_a_table_the_menu_drops_the_table_edits_and_their_group() {
890 fn outside_a_table_the_menu_drops_the_table_edits_and_their_group() {
877 let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
891 let fit = fit_groups(groups_width(&BAR_GROUPS) - 1., &BAR_GROUPS);
878 let outside = |format: FormatButton| match format {
892 let outside = |format: FormatButton| match format {
879 FormatButton::TableInsertLine | FormatButton::TableRemoveLine => ButtonState::disabled(),
893 FormatButton::TableInsertLine | FormatButton::TableRemoveLine => {
894 ButtonState::disabled()
895 }
880 _ => ButtonState::enabled(FormatState::Off),
896 _ => ButtonState::enabled(FormatState::Off),
881 };
897 };
882 assert!(menu_groups(&fit.overflow, &outside).is_empty());
898 assert!(menu_groups(&fit.overflow, &outside).is_empty());
crates/app/src/views/forward_dialog.rs +3 −2
@@ -1,5 +1,5 @@
1 use gpui_kit::component::scroll::ScrollableElement as _;
2 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 3 use gpui_kit::component::{
4 4 button::{Button, ButtonVariants as _},
5 5 h_flex,
@@ -462,7 +462,8 @@ fn preview_quote(item: &ForwardItem, lines: usize) -> Div {
462 462 )
463 463 .child(
464 464 div()
465 .line_clamp(lines).text_ellipsis()
465 .line_clamp(lines)
466 .text_ellipsis()
466 467 .text_size(px(12.5))
467 468 .text_color(theme::text_muted())
468 469 .child(text),
@@ -1,5 +1,5 @@
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::component::{
3use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
4 button::{Button, ButtonVariants as _},
5 h_flex,
5 h_flex,
@@ -462,7 +462,8 @@ fn preview_quote(item: &ForwardItem, lines: usize) -> Div {
462 )
462 )
463 .child(
463 .child(
464 div()
464 div()
465 .line_clamp(lines).text_ellipsis()
465 .line_clamp(lines)
466 .text_ellipsis()
466 .text_size(px(12.5))
467 .text_size(px(12.5))
467 .text_color(theme::text_muted())
468 .text_color(theme::text_muted())
468 .child(text),
469 .child(text),
crates/app/src/views/fun_picker.rs +5 −3
@@ -2,8 +2,8 @@ use crate::views::image_memory::bounded;
2 2 use std::rc::Rc;
3 3 use std::time::Duration;
4 4
5 use gpui_kit::component::scroll::ScrollableElement as _;
6 5 use gpui_kit::base::PopoverState;
6 use gpui_kit::component::scroll::ScrollableElement as _;
7 7 use gpui_kit::component::{
8 8 h_flex,
9 9 input::{Input, InputEvent, InputState},
@@ -28,7 +28,8 @@ const HEIGHT: f32 = 380.;
28 28 const PADDING: f32 = 8.;
29 29 const CONTENT_WIDTH: f32 = WIDTH - 2. * PADDING;
30 30 const EMOJI_COLUMNS: usize = 10;
31 const EMOJI_CELL: f32 = (CONTENT_WIDTH - EMOJI_GAP * (EMOJI_COLUMNS - 1) as f32) / EMOJI_COLUMNS as f32;
31 const EMOJI_CELL: f32 =
32 (CONTENT_WIDTH - EMOJI_GAP * (EMOJI_COLUMNS - 1) as f32) / EMOJI_COLUMNS as f32;
32 33 const EMOJI_GAP: f32 = 2.;
33 34 const EMOJI_SEARCH_LIMIT: usize = 240;
34 35 const GIF_COLUMNS: usize = 3;
@@ -342,7 +343,8 @@ impl FunPicker {
342 343
343 344 fn pick_tone(&mut self, glyph: &str, tone: u8, cx: &mut Context<Self>) {
344 345 self.skin_tone = tone;
345 self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));
346 self.app
347 .update(cx, |state, cx| state.set_skin_tone(tone, cx));
346 348 self.pick_emoji(&emoticons::with_tone(glyph, tone), cx);
347 349 }
348 350
@@ -2,8 +2,8 @@ use crate::views::image_memory::bounded;
2use std::rc::Rc;
2use std::rc::Rc;
3use std::time::Duration;
3use std::time::Duration;
4
4
5use gpui_kit::component::scroll::ScrollableElement as _;
6use gpui_kit::base::PopoverState;
5use gpui_kit::base::PopoverState;
6use gpui_kit::component::scroll::ScrollableElement as _;
7use gpui_kit::component::{
7use gpui_kit::component::{
8 h_flex,
8 h_flex,
9 input::{Input, InputEvent, InputState},
9 input::{Input, InputEvent, InputState},
@@ -28,7 +28,8 @@ const HEIGHT: f32 = 380.;
28const PADDING: f32 = 8.;
28const PADDING: f32 = 8.;
29const CONTENT_WIDTH: f32 = WIDTH - 2. * PADDING;
29const CONTENT_WIDTH: f32 = WIDTH - 2. * PADDING;
30const EMOJI_COLUMNS: usize = 10;
30const EMOJI_COLUMNS: usize = 10;
31const EMOJI_CELL: f32 = (CONTENT_WIDTH - EMOJI_GAP * (EMOJI_COLUMNS - 1) as f32) / EMOJI_COLUMNS as f32;
31const EMOJI_CELL: f32 =
32 (CONTENT_WIDTH - EMOJI_GAP * (EMOJI_COLUMNS - 1) as f32) / EMOJI_COLUMNS as f32;
32const EMOJI_GAP: f32 = 2.;
33const EMOJI_GAP: f32 = 2.;
33const EMOJI_SEARCH_LIMIT: usize = 240;
34const EMOJI_SEARCH_LIMIT: usize = 240;
34const GIF_COLUMNS: usize = 3;
35const GIF_COLUMNS: usize = 3;
@@ -342,7 +343,8 @@ impl FunPicker {
342
343
343 fn pick_tone(&mut self, glyph: &str, tone: u8, cx: &mut Context<Self>) {
344 fn pick_tone(&mut self, glyph: &str, tone: u8, cx: &mut Context<Self>) {
344 self.skin_tone = tone;
345 self.skin_tone = tone;
345 self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));
346 self.app
347 .update(cx, |state, cx| state.set_skin_tone(tone, cx));
346 self.pick_emoji(&emoticons::with_tone(glyph, tone), cx);
348 self.pick_emoji(&emoticons::with_tone(glyph, tone), cx);
347 }
349 }
348
350
crates/app/src/views/group_name.rs +8 −2
@@ -152,7 +152,12 @@ impl Render for GroupNameForm {
152 152 #[derive(Clone, Default)]
153 153 pub struct GroupNameSlot(Rc<RefCell<Option<Entity<GroupNameForm>>>>);
154 154
155 pub fn group_name_button(app: &Entity<AppState>, slot: &GroupNameSlot, chat_id: &str, title: &str) -> AnyElement {
155 pub fn group_name_button(
156 app: &Entity<AppState>,
157 slot: &GroupNameSlot,
158 chat_id: &str,
159 title: &str,
160 ) -> AnyElement {
156 161 let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());
157 162 let form = slot.0.clone();
158 163 let reset = form.clone();
@@ -174,7 +179,8 @@ pub fn group_name_button(app: &Entity<AppState>, slot: &GroupNameSlot, chat_id:
174 179 })
175 180 .content(move |_, window, cx| {
176 181 let existing = form.borrow().clone();
177 if let Some(existing) = existing.filter(|existing| existing.read(cx).chat_id == chat_id) {
182 if let Some(existing) = existing.filter(|existing| existing.read(cx).chat_id == chat_id)
183 {
178 184 return existing;
179 185 }
180 186 let popover = cx.entity().downgrade();
@@ -152,7 +152,12 @@ impl Render for GroupNameForm {
152#[derive(Clone, Default)]
152#[derive(Clone, Default)]
153pub struct GroupNameSlot(Rc<RefCell<Option<Entity<GroupNameForm>>>>);
153pub struct GroupNameSlot(Rc<RefCell<Option<Entity<GroupNameForm>>>>);
154
154
155pub fn group_name_button(app: &Entity<AppState>, slot: &GroupNameSlot, chat_id: &str, title: &str) -> AnyElement {
155pub fn group_name_button(
156 app: &Entity<AppState>,
157 slot: &GroupNameSlot,
158 chat_id: &str,
159 title: &str,
160) -> AnyElement {
156 let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());
161 let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());
157 let form = slot.0.clone();
162 let form = slot.0.clone();
158 let reset = form.clone();
163 let reset = form.clone();
@@ -174,7 +179,8 @@ pub fn group_name_button(app: &Entity<AppState>, slot: &GroupNameSlot, chat_id:
174 })
179 })
175 .content(move |_, window, cx| {
180 .content(move |_, window, cx| {
176 let existing = form.borrow().clone();
181 let existing = form.borrow().clone();
177 if let Some(existing) = existing.filter(|existing| existing.read(cx).chat_id == chat_id) {
182 if let Some(existing) = existing.filter(|existing| existing.read(cx).chat_id == chat_id)
183 {
178 return existing;
184 return existing;
179 }
185 }
180 let popover = cx.entity().downgrade();
186 let popover = cx.entity().downgrade();
crates/app/src/views/image_memory.rs +59 −19
@@ -4,8 +4,8 @@ use std::sync::Arc;
4 4 use std::time::{Duration, Instant};
5 5
6 6 use gpui_kit::{
7 App, AppContext, Entity, EntityId, Global, ImageCacheError, ImageCacheItem, ImageSource, RenderImage, Resource,
8 Window, hash,
7 App, AppContext, Entity, EntityId, Global, ImageCacheError, ImageCacheItem, ImageSource,
8 RenderImage, Resource, Window, hash,
9 9 };
10 10 use image::imageops::FilterType;
11 11 use image::{Frame, ImageFormat, ImageReader};
@@ -19,9 +19,9 @@ const PREVIEW_EDGE: u32 = 720;
19 19 /// An image source whose decoded pixels are freed again once the image has been off screen for a while and the budget is full.
20 20 pub fn bounded(source: impl Into<ImageSource>) -> ImageSource {
21 21 match source.into() {
22 ImageSource::Resource(resource) => {
23 ImageSource::Custom(Arc::new(move |window, cx| load(Request::Full(&resource), window, cx)))
24 }
22 ImageSource::Resource(resource) => ImageSource::Custom(Arc::new(move |window, cx| {
23 load(Request::Full(&resource), window, cx)
24 })),
25 25 other => other,
26 26 }
27 27 }
@@ -29,7 +29,9 @@ pub fn bounded(source: impl Into<ImageSource>) -> ImageSource {
29 29 /// Like [`bounded`], but a still picture is decoded scaled down to at most [`PREVIEW_EDGE`] pixels, for thumbnails of full-size photos.
30 30 pub fn preview(path: PathBuf) -> ImageSource {
31 31 let path: Arc<Path> = path.into();
32 ImageSource::Custom(Arc::new(move |window, cx| load(Request::Preview(&path), window, cx)))
32 ImageSource::Custom(Arc::new(move |window, cx| {
33 load(Request::Preview(&path), window, cx)
34 }))
33 35 }
34 36
35 37 #[derive(Clone, Copy)]
@@ -42,7 +44,11 @@ struct SharedImages(Entity<BoundedImages>);
42 44
43 45 impl Global for SharedImages {}
44 46
45 fn load(request: Request, window: &mut Window, cx: &mut App) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
47 fn load(
48 request: Request,
49 window: &mut Window,
50 cx: &mut App,
51 ) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
46 52 let images = match cx.try_global::<SharedImages>() {
47 53 Some(shared) => shared.0.clone(),
48 54 None => {
@@ -92,7 +98,9 @@ impl BoundedImages {
92 98 Request::Full(resource) => Pixels::Item(ImageCacheItem::new(resource, cx)),
93 99 Request::Preview(path) => {
94 100 start_preview(handle, key, path.clone(), cx);
95 Pixels::Decoding { waiting: Vec::new() }
101 Pixels::Decoding {
102 waiting: Vec::new(),
103 }
96 104 }
97 105 },
98 106 last_use: now,
@@ -119,7 +127,13 @@ impl BoundedImages {
119 127 result
120 128 }
121 129
122 fn finish_preview(&mut self, key: u64, path: Arc<Path>, decoded: Option<RenderImage>, cx: &mut App) {
130 fn finish_preview(
131 &mut self,
132 key: u64,
133 path: Arc<Path>,
134 decoded: Option<RenderImage>,
135 cx: &mut App,
136 ) {
123 137 let Some(entry) = self.entries.get_mut(&key) else {
124 138 return;
125 139 };
@@ -135,14 +149,20 @@ impl BoundedImages {
135 149 }
136 150
137 151 fn trim(&mut self, now: Instant) {
138 let sizes: Vec<(u64, Instant, u64)> =
139 self.entries.iter().map(|(key, entry)| (*key, entry.last_use, entry.bytes)).collect();
152 let sizes: Vec<(u64, Instant, u64)> = self
153 .entries
154 .iter()
155 .map(|(key, entry)| (*key, entry.last_use, entry.bytes))
156 .collect();
140 157 let mut freed_bytes = 0;
141 158 for key in evictions(sizes, now) {
142 159 freed_bytes += self.entries.remove(&key).map_or(0, |entry| entry.bytes);
143 160 }
144 161 self.freed_bytes += freed_bytes;
145 if self.last_report.is_none_or(|last| now.duration_since(last) >= REPORT_EVERY) {
162 if self
163 .last_report
164 .is_none_or(|last| now.duration_since(last) >= REPORT_EVERY)
165 {
146 166 self.last_report = Some(now);
147 167 let kept_bytes: u64 = self.entries.values().map(|entry| entry.bytes).sum();
148 168 app_base::diagnostics::record(&format!(
@@ -159,15 +179,25 @@ fn start_preview(handle: &Entity<BoundedImages>, key: u64, path: Arc<Path>, cx:
159 179 let images = handle.downgrade();
160 180 cx.spawn(async move |cx| {
161 181 let source = path.clone();
162 let decoded = cx.background_executor().spawn(async move { decode_preview(&source) }).await;
163 images.update(cx, |images, cx| images.finish_preview(key, path, decoded, cx)).ok();
182 let decoded = cx
183 .background_executor()
184 .spawn(async move { decode_preview(&source) })
185 .await;
186 images
187 .update(cx, |images, cx| {
188 images.finish_preview(key, path, decoded, cx)
189 })
190 .ok();
164 191 })
165 192 .detach();
166 193 }
167 194
168 195 fn decode_preview(path: &Path) -> Option<RenderImage> {
169 196 let reader = ImageReader::open(path).ok()?.with_guessed_format().ok()?;
170 if !matches!(reader.format()?, ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Bmp) {
197 if !matches!(
198 reader.format()?,
199 ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Bmp
200 ) {
171 201 return None;
172 202 }
173 203 let decoded = reader.decode().ok()?;
@@ -225,7 +255,10 @@ mod tests {
225 255 #[test]
226 256 fn images_shown_just_now_stay_even_over_budget() {
227 257 let now = Instant::now() + Duration::from_secs(600);
228 let sizes = vec![(1, now - Duration::from_secs(2), 50 * MEGABYTE), (2, now, 50 * MEGABYTE)];
258 let sizes = vec![
259 (1, now - Duration::from_secs(2), 50 * MEGABYTE),
260 (2, now, 50 * MEGABYTE),
261 ];
229 262 assert!(evictions(sizes, now).is_empty());
230 263 }
231 264
@@ -239,11 +272,18 @@ mod tests {
239 272 fn a_large_photo_is_decoded_scaled_down_and_an_animation_is_left_to_gpui() {
240 273 let directory = tempfile::tempdir().unwrap();
241 274 let photo = directory.path().join("photo");
242 image::RgbaImage::new(3000, 2000).save_with_format(&photo, ImageFormat::Png).unwrap();
275 image::RgbaImage::new(3000, 2000)
276 .save_with_format(&photo, ImageFormat::Png)
277 .unwrap();
243 278 let decoded = decode_preview(&photo).unwrap();
244 assert_eq!((decoded.size(0).width.0, decoded.size(0).height.0), (720, 480));
279 assert_eq!(
280 (decoded.size(0).width.0, decoded.size(0).height.0),
281 (720, 480)
282 );
245 283 let animation = directory.path().join("animation");
246 image::RgbaImage::new(10, 10).save_with_format(&animation, ImageFormat::Gif).unwrap();
284 image::RgbaImage::new(10, 10)
285 .save_with_format(&animation, ImageFormat::Gif)
286 .unwrap();
247 287 assert!(decode_preview(&animation).is_none());
248 288 }
249 289 }
@@ -4,8 +4,8 @@ use std::sync::Arc;
4use std::time::{Duration, Instant};
4use std::time::{Duration, Instant};
5
5
6use gpui_kit::{
6use gpui_kit::{
7 App, AppContext, Entity, EntityId, Global, ImageCacheError, ImageCacheItem, ImageSource, RenderImage, Resource,
7 App, AppContext, Entity, EntityId, Global, ImageCacheError, ImageCacheItem, ImageSource,
8 Window, hash,
8 RenderImage, Resource, Window, hash,
9};
9};
10use image::imageops::FilterType;
10use image::imageops::FilterType;
11use image::{Frame, ImageFormat, ImageReader};
11use image::{Frame, ImageFormat, ImageReader};
@@ -19,9 +19,9 @@ const PREVIEW_EDGE: u32 = 720;
19/// An image source whose decoded pixels are freed again once the image has been off screen for a while and the budget is full.
19/// An image source whose decoded pixels are freed again once the image has been off screen for a while and the budget is full.
20pub fn bounded(source: impl Into<ImageSource>) -> ImageSource {
20pub fn bounded(source: impl Into<ImageSource>) -> ImageSource {
21 match source.into() {
21 match source.into() {
22 ImageSource::Resource(resource) => {
22 ImageSource::Resource(resource) => ImageSource::Custom(Arc::new(move |window, cx| {
23 ImageSource::Custom(Arc::new(move |window, cx| load(Request::Full(&resource), window, cx)))
23 load(Request::Full(&resource), window, cx)
24 }
24 })),
25 other => other,
25 other => other,
26 }
26 }
27}
27}
@@ -29,7 +29,9 @@ pub fn bounded(source: impl Into<ImageSource>) -> ImageSource {
29/// Like [`bounded`], but a still picture is decoded scaled down to at most [`PREVIEW_EDGE`] pixels, for thumbnails of full-size photos.
29/// Like [`bounded`], but a still picture is decoded scaled down to at most [`PREVIEW_EDGE`] pixels, for thumbnails of full-size photos.
30pub fn preview(path: PathBuf) -> ImageSource {
30pub fn preview(path: PathBuf) -> ImageSource {
31 let path: Arc<Path> = path.into();
31 let path: Arc<Path> = path.into();
32 ImageSource::Custom(Arc::new(move |window, cx| load(Request::Preview(&path), window, cx)))
32 ImageSource::Custom(Arc::new(move |window, cx| {
33 load(Request::Preview(&path), window, cx)
34 }))
33}
35}
34
36
35#[derive(Clone, Copy)]
37#[derive(Clone, Copy)]
@@ -42,7 +44,11 @@ struct SharedImages(Entity<BoundedImages>);
42
44
43impl Global for SharedImages {}
45impl Global for SharedImages {}
44
46
45fn load(request: Request, window: &mut Window, cx: &mut App) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
47fn load(
48 request: Request,
49 window: &mut Window,
50 cx: &mut App,
51) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
46 let images = match cx.try_global::<SharedImages>() {
52 let images = match cx.try_global::<SharedImages>() {
47 Some(shared) => shared.0.clone(),
53 Some(shared) => shared.0.clone(),
48 None => {
54 None => {
@@ -92,7 +98,9 @@ impl BoundedImages {
92 Request::Full(resource) => Pixels::Item(ImageCacheItem::new(resource, cx)),
98 Request::Full(resource) => Pixels::Item(ImageCacheItem::new(resource, cx)),
93 Request::Preview(path) => {
99 Request::Preview(path) => {
94 start_preview(handle, key, path.clone(), cx);
100 start_preview(handle, key, path.clone(), cx);
95 Pixels::Decoding { waiting: Vec::new() }
101 Pixels::Decoding {
102 waiting: Vec::new(),
103 }
96 }
104 }
97 },
105 },
98 last_use: now,
106 last_use: now,
@@ -119,7 +127,13 @@ impl BoundedImages {
119 result
127 result
120 }
128 }
121
129
122 fn finish_preview(&mut self, key: u64, path: Arc<Path>, decoded: Option<RenderImage>, cx: &mut App) {
130 fn finish_preview(
131 &mut self,
132 key: u64,
133 path: Arc<Path>,
134 decoded: Option<RenderImage>,
135 cx: &mut App,
136 ) {
123 let Some(entry) = self.entries.get_mut(&key) else {
137 let Some(entry) = self.entries.get_mut(&key) else {
124 return;
138 return;
125 };
139 };
@@ -135,14 +149,20 @@ impl BoundedImages {
135 }
149 }
136
150
137 fn trim(&mut self, now: Instant) {
151 fn trim(&mut self, now: Instant) {
138 let sizes: Vec<(u64, Instant, u64)> =
152 let sizes: Vec<(u64, Instant, u64)> = self
139 self.entries.iter().map(|(key, entry)| (*key, entry.last_use, entry.bytes)).collect();
153 .entries
154 .iter()
155 .map(|(key, entry)| (*key, entry.last_use, entry.bytes))
156 .collect();
140 let mut freed_bytes = 0;
157 let mut freed_bytes = 0;
141 for key in evictions(sizes, now) {
158 for key in evictions(sizes, now) {
142 freed_bytes += self.entries.remove(&key).map_or(0, |entry| entry.bytes);
159 freed_bytes += self.entries.remove(&key).map_or(0, |entry| entry.bytes);
143 }
160 }
144 self.freed_bytes += freed_bytes;
161 self.freed_bytes += freed_bytes;
145 if self.last_report.is_none_or(|last| now.duration_since(last) >= REPORT_EVERY) {
162 if self
163 .last_report
164 .is_none_or(|last| now.duration_since(last) >= REPORT_EVERY)
165 {
146 self.last_report = Some(now);
166 self.last_report = Some(now);
147 let kept_bytes: u64 = self.entries.values().map(|entry| entry.bytes).sum();
167 let kept_bytes: u64 = self.entries.values().map(|entry| entry.bytes).sum();
148 app_base::diagnostics::record(&format!(
168 app_base::diagnostics::record(&format!(
@@ -159,15 +179,25 @@ fn start_preview(handle: &Entity<BoundedImages>, key: u64, path: Arc<Path>, cx:
159 let images = handle.downgrade();
179 let images = handle.downgrade();
160 cx.spawn(async move |cx| {
180 cx.spawn(async move |cx| {
161 let source = path.clone();
181 let source = path.clone();
162 let decoded = cx.background_executor().spawn(async move { decode_preview(&source) }).await;
182 let decoded = cx
163 images.update(cx, |images, cx| images.finish_preview(key, path, decoded, cx)).ok();
183 .background_executor()
184 .spawn(async move { decode_preview(&source) })
185 .await;
186 images
187 .update(cx, |images, cx| {
188 images.finish_preview(key, path, decoded, cx)
189 })
190 .ok();
164 })
191 })
165 .detach();
192 .detach();
166}
193}
167
194
168fn decode_preview(path: &Path) -> Option<RenderImage> {
195fn decode_preview(path: &Path) -> Option<RenderImage> {
169 let reader = ImageReader::open(path).ok()?.with_guessed_format().ok()?;
196 let reader = ImageReader::open(path).ok()?.with_guessed_format().ok()?;
170 if !matches!(reader.format()?, ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Bmp) {
197 if !matches!(
198 reader.format()?,
199 ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Bmp
200 ) {
171 return None;
201 return None;
172 }
202 }
173 let decoded = reader.decode().ok()?;
203 let decoded = reader.decode().ok()?;
@@ -225,7 +255,10 @@ mod tests {
225 #[test]
255 #[test]
226 fn images_shown_just_now_stay_even_over_budget() {
256 fn images_shown_just_now_stay_even_over_budget() {
227 let now = Instant::now() + Duration::from_secs(600);
257 let now = Instant::now() + Duration::from_secs(600);
228 let sizes = vec![(1, now - Duration::from_secs(2), 50 * MEGABYTE), (2, now, 50 * MEGABYTE)];
258 let sizes = vec![
259 (1, now - Duration::from_secs(2), 50 * MEGABYTE),
260 (2, now, 50 * MEGABYTE),
261 ];
229 assert!(evictions(sizes, now).is_empty());
262 assert!(evictions(sizes, now).is_empty());
230 }
263 }
231
264
@@ -239,11 +272,18 @@ mod tests {
239 fn a_large_photo_is_decoded_scaled_down_and_an_animation_is_left_to_gpui() {
272 fn a_large_photo_is_decoded_scaled_down_and_an_animation_is_left_to_gpui() {
240 let directory = tempfile::tempdir().unwrap();
273 let directory = tempfile::tempdir().unwrap();
241 let photo = directory.path().join("photo");
274 let photo = directory.path().join("photo");
242 image::RgbaImage::new(3000, 2000).save_with_format(&photo, ImageFormat::Png).unwrap();
275 image::RgbaImage::new(3000, 2000)
276 .save_with_format(&photo, ImageFormat::Png)
277 .unwrap();
243 let decoded = decode_preview(&photo).unwrap();
278 let decoded = decode_preview(&photo).unwrap();
244 assert_eq!((decoded.size(0).width.0, decoded.size(0).height.0), (720, 480));
279 assert_eq!(
280 (decoded.size(0).width.0, decoded.size(0).height.0),
281 (720, 480)
282 );
245 let animation = directory.path().join("animation");
283 let animation = directory.path().join("animation");
246 image::RgbaImage::new(10, 10).save_with_format(&animation, ImageFormat::Gif).unwrap();
284 image::RgbaImage::new(10, 10)
285 .save_with_format(&animation, ImageFormat::Gif)
286 .unwrap();
247 assert!(decode_preview(&animation).is_none());
287 assert!(decode_preview(&animation).is_none());
248 }
288 }
249}
289}
crates/app/src/views/last_views.rs +12 −3
@@ -59,8 +59,14 @@ mod tests {
59 59 last.restore(SidebarTab::Channels, Some(&chat), None, Some("19:general")),
60 60 Some(channel.clone())
61 61 );
62 assert_eq!(last.restore(SidebarTab::Chats, Some(&chat), None, None), None);
63 assert_eq!(last.restore(SidebarTab::Calendar, Some(&channel), None, None), None);
62 assert_eq!(
63 last.restore(SidebarTab::Chats, Some(&chat), None, None),
64 None
65 );
66 assert_eq!(
67 last.restore(SidebarTab::Calendar, Some(&channel), None, None),
68 None
69 );
64 70 }
65 71
66 72 #[test]
@@ -76,6 +82,9 @@ mod tests {
76 82 last.restore(SidebarTab::Channels, Some(&chat), None, Some("19:general")),
77 83 Some(Selection::Channel("19:general".to_owned()))
78 84 );
79 assert_eq!(last.restore(SidebarTab::Channels, Some(&chat), None, None), None);
85 assert_eq!(
86 last.restore(SidebarTab::Channels, Some(&chat), None, None),
87 None
88 );
80 89 }
81 90 }
@@ -59,8 +59,14 @@ mod tests {
59 last.restore(SidebarTab::Channels, Some(&chat), None, Some("19:general")),
59 last.restore(SidebarTab::Channels, Some(&chat), None, Some("19:general")),
60 Some(channel.clone())
60 Some(channel.clone())
61 );
61 );
62 assert_eq!(last.restore(SidebarTab::Chats, Some(&chat), None, None), None);
62 assert_eq!(
63 assert_eq!(last.restore(SidebarTab::Calendar, Some(&channel), None, None), None);
63 last.restore(SidebarTab::Chats, Some(&chat), None, None),
64 None
65 );
66 assert_eq!(
67 last.restore(SidebarTab::Calendar, Some(&channel), None, None),
68 None
69 );
64 }
70 }
65
71
66 #[test]
72 #[test]
@@ -76,6 +82,9 @@ mod tests {
76 last.restore(SidebarTab::Channels, Some(&chat), None, Some("19:general")),
82 last.restore(SidebarTab::Channels, Some(&chat), None, Some("19:general")),
77 Some(Selection::Channel("19:general".to_owned()))
83 Some(Selection::Channel("19:general".to_owned()))
78 );
84 );
79 assert_eq!(last.restore(SidebarTab::Channels, Some(&chat), None, None), None);
85 assert_eq!(
86 last.restore(SidebarTab::Channels, Some(&chat), None, None),
87 None
88 );
80 }
89 }
81}
90}
crates/app/src/views/message_actions.rs +7 −2
@@ -15,8 +15,8 @@ use gpui_kit::*;
15 15 use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
16 16 use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
17 17 use super::widgets::{icon, symbol};
18 use crate::post_follow::follow_label;
19 18 use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};
19 use crate::post_follow::follow_label;
20 20 use crate::rows::reaction_glyph;
21 21 use crate::share_outlook::SHARE_TO_OUTLOOK_LABEL;
22 22 use crate::theme::{self, ElevatedSurface as _};
@@ -133,7 +133,12 @@ impl MessageMenu {
133 133 }
134 134 }
135 135
136 fn picker_popover(adder: ReactionAdder, prefix: &str, trigger: Button, anchor: Anchor) -> AnyElement {
136 fn picker_popover(
137 adder: ReactionAdder,
138 prefix: &str,
139 trigger: Button,
140 anchor: Anchor,
141 ) -> AnyElement {
137 142 let ReactionAdder {
138 143 key,
139 144 picker,
@@ -15,8 +15,8 @@ use gpui_kit::*;
15use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
15use super::reaction_picker::{DoneHandler, PickHandler, ReactionPicker};
16use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
16use super::toolbar_placement::{HoverChange, TOOLBAR_HEIGHT, toolbar_slot};
17use super::widgets::{icon, symbol};
17use super::widgets::{icon, symbol};
18use crate::post_follow::follow_label;
19use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};
18use crate::forward_selection::{FORWARD_LABEL, MULTIPLE_MESSAGES_LABEL, THIS_MESSAGE_LABEL};
19use crate::post_follow::follow_label;
20use crate::rows::reaction_glyph;
20use crate::rows::reaction_glyph;
21use crate::share_outlook::SHARE_TO_OUTLOOK_LABEL;
21use crate::share_outlook::SHARE_TO_OUTLOOK_LABEL;
22use crate::theme::{self, ElevatedSurface as _};
22use crate::theme::{self, ElevatedSurface as _};
@@ -133,7 +133,12 @@ impl MessageMenu {
133 }
133 }
134}
134}
135
135
136fn picker_popover(adder: ReactionAdder, prefix: &str, trigger: Button, anchor: Anchor) -> AnyElement {
136fn picker_popover(
137 adder: ReactionAdder,
138 prefix: &str,
139 trigger: Button,
140 anchor: Anchor,
141) -> AnyElement {
137 let ReactionAdder {
142 let ReactionAdder {
138 key,
143 key,
139 picker,
144 picker,
crates/app/src/views/message_row.rs +52 −68
@@ -3,7 +3,6 @@ use gpui_kit::component::{h_flex, v_flex};
3 3 use gpui_kit::prelude::FluentBuilder as _;
4 4 use gpui_kit::*;
5 5 use std::time::Duration;
6 use std::rc::Rc;
7 6
8 7 use super::adaptive_card::cards_view;
9 8 use super::attachments::{FileActions, ImageActions, attachments_view, message_body};
@@ -11,7 +10,6 @@ use super::avatar::{bot_avatar, person_avatar};
11 10 use super::call_card::{CallActions, call_card_row};
12 11 use super::jumbo_emoji::jumbo_row;
13 12 use super::link_preview::{link_preview_card, meeting_join_chip};
14 use super::message_appear::{AppearKind, appear};
15 13 use super::message_actions::{MessageMenu, ReactionAdder, message_toolbar};
16 14 use super::profile_card::opens_profile;
17 15 use super::reaction_picker::PickHandler;
@@ -66,7 +64,6 @@ const BUBBLE_PADDING_Y: f32 = 8.;
66 64 const META_BOTTOM_INSET: f32 = 4.;
67 65 const META_SIZE: f32 = 11.;
68 66 const META_CHECK_SIZE: f32 = 15.;
69 const TICK_BASELINE_DROP: f32 = 0.5;
70 67 const SAVED_MARK_SIZE: f32 = 12.;
71 68 const FORWARDED_SIZE: f32 = 11.;
72 69 const IMPORTANCE_LABEL_SIZE: f32 = 12.;
@@ -108,8 +105,6 @@ pub struct RowActions {
108 105 pub bot: Option<BotIdentity>,
109 106 pub delivery: DeliveryActions,
110 107 pub reply: RowAction,
111 pub open_context: Option<Rc<dyn Fn(Point<Pixels>, &mut App)>>,
112 pub context_menu: Option<AnyElement>,
113 108 pub hovered: Option<HoverChange>,
114 109 pub menu: Option<MessageMenu>,
115 110 pub scheduled_menu: Option<ScheduledMenu>,
@@ -128,7 +123,6 @@ pub struct RowActions {
128 123 pub reaction_proposal: Option<ReactionPill>,
129 124 pub undo_delete: SharedRowAction,
130 125 pub compact: bool,
131 pub appear: Option<AppearKind>,
132 126 }
133 127
134 128 pub fn row_spacing(has_previous: bool, compact: bool) -> f32 {
@@ -303,7 +297,6 @@ fn bubble(
303 297 &row.blocks,
304 298 &row.images,
305 299 &row.local_images,
306 &row.sent_previews,
307 300 &row.files,
308 301 &format!("message-{index}"),
309 302 directory,
@@ -328,7 +321,6 @@ fn bubble(
328 321 padded_blocks.as_deref().unwrap_or(&row.blocks),
329 322 &row.images,
330 323 &row.local_images,
331 &row.sent_previews,
332 324 &format!("message-{index}"),
333 325 own,
334 326 directory,
@@ -353,20 +345,21 @@ fn bubble(
353 345 }));
354 346 content = content.children(cards);
355 347 if has_reactions {
356 let pills = reaction_pills(
357 &row.reactions,
358 index,
359 own,
360 directory,
361 extras.react.clone(),
362 extras.controls.as_ref(),
363 );
364 348 content = content.child(
365 349 h_flex()
366 350 .gap(px(8.))
367 351 .items_end()
368 .when(jumbo.is_some() && own, |line| line.justify_end())
369 .child(if jumbo.is_some() { pills } else { pills.flex_auto() })
352 .child(
353 reaction_pills(
354 &row.reactions,
355 index,
356 own,
357 directory,
358 extras.react.clone(),
359 extras.controls.as_ref(),
360 )
361 .flex_auto(),
362 )
370 363 .child(
371 364 h_flex()
372 365 .flex_none()
@@ -483,33 +476,29 @@ fn bubble_meta(row: &MessageRow, own: bool, saved: bool) -> Div {
483 476 .when(matches!(row.delivery, Delivery::Scheduled(_)), |meta| {
484 477 meta.child(symbol("schedule", META_SIZE + 3., tint))
485 478 })
486 .when(
487 own && row.delivery == Delivery::Delivered,
488 |meta| {
489 let check = match row.receipt {
490 Receipt::Hidden => return meta,
491 Receipt::Sent => symbol("done", META_CHECK_SIZE, tint).into_any_element(),
492 Receipt::Read => symbol("done_all", META_CHECK_SIZE, theme::own_read()).into_any_element(),
493 Receipt::ReadLive => receipt_fade_in(
494 &row.key,
495 div().child(symbol("done_all", META_CHECK_SIZE, theme::own_read())),
496 )
497 .into_any_element(),
498 };
499 // The tick glyph ends about half a pixel above the time baseline (measured at 100 % and 125 %).
500 let holder = div()
501 .id(ElementId::Name(format!("{}-receipt", row.key).into()))
502 .relative()
503 .top(px(TICK_BASELINE_DROP))
504 .child(check);
505 meta.child(match row.receipt_label.clone() {
506 Some(label) => holder.tooltip(move |window, cx| {
507 gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx)
508 }),
509 None => holder,
510 })
511 },
512 )
479 .when(own && row.delivery == Delivery::Delivered, |meta| {
480 let check = match row.receipt {
481 Receipt::Hidden => return meta,
482 Receipt::Sent => symbol("done", META_CHECK_SIZE, tint).into_any_element(),
483 Receipt::Read => {
484 symbol("done_all", META_CHECK_SIZE, theme::own_read()).into_any_element()
485 }
486 Receipt::ReadLive => receipt_fade_in(
487 &row.key,
488 div().child(symbol("done_all", META_CHECK_SIZE, theme::own_read())),
489 )
490 .into_any_element(),
491 };
492 let holder = div()
493 .id(ElementId::Name(format!("{}-receipt", row.key).into()))
494 .child(check);
495 meta.child(match row.receipt_label.clone() {
496 Some(label) => holder.tooltip(move |window, cx| {
497 gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx)
498 }),
499 None => holder,
500 })
501 })
513 502 }
514 503
515 504 fn pulse<E: IntoElement + Styled + 'static>(id: &'static str, element: E) -> AnimationElement<E> {
@@ -695,7 +684,11 @@ fn others_row(
695 684 .gap(px(2.))
696 685 .flex_1()
697 686 .min_w_0()
698 .max_w(bubble_max_width(&extras.timeline, AVATAR_SIZE + AVATAR_GAP, extras.compact))
687 .max_w(bubble_max_width(
688 &extras.timeline,
689 AVATAR_SIZE + AVATAR_GAP,
690 extras.compact,
691 ))
699 692 .items_start();
700 693 if first {
701 694 column = column.child(
@@ -800,8 +793,6 @@ pub fn render_message_row(
800 793 bot,
801 794 delivery,
802 795 reply,
803 open_context,
804 context_menu,
805 796 hovered,
806 797 menu,
807 798 scheduled_menu,
@@ -820,7 +811,6 @@ pub fn render_message_row(
820 811 reaction_proposal,
821 812 undo_delete,
822 813 compact,
823 appear: appear_kind,
824 814 } = actions;
825 815 let extras = BubbleExtras {
826 816 hover: hovered,
@@ -853,35 +843,29 @@ pub fn render_message_row(
853 843 } else {
854 844 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
855 845 };
856 let body = match appear_kind.filter(|_| !cx.reduce_motion()) {
857 Some(kind) => appear(body, &row.key, kind).into_any_element(),
858 None => body.into_any_element(),
859 };
860 846 let checked = select.as_ref().is_some_and(|select| select.checked);
861 847 let body = match select {
862 848 Some(select) => selectable_body(select, index, body).into_any_element(),
863 None => body,
849 None => body.into_any_element(),
864 850 };
865 851 container
866 852 .child(
867 853 div()
868 854 .id(ElementId::Name(format!("row-{index}").into()))
869 .mx(px(-ROW_PADDING))
870 .px(px(ROW_PADDING))
855 .w_full()
871 856 .pt(spacing)
872 .when(checked && !highlighted, |element| {
873 element.bg(theme::accent().opacity(SELECTED_TINT))
874 })
875 .map(|element| match (open_context, reply) {
876 (Some(open_context), _) => element.on_mouse_down(MouseButton::Right, move |event, _, cx| {
877 cx.stop_propagation();
878 open_context(event.position, cx)
879 }),
880 (None, Some(reply)) => element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx)),
881 (None, None) => element,
857 .when_some(reply, |element, reply| {
858 element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
882 859 })
883 .children(context_menu)
884 .child(body),
860 .child(
861 div()
862 .w_full()
863 .rounded(px(10.))
864 .when(checked && !highlighted, |element| {
865 element.bg(theme::accent().opacity(SELECTED_TINT))
866 })
867 .child(body),
868 ),
885 869 )
886 870 .into_any_element()
887 871 }
@@ -3,7 +3,6 @@ use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
4use gpui_kit::*;
5use std::time::Duration;
5use std::time::Duration;
6use std::rc::Rc;
7
6
8use super::adaptive_card::cards_view;
7use super::adaptive_card::cards_view;
9use super::attachments::{FileActions, ImageActions, attachments_view, message_body};
8use super::attachments::{FileActions, ImageActions, attachments_view, message_body};
@@ -11,7 +10,6 @@ use super::avatar::{bot_avatar, person_avatar};
11use super::call_card::{CallActions, call_card_row};
10use super::call_card::{CallActions, call_card_row};
12use super::jumbo_emoji::jumbo_row;
11use super::jumbo_emoji::jumbo_row;
13use super::link_preview::{link_preview_card, meeting_join_chip};
12use super::link_preview::{link_preview_card, meeting_join_chip};
14use super::message_appear::{AppearKind, appear};
15use super::message_actions::{MessageMenu, ReactionAdder, message_toolbar};
13use super::message_actions::{MessageMenu, ReactionAdder, message_toolbar};
16use super::profile_card::opens_profile;
14use super::profile_card::opens_profile;
17use super::reaction_picker::PickHandler;
15use super::reaction_picker::PickHandler;
@@ -66,7 +64,6 @@ const BUBBLE_PADDING_Y: f32 = 8.;
66const META_BOTTOM_INSET: f32 = 4.;
64const META_BOTTOM_INSET: f32 = 4.;
67const META_SIZE: f32 = 11.;
65const META_SIZE: f32 = 11.;
68const META_CHECK_SIZE: f32 = 15.;
66const META_CHECK_SIZE: f32 = 15.;
69const TICK_BASELINE_DROP: f32 = 0.5;
70const SAVED_MARK_SIZE: f32 = 12.;
67const SAVED_MARK_SIZE: f32 = 12.;
71const FORWARDED_SIZE: f32 = 11.;
68const FORWARDED_SIZE: f32 = 11.;
72const IMPORTANCE_LABEL_SIZE: f32 = 12.;
69const IMPORTANCE_LABEL_SIZE: f32 = 12.;
@@ -108,8 +105,6 @@ pub struct RowActions {
108 pub bot: Option<BotIdentity>,
105 pub bot: Option<BotIdentity>,
109 pub delivery: DeliveryActions,
106 pub delivery: DeliveryActions,
110 pub reply: RowAction,
107 pub reply: RowAction,
111 pub open_context: Option<Rc<dyn Fn(Point<Pixels>, &mut App)>>,
112 pub context_menu: Option<AnyElement>,
113 pub hovered: Option<HoverChange>,
108 pub hovered: Option<HoverChange>,
114 pub menu: Option<MessageMenu>,
109 pub menu: Option<MessageMenu>,
115 pub scheduled_menu: Option<ScheduledMenu>,
110 pub scheduled_menu: Option<ScheduledMenu>,
@@ -128,7 +123,6 @@ pub struct RowActions {
128 pub reaction_proposal: Option<ReactionPill>,
123 pub reaction_proposal: Option<ReactionPill>,
129 pub undo_delete: SharedRowAction,
124 pub undo_delete: SharedRowAction,
130 pub compact: bool,
125 pub compact: bool,
131 pub appear: Option<AppearKind>,
132}
126}
133
127
134pub fn row_spacing(has_previous: bool, compact: bool) -> f32 {
128pub fn row_spacing(has_previous: bool, compact: bool) -> f32 {
@@ -303,7 +297,6 @@ fn bubble(
303 &row.blocks,
297 &row.blocks,
304 &row.images,
298 &row.images,
305 &row.local_images,
299 &row.local_images,
306 &row.sent_previews,
307 &row.files,
300 &row.files,
308 &format!("message-{index}"),
301 &format!("message-{index}"),
309 directory,
302 directory,
@@ -328,7 +321,6 @@ fn bubble(
328 padded_blocks.as_deref().unwrap_or(&row.blocks),
321 padded_blocks.as_deref().unwrap_or(&row.blocks),
329 &row.images,
322 &row.images,
330 &row.local_images,
323 &row.local_images,
331 &row.sent_previews,
332 &format!("message-{index}"),
324 &format!("message-{index}"),
333 own,
325 own,
334 directory,
326 directory,
@@ -353,20 +345,21 @@ fn bubble(
353 }));
345 }));
354 content = content.children(cards);
346 content = content.children(cards);
355 if has_reactions {
347 if has_reactions {
356 let pills = reaction_pills(
357 &row.reactions,
358 index,
359 own,
360 directory,
361 extras.react.clone(),
362 extras.controls.as_ref(),
363 );
364 content = content.child(
348 content = content.child(
365 h_flex()
349 h_flex()
366 .gap(px(8.))
350 .gap(px(8.))
367 .items_end()
351 .items_end()
368 .when(jumbo.is_some() && own, |line| line.justify_end())
352 .child(
369 .child(if jumbo.is_some() { pills } else { pills.flex_auto() })
353 reaction_pills(
354 &row.reactions,
355 index,
356 own,
357 directory,
358 extras.react.clone(),
359 extras.controls.as_ref(),
360 )
361 .flex_auto(),
362 )
370 .child(
363 .child(
371 h_flex()
364 h_flex()
372 .flex_none()
365 .flex_none()
@@ -483,33 +476,29 @@ fn bubble_meta(row: &MessageRow, own: bool, saved: bool) -> Div {
483 .when(matches!(row.delivery, Delivery::Scheduled(_)), |meta| {
476 .when(matches!(row.delivery, Delivery::Scheduled(_)), |meta| {
484 meta.child(symbol("schedule", META_SIZE + 3., tint))
477 meta.child(symbol("schedule", META_SIZE + 3., tint))
485 })
478 })
486 .when(
479 .when(own && row.delivery == Delivery::Delivered, |meta| {
487 own && row.delivery == Delivery::Delivered,
480 let check = match row.receipt {
488 |meta| {
481 Receipt::Hidden => return meta,
489 let check = match row.receipt {
482 Receipt::Sent => symbol("done", META_CHECK_SIZE, tint).into_any_element(),
490 Receipt::Hidden => return meta,
483 Receipt::Read => {
491 Receipt::Sent => symbol("done", META_CHECK_SIZE, tint).into_any_element(),
484 symbol("done_all", META_CHECK_SIZE, theme::own_read()).into_any_element()
492 Receipt::Read => symbol("done_all", META_CHECK_SIZE, theme::own_read()).into_any_element(),
485 }
493 Receipt::ReadLive => receipt_fade_in(
486 Receipt::ReadLive => receipt_fade_in(
494 &row.key,
487 &row.key,
495 div().child(symbol("done_all", META_CHECK_SIZE, theme::own_read())),
488 div().child(symbol("done_all", META_CHECK_SIZE, theme::own_read())),
496 )
489 )
497 .into_any_element(),
490 .into_any_element(),
498 };
491 };
499 // The tick glyph ends about half a pixel above the time baseline (measured at 100 % and 125 %).
492 let holder = div()
500 let holder = div()
493 .id(ElementId::Name(format!("{}-receipt", row.key).into()))
501 .id(ElementId::Name(format!("{}-receipt", row.key).into()))
494 .child(check);
502 .relative()
495 meta.child(match row.receipt_label.clone() {
503 .top(px(TICK_BASELINE_DROP))
496 Some(label) => holder.tooltip(move |window, cx| {
504 .child(check);
497 gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx)
505 meta.child(match row.receipt_label.clone() {
498 }),
506 Some(label) => holder.tooltip(move |window, cx| {
499 None => holder,
507 gpui_kit::component::tooltip::Tooltip::new(label.clone()).build(window, cx)
500 })
508 }),
501 })
509 None => holder,
510 })
511 },
512 )
513}
502}
514
503
515fn pulse<E: IntoElement + Styled + 'static>(id: &'static str, element: E) -> AnimationElement<E> {
504fn pulse<E: IntoElement + Styled + 'static>(id: &'static str, element: E) -> AnimationElement<E> {
@@ -695,7 +684,11 @@ fn others_row(
695 .gap(px(2.))
684 .gap(px(2.))
696 .flex_1()
685 .flex_1()
697 .min_w_0()
686 .min_w_0()
698 .max_w(bubble_max_width(&extras.timeline, AVATAR_SIZE + AVATAR_GAP, extras.compact))
687 .max_w(bubble_max_width(
688 &extras.timeline,
689 AVATAR_SIZE + AVATAR_GAP,
690 extras.compact,
691 ))
699 .items_start();
692 .items_start();
700 if first {
693 if first {
701 column = column.child(
694 column = column.child(
@@ -800,8 +793,6 @@ pub fn render_message_row(
800 bot,
793 bot,
801 delivery,
794 delivery,
802 reply,
795 reply,
803 open_context,
804 context_menu,
805 hovered,
796 hovered,
806 menu,
797 menu,
807 scheduled_menu,
798 scheduled_menu,
@@ -820,7 +811,6 @@ pub fn render_message_row(
820 reaction_proposal,
811 reaction_proposal,
821 undo_delete,
812 undo_delete,
822 compact,
813 compact,
823 appear: appear_kind,
824 } = actions;
814 } = actions;
825 let extras = BubbleExtras {
815 let extras = BubbleExtras {
826 hover: hovered,
816 hover: hovered,
@@ -853,35 +843,29 @@ pub fn render_message_row(
853 } else {
843 } else {
854 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
844 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
855 };
845 };
856 let body = match appear_kind.filter(|_| !cx.reduce_motion()) {
857 Some(kind) => appear(body, &row.key, kind).into_any_element(),
858 None => body.into_any_element(),
859 };
860 let checked = select.as_ref().is_some_and(|select| select.checked);
846 let checked = select.as_ref().is_some_and(|select| select.checked);
861 let body = match select {
847 let body = match select {
862 Some(select) => selectable_body(select, index, body).into_any_element(),
848 Some(select) => selectable_body(select, index, body).into_any_element(),
863 None => body,
849 None => body.into_any_element(),
864 };
850 };
865 container
851 container
866 .child(
852 .child(
867 div()
853 div()
868 .id(ElementId::Name(format!("row-{index}").into()))
854 .id(ElementId::Name(format!("row-{index}").into()))
869 .mx(px(-ROW_PADDING))
855 .w_full()
870 .px(px(ROW_PADDING))
871 .pt(spacing)
856 .pt(spacing)
872 .when(checked && !highlighted, |element| {
857 .when_some(reply, |element, reply| {
873 element.bg(theme::accent().opacity(SELECTED_TINT))
858 element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
874 })
875 .map(|element| match (open_context, reply) {
876 (Some(open_context), _) => element.on_mouse_down(MouseButton::Right, move |event, _, cx| {
877 cx.stop_propagation();
878 open_context(event.position, cx)
879 }),
880 (None, Some(reply)) => element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx)),
881 (None, None) => element,
882 })
859 })
883 .children(context_menu)
860 .child(
884 .child(body),
861 div()
862 .w_full()
863 .rounded(px(10.))
864 .when(checked && !highlighted, |element| {
865 element.bg(theme::accent().opacity(SELECTED_TINT))
866 })
867 .child(body),
868 ),
885 )
869 )
886 .into_any_element()
870 .into_any_element()
887}
871}
crates/app/src/views/mod.rs +18 −24
@@ -1,58 +1,57 @@
1 1 pub mod actions;
2 2 pub mod activity_panel;
3 3 pub mod adaptive_card;
4 pub mod announcement_banner;
5 4 pub mod add_people_dialog;
5 pub mod announcement_banner;
6 6 pub mod attachment_tray;
7 7 pub mod attachments;
8 8 pub mod avatar;
9 pub mod calendar_date_picker;
10 pub mod calendar_month;
11 pub mod calendar_view;
9 12 pub mod call_card;
10 pub mod call_notice;
11 13 pub mod call_control_fold;
12 pub mod call_end_view;
13 14 pub mod call_controls;
15 pub mod call_end_view;
14 16 pub mod call_extras;
15 17 pub mod call_health;
16 18 pub mod call_layouts;
19 pub mod call_mini;
17 20 pub mod call_mini_window;
21 pub mod call_notice;
18 22 pub mod call_organizer;
19 23 pub mod call_people;
20 24 pub mod call_pop_out;
21 pub mod call_share_gallery;
22 25 pub mod call_record;
26 pub mod call_share_gallery;
23 27 pub mod call_stage;
24 28 pub mod call_transcript;
25 29 pub mod call_view;
26 pub mod call_window;
27 pub mod call_toolbar;
28 30 pub mod call_view_menu;
29 pub mod calendar_date_picker;
30 pub mod calendar_month;
31 pub mod calendar_view;
32 31 pub mod calls_page;
33 mod rsvp_menu;
34 32 pub mod card_carousel;
35 #[cfg(test)]
36 mod card_input_tests;
37 33 pub mod card_code_block;
38 34 pub mod card_icon;
39 35 pub mod card_input;
36 #[cfg(test)]
37 mod card_input_tests;
40 38 pub mod card_media;
41 39 pub mod card_table;
42 40 pub mod card_widgets;
41 pub mod channel_admin_dialogs;
43 42 pub mod chat_members;
43 mod chat_menu;
44 44 pub mod chat_pop_out;
45 45 pub mod composer;
46 46 pub mod connection_banner;
47 47 pub mod conversation;
48 pub mod channel_admin_dialogs;
49 48 pub mod create_channel_dialog;
50 49 pub mod customize_reactions;
51 50 pub mod dialog_overlay;
52 51 pub mod emoji_popup;
52 pub mod find_panel;
53 53 pub mod format_toolbar;
54 54 pub mod forward_dialog;
55 pub mod find_panel;
56 55 pub mod fun_picker;
57 56 pub mod group_name;
58 57 pub mod image_memory;
@@ -60,14 +59,13 @@ pub mod image_menu;
60 59 pub mod image_viewer;
61 60 pub mod join_dialog;
62 61 pub mod jumbo_emoji;
62 mod last_views;
63 63 pub mod link_preview;
64 64 pub mod message_actions;
65 pub mod message_appear;
66 pub mod message_context_menu;
67 65 pub mod message_row;
68 66 pub mod new_chat;
69 pub mod notice_toast;
70 67 pub mod new_meeting_dialog;
68 pub mod notice_toast;
71 69 pub mod pin_banner;
72 70 #[cfg(test)]
73 71 mod popup_tooltip_tests;
@@ -75,25 +73,21 @@ pub mod post_card;
75 73 pub mod prejoin_view;
76 74 pub mod profile_card;
77 75 pub mod proposal_card;
78 pub mod meeting_proposal_card;
76 pub mod quick_view_pane;
79 77 pub mod rail;
80 78 pub mod reaction_picker;
81 79 pub mod reaction_pills;
82 80 pub mod recap_tab;
83 pub mod manage_team_page;
84 pub mod quick_view_pane;
81 mod rsvp_menu;
85 82 pub mod scheduled_toolbar;
86 83 pub mod section_dialog;
87 84 pub mod share_bar;
88 85 pub mod shared_tab;
89 pub mod skin_tone_choices;
90 86 pub mod shell;
91 87 pub mod shortcuts;
92 88 pub mod shortcuts_dialog;
93 mod chat_menu;
94 mod last_views;
95 89 pub mod sidebar;
96 pub mod splash;
90 pub mod skin_tone_choices;
97 91 pub mod status_menu;
98 92 pub mod status_message_dialog;
99 93 pub mod switcher;
@@ -1,58 +1,57 @@
1pub mod actions;
1pub mod actions;
2pub mod activity_panel;
2pub mod activity_panel;
3pub mod adaptive_card;
3pub mod adaptive_card;
4pub mod announcement_banner;
5pub mod add_people_dialog;
4pub mod add_people_dialog;
5pub mod announcement_banner;
6pub mod attachment_tray;
6pub mod attachment_tray;
7pub mod attachments;
7pub mod attachments;
8pub mod avatar;
8pub mod avatar;
9pub mod calendar_date_picker;
10pub mod calendar_month;
11pub mod calendar_view;
9pub mod call_card;
12pub mod call_card;
10pub mod call_notice;
11pub mod call_control_fold;
13pub mod call_control_fold;
12pub mod call_end_view;
13pub mod call_controls;
14pub mod call_controls;
15pub mod call_end_view;
14pub mod call_extras;
16pub mod call_extras;
15pub mod call_health;
17pub mod call_health;
16pub mod call_layouts;
18pub mod call_layouts;
19pub mod call_mini;
17pub mod call_mini_window;
20pub mod call_mini_window;
21pub mod call_notice;
18pub mod call_organizer;
22pub mod call_organizer;
19pub mod call_people;
23pub mod call_people;
20pub mod call_pop_out;
24pub mod call_pop_out;
21pub mod call_share_gallery;
22pub mod call_record;
25pub mod call_record;
26pub mod call_share_gallery;
23pub mod call_stage;
27pub mod call_stage;
24pub mod call_transcript;
28pub mod call_transcript;
25pub mod call_view;
29pub mod call_view;
26pub mod call_window;
27pub mod call_toolbar;
28pub mod call_view_menu;
30pub mod call_view_menu;
29pub mod calendar_date_picker;
30pub mod calendar_month;
31pub mod calendar_view;
32pub mod calls_page;
31pub mod calls_page;
33mod rsvp_menu;
34pub mod card_carousel;
32pub mod card_carousel;
35#[cfg(test)]
36mod card_input_tests;
37pub mod card_code_block;
33pub mod card_code_block;
38pub mod card_icon;
34pub mod card_icon;
39pub mod card_input;
35pub mod card_input;
36#[cfg(test)]
37mod card_input_tests;
40pub mod card_media;
38pub mod card_media;
41pub mod card_table;
39pub mod card_table;
42pub mod card_widgets;
40pub mod card_widgets;
41pub mod channel_admin_dialogs;
43pub mod chat_members;
42pub mod chat_members;
43mod chat_menu;
44pub mod chat_pop_out;
44pub mod chat_pop_out;
45pub mod composer;
45pub mod composer;
46pub mod connection_banner;
46pub mod connection_banner;
47pub mod conversation;
47pub mod conversation;
48pub mod channel_admin_dialogs;
49pub mod create_channel_dialog;
48pub mod create_channel_dialog;
50pub mod customize_reactions;
49pub mod customize_reactions;
51pub mod dialog_overlay;
50pub mod dialog_overlay;
52pub mod emoji_popup;
51pub mod emoji_popup;
52pub mod find_panel;
53pub mod format_toolbar;
53pub mod format_toolbar;
54pub mod forward_dialog;
54pub mod forward_dialog;
55pub mod find_panel;
56pub mod fun_picker;
55pub mod fun_picker;
57pub mod group_name;
56pub mod group_name;
58pub mod image_memory;
57pub mod image_memory;
@@ -60,14 +59,13 @@ pub mod image_menu;
60pub mod image_viewer;
59pub mod image_viewer;
61pub mod join_dialog;
60pub mod join_dialog;
62pub mod jumbo_emoji;
61pub mod jumbo_emoji;
62mod last_views;
63pub mod link_preview;
63pub mod link_preview;
64pub mod message_actions;
64pub mod message_actions;
65pub mod message_appear;
66pub mod message_context_menu;
67pub mod message_row;
65pub mod message_row;
68pub mod new_chat;
66pub mod new_chat;
69pub mod notice_toast;
70pub mod new_meeting_dialog;
67pub mod new_meeting_dialog;
68pub mod notice_toast;
71pub mod pin_banner;
69pub mod pin_banner;
72#[cfg(test)]
70#[cfg(test)]
73mod popup_tooltip_tests;
71mod popup_tooltip_tests;
@@ -75,25 +73,21 @@ pub mod post_card;
75pub mod prejoin_view;
73pub mod prejoin_view;
76pub mod profile_card;
74pub mod profile_card;
77pub mod proposal_card;
75pub mod proposal_card;
78pub mod meeting_proposal_card;
76pub mod quick_view_pane;
79pub mod rail;
77pub mod rail;
80pub mod reaction_picker;
78pub mod reaction_picker;
81pub mod reaction_pills;
79pub mod reaction_pills;
82pub mod recap_tab;
80pub mod recap_tab;
83pub mod manage_team_page;
81mod rsvp_menu;
84pub mod quick_view_pane;
85pub mod scheduled_toolbar;
82pub mod scheduled_toolbar;
86pub mod section_dialog;
83pub mod section_dialog;
87pub mod share_bar;
84pub mod share_bar;
88pub mod shared_tab;
85pub mod shared_tab;
89pub mod skin_tone_choices;
90pub mod shell;
86pub mod shell;
91pub mod shortcuts;
87pub mod shortcuts;
92pub mod shortcuts_dialog;
88pub mod shortcuts_dialog;
93mod chat_menu;
94mod last_views;
95pub mod sidebar;
89pub mod sidebar;
96pub mod splash;
90pub mod skin_tone_choices;
97pub mod status_menu;
91pub mod status_menu;
98pub mod status_message_dialog;
92pub mod status_message_dialog;
99pub mod switcher;
93pub mod switcher;
crates/app/src/views/post_card.rs +35 −18
@@ -329,31 +329,44 @@ fn message_block(
329 329 .items_center()
330 330 .gap(px(AVATAR_GAP))
331 331 .child(avatar.debug_selector(|| POST_AVATAR_TAG.into()))
332 .child(message_header(row, index, author, profile_user, saved, pinned)),
332 .child(message_header(
333 row,
334 index,
335 author,
336 profile_user,
337 saved,
338 pinned,
339 )),
333 340 )
334 341 .child(details.debug_selector(|| POST_BODY_TAG.into())),
335 Role::Reply => h_flex().items_start().gap(px(REPLY_AVATAR_GAP)).child(avatar).child(
336 v_flex()
337 .flex_1()
338 .min_w_0()
339 .gap(px(6.))
340 .child(message_header(
341 row,
342 index,
343 author,
344 profile_user,
345 saved,
346 pinned,
347 ))
348 .child(details),
349 ),
342 Role::Reply => h_flex()
343 .items_start()
344 .gap(px(REPLY_AVATAR_GAP))
345 .child(avatar)
346 .child(
347 v_flex()
348 .flex_1()
349 .min_w_0()
350 .gap(px(6.))
351 .child(message_header(
352 row,
353 index,
354 author,
355 profile_user,
356 saved,
357 pinned,
358 ))
359 .child(details),
360 ),
350 361 };
351 362 div()
352 363 .id(ElementId::Name(format!("post-message-{index}").into()))
353 364 .relative()
354 365 .w_full()
355 366 .p(px(CARD_PADDING))
356 .when(role == Role::Reply, |block| block.bg(theme::reply_surface()))
367 .when(role == Role::Reply, |block| {
368 block.bg(theme::reply_surface())
369 })
357 370 .when(highlighted, |block| block.bg(theme::accent().opacity(0.2)))
358 371 .when_some(hovered, |block, hovered| {
359 372 block.on_hover(move |is_hovered, _, cx| hovered(*is_hovered, cx))
@@ -477,7 +490,11 @@ fn card_action(label: &'static str, glyph: IconName, primary: bool) -> Div {
477 490 .child(label)
478 491 }
479 492
480 pub fn post_in_channel_card(directory: &Directory, open: PostAction, announce: PostAction) -> AnyElement {
493 pub fn post_in_channel_card(
494 directory: &Directory,
495 open: PostAction,
496 announce: PostAction,
497 ) -> AnyElement {
481 498 let own_avatar = directory.me.as_ref().map(|me| {
482 499 div().flex_none().child(person_avatar(
483 500 directory,
@@ -329,31 +329,44 @@ fn message_block(
329 .items_center()
329 .items_center()
330 .gap(px(AVATAR_GAP))
330 .gap(px(AVATAR_GAP))
331 .child(avatar.debug_selector(|| POST_AVATAR_TAG.into()))
331 .child(avatar.debug_selector(|| POST_AVATAR_TAG.into()))
332 .child(message_header(row, index, author, profile_user, saved, pinned)),
332 .child(message_header(
333 row,
334 index,
335 author,
336 profile_user,
337 saved,
338 pinned,
339 )),
333 )
340 )
334 .child(details.debug_selector(|| POST_BODY_TAG.into())),
341 .child(details.debug_selector(|| POST_BODY_TAG.into())),
335 Role::Reply => h_flex().items_start().gap(px(REPLY_AVATAR_GAP)).child(avatar).child(
342 Role::Reply => h_flex()
336 v_flex()
343 .items_start()
337 .flex_1()
344 .gap(px(REPLY_AVATAR_GAP))
338 .min_w_0()
345 .child(avatar)
339 .gap(px(6.))
346 .child(
340 .child(message_header(
347 v_flex()
341 row,
348 .flex_1()
342 index,
349 .min_w_0()
343 author,
350 .gap(px(6.))
344 profile_user,
351 .child(message_header(
345 saved,
352 row,
346 pinned,
353 index,
347 ))
354 author,
348 .child(details),
355 profile_user,
349 ),
356 saved,
357 pinned,
358 ))
359 .child(details),
360 ),
350 };
361 };
351 div()
362 div()
352 .id(ElementId::Name(format!("post-message-{index}").into()))
363 .id(ElementId::Name(format!("post-message-{index}").into()))
353 .relative()
364 .relative()
354 .w_full()
365 .w_full()
355 .p(px(CARD_PADDING))
366 .p(px(CARD_PADDING))
356 .when(role == Role::Reply, |block| block.bg(theme::reply_surface()))
367 .when(role == Role::Reply, |block| {
368 block.bg(theme::reply_surface())
369 })
357 .when(highlighted, |block| block.bg(theme::accent().opacity(0.2)))
370 .when(highlighted, |block| block.bg(theme::accent().opacity(0.2)))
358 .when_some(hovered, |block, hovered| {
371 .when_some(hovered, |block, hovered| {
359 block.on_hover(move |is_hovered, _, cx| hovered(*is_hovered, cx))
372 block.on_hover(move |is_hovered, _, cx| hovered(*is_hovered, cx))
@@ -477,7 +490,11 @@ fn card_action(label: &'static str, glyph: IconName, primary: bool) -> Div {
477 .child(label)
490 .child(label)
478}
491}
479
492
480pub fn post_in_channel_card(directory: &Directory, open: PostAction, announce: PostAction) -> AnyElement {
493pub fn post_in_channel_card(
494 directory: &Directory,
495 open: PostAction,
496 announce: PostAction,
497) -> AnyElement {
481 let own_avatar = directory.me.as_ref().map(|me| {
498 let own_avatar = directory.me.as_ref().map(|me| {
482 div().flex_none().child(person_avatar(
499 div().flex_none().child(person_avatar(
483 directory,
500 directory,
crates/app/src/views/profile_card.rs +2 −2
@@ -1,9 +1,9 @@
1 1 use std::sync::Arc;
2 2
3 3 use chrono::Utc;
4 use gpui_kit::component::scroll::ScrollableElement as _;
5 4 use gpui_kit::assets::IconName;
6 5 use gpui_kit::base::GlobalState;
6 use gpui_kit::component::scroll::ScrollableElement as _;
7 7 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
8 8 use gpui_kit::prelude::FluentBuilder as _;
9 9 use gpui_kit::*;
@@ -16,12 +16,12 @@ use super::widgets::icon;
16 16 use crate::app_state::{AppHandle, AppState};
17 17 use crate::data::{Presence, PresenceKind, presence_kind_of};
18 18 use crate::people::resolve_names;
19 use crate::presence_follow::{NOTIFY_WHEN_AVAILABLE, TURN_OFF_NOTIFICATIONS};
19 20 use crate::profile_model::{
20 21 ContactKind, ContactRow, StatusBox, contact_rows, has_organization, local_time_label,
21 22 mailto_url, status_box, status_line, work_location_label,
22 23 };
23 24 use crate::theme::{self, ElevatedSurface as _};
24 use crate::presence_follow::{NOTIFY_WHEN_AVAILABLE, TURN_OFF_NOTIFICATIONS};
25 25
26 26 const CARD_WIDTH: f32 = 340.;
27 27 const CARD_RADIUS: f32 = 10.;
@@ -1,9 +1,9 @@
1use std::sync::Arc;
1use std::sync::Arc;
2
2
3use chrono::Utc;
3use chrono::Utc;
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
6use gpui_kit::base::GlobalState;
5use gpui_kit::base::GlobalState;
6use gpui_kit::component::scroll::ScrollableElement as _;
7use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
8use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
9use gpui_kit::*;
@@ -16,12 +16,12 @@ use super::widgets::icon;
16use crate::app_state::{AppHandle, AppState};
16use crate::app_state::{AppHandle, AppState};
17use crate::data::{Presence, PresenceKind, presence_kind_of};
17use crate::data::{Presence, PresenceKind, presence_kind_of};
18use crate::people::resolve_names;
18use crate::people::resolve_names;
19use crate::presence_follow::{NOTIFY_WHEN_AVAILABLE, TURN_OFF_NOTIFICATIONS};
19use crate::profile_model::{
20use crate::profile_model::{
20 ContactKind, ContactRow, StatusBox, contact_rows, has_organization, local_time_label,
21 ContactKind, ContactRow, StatusBox, contact_rows, has_organization, local_time_label,
21 mailto_url, status_box, status_line, work_location_label,
22 mailto_url, status_box, status_line, work_location_label,
22};
23};
23use crate::theme::{self, ElevatedSurface as _};
24use crate::theme::{self, ElevatedSurface as _};
24use crate::presence_follow::{NOTIFY_WHEN_AVAILABLE, TURN_OFF_NOTIFICATIONS};
25
25
26const CARD_WIDTH: f32 = 340.;
26const CARD_WIDTH: f32 = 340.;
27const CARD_RADIUS: f32 = 10.;
27const CARD_RADIUS: f32 = 10.;
crates/app/src/views/proposal_card.rs +5 −112
@@ -25,7 +25,7 @@ const CARD_GAP: f32 = 8.;
25 25 const BUTTON_HEIGHT: f32 = 28.;
26 26 const BUTTON_RADIUS: f32 = 7.;
27 27 const BODY_LINE_HEIGHT: f32 = 20.;
28 const BODY_MAX_LINES: f32 = 12.;
28 const BODY_MAX_LINES: f32 = 4.;
29 29 const QUOTE_BAR_WIDTH: f32 = 2.;
30 30 const THUMBNAIL_HEIGHT: f32 = 48.;
31 31 const THUMBNAIL_MAX_WIDTH: f32 = 120.;
@@ -36,104 +36,12 @@ pub const PROPOSAL_THUMBNAILS: &str = "shell/islands/main/proposal-card/thumbnai
36 36 pub const PROPOSAL_BUTTONS: &str = "shell/islands/main/proposal-card/buttons";
37 37
38 38 pub type CardAction = Rc<dyn Fn(&mut Window, &mut App)>;
39 pub type AllowAction = Rc<dyn Fn(u32, &mut Window, &mut App)>;
40 39
41 40 #[derive(Clone)]
42 41 pub struct CardActions {
43 42 pub send: CardAction,
44 43 pub edit: CardAction,
45 44 pub discard: CardAction,
46 pub allow: AllowAction,
47 }
48
49 pub const FREE_WRITING_CHOICES: [u32; 3] = [15, 60, 240];
50 pub const FREE_WRITING_BAR: &str = "shell/islands/main/free-writing-bar";
51
52 pub fn free_writing_choices(asked: u32) -> Vec<u32> {
53 let mut choices: Vec<u32> = FREE_WRITING_CHOICES.to_vec();
54 if !choices.contains(&asked) {
55 choices.push(asked);
56 choices.sort_unstable();
57 }
58 choices
59 }
60
61 pub fn duration_label(minutes: u32) -> String {
62 match (minutes / 60, minutes % 60) {
63 (0, rest) => format!("{rest} min"),
64 (hours, 0) => format!("{hours} h"),
65 (hours, rest) => format!("{hours} h {rest} min"),
66 }
67 }
68
69 fn free_writing_row(entry: &ProposalEntry, allow: AllowAction) -> Option<Div> {
70 let ask = entry.proposal.free_writing_ask.as_ref()?;
71 let agent = agent_label(entry.proposal.agent.as_deref());
72 let chips = free_writing_choices(ask.minutes).into_iter().map(|minutes| {
73 let allow = allow.clone();
74 div()
75 .id(ElementId::Name(format!("proposal-allow-{minutes}").into()))
76 .h(px(BUTTON_HEIGHT))
77 .px(px(10.))
78 .flex()
79 .items_center()
80 .rounded(px(BUTTON_RADIUS))
81 .cursor_pointer()
82 .text_size(px(12.))
83 .bg(theme::surface_raised())
84 .text_color(theme::text())
85 .hover(|chip| chip.opacity(0.85))
86 .child(duration_label(minutes))
87 .on_click(move |_, window, cx| allow(minutes, window, cx))
88 });
89 let reason = (!ask.reason.is_empty()).then(|| format!(": {}", ask.reason)).unwrap_or_default();
90 Some(
91 v_flex()
92 .w_full()
93 .gap(px(6.))
94 .child(
95 div()
96 .text_size(px(12.))
97 .text_color(theme::text_muted())
98 .child(format!(
99 "{agent} asks to keep writing here without review for {}{reason}",
100 duration_label(ask.minutes)
101 )),
102 )
103 .child(
104 h_flex()
105 .flex_wrap()
106 .items_center()
107 .gap(px(6.))
108 .child(div().text_size(px(12.)).text_color(theme::text_soft()).child("Send and allow for"))
109 .children(chips),
110 ),
111 )
112 }
113
114 pub fn free_writing_bar(agent: &str, until: DateTime<Utc>, stop: CardAction) -> Div {
115 let until = until.with_timezone(&chrono::Local).format(crate::format::clock_format());
116 h_flex()
117 .flex_none()
118 .mx(px(CARD_MARGIN_X))
119 .mb(px(CARD_MARGIN_BOTTOM))
120 .px(px(CARD_PADDING))
121 .h(px(BUTTON_HEIGHT + CARD_GAP))
122 .gap(px(CARD_GAP))
123 .items_center()
124 .rounded(px(CARD_RADIUS))
125 .bg(theme::row_hover())
126 .debug_selector(|| FREE_WRITING_BAR.into())
127 .child(
128 div()
129 .flex_1()
130 .min_w_0()
131 .truncate()
132 .text_size(px(12.))
133 .text_color(theme::text_muted())
134 .child(format!("{agent} writes here without review until {until}")),
135 )
136 .child(card_button("free-writing-stop", "Stop", theme::surface_raised(), theme::text(), stop))
137 45 }
138 46
139 47 fn open_session_available(session_id: &str, cx: &App) -> bool {
@@ -256,7 +164,7 @@ pub fn age_label(created_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
256 164 }
257 165 }
258 166
259 pub(super) fn card_button(
167 fn card_button(
260 168 id: &'static str,
261 169 label: &'static str,
262 170 background: Hsla,
@@ -367,7 +275,7 @@ pub fn render(
367 275 .id("proposal-text")
368 276 .w_full()
369 277 .max_h(px(BODY_LINE_HEIGHT * BODY_MAX_LINES))
370 .overflow_y_scroll()
278 .overflow_hidden()
371 279 .text_size(px(14.))
372 280 .line_height(px(BODY_LINE_HEIGHT))
373 281 .when(stale, |body| body.opacity(0.6))
@@ -378,9 +286,6 @@ pub fn render(
378 286 })
379 287 });
380 288 let images = (!entry.images.is_empty()).then(|| thumbnails(&entry.images));
381 let free_writing = (!stale && !failed)
382 .then(|| free_writing_row(entry, actions.allow.clone()))
383 .flatten();
384 289 let session = entry
385 290 .proposal
386 291 .session_id
@@ -438,7 +343,6 @@ pub fn render(
438 343 .child(body)
439 344 .children(images)
440 345 .child(buttons)
441 .children(free_writing)
442 346 }
443 347
444 348 #[cfg(test)]
@@ -474,11 +378,9 @@ pub fn sample_entry(text: &str, mentions: &[(&str, &str)], images: &[Vec<u8>]) -
474 378 })
475 379 .collect(),
476 380 images: Vec::new(),
477 free_writing_ask: None,
478 381 agent: None,
479 382 session_id: None,
480 383 created_at: Utc::now(),
481 direct: false,
482 384 },
483 385 images: images
484 386 .iter()
@@ -499,22 +401,13 @@ mod tests {
499 401 use teams_core::MentionInput;
500 402
501 403 use super::{
502 age_label, duration_label, free_writing_choices, needs_upload, outgoing_for, picture_files, sample_entry,
503 sample_png, thumbnail_size,
404 age_label, needs_upload, outgoing_for, picture_files, sample_entry, sample_png,
405 thumbnail_size,
504 406 };
505 407 use crate::views::attachment_tray::{AttachmentTray, INLINE_IMAGE_MAX_BYTES, OutgoingImage};
506 408
507 409 const TWO_MEGABYTES: usize = 2 * 1024 * 1024;
508 410
509 #[test]
510 fn the_asked_window_joins_the_usual_choices() {
511 assert_eq!(free_writing_choices(60), [15, 60, 240]);
512 assert_eq!(free_writing_choices(30), [15, 30, 60, 240]);
513 assert_eq!(duration_label(15), "15 min");
514 assert_eq!(duration_label(240), "4 h");
515 assert_eq!(duration_label(90), "1 h 30 min");
516 }
517
518 411 #[test]
519 412 fn age_labels_follow_the_elapsed_time() {
520 413 let now = Utc::now();
@@ -25,7 +25,7 @@ const CARD_GAP: f32 = 8.;
25const BUTTON_HEIGHT: f32 = 28.;
25const BUTTON_HEIGHT: f32 = 28.;
26const BUTTON_RADIUS: f32 = 7.;
26const BUTTON_RADIUS: f32 = 7.;
27const BODY_LINE_HEIGHT: f32 = 20.;
27const BODY_LINE_HEIGHT: f32 = 20.;
28const BODY_MAX_LINES: f32 = 12.;
28const BODY_MAX_LINES: f32 = 4.;
29const QUOTE_BAR_WIDTH: f32 = 2.;
29const QUOTE_BAR_WIDTH: f32 = 2.;
30const THUMBNAIL_HEIGHT: f32 = 48.;
30const THUMBNAIL_HEIGHT: f32 = 48.;
31const THUMBNAIL_MAX_WIDTH: f32 = 120.;
31const THUMBNAIL_MAX_WIDTH: f32 = 120.;
@@ -36,104 +36,12 @@ pub const PROPOSAL_THUMBNAILS: &str = "shell/islands/main/proposal-card/thumbnai
36pub const PROPOSAL_BUTTONS: &str = "shell/islands/main/proposal-card/buttons";
36pub const PROPOSAL_BUTTONS: &str = "shell/islands/main/proposal-card/buttons";
37
37
38pub type CardAction = Rc<dyn Fn(&mut Window, &mut App)>;
38pub type CardAction = Rc<dyn Fn(&mut Window, &mut App)>;
39pub type AllowAction = Rc<dyn Fn(u32, &mut Window, &mut App)>;
40
39
41#[derive(Clone)]
40#[derive(Clone)]
42pub struct CardActions {
41pub struct CardActions {
43 pub send: CardAction,
42 pub send: CardAction,
44 pub edit: CardAction,
43 pub edit: CardAction,
45 pub discard: CardAction,
44 pub discard: CardAction,
46 pub allow: AllowAction,
47}
48
49pub const FREE_WRITING_CHOICES: [u32; 3] = [15, 60, 240];
50pub const FREE_WRITING_BAR: &str = "shell/islands/main/free-writing-bar";
51
52pub fn free_writing_choices(asked: u32) -> Vec<u32> {
53 let mut choices: Vec<u32> = FREE_WRITING_CHOICES.to_vec();
54 if !choices.contains(&asked) {
55 choices.push(asked);
56 choices.sort_unstable();
57 }
58 choices
59}
60
61pub fn duration_label(minutes: u32) -> String {
62 match (minutes / 60, minutes % 60) {
63 (0, rest) => format!("{rest} min"),
64 (hours, 0) => format!("{hours} h"),
65 (hours, rest) => format!("{hours} h {rest} min"),
66 }
67}
68
69fn free_writing_row(entry: &ProposalEntry, allow: AllowAction) -> Option<Div> {
70 let ask = entry.proposal.free_writing_ask.as_ref()?;
71 let agent = agent_label(entry.proposal.agent.as_deref());
72 let chips = free_writing_choices(ask.minutes).into_iter().map(|minutes| {
73 let allow = allow.clone();
74 div()
75 .id(ElementId::Name(format!("proposal-allow-{minutes}").into()))
76 .h(px(BUTTON_HEIGHT))
77 .px(px(10.))
78 .flex()
79 .items_center()
80 .rounded(px(BUTTON_RADIUS))
81 .cursor_pointer()
82 .text_size(px(12.))
83 .bg(theme::surface_raised())
84 .text_color(theme::text())
85 .hover(|chip| chip.opacity(0.85))
86 .child(duration_label(minutes))
87 .on_click(move |_, window, cx| allow(minutes, window, cx))
88 });
89 let reason = (!ask.reason.is_empty()).then(|| format!(": {}", ask.reason)).unwrap_or_default();
90 Some(
91 v_flex()
92 .w_full()
93 .gap(px(6.))
94 .child(
95 div()
96 .text_size(px(12.))
97 .text_color(theme::text_muted())
98 .child(format!(
99 "{agent} asks to keep writing here without review for {}{reason}",
100 duration_label(ask.minutes)
101 )),
102 )
103 .child(
104 h_flex()
105 .flex_wrap()
106 .items_center()
107 .gap(px(6.))
108 .child(div().text_size(px(12.)).text_color(theme::text_soft()).child("Send and allow for"))
109 .children(chips),
110 ),
111 )
112}
113
114pub fn free_writing_bar(agent: &str, until: DateTime<Utc>, stop: CardAction) -> Div {
115 let until = until.with_timezone(&chrono::Local).format(crate::format::clock_format());
116 h_flex()
117 .flex_none()
118 .mx(px(CARD_MARGIN_X))
119 .mb(px(CARD_MARGIN_BOTTOM))
120 .px(px(CARD_PADDING))
121 .h(px(BUTTON_HEIGHT + CARD_GAP))
122 .gap(px(CARD_GAP))
123 .items_center()
124 .rounded(px(CARD_RADIUS))
125 .bg(theme::row_hover())
126 .debug_selector(|| FREE_WRITING_BAR.into())
127 .child(
128 div()
129 .flex_1()
130 .min_w_0()
131 .truncate()
132 .text_size(px(12.))
133 .text_color(theme::text_muted())
134 .child(format!("{agent} writes here without review until {until}")),
135 )
136 .child(card_button("free-writing-stop", "Stop", theme::surface_raised(), theme::text(), stop))
137}
45}
138
46
139fn open_session_available(session_id: &str, cx: &App) -> bool {
47fn open_session_available(session_id: &str, cx: &App) -> bool {
@@ -256,7 +164,7 @@ pub fn age_label(created_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
256 }
164 }
257}
165}
258
166
259pub(super) fn card_button(
167fn card_button(
260 id: &'static str,
168 id: &'static str,
261 label: &'static str,
169 label: &'static str,
262 background: Hsla,
170 background: Hsla,
@@ -367,7 +275,7 @@ pub fn render(
367 .id("proposal-text")
275 .id("proposal-text")
368 .w_full()
276 .w_full()
369 .max_h(px(BODY_LINE_HEIGHT * BODY_MAX_LINES))
277 .max_h(px(BODY_LINE_HEIGHT * BODY_MAX_LINES))
370 .overflow_y_scroll()
278 .overflow_hidden()
371 .text_size(px(14.))
279 .text_size(px(14.))
372 .line_height(px(BODY_LINE_HEIGHT))
280 .line_height(px(BODY_LINE_HEIGHT))
373 .when(stale, |body| body.opacity(0.6))
281 .when(stale, |body| body.opacity(0.6))
@@ -378,9 +286,6 @@ pub fn render(
378 })
286 })
379 });
287 });
380 let images = (!entry.images.is_empty()).then(|| thumbnails(&entry.images));
288 let images = (!entry.images.is_empty()).then(|| thumbnails(&entry.images));
381 let free_writing = (!stale && !failed)
382 .then(|| free_writing_row(entry, actions.allow.clone()))
383 .flatten();
384 let session = entry
289 let session = entry
385 .proposal
290 .proposal
386 .session_id
291 .session_id
@@ -438,7 +343,6 @@ pub fn render(
438 .child(body)
343 .child(body)
439 .children(images)
344 .children(images)
440 .child(buttons)
345 .child(buttons)
441 .children(free_writing)
442}
346}
443
347
444#[cfg(test)]
348#[cfg(test)]
@@ -474,11 +378,9 @@ pub fn sample_entry(text: &str, mentions: &[(&str, &str)], images: &[Vec<u8>]) -
474 })
378 })
475 .collect(),
379 .collect(),
476 images: Vec::new(),
380 images: Vec::new(),
477 free_writing_ask: None,
478 agent: None,
381 agent: None,
479 session_id: None,
382 session_id: None,
480 created_at: Utc::now(),
383 created_at: Utc::now(),
481 direct: false,
482 },
384 },
483 images: images
385 images: images
484 .iter()
386 .iter()
@@ -499,22 +401,13 @@ mod tests {
499 use teams_core::MentionInput;
401 use teams_core::MentionInput;
500
402
501 use super::{
403 use super::{
502 age_label, duration_label, free_writing_choices, needs_upload, outgoing_for, picture_files, sample_entry,
404 age_label, needs_upload, outgoing_for, picture_files, sample_entry, sample_png,
503 sample_png, thumbnail_size,
405 thumbnail_size,
504 };
406 };
505 use crate::views::attachment_tray::{AttachmentTray, INLINE_IMAGE_MAX_BYTES, OutgoingImage};
407 use crate::views::attachment_tray::{AttachmentTray, INLINE_IMAGE_MAX_BYTES, OutgoingImage};
506
408
507 const TWO_MEGABYTES: usize = 2 * 1024 * 1024;
409 const TWO_MEGABYTES: usize = 2 * 1024 * 1024;
508
410
509 #[test]
510 fn the_asked_window_joins_the_usual_choices() {
511 assert_eq!(free_writing_choices(60), [15, 60, 240]);
512 assert_eq!(free_writing_choices(30), [15, 30, 60, 240]);
513 assert_eq!(duration_label(15), "15 min");
514 assert_eq!(duration_label(240), "4 h");
515 assert_eq!(duration_label(90), "1 h 30 min");
516 }
517
518 #[test]
411 #[test]
519 fn age_labels_follow_the_elapsed_time() {
412 fn age_labels_follow_the_elapsed_time() {
520 let now = Utc::now();
413 let now = Utc::now();
crates/app/src/views/quick_view_pane.rs +4 −2
@@ -383,7 +383,6 @@ mod tests {
383 383 }
384 384 }
385 385
386
387 386 #[test]
388 387 fn mentions_list_only_mentions_newest_first() {
389 388 let entries = [
@@ -394,7 +393,10 @@ mod tests {
394 393 let offset = FixedOffset::east_opt(0).unwrap();
395 394 let today = NaiveDate::from_ymd_opt(2026, 11, 8).unwrap();
396 395 let rows = mention_rows(&entries, &Sidebar::default(), today, offset);
397 let ids: Vec<_> = rows.iter().map(|row| row.message_id.clone().unwrap()).collect();
396 let ids: Vec<_> = rows
397 .iter()
398 .map(|row| row.message_id.clone().unwrap())
399 .collect();
398 400 assert_eq!(ids, ["m-c", "m-a"]);
399 401 assert_eq!(rows[0].author, "Ada");
400 402 }
@@ -383,7 +383,6 @@ mod tests {
383 }
383 }
384 }
384 }
385
385
386
387 #[test]
386 #[test]
388 fn mentions_list_only_mentions_newest_first() {
387 fn mentions_list_only_mentions_newest_first() {
389 let entries = [
388 let entries = [
@@ -394,7 +393,10 @@ mod tests {
394 let offset = FixedOffset::east_opt(0).unwrap();
393 let offset = FixedOffset::east_opt(0).unwrap();
395 let today = NaiveDate::from_ymd_opt(2026, 11, 8).unwrap();
394 let today = NaiveDate::from_ymd_opt(2026, 11, 8).unwrap();
396 let rows = mention_rows(&entries, &Sidebar::default(), today, offset);
395 let rows = mention_rows(&entries, &Sidebar::default(), today, offset);
397 let ids: Vec<_> = rows.iter().map(|row| row.message_id.clone().unwrap()).collect();
396 let ids: Vec<_> = rows
397 .iter()
398 .map(|row| row.message_id.clone().unwrap())
399 .collect();
398 assert_eq!(ids, ["m-c", "m-a"]);
400 assert_eq!(ids, ["m-c", "m-a"]);
399 assert_eq!(rows[0].author, "Ada");
401 assert_eq!(rows[0].author, "Ada");
400 }
402 }
crates/app/src/views/rail.rs +6 −6
@@ -140,7 +140,11 @@ fn item_element(item: &RailItem, active: bool) -> Stateful<Div> {
140 140 .when(!active, |button| {
141 141 button.hover(|button| button.bg(theme::row_hover()))
142 142 })
143 .child(if active { filled_icon(item.icon, ICON_SIZE, color) } else { icon(item.icon, ICON_SIZE, color) })
143 .child(if active {
144 filled_icon(item.icon, ICON_SIZE, color)
145 } else {
146 icon(item.icon, ICON_SIZE, color)
147 })
144 148 .child(
145 149 div()
146 150 .max_w(px(RAIL_ITEM_WIDTH - 2. * LABEL_INSET))
@@ -242,11 +246,7 @@ impl Render for RailView {
242 246 .items_center()
243 247 .gap(px(2.))
244 248 .pt(px(0.))
245 .children(
246 items
247 .iter()
248 .map(|item| self.item(item, item.tab == active)),
249 )
249 .children(items.iter().map(|item| self.item(item, item.tab == active)))
250 250 }
251 251 }
252 252
@@ -140,7 +140,11 @@ fn item_element(item: &RailItem, active: bool) -> Stateful<Div> {
140 .when(!active, |button| {
140 .when(!active, |button| {
141 button.hover(|button| button.bg(theme::row_hover()))
141 button.hover(|button| button.bg(theme::row_hover()))
142 })
142 })
143 .child(if active { filled_icon(item.icon, ICON_SIZE, color) } else { icon(item.icon, ICON_SIZE, color) })
143 .child(if active {
144 filled_icon(item.icon, ICON_SIZE, color)
145 } else {
146 icon(item.icon, ICON_SIZE, color)
147 })
144 .child(
148 .child(
145 div()
149 div()
146 .max_w(px(RAIL_ITEM_WIDTH - 2. * LABEL_INSET))
150 .max_w(px(RAIL_ITEM_WIDTH - 2. * LABEL_INSET))
@@ -242,11 +246,7 @@ impl Render for RailView {
242 .items_center()
246 .items_center()
243 .gap(px(2.))
247 .gap(px(2.))
244 .pt(px(0.))
248 .pt(px(0.))
245 .children(
249 .children(items.iter().map(|item| self.item(item, item.tab == active)))
246 items
247 .iter()
248 .map(|item| self.item(item, item.tab == active)),
249 )
250 }
250 }
251}
251}
252
252
crates/app/src/views/reaction_pills.rs +7 −5
@@ -2,8 +2,8 @@ use crate::views::image_memory::bounded;
2 2 use std::rc::Rc;
3 3
4 4 use chrono::Local;
5 use gpui_kit::component::scroll::ScrollableElement as _;
6 5 use gpui_kit::base::GlobalState;
6 use gpui_kit::component::scroll::ScrollableElement as _;
7 7 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
8 8 use gpui_kit::prelude::FluentBuilder as _;
9 9 use gpui_kit::*;
@@ -120,9 +120,7 @@ fn pill_content(chip: &ReactionChip, background: Hsla, directory: &Directory) ->
120 120 ),
121 121 )
122 122 } else {
123 content
124 .gap(px(PILL_GAP))
125 .child(chip.count.to_string())
123 content.gap(px(PILL_GAP)).child(chip.count.to_string())
126 124 }
127 125 }
128 126
@@ -162,7 +160,11 @@ fn pill(
162 160 .h(px(PILL_HEIGHT))
163 161 .flex_none()
164 162 .pl(px(5.))
165 .pr(px(if shows_faces(chip.reactors.len()) { 2. } else { 8. }))
163 .pr(px(if shows_faces(chip.reactors.len()) {
164 2.
165 } else {
166 8.
167 }))
166 168 .items_center()
167 169 .rounded(px(PILL_HEIGHT / 2.))
168 170 .bg(background)
@@ -2,8 +2,8 @@ use crate::views::image_memory::bounded;
2use std::rc::Rc;
2use std::rc::Rc;
3
3
4use chrono::Local;
4use chrono::Local;
5use gpui_kit::component::scroll::ScrollableElement as _;
6use gpui_kit::base::GlobalState;
5use gpui_kit::base::GlobalState;
6use gpui_kit::component::scroll::ScrollableElement as _;
7use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
8use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
9use gpui_kit::*;
@@ -120,9 +120,7 @@ fn pill_content(chip: &ReactionChip, background: Hsla, directory: &Directory) ->
120 ),
120 ),
121 )
121 )
122 } else {
122 } else {
123 content
123 content.gap(px(PILL_GAP)).child(chip.count.to_string())
124 .gap(px(PILL_GAP))
125 .child(chip.count.to_string())
126 }
124 }
127}
125}
128
126
@@ -162,7 +160,11 @@ fn pill(
162 .h(px(PILL_HEIGHT))
160 .h(px(PILL_HEIGHT))
163 .flex_none()
161 .flex_none()
164 .pl(px(5.))
162 .pl(px(5.))
165 .pr(px(if shows_faces(chip.reactors.len()) { 2. } else { 8. }))
163 .pr(px(if shows_faces(chip.reactors.len()) {
164 2.
165 } else {
166 8.
167 }))
166 .items_center()
168 .items_center()
167 .rounded(px(PILL_HEIGHT / 2.))
169 .rounded(px(PILL_HEIGHT / 2.))
168 .bg(background)
170 .bg(background)
crates/app/src/views/recap_tab.rs +57 −48
@@ -5,8 +5,8 @@ use chatsvc::{
5 5 days_until_expiry,
6 6 };
7 7 use chrono::{DateTime, FixedOffset, Local, NaiveDate, Offset as _, Utc};
8 use gpui_kit::component::scroll::ScrollableElement as _;
9 8 use gpui_kit::assets::IconName;
9 use gpui_kit::component::scroll::ScrollableElement as _;
10 10 use gpui_kit::component::{
11 11 button::{Button, ButtonVariants as _},
12 12 h_flex,
@@ -77,17 +77,13 @@ pub struct RecapView<'a> {
77 77 }
78 78
79 79 fn section(title: &'static str) -> Div {
80 v_flex()
81 .w_full()
82 .flex_none()
83 .gap(px(10.))
84 .child(
85 div()
86 .text_size(px(13.))
87 .font_weight(FontWeight::SEMIBOLD)
88 .text_color(theme::text())
89 .child(title),
90 )
80 v_flex().w_full().flex_none().gap(px(10.)).child(
81 div()
82 .text_size(px(13.))
83 .font_weight(FontWeight::SEMIBOLD)
84 .text_color(theme::text())
85 .child(title),
86 )
91 87 }
92 88
93 89 fn muted(text: impl Into<SharedString>) -> Div {
@@ -139,31 +135,39 @@ fn picker(view: &RecapView, offset: FixedOffset, today: NaiveDate, run: &RecapRu
139 135 .flex_none()
140 136 .gap(px(6.))
141 137 .flex_wrap()
142 .children(view.occurrences.iter().enumerate().map(|(index, occurrence)| {
143 let run = run.clone();
144 let active = index == view.selected;
145 div()
146 .id(ElementId::NamedInteger("recap-occurrence".into(), index as u64))
147 .px(px(12.))
148 .py(px(4.))
149 .rounded_full()
150 .cursor_pointer()
151 .text_size(px(12.))
152 .bg(if active {
153 theme::accent()
154 } else {
155 theme::surface_raised()
156 })
157 .text_color(if active {
158 theme::on_accent()
159 } else {
160 theme::text_soft()
161 })
162 .on_click(move |_, window, cx| {
163 run(RecapCommand::Occurrence(index), window, cx)
164 })
165 .child(occurrence_label(occurrence, today, offset))
166 }))
138 .children(
139 view.occurrences
140 .iter()
141 .enumerate()
142 .map(|(index, occurrence)| {
143 let run = run.clone();
144 let active = index == view.selected;
145 div()
146 .id(ElementId::NamedInteger(
147 "recap-occurrence".into(),
148 index as u64,
149 ))
150 .px(px(12.))
151 .py(px(4.))
152 .rounded_full()
153 .cursor_pointer()
154 .text_size(px(12.))
155 .bg(if active {
156 theme::accent()
157 } else {
158 theme::surface_raised()
159 })
160 .text_color(if active {
161 theme::on_accent()
162 } else {
163 theme::text_soft()
164 })
165 .on_click(move |_, window, cx| {
166 run(RecapCommand::Occurrence(index), window, cx)
167 })
168 .child(occurrence_label(occurrence, today, offset))
169 }),
170 )
167 171 }
168 172
169 173 fn recording_card(details: &RecordingDetails) -> Div {
@@ -175,13 +179,17 @@ fn recording_card(details: &RecordingDetails) -> Div {
175 179 .justify_between()
176 180 .text_size(px(12.))
177 181 .text_color(gpui_kit::white())
178 .child(div().child(
179 details
180 .duration_seconds
181 .map(clock_label)
182 .unwrap_or_default(),
183 ))
184 .when(details.audio_only, |row| row.child(div().child("Audio only")));
182 .child(
183 div().child(
184 details
185 .duration_seconds
186 .map(clock_label)
187 .unwrap_or_default(),
188 ),
189 )
190 .when(details.audio_only, |row| {
191 row.child(div().child("Audio only"))
192 });
185 193 div()
186 194 .relative()
187 195 .w(px(CARD_WIDTH))
@@ -389,9 +397,7 @@ fn transcript_section(view: &RecapView, run: &RecapRun) -> Div {
389 397 .into_any_element()
390 398 }
391 399 };
392 section("Transcript")
393 .child(downloads)
394 .child(body)
400 section("Transcript").child(downloads).child(body)
395 401 }
396 402
397 403 fn attendance_row(record: &AttendanceRecord, offset: FixedOffset) -> Div {
@@ -416,7 +422,10 @@ fn attendance_row(record: &AttendanceRecord, offset: FixedOffset) -> Div {
416 422 .text_color(theme::text())
417 423 .child(record.name.clone()),
418 424 )
419 .child(cell(time_label(record.joined_at, offset), ATTENDANCE_COLUMN))
425 .child(cell(
426 time_label(record.joined_at, offset),
427 ATTENDANCE_COLUMN,
428 ))
420 429 .child(cell(time_label(record.left_at, offset), ATTENDANCE_COLUMN))
421 430 .child(cell(span_label(record.duration_seconds), ATTENDANCE_COLUMN))
422 431 }
@@ -5,8 +5,8 @@ use chatsvc::{
5 days_until_expiry,
5 days_until_expiry,
6};
6};
7use chrono::{DateTime, FixedOffset, Local, NaiveDate, Offset as _, Utc};
7use chrono::{DateTime, FixedOffset, Local, NaiveDate, Offset as _, Utc};
8use gpui_kit::component::scroll::ScrollableElement as _;
9use gpui_kit::assets::IconName;
8use gpui_kit::assets::IconName;
9use gpui_kit::component::scroll::ScrollableElement as _;
10use gpui_kit::component::{
10use gpui_kit::component::{
11 button::{Button, ButtonVariants as _},
11 button::{Button, ButtonVariants as _},
12 h_flex,
12 h_flex,
@@ -77,17 +77,13 @@ pub struct RecapView<'a> {
77}
77}
78
78
79fn section(title: &'static str) -> Div {
79fn section(title: &'static str) -> Div {
80 v_flex()
80 v_flex().w_full().flex_none().gap(px(10.)).child(
81 .w_full()
81 div()
82 .flex_none()
82 .text_size(px(13.))
83 .gap(px(10.))
83 .font_weight(FontWeight::SEMIBOLD)
84 .child(
84 .text_color(theme::text())
85 div()
85 .child(title),
86 .text_size(px(13.))
86 )
87 .font_weight(FontWeight::SEMIBOLD)
88 .text_color(theme::text())
89 .child(title),
90 )
91}
87}
92
88
93fn muted(text: impl Into<SharedString>) -> Div {
89fn muted(text: impl Into<SharedString>) -> Div {
@@ -139,31 +135,39 @@ fn picker(view: &RecapView, offset: FixedOffset, today: NaiveDate, run: &RecapRu
139 .flex_none()
135 .flex_none()
140 .gap(px(6.))
136 .gap(px(6.))
141 .flex_wrap()
137 .flex_wrap()
142 .children(view.occurrences.iter().enumerate().map(|(index, occurrence)| {
138 .children(
143 let run = run.clone();
139 view.occurrences
144 let active = index == view.selected;
140 .iter()
145 div()
141 .enumerate()
146 .id(ElementId::NamedInteger("recap-occurrence".into(), index as u64))
142 .map(|(index, occurrence)| {
147 .px(px(12.))
143 let run = run.clone();
148 .py(px(4.))
144 let active = index == view.selected;
149 .rounded_full()
145 div()
150 .cursor_pointer()
146 .id(ElementId::NamedInteger(
151 .text_size(px(12.))
147 "recap-occurrence".into(),
152 .bg(if active {
148 index as u64,
153 theme::accent()
149 ))
154 } else {
150 .px(px(12.))
155 theme::surface_raised()
151 .py(px(4.))
156 })
152 .rounded_full()
157 .text_color(if active {
153 .cursor_pointer()
158 theme::on_accent()
154 .text_size(px(12.))
159 } else {
155 .bg(if active {
160 theme::text_soft()
156 theme::accent()
161 })
157 } else {
162 .on_click(move |_, window, cx| {
158 theme::surface_raised()
163 run(RecapCommand::Occurrence(index), window, cx)
159 })
164 })
160 .text_color(if active {
165 .child(occurrence_label(occurrence, today, offset))
161 theme::on_accent()
166 }))
162 } else {
163 theme::text_soft()
164 })
165 .on_click(move |_, window, cx| {
166 run(RecapCommand::Occurrence(index), window, cx)
167 })
168 .child(occurrence_label(occurrence, today, offset))
169 }),
170 )
167}
171}
168
172
169fn recording_card(details: &RecordingDetails) -> Div {
173fn recording_card(details: &RecordingDetails) -> Div {
@@ -175,13 +179,17 @@ fn recording_card(details: &RecordingDetails) -> Div {
175 .justify_between()
179 .justify_between()
176 .text_size(px(12.))
180 .text_size(px(12.))
177 .text_color(gpui_kit::white())
181 .text_color(gpui_kit::white())
178 .child(div().child(
182 .child(
179 details
183 div().child(
180 .duration_seconds
184 details
181 .map(clock_label)
185 .duration_seconds
182 .unwrap_or_default(),
186 .map(clock_label)
183 ))
187 .unwrap_or_default(),
184 .when(details.audio_only, |row| row.child(div().child("Audio only")));
188 ),
189 )
190 .when(details.audio_only, |row| {
191 row.child(div().child("Audio only"))
192 });
185 div()
193 div()
186 .relative()
194 .relative()
187 .w(px(CARD_WIDTH))
195 .w(px(CARD_WIDTH))
@@ -389,9 +397,7 @@ fn transcript_section(view: &RecapView, run: &RecapRun) -> Div {
389 .into_any_element()
397 .into_any_element()
390 }
398 }
391 };
399 };
392 section("Transcript")
400 section("Transcript").child(downloads).child(body)
393 .child(downloads)
394 .child(body)
395}
401}
396
402
397fn attendance_row(record: &AttendanceRecord, offset: FixedOffset) -> Div {
403fn attendance_row(record: &AttendanceRecord, offset: FixedOffset) -> Div {
@@ -416,7 +422,10 @@ fn attendance_row(record: &AttendanceRecord, offset: FixedOffset) -> Div {
416 .text_color(theme::text())
422 .text_color(theme::text())
417 .child(record.name.clone()),
423 .child(record.name.clone()),
418 )
424 )
419 .child(cell(time_label(record.joined_at, offset), ATTENDANCE_COLUMN))
425 .child(cell(
426 time_label(record.joined_at, offset),
427 ATTENDANCE_COLUMN,
428 ))
420 .child(cell(time_label(record.left_at, offset), ATTENDANCE_COLUMN))
429 .child(cell(time_label(record.left_at, offset), ATTENDANCE_COLUMN))
421 .child(cell(span_label(record.duration_seconds), ATTENDANCE_COLUMN))
430 .child(cell(span_label(record.duration_seconds), ATTENDANCE_COLUMN))
422}
431}
crates/app/src/views/shared_tab.rs +1 −1
@@ -1,8 +1,8 @@
1 1 use std::rc::Rc;
2 2
3 3 use chrono::{Local, Offset as _};
4 use gpui_kit::component::scroll::ScrollableElement as _;
5 4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::scroll::ScrollableElement as _;
6 6 use gpui_kit::component::{
7 7 button::{Button, ButtonVariants as _},
8 8 h_flex,
@@ -1,8 +1,8 @@
1use std::rc::Rc;
1use std::rc::Rc;
2
2
3use chrono::{Local, Offset as _};
3use chrono::{Local, Offset as _};
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
5use gpui_kit::component::scroll::ScrollableElement as _;
6use gpui_kit::component::{
6use gpui_kit::component::{
7 button::{Button, ButtonVariants as _},
7 button::{Button, ButtonVariants as _},
8 h_flex,
8 h_flex,
crates/app/src/views/shell.rs +257 −144
@@ -5,46 +5,47 @@ use std::sync::Arc;
5 5 use gpui_kit::component::{elevation, h_flex, v_flex};
6 6 use gpui_kit::*;
7 7
8 use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
9 8 use super::actions::{NewChat, OpenSwitcher, ReplyToHovered, ToggleCallMute};
9 use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
10 10 use super::calendar_view::CalendarView;
11 use super::call_end_view::render_call_end;
12 use super::call_mini::CallMiniView;
13 use super::call_pop_out::zoom_listener;
14 use super::call_stage::{render_call_overlay, render_stage_overlay};
15 use super::call_view::{CHAT_PANEL_WIDTH, OVERLAY_BELOW as CALL_COLUMN_MIN, render_call_view};
16 use super::calls_page::CallsPage;
17 use super::chat_pop_out;
18 use super::connection_banner::render_connection_banner;
11 19 use super::conversation::ConversationView;
12 20 use super::dialog_overlay::render_task_dialog;
13 21 use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
14 22 use super::image_viewer::{ImageViewer, ImageViewerEvent};
23 use super::notice_toast::NoticeToasts;
24 use super::prejoin_view::PrejoinView;
15 25 use super::profile_card::{ProfileCard, ProfileCardEvent};
16 use gpui_kit::prelude::FluentBuilder as _;
17 use super::rail::RailView;
18 use crate::chat_filter::ChatFilterPill;
19 use super::calls_page::CallsPage;
20 26 use super::quick_view_pane::{QuickViewEvent, QuickViewPane};
27 use super::rail::RailView;
21 28 use super::shortcuts::{
22 ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats,
23 FilterNonMeetingChats, FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
24 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatFilter, OpenChatsTab, PopOutSelectedChat, OpenLobbyList, OpenSaved, OpenCalendar, PreviousConversation, PushToTalk,
25 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera,
26 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
27 ZoomShareReset,
29 ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats, FilterNonMeetingChats,
30 FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest,
31 NextConversation, OpenActivity, OpenAgents, OpenCalendar, OpenCallsTab, OpenChannelsTab,
32 OpenChatFilter, OpenChatsTab, OpenLobbyList, OpenSaved, OpenSettings, PopOutSelectedChat,
33 PreviousConversation, PushToTalk, Scope, ShowShortcuts, StartAudioCall, StartVideoCall,
34 ToggleCallCamera, ToggleCallFullscreen, ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut,
35 ZoomReset, ZoomShareIn, ZoomShareOut, ZoomShareReset,
28 36 };
29 use super::window_zoom::{WindowZoom, change_zoom};
30 use super::call_pop_out::zoom_listener;
31 use super::chat_pop_out;
32 37 use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
33 38 use super::sidebar::{SidebarEvent, SidebarTab, SidebarView};
34 use app_ui_kit::render::hooks::RenderHooks;
35 use app_ui_kit::layout::{ISLAND_GAP, SIDEBAR_WIDTH};
36 use super::connection_banner::render_connection_banner;
37 use super::manage_team_page::ManageTeamPage;
38 use super::splash::{self, Phase, Splash, StartupFacts};
39 use super::notice_toast::NoticeToasts;
40 39 use super::status_menu::{own_status_button, settings_more_button};
41 40 use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};
42 41 use super::switcher::{Switcher, SwitcherEvent, candidates_from};
43 42 use super::title_bar::{mode_label, render_title_bar, update_button};
43 use super::window_zoom::{WindowZoom, change_zoom};
44 44 use crate::activity::ActivityCenter;
45 45 use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};
46 46 use crate::app_state::{AppEvent, AppState, QuickView, Selection, selection_for};
47 47 use crate::call::{CallMedia, CallWindows, ZoomStep};
48 use crate::chat_filter::ChatFilterPill;
48 49 use crate::notice::NoticeAction;
49 50 use crate::notify::NotificationCenter;
50 51 use crate::settings::{SettingsDialog, SettingsDialogEvent};
@@ -53,6 +54,9 @@ use crate::sidebar_model::Step;
53 54 use crate::theme;
54 55 use crate::updater::{self, IdleInputs, UpdateStatus};
55 56 use crate::user_activity::{self, UserInput};
57 use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
58 use app_ui_kit::render::hooks::RenderHooks;
59 use gpui_kit::prelude::FluentBuilder as _;
56 60
57 61 pub fn bind_keys(cx: &mut App) {
58 62 super::composer::bind_keys(cx);
@@ -81,6 +85,19 @@ pub struct Startup {
81 85 pub launched_by_autostart: bool,
82 86 }
83 87
88 pub const SIDEBAR_HIDDEN_BELOW: f32 = 960.;
89
90 pub fn sidebar_hidden_in_call(window_width: f32, panel_open: bool) -> bool {
91 let panel_width = if panel_open {
92 CHAT_PANEL_WIDTH + ISLAND_GAP
93 } else {
94 0.
95 };
96 window_width < SIDEBAR_HIDDEN_BELOW
97 || window_width - RAIL_WIDTH - SIDEBAR_WIDTH - 2. * ISLAND_GAP - panel_width
98 < CALL_COLUMN_MIN
99 }
100
84 101 pub struct UserInputHandle(pub Arc<UserInput>);
85 102
86 103 impl Global for UserInputHandle {}
@@ -99,7 +116,10 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:
99 116 fn open_link(url: &str, cx: &mut App) {
100 117 if let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() {
101 118 let text = opening_link_text(url);
102 handle.0.clone().update(cx, |state, cx| state.raise_notice(text, None, cx));
119 handle
120 .0
121 .clone()
122 .update(cx, |state, cx| state.raise_notice(text, None, cx));
103 123 }
104 124 cx.open_url(url);
105 125 }
@@ -168,10 +188,11 @@ pub struct AppShell {
168 188 sidebar: Entity<SidebarView>,
169 189 calendar: Entity<CalendarView>,
170 190 quick_pane: Entity<QuickViewPane>,
171 manage_team_page: Entity<ManageTeamPage>,
172 191 calls_page: Entity<CallsPage>,
173 192 shown_quick_view: Option<QuickView>,
174 193 conversation: Entity<ConversationView>,
194 call_chat: Option<(String, Entity<ConversationView>)>,
195 prejoin: Option<Entity<PrejoinView>>,
175 196 switcher: Option<Entity<Switcher>>,
176 197 notifications: Entity<NotificationCenter>,
177 198 _call_windows: Entity<CallWindows>,
@@ -183,12 +204,15 @@ pub struct AppShell {
183 204 settings_dialog: Option<Entity<SettingsDialog>>,
184 205 profile_card: Option<Entity<ProfileCard>>,
185 206 focus_handle: FocusHandle,
207 call_window_fullscreen: bool,
208 window_was_fullscreen: bool,
186 209 open_target: Option<OpenTarget>,
187 210 update: UpdateStatus,
188 splash: Splash,
189 211 toasts: NoticeToasts,
190 212 user_input: Arc<UserInput>,
191 213 _subscription: Subscription,
214 call_mini: Entity<CallMiniView>,
215 _call_media_observation: Subscription,
192 216 _panel_subscriptions: [Subscription; 2],
193 217 _sidebar_subscription: Subscription,
194 218 _agents_subscription: Option<Subscription>,
@@ -205,6 +229,24 @@ impl AppShell {
205 229 cx.notify();
206 230 }
207 231
232 fn sync_call_chat(
233 &mut self,
234 thread: Option<String>,
235 window: &mut Window,
236 cx: &mut Context<Self>,
237 ) {
238 match (thread, &self.call_chat) {
239 (Some(wanted), Some((open, _))) if &wanted == open => {}
240 (Some(wanted), _) => {
241 let app = self.state.clone();
242 let selection = Selection::Chat(wanted.clone());
243 let view = cx.new(|cx| ConversationView::pinned_to(app, selection, window, cx));
244 self.call_chat = Some((wanted, view));
245 }
246 (None, _) => self.call_chat = None,
247 }
248 }
249
208 250 fn focus_opened_quick_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
209 251 let quick_view = self.state.read(cx).quick_view;
210 252 if std::mem::replace(&mut self.shown_quick_view, quick_view) != quick_view
@@ -229,6 +271,19 @@ impl AppShell {
229 271 });
230 272 }
231 273
274 fn sync_prejoin(&mut self, window: &mut Window, cx: &mut Context<Self>) {
275 let wanted = self.state.read(cx).prejoin.clone();
276 let open = self.prejoin.as_ref().map(|view| view.read(cx).pending_id());
277 match (wanted, open) {
278 (Some(pending), Some(id)) if pending.id == id => {}
279 (Some(pending), _) => {
280 let app = self.state.clone();
281 self.prejoin = Some(cx.new(|cx| PrejoinView::new(app, &pending, window, cx)));
282 }
283 (None, _) => self.prejoin = None,
284 }
285 }
286
232 287 pub fn new(
233 288 state: Entity<AppState>,
234 289 open_target: Option<OpenTarget>,
@@ -238,10 +293,14 @@ impl AppShell {
238 293 ) -> Self {
239 294 let call_media = cx.new(|_| CallMedia);
240 295 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
296 let call_media_observation = cx.observe(&call_media, |this, _, cx| {
297 if this.state.read(cx).viewing_call() {
298 cx.notify();
299 }
300 });
241 301 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
242 302 let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));
243 303 let quick_pane = cx.new(|cx| QuickViewPane::new(state.clone(), activity.clone(), cx));
244 let manage_team_page = cx.new(|cx| ManageTeamPage::new(state.clone(), window, cx));
245 304 let calls_page = cx.new(|cx| CallsPage::new(state.clone(), window, cx));
246 305 let agents_panel = crate::agents::runs_handle(cx)
247 306 .map(|runs| cx.new(|cx| crate::agents::AgentsPanel::new(runs, cx)));
@@ -284,7 +343,11 @@ impl AppShell {
284 343 } = event;
285 344 this.state
286 345 .update(cx, |state, cx| state.close_quick_view(cx));
287 this.open_message(conversation_id, message_id.as_deref().unwrap_or_default(), cx);
346 this.open_message(
347 conversation_id,
348 message_id.as_deref().unwrap_or_default(),
349 cx,
350 );
288 351 }),
289 352 ];
290 353 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
@@ -302,9 +365,12 @@ impl AppShell {
302 365 },
303 366 )
304 367 });
305 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, agents_panel, cx));
306 let sidebar_subscription = cx.subscribe_in(&sidebar, window, |this, _, event: &SidebarEvent, window, cx| {
307 match event {
368 let sidebar =
369 cx.new(|cx| SidebarView::new(state.clone(), activity_panel, agents_panel, cx));
370 let sidebar_subscription = cx.subscribe_in(
371 &sidebar,
372 window,
373 |this, _, event: &SidebarEvent, window, cx| match event {
308 374 SidebarEvent::RestoreFocus => this.restore_focus(window, cx),
309 375 SidebarEvent::TabChanged => {
310 376 if this.sidebar.read(cx).tab() == SidebarTab::Calendar {
@@ -312,14 +378,16 @@ impl AppShell {
312 378 }
313 379 cx.notify();
314 380 }
315 SidebarEvent::NewChannelPost => this
316 .conversation
317 .update(cx, |conversation, cx| conversation.start_channel_post(window, cx)),
318 }
319 });
381 SidebarEvent::NewChannelPost => this.conversation.update(cx, |conversation, cx| {
382 conversation.start_channel_post(window, cx)
383 }),
384 },
385 );
320 386 let calendar = cx.new(|cx| CalendarView::new(state.clone(), cx));
321 387 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
322 388 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
389 let timeline = conversation.read(cx).timeline_bounds();
390 let call_mini = cx.new(|cx| CallMiniView::new(state.clone(), timeline, cx));
323 391 let subscription =
324 392 cx.subscribe_in(&state, window, |this, _, event: &AppEvent, window, cx| {
325 393 if matches!(event, AppEvent::Sidebar | AppEvent::Status) {
@@ -381,10 +449,11 @@ impl AppShell {
381 449 sidebar,
382 450 calendar,
383 451 quick_pane,
384 manage_team_page,
385 452 calls_page,
386 453 shown_quick_view: None,
387 454 conversation,
455 call_chat: None,
456 prejoin: None,
388 457 switcher: None,
389 458 notifications,
390 459 _call_windows: call_windows,
@@ -396,12 +465,15 @@ impl AppShell {
396 465 settings_dialog: None,
397 466 profile_card: None,
398 467 focus_handle,
468 call_window_fullscreen: false,
469 window_was_fullscreen: false,
399 470 open_target,
400 471 update: UpdateStatus::UpToDate,
401 splash: Splash::default(),
402 472 toasts: NoticeToasts::default(),
403 473 user_input,
404 474 _subscription: subscription,
475 call_mini,
476 _call_media_observation: call_media_observation,
405 477 _panel_subscriptions: panel_subscriptions,
406 478 _sidebar_subscription: sidebar_subscription,
407 479 _agents_subscription: agents_subscription,
@@ -802,6 +874,19 @@ impl AppShell {
802 874 });
803 875 }
804 876
877 fn sync_window_fullscreen(&mut self, wanted: bool, window: &mut Window) {
878 if wanted == self.call_window_fullscreen {
879 return;
880 }
881 self.call_window_fullscreen = wanted;
882 if wanted {
883 self.window_was_fullscreen = window.is_fullscreen();
884 }
885 if wanted != window.is_fullscreen() && (wanted || !self.window_was_fullscreen) {
886 window.toggle_fullscreen();
887 }
888 }
889
805 890 fn close_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
806 891 if self.image_viewer.take().is_some() {
807 892 window.focus(&self.focus_handle, cx);
@@ -856,53 +941,14 @@ impl AppShell {
856 941 }
857 942
858 943 impl AppShell {
859 fn render_splash(&mut self, cx: &mut Context<Self>) -> Option<AnyElement> {
860 let phase = if self.splash.is_up() {
861 let opening = self.conversation.read(cx).opening_title();
862 let state = self.state.read(cx);
863 let phase = splash::phase(&StartupFacts {
864 elapsed: self.splash.elapsed(),
865 connection: &state.connection,
866 has_chats: !state.sidebar.chats.is_empty() || !state.sidebar.teams.is_empty(),
867 synced: state.last_sync.is_some(),
868 demo: state.mode.demo,
869 opening,
870 });
871 if phase != Phase::Ready && cx.reduce_motion() && !self.splash.recheck_scheduled {
872 self.splash.recheck_scheduled = true;
873 cx.spawn(async move |this, cx| {
874 cx.background_executor().timer(splash::STILL_RECHECK).await;
875 this.update(cx, |this, cx| {
876 this.splash.recheck_scheduled = false;
877 cx.notify();
878 })
879 .ok();
880 })
881 .detach();
882 }
883 if phase == Phase::Ready {
884 self.splash.hide();
885 cx.spawn(async move |this, cx| {
886 cx.background_executor().timer(splash::CONTENT_RISE).await;
887 this.update(cx, |_, cx| cx.notify()).ok();
888 })
889 .detach();
890 }
891 phase
892 } else {
893 Phase::Ready
894 };
895 self.splash.render(&phase, cx)
896 }
897
898 944 fn islands(
899 945 &self,
946 call_view: Option<AnyElement>,
900 947 show_sidebar: bool,
901 948 calendar_open: bool,
902 949 quick_view_open: bool,
903 950 calls_open: bool,
904 manage_team_open: bool,
905 ) -> Div {
951 ) -> impl IntoElement {
906 952 h_flex()
907 953 .debug_selector(|| "shell/islands".into())
908 954 .flex_1()
@@ -911,44 +957,40 @@ impl AppShell {
911 957 .when(show_sidebar, |islands| islands.gap(px(ISLAND_GAP)))
912 958 .pr(px(ISLAND_GAP))
913 959 .pb(px(ISLAND_GAP))
914 .child(
915 h_flex()
916 .h_full()
917 .flex_none()
918 .child(self.rail.clone())
919 .when(show_sidebar, |group| {
920 group.child(
921 self.sidebar.clone().cached(
922 StyleRefinement::default()
923 .w(px(SIDEBAR_WIDTH))
924 .h_full()
925 .flex_none(),
926 ),
927 )
928 }),
929 )
930 .child(match () {
931 _ if calls_open => self
932 .calls_page
933 .clone()
960 .child(h_flex().h_full().flex_none().child(self.rail.clone()).when(
961 show_sidebar,
962 |group| {
963 group.child(
964 self.sidebar.clone().cached(
965 StyleRefinement::default()
966 .w(px(SIDEBAR_WIDTH))
967 .h_full()
968 .flex_none(),
969 ),
970 )
971 },
972 ))
973 .child(match (call_view, self.prejoin.clone()) {
974 (Some(call_view), _) => call_view,
975 (None, Some(prejoin)) => prejoin
934 976 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
935 977 .into_any_element(),
936 _ if manage_team_open => self
937 .manage_team_page
978 (None, None) if calls_open => self
979 .calls_page
938 980 .clone()
939 981 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
940 982 .into_any_element(),
941 _ if quick_view_open => self
983 (None, None) if quick_view_open => self
942 984 .quick_pane
943 985 .clone()
944 986 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
945 987 .into_any_element(),
946 _ if calendar_open => self
988 (None, None) if calendar_open => self
947 989 .calendar
948 990 .clone()
949 991 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
950 992 .into_any_element(),
951 _ => self
993 (None, None) => self
952 994 .conversation
953 995 .clone()
954 996 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
@@ -959,6 +1001,12 @@ impl AppShell {
959 1001
960 1002 impl Render for AppShell {
961 1003 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1004 let viewed_call = self
1005 .state
1006 .read(cx)
1007 .call
1008 .as_ref()
1009 .filter(|call| call.viewing);
962 1010 let open_dialogs = [
963 1011 self.state.read(cx).task_dialog.is_some(),
964 1012 self.forward_dialog.is_some(),
@@ -966,6 +1014,9 @@ impl Render for AppShell {
966 1014 self.shortcuts_dialog.is_some(),
967 1015 self.agent_dialog.is_some(),
968 1016 self.settings_dialog.is_some(),
1017 viewed_call.is_some() && self.state.read(cx).transfer_picker.is_some(),
1018 viewed_call.is_some_and(|call| call.options_dialog.is_some()),
1019 viewed_call.is_some_and(|call| call.model.consent_required),
969 1020 ]
970 1021 .into_iter()
971 1022 .filter(|open| *open)
@@ -994,29 +1045,68 @@ impl Render for AppShell {
994 1045 });
995 1046 });
996 1047 }
1048 let chat_thread = self.state.read(cx).call_chat_thread();
1049 self.sync_call_chat(chat_thread, window, cx);
1050 self.sync_prejoin(window, cx);
997 1051 let notice = self.state.read(cx).notice.clone();
998 1052 self.toasts.sync(&self.state, notice.as_ref(), window, cx);
999 1053 let update_failure = match &self.update {
1000 1054 UpdateStatus::Failed(message) => Some(message.clone()),
1001 1055 _ => None,
1002 1056 };
1003 self.toasts.update_failed(update_failure.as_deref(), window, cx);
1057 self.toasts
1058 .update_failed(update_failure.as_deref(), window, cx);
1059 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone().into());
1004 1060 let calendar_tab = self.sidebar.read(cx).tab() == SidebarTab::Calendar;
1005 1061 let chats_tab = self.sidebar.read(cx).tab() == SidebarTab::Chats;
1006 1062 let calls_tab = self.sidebar.read(cx).tab() == SidebarTab::Calls;
1007 let splash = self.render_splash(cx);
1008 1063 let state = self.state.read(cx);
1009 let calendar_open = calendar_tab;
1064 let call_fullscreen = state.call_fullscreen();
1065 let window_width = f32::from(window.viewport_size().width);
1066 let panel_open = state
1067 .call
1068 .as_ref()
1069 .is_some_and(|call| call.chat_open || call.people_open || call.transcript_open);
1070 let calendar_open = calendar_tab && !state.viewing_call();
1010 1071 let quick_view_open = chats_tab && state.quick_view.is_some();
1011 let manage_team_open = !calendar_tab && !calls_tab && state.manage_team.is_some();
1012 let calls_open = calls_tab;
1013 let show_sidebar = !calendar_open && !calls_open;
1014 let banner = state.connection_banner_text().filter(|_| !self.splash.is_up()).map(|banner| {
1072 let calls_open = calls_tab && !state.viewing_call();
1073 let show_sidebar = !calendar_open
1074 && !calls_open
1075 && !(state.viewing_call()
1076 && !call_fullscreen
1077 && sidebar_hidden_in_call(window_width, panel_open));
1078 let island_width = window_width
1079 - RAIL_WIDTH
1080 - if show_sidebar {
1081 SIDEBAR_WIDTH + ISLAND_GAP
1082 } else {
1083 0.
1084 }
1085 - ISLAND_GAP;
1086 let call_view = render_call_view(
1087 &self.state,
1088 state,
1089 chat_panel,
1090 call_fullscreen,
1091 island_width,
1092 )
1093 .filter(|_| state.viewing_call())
1094 .or_else(|| render_call_end(&self.state, state));
1095 let (call_view, call_overlay) = match call_view {
1096 Some(view) if call_fullscreen => (None, Some(render_call_overlay(view))),
1097 view => (view, None),
1098 };
1099 self.sync_window_fullscreen(call_fullscreen, window);
1100 let call_mini = state
1101 .call
1102 .as_ref()
1103 .is_some_and(|call| !call.viewing)
1104 .then(|| self.call_mini.clone());
1105 let stage_overlay = render_stage_overlay(&self.state, state);
1106 let banner = state.connection_banner_text().map(|banner| {
1015 1107 render_connection_banner(
1016 1108 banner,
1017 cx.listener(|this, _, _, cx| {
1018 this.state.update(cx, |state, _| state.retry_live())
1019 }),
1109 cx.listener(|this, _, _, cx| this.state.update(cx, |state, _| state.retry_live())),
1020 1110 )
1021 1111 });
1022 1112 let title_bar = render_title_bar(
@@ -1079,8 +1169,9 @@ impl Render for AppShell {
1079 1169 }))
1080 1170 .on_action(cx.listener(|this, _: &OpenSaved, window, cx| {
1081 1171 this.close_image_viewer(window, cx);
1082 this.sidebar
1083 .update(cx, |sidebar, cx| sidebar.open_quick_view(QuickView::Saved, cx));
1172 this.sidebar.update(cx, |sidebar, cx| {
1173 sidebar.open_quick_view(QuickView::Saved, cx)
1174 });
1084 1175 }))
1085 1176 .on_action(cx.listener(|this, _: &OpenCalendar, window, cx| {
1086 1177 this.close_image_viewer(window, cx);
@@ -1116,20 +1207,24 @@ impl Render for AppShell {
1116 1207 .update(cx, |sidebar, cx| sidebar.toggle_filter_box(window, cx));
1117 1208 }))
1118 1209 .on_action(cx.listener(|this, _: &FilterUnreadChats, _, cx| {
1119 this.sidebar
1120 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Unread, cx));
1210 this.sidebar.update(cx, |sidebar, cx| {
1211 sidebar.toggle_pill(ChatFilterPill::Unread, cx)
1212 });
1121 1213 }))
1122 1214 .on_action(cx.listener(|this, _: &FilterNonMeetingChats, _, cx| {
1123 this.sidebar
1124 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Chats, cx));
1215 this.sidebar.update(cx, |sidebar, cx| {
1216 sidebar.toggle_pill(ChatFilterPill::Chats, cx)
1217 });
1125 1218 }))
1126 1219 .on_action(cx.listener(|this, _: &FilterMeetingChats, _, cx| {
1127 this.sidebar
1128 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Meetings, cx));
1220 this.sidebar.update(cx, |sidebar, cx| {
1221 sidebar.toggle_pill(ChatFilterPill::Meetings, cx)
1222 });
1129 1223 }))
1130 1224 .on_action(cx.listener(|this, _: &FilterMutedChats, _, cx| {
1131 this.sidebar
1132 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Muted, cx));
1225 this.sidebar.update(cx, |sidebar, cx| {
1226 sidebar.toggle_pill(ChatFilterPill::Muted, cx)
1227 });
1133 1228 }))
1134 1229 .on_action(cx.listener(|this, _: &ClearChatFilters, window, cx| {
1135 1230 this.sidebar
@@ -1189,19 +1284,39 @@ impl Render for AppShell {
1189 1284 .on_action(cx.listener(|this, _: &StartVideoCall, _, cx| {
1190 1285 this.start_call_in_open_chat(true, cx);
1191 1286 }))
1192 .on_action(cx.listener(|this, _: &ZoomIn, _, cx| change_zoom(&this.state, WindowZoom::In, cx)))
1193 .on_action(cx.listener(|this, _: &ZoomOut, _, cx| change_zoom(&this.state, WindowZoom::Out, cx)))
1194 .on_action(cx.listener(|this, _: &ZoomReset, _, cx| change_zoom(&this.state, WindowZoom::Reset, cx)))
1287 .on_action(cx.listener(|this, _: &ToggleCallFullscreen, _, cx| {
1288 if this.image_viewer.is_some() || !this.state.read(cx).viewing_call() {
1289 cx.propagate();
1290 return;
1291 }
1292 this.state
1293 .update(cx, |state, cx| state.toggle_call_fullscreen(cx));
1294 }))
1295 .on_action(
1296 cx.listener(|this, _: &ZoomIn, _, cx| change_zoom(&this.state, WindowZoom::In, cx)),
1297 )
1298 .on_action(
1299 cx.listener(|this, _: &ZoomOut, _, cx| {
1300 change_zoom(&this.state, WindowZoom::Out, cx)
1301 }),
1302 )
1303 .on_action(cx.listener(|this, _: &ZoomReset, _, cx| {
1304 change_zoom(&this.state, WindowZoom::Reset, cx)
1305 }))
1195 1306 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1196 1307 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1197 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
1308 .on_action(zoom_listener::<ZoomShareReset>(
1309 &self.state,
1310 ZoomStep::Reset,
1311 ))
1198 1312 .on_action(cx.listener(|this, _: &JumpToLastReadOrNewest, _, cx| {
1199 if this.image_viewer.is_some() {
1313 if this.image_viewer.is_some() || this.state.read(cx).viewing_call() {
1200 1314 cx.propagate();
1201 1315 return;
1202 1316 }
1203 this.conversation
1204 .update(cx, |conversation, cx| conversation.jump_to_last_read_or_newest(cx));
1317 this.conversation.update(cx, |conversation, cx| {
1318 conversation.jump_to_last_read_or_newest(cx)
1319 });
1205 1320 }))
1206 1321 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
1207 1322 this.close_image_viewer(window, cx);
@@ -1223,9 +1338,17 @@ impl Render for AppShell {
1223 1338 .size_full()
1224 1339 .child(title_bar)
1225 1340 .children(banner)
1226 .child(rising_in(self.islands(show_sidebar, calendar_open, quick_view_open, calls_open, manage_team_open), &self.splash, cx)),
1341 .child(self.islands(
1342 call_view,
1343 show_sidebar,
1344 calendar_open,
1345 quick_view_open,
1346 calls_open,
1347 )),
1227 1348 )
1228 .children(splash)
1349 .children(call_mini)
1350 .children(call_overlay)
1351 .children(stage_overlay)
1229 1352 .children(self.image_viewer.clone())
1230 1353 .children(self.switcher.clone())
1231 1354 .children(render_task_dialog(self.state.read(cx), cx))
@@ -1239,27 +1362,17 @@ impl Render for AppShell {
1239 1362 }
1240 1363 }
1241 1364
1242 fn rising_in(islands: Div, splash: &Splash, cx: &App) -> AnyElement {
1243 if splash.content_rising().is_none() || cx.reduce_motion() {
1244 return islands.into_any_element();
1245 }
1246 islands
1247 .relative()
1248 .with_animation("startup-content-rise", Animation::new(splash::CONTENT_RISE).with_easing(ease_out_quint()), |islands, delta| {
1249 islands.top(px(splash::CONTENT_RISE_OFFSET * (1. - delta))).opacity(delta)
1250 })
1251 .into_any_element()
1252 }
1253
1254 1365 #[cfg(test)]
1255 1366 mod opening_link_tests {
1256 1367 use super::opening_link_text;
1257 1368
1258 1369 #[test]
1259 1370 fn the_notice_names_the_host() {
1260 assert_eq!(opening_link_text("https://example.com/a?b#c"), "Opening example.com...");
1371 assert_eq!(
1372 opening_link_text("https://example.com/a?b#c"),
1373 "Opening example.com..."
1374 );
1261 1375 assert_eq!(opening_link_text("mailto:"), "Opening mailto:...");
1262 1376 assert_eq!(opening_link_text(""), "Opening link...");
1263 1377 }
1264 1378 }
1265
@@ -5,46 +5,47 @@ use std::sync::Arc;
5use gpui_kit::component::{elevation, h_flex, v_flex};
5use gpui_kit::component::{elevation, h_flex, v_flex};
6use gpui_kit::*;
6use gpui_kit::*;
7
7
8use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
9use super::actions::{NewChat, OpenSwitcher, ReplyToHovered, ToggleCallMute};
8use super::actions::{NewChat, OpenSwitcher, ReplyToHovered, ToggleCallMute};
9use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
10use super::calendar_view::CalendarView;
10use super::calendar_view::CalendarView;
11use super::call_end_view::render_call_end;
12use super::call_mini::CallMiniView;
13use super::call_pop_out::zoom_listener;
14use super::call_stage::{render_call_overlay, render_stage_overlay};
15use super::call_view::{CHAT_PANEL_WIDTH, OVERLAY_BELOW as CALL_COLUMN_MIN, render_call_view};
16use super::calls_page::CallsPage;
17use super::chat_pop_out;
18use super::connection_banner::render_connection_banner;
11use super::conversation::ConversationView;
19use super::conversation::ConversationView;
12use super::dialog_overlay::render_task_dialog;
20use super::dialog_overlay::render_task_dialog;
13use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
21use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
14use super::image_viewer::{ImageViewer, ImageViewerEvent};
22use super::image_viewer::{ImageViewer, ImageViewerEvent};
23use super::notice_toast::NoticeToasts;
24use super::prejoin_view::PrejoinView;
15use super::profile_card::{ProfileCard, ProfileCardEvent};
25use super::profile_card::{ProfileCard, ProfileCardEvent};
16use gpui_kit::prelude::FluentBuilder as _;
17use super::rail::RailView;
18use crate::chat_filter::ChatFilterPill;
19use super::calls_page::CallsPage;
20use super::quick_view_pane::{QuickViewEvent, QuickViewPane};
26use super::quick_view_pane::{QuickViewEvent, QuickViewPane};
27use super::rail::RailView;
21use super::shortcuts::{
28use super::shortcuts::{
22 ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats,
29 ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats, FilterNonMeetingChats,
23 FilterNonMeetingChats, FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
30 FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest,
24 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatFilter, OpenChatsTab, PopOutSelectedChat, OpenLobbyList, OpenSaved, OpenCalendar, PreviousConversation, PushToTalk,
31 NextConversation, OpenActivity, OpenAgents, OpenCalendar, OpenCallsTab, OpenChannelsTab,
25 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera,
32 OpenChatFilter, OpenChatsTab, OpenLobbyList, OpenSaved, OpenSettings, PopOutSelectedChat,
26 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
33 PreviousConversation, PushToTalk, Scope, ShowShortcuts, StartAudioCall, StartVideoCall,
27 ZoomShareReset,
34 ToggleCallCamera, ToggleCallFullscreen, ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut,
35 ZoomReset, ZoomShareIn, ZoomShareOut, ZoomShareReset,
28};
36};
29use super::window_zoom::{WindowZoom, change_zoom};
30use super::call_pop_out::zoom_listener;
31use super::chat_pop_out;
32use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
37use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
33use super::sidebar::{SidebarEvent, SidebarTab, SidebarView};
38use super::sidebar::{SidebarEvent, SidebarTab, SidebarView};
34use app_ui_kit::render::hooks::RenderHooks;
35use app_ui_kit::layout::{ISLAND_GAP, SIDEBAR_WIDTH};
36use super::connection_banner::render_connection_banner;
37use super::manage_team_page::ManageTeamPage;
38use super::splash::{self, Phase, Splash, StartupFacts};
39use super::notice_toast::NoticeToasts;
40use super::status_menu::{own_status_button, settings_more_button};
39use super::status_menu::{own_status_button, settings_more_button};
41use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};
40use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent};
42use super::switcher::{Switcher, SwitcherEvent, candidates_from};
41use super::switcher::{Switcher, SwitcherEvent, candidates_from};
43use super::title_bar::{mode_label, render_title_bar, update_button};
42use super::title_bar::{mode_label, render_title_bar, update_button};
43use super::window_zoom::{WindowZoom, change_zoom};
44use crate::activity::ActivityCenter;
44use crate::activity::ActivityCenter;
45use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};
45use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};
46use crate::app_state::{AppEvent, AppState, QuickView, Selection, selection_for};
46use crate::app_state::{AppEvent, AppState, QuickView, Selection, selection_for};
47use crate::call::{CallMedia, CallWindows, ZoomStep};
47use crate::call::{CallMedia, CallWindows, ZoomStep};
48use crate::chat_filter::ChatFilterPill;
48use crate::notice::NoticeAction;
49use crate::notice::NoticeAction;
49use crate::notify::NotificationCenter;
50use crate::notify::NotificationCenter;
50use crate::settings::{SettingsDialog, SettingsDialogEvent};
51use crate::settings::{SettingsDialog, SettingsDialogEvent};
@@ -53,6 +54,9 @@ use crate::sidebar_model::Step;
53use crate::theme;
54use crate::theme;
54use crate::updater::{self, IdleInputs, UpdateStatus};
55use crate::updater::{self, IdleInputs, UpdateStatus};
55use crate::user_activity::{self, UserInput};
56use crate::user_activity::{self, UserInput};
57use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
58use app_ui_kit::render::hooks::RenderHooks;
59use gpui_kit::prelude::FluentBuilder as _;
56
60
57pub fn bind_keys(cx: &mut App) {
61pub fn bind_keys(cx: &mut App) {
58 super::composer::bind_keys(cx);
62 super::composer::bind_keys(cx);
@@ -81,6 +85,19 @@ pub struct Startup {
81 pub launched_by_autostart: bool,
85 pub launched_by_autostart: bool,
82}
86}
83
87
88pub const SIDEBAR_HIDDEN_BELOW: f32 = 960.;
89
90pub fn sidebar_hidden_in_call(window_width: f32, panel_open: bool) -> bool {
91 let panel_width = if panel_open {
92 CHAT_PANEL_WIDTH + ISLAND_GAP
93 } else {
94 0.
95 };
96 window_width < SIDEBAR_HIDDEN_BELOW
97 || window_width - RAIL_WIDTH - SIDEBAR_WIDTH - 2. * ISLAND_GAP - panel_width
98 < CALL_COLUMN_MIN
99}
100
84pub struct UserInputHandle(pub Arc<UserInput>);
101pub struct UserInputHandle(pub Arc<UserInput>);
85
102
86impl Global for UserInputHandle {}
103impl Global for UserInputHandle {}
@@ -99,7 +116,10 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:
99fn open_link(url: &str, cx: &mut App) {
116fn open_link(url: &str, cx: &mut App) {
100 if let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() {
117 if let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() {
101 let text = opening_link_text(url);
118 let text = opening_link_text(url);
102 handle.0.clone().update(cx, |state, cx| state.raise_notice(text, None, cx));
119 handle
120 .0
121 .clone()
122 .update(cx, |state, cx| state.raise_notice(text, None, cx));
103 }
123 }
104 cx.open_url(url);
124 cx.open_url(url);
105}
125}
@@ -168,10 +188,11 @@ pub struct AppShell {
168 sidebar: Entity<SidebarView>,
188 sidebar: Entity<SidebarView>,
169 calendar: Entity<CalendarView>,
189 calendar: Entity<CalendarView>,
170 quick_pane: Entity<QuickViewPane>,
190 quick_pane: Entity<QuickViewPane>,
171 manage_team_page: Entity<ManageTeamPage>,
172 calls_page: Entity<CallsPage>,
191 calls_page: Entity<CallsPage>,
173 shown_quick_view: Option<QuickView>,
192 shown_quick_view: Option<QuickView>,
174 conversation: Entity<ConversationView>,
193 conversation: Entity<ConversationView>,
194 call_chat: Option<(String, Entity<ConversationView>)>,
195 prejoin: Option<Entity<PrejoinView>>,
175 switcher: Option<Entity<Switcher>>,
196 switcher: Option<Entity<Switcher>>,
176 notifications: Entity<NotificationCenter>,
197 notifications: Entity<NotificationCenter>,
177 _call_windows: Entity<CallWindows>,
198 _call_windows: Entity<CallWindows>,
@@ -183,12 +204,15 @@ pub struct AppShell {
183 settings_dialog: Option<Entity<SettingsDialog>>,
204 settings_dialog: Option<Entity<SettingsDialog>>,
184 profile_card: Option<Entity<ProfileCard>>,
205 profile_card: Option<Entity<ProfileCard>>,
185 focus_handle: FocusHandle,
206 focus_handle: FocusHandle,
207 call_window_fullscreen: bool,
208 window_was_fullscreen: bool,
186 open_target: Option<OpenTarget>,
209 open_target: Option<OpenTarget>,
187 update: UpdateStatus,
210 update: UpdateStatus,
188 splash: Splash,
189 toasts: NoticeToasts,
211 toasts: NoticeToasts,
190 user_input: Arc<UserInput>,
212 user_input: Arc<UserInput>,
191 _subscription: Subscription,
213 _subscription: Subscription,
214 call_mini: Entity<CallMiniView>,
215 _call_media_observation: Subscription,
192 _panel_subscriptions: [Subscription; 2],
216 _panel_subscriptions: [Subscription; 2],
193 _sidebar_subscription: Subscription,
217 _sidebar_subscription: Subscription,
194 _agents_subscription: Option<Subscription>,
218 _agents_subscription: Option<Subscription>,
@@ -205,6 +229,24 @@ impl AppShell {
205 cx.notify();
229 cx.notify();
206 }
230 }
207
231
232 fn sync_call_chat(
233 &mut self,
234 thread: Option<String>,
235 window: &mut Window,
236 cx: &mut Context<Self>,
237 ) {
238 match (thread, &self.call_chat) {
239 (Some(wanted), Some((open, _))) if &wanted == open => {}
240 (Some(wanted), _) => {
241 let app = self.state.clone();
242 let selection = Selection::Chat(wanted.clone());
243 let view = cx.new(|cx| ConversationView::pinned_to(app, selection, window, cx));
244 self.call_chat = Some((wanted, view));
245 }
246 (None, _) => self.call_chat = None,
247 }
248 }
249
208 fn focus_opened_quick_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
250 fn focus_opened_quick_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
209 let quick_view = self.state.read(cx).quick_view;
251 let quick_view = self.state.read(cx).quick_view;
210 if std::mem::replace(&mut self.shown_quick_view, quick_view) != quick_view
252 if std::mem::replace(&mut self.shown_quick_view, quick_view) != quick_view
@@ -229,6 +271,19 @@ impl AppShell {
229 });
271 });
230 }
272 }
231
273
274 fn sync_prejoin(&mut self, window: &mut Window, cx: &mut Context<Self>) {
275 let wanted = self.state.read(cx).prejoin.clone();
276 let open = self.prejoin.as_ref().map(|view| view.read(cx).pending_id());
277 match (wanted, open) {
278 (Some(pending), Some(id)) if pending.id == id => {}
279 (Some(pending), _) => {
280 let app = self.state.clone();
281 self.prejoin = Some(cx.new(|cx| PrejoinView::new(app, &pending, window, cx)));
282 }
283 (None, _) => self.prejoin = None,
284 }
285 }
286
232 pub fn new(
287 pub fn new(
233 state: Entity<AppState>,
288 state: Entity<AppState>,
234 open_target: Option<OpenTarget>,
289 open_target: Option<OpenTarget>,
@@ -238,10 +293,14 @@ impl AppShell {
238 ) -> Self {
293 ) -> Self {
239 let call_media = cx.new(|_| CallMedia);
294 let call_media = cx.new(|_| CallMedia);
240 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
295 state.update(cx, |state, _| state.call_media = Some(call_media.clone()));
296 let call_media_observation = cx.observe(&call_media, |this, _, cx| {
297 if this.state.read(cx).viewing_call() {
298 cx.notify();
299 }
300 });
241 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
301 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
242 let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));
302 let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));
243 let quick_pane = cx.new(|cx| QuickViewPane::new(state.clone(), activity.clone(), cx));
303 let quick_pane = cx.new(|cx| QuickViewPane::new(state.clone(), activity.clone(), cx));
244 let manage_team_page = cx.new(|cx| ManageTeamPage::new(state.clone(), window, cx));
245 let calls_page = cx.new(|cx| CallsPage::new(state.clone(), window, cx));
304 let calls_page = cx.new(|cx| CallsPage::new(state.clone(), window, cx));
246 let agents_panel = crate::agents::runs_handle(cx)
305 let agents_panel = crate::agents::runs_handle(cx)
247 .map(|runs| cx.new(|cx| crate::agents::AgentsPanel::new(runs, cx)));
306 .map(|runs| cx.new(|cx| crate::agents::AgentsPanel::new(runs, cx)));
@@ -284,7 +343,11 @@ impl AppShell {
284 } = event;
343 } = event;
285 this.state
344 this.state
286 .update(cx, |state, cx| state.close_quick_view(cx));
345 .update(cx, |state, cx| state.close_quick_view(cx));
287 this.open_message(conversation_id, message_id.as_deref().unwrap_or_default(), cx);
346 this.open_message(
347 conversation_id,
348 message_id.as_deref().unwrap_or_default(),
349 cx,
350 );
288 }),
351 }),
289 ];
352 ];
290 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
353 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
@@ -302,9 +365,12 @@ impl AppShell {
302 },
365 },
303 )
366 )
304 });
367 });
305 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, agents_panel, cx));
368 let sidebar =
306 let sidebar_subscription = cx.subscribe_in(&sidebar, window, |this, _, event: &SidebarEvent, window, cx| {
369 cx.new(|cx| SidebarView::new(state.clone(), activity_panel, agents_panel, cx));
307 match event {
370 let sidebar_subscription = cx.subscribe_in(
371 &sidebar,
372 window,
373 |this, _, event: &SidebarEvent, window, cx| match event {
308 SidebarEvent::RestoreFocus => this.restore_focus(window, cx),
374 SidebarEvent::RestoreFocus => this.restore_focus(window, cx),
309 SidebarEvent::TabChanged => {
375 SidebarEvent::TabChanged => {
310 if this.sidebar.read(cx).tab() == SidebarTab::Calendar {
376 if this.sidebar.read(cx).tab() == SidebarTab::Calendar {
@@ -312,14 +378,16 @@ impl AppShell {
312 }
378 }
313 cx.notify();
379 cx.notify();
314 }
380 }
315 SidebarEvent::NewChannelPost => this
381 SidebarEvent::NewChannelPost => this.conversation.update(cx, |conversation, cx| {
316 .conversation
382 conversation.start_channel_post(window, cx)
317 .update(cx, |conversation, cx| conversation.start_channel_post(window, cx)),
383 }),
318 }
384 },
319 });
385 );
320 let calendar = cx.new(|cx| CalendarView::new(state.clone(), cx));
386 let calendar = cx.new(|cx| CalendarView::new(state.clone(), cx));
321 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
387 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
322 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
388 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
389 let timeline = conversation.read(cx).timeline_bounds();
390 let call_mini = cx.new(|cx| CallMiniView::new(state.clone(), timeline, cx));
323 let subscription =
391 let subscription =
324 cx.subscribe_in(&state, window, |this, _, event: &AppEvent, window, cx| {
392 cx.subscribe_in(&state, window, |this, _, event: &AppEvent, window, cx| {
325 if matches!(event, AppEvent::Sidebar | AppEvent::Status) {
393 if matches!(event, AppEvent::Sidebar | AppEvent::Status) {
@@ -381,10 +449,11 @@ impl AppShell {
381 sidebar,
449 sidebar,
382 calendar,
450 calendar,
383 quick_pane,
451 quick_pane,
384 manage_team_page,
385 calls_page,
452 calls_page,
386 shown_quick_view: None,
453 shown_quick_view: None,
387 conversation,
454 conversation,
455 call_chat: None,
456 prejoin: None,
388 switcher: None,
457 switcher: None,
389 notifications,
458 notifications,
390 _call_windows: call_windows,
459 _call_windows: call_windows,
@@ -396,12 +465,15 @@ impl AppShell {
396 settings_dialog: None,
465 settings_dialog: None,
397 profile_card: None,
466 profile_card: None,
398 focus_handle,
467 focus_handle,
468 call_window_fullscreen: false,
469 window_was_fullscreen: false,
399 open_target,
470 open_target,
400 update: UpdateStatus::UpToDate,
471 update: UpdateStatus::UpToDate,
401 splash: Splash::default(),
402 toasts: NoticeToasts::default(),
472 toasts: NoticeToasts::default(),
403 user_input,
473 user_input,
404 _subscription: subscription,
474 _subscription: subscription,
475 call_mini,
476 _call_media_observation: call_media_observation,
405 _panel_subscriptions: panel_subscriptions,
477 _panel_subscriptions: panel_subscriptions,
406 _sidebar_subscription: sidebar_subscription,
478 _sidebar_subscription: sidebar_subscription,
407 _agents_subscription: agents_subscription,
479 _agents_subscription: agents_subscription,
@@ -802,6 +874,19 @@ impl AppShell {
802 });
874 });
803 }
875 }
804
876
877 fn sync_window_fullscreen(&mut self, wanted: bool, window: &mut Window) {
878 if wanted == self.call_window_fullscreen {
879 return;
880 }
881 self.call_window_fullscreen = wanted;
882 if wanted {
883 self.window_was_fullscreen = window.is_fullscreen();
884 }
885 if wanted != window.is_fullscreen() && (wanted || !self.window_was_fullscreen) {
886 window.toggle_fullscreen();
887 }
888 }
889
805 fn close_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
890 fn close_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
806 if self.image_viewer.take().is_some() {
891 if self.image_viewer.take().is_some() {
807 window.focus(&self.focus_handle, cx);
892 window.focus(&self.focus_handle, cx);
@@ -856,53 +941,14 @@ impl AppShell {
856}
941}
857
942
858impl AppShell {
943impl AppShell {
859 fn render_splash(&mut self, cx: &mut Context<Self>) -> Option<AnyElement> {
860 let phase = if self.splash.is_up() {
861 let opening = self.conversation.read(cx).opening_title();
862 let state = self.state.read(cx);
863 let phase = splash::phase(&StartupFacts {
864 elapsed: self.splash.elapsed(),
865 connection: &state.connection,
866 has_chats: !state.sidebar.chats.is_empty() || !state.sidebar.teams.is_empty(),
867 synced: state.last_sync.is_some(),
868 demo: state.mode.demo,
869 opening,
870 });
871 if phase != Phase::Ready && cx.reduce_motion() && !self.splash.recheck_scheduled {
872 self.splash.recheck_scheduled = true;
873 cx.spawn(async move |this, cx| {
874 cx.background_executor().timer(splash::STILL_RECHECK).await;
875 this.update(cx, |this, cx| {
876 this.splash.recheck_scheduled = false;
877 cx.notify();
878 })
879 .ok();
880 })
881 .detach();
882 }
883 if phase == Phase::Ready {
884 self.splash.hide();
885 cx.spawn(async move |this, cx| {
886 cx.background_executor().timer(splash::CONTENT_RISE).await;
887 this.update(cx, |_, cx| cx.notify()).ok();
888 })
889 .detach();
890 }
891 phase
892 } else {
893 Phase::Ready
894 };
895 self.splash.render(&phase, cx)
896 }
897
898 fn islands(
944 fn islands(
899 &self,
945 &self,
946 call_view: Option<AnyElement>,
900 show_sidebar: bool,
947 show_sidebar: bool,
901 calendar_open: bool,
948 calendar_open: bool,
902 quick_view_open: bool,
949 quick_view_open: bool,
903 calls_open: bool,
950 calls_open: bool,
904 manage_team_open: bool,
951 ) -> impl IntoElement {
905 ) -> Div {
906 h_flex()
952 h_flex()
907 .debug_selector(|| "shell/islands".into())
953 .debug_selector(|| "shell/islands".into())
908 .flex_1()
954 .flex_1()
@@ -911,44 +957,40 @@ impl AppShell {
911 .when(show_sidebar, |islands| islands.gap(px(ISLAND_GAP)))
957 .when(show_sidebar, |islands| islands.gap(px(ISLAND_GAP)))
912 .pr(px(ISLAND_GAP))
958 .pr(px(ISLAND_GAP))
913 .pb(px(ISLAND_GAP))
959 .pb(px(ISLAND_GAP))
914 .child(
960 .child(h_flex().h_full().flex_none().child(self.rail.clone()).when(
915 h_flex()
961 show_sidebar,
916 .h_full()
962 |group| {
917 .flex_none()
963 group.child(
918 .child(self.rail.clone())
964 self.sidebar.clone().cached(
919 .when(show_sidebar, |group| {
965 StyleRefinement::default()
920 group.child(
966 .w(px(SIDEBAR_WIDTH))
921 self.sidebar.clone().cached(
967 .h_full()
922 StyleRefinement::default()
968 .flex_none(),
923 .w(px(SIDEBAR_WIDTH))
969 ),
924 .h_full()
970 )
925 .flex_none(),
971 },
926 ),
972 ))
927 )
973 .child(match (call_view, self.prejoin.clone()) {
928 }),
974 (Some(call_view), _) => call_view,
929 )
975 (None, Some(prejoin)) => prejoin
930 .child(match () {
931 _ if calls_open => self
932 .calls_page
933 .clone()
934 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
976 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
935 .into_any_element(),
977 .into_any_element(),
936 _ if manage_team_open => self
978 (None, None) if calls_open => self
937 .manage_team_page
979 .calls_page
938 .clone()
980 .clone()
939 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
981 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
940 .into_any_element(),
982 .into_any_element(),
941 _ if quick_view_open => self
983 (None, None) if quick_view_open => self
942 .quick_pane
984 .quick_pane
943 .clone()
985 .clone()
944 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
986 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
945 .into_any_element(),
987 .into_any_element(),
946 _ if calendar_open => self
988 (None, None) if calendar_open => self
947 .calendar
989 .calendar
948 .clone()
990 .clone()
949 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
991 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
950 .into_any_element(),
992 .into_any_element(),
951 _ => self
993 (None, None) => self
952 .conversation
994 .conversation
953 .clone()
995 .clone()
954 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
996 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
@@ -959,6 +1001,12 @@ impl AppShell {
959
1001
960impl Render for AppShell {
1002impl Render for AppShell {
961 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1003 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1004 let viewed_call = self
1005 .state
1006 .read(cx)
1007 .call
1008 .as_ref()
1009 .filter(|call| call.viewing);
962 let open_dialogs = [
1010 let open_dialogs = [
963 self.state.read(cx).task_dialog.is_some(),
1011 self.state.read(cx).task_dialog.is_some(),
964 self.forward_dialog.is_some(),
1012 self.forward_dialog.is_some(),
@@ -966,6 +1014,9 @@ impl Render for AppShell {
966 self.shortcuts_dialog.is_some(),
1014 self.shortcuts_dialog.is_some(),
967 self.agent_dialog.is_some(),
1015 self.agent_dialog.is_some(),
968 self.settings_dialog.is_some(),
1016 self.settings_dialog.is_some(),
1017 viewed_call.is_some() && self.state.read(cx).transfer_picker.is_some(),
1018 viewed_call.is_some_and(|call| call.options_dialog.is_some()),
1019 viewed_call.is_some_and(|call| call.model.consent_required),
969 ]
1020 ]
970 .into_iter()
1021 .into_iter()
971 .filter(|open| *open)
1022 .filter(|open| *open)
@@ -994,29 +1045,68 @@ impl Render for AppShell {
994 });
1045 });
995 });
1046 });
996 }
1047 }
1048 let chat_thread = self.state.read(cx).call_chat_thread();
1049 self.sync_call_chat(chat_thread, window, cx);
1050 self.sync_prejoin(window, cx);
997 let notice = self.state.read(cx).notice.clone();
1051 let notice = self.state.read(cx).notice.clone();
998 self.toasts.sync(&self.state, notice.as_ref(), window, cx);
1052 self.toasts.sync(&self.state, notice.as_ref(), window, cx);
999 let update_failure = match &self.update {
1053 let update_failure = match &self.update {
1000 UpdateStatus::Failed(message) => Some(message.clone()),
1054 UpdateStatus::Failed(message) => Some(message.clone()),
1001 _ => None,
1055 _ => None,
1002 };
1056 };
1003 self.toasts.update_failed(update_failure.as_deref(), window, cx);
1057 self.toasts
1058 .update_failed(update_failure.as_deref(), window, cx);
1059 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone().into());
1004 let calendar_tab = self.sidebar.read(cx).tab() == SidebarTab::Calendar;
1060 let calendar_tab = self.sidebar.read(cx).tab() == SidebarTab::Calendar;
1005 let chats_tab = self.sidebar.read(cx).tab() == SidebarTab::Chats;
1061 let chats_tab = self.sidebar.read(cx).tab() == SidebarTab::Chats;
1006 let calls_tab = self.sidebar.read(cx).tab() == SidebarTab::Calls;
1062 let calls_tab = self.sidebar.read(cx).tab() == SidebarTab::Calls;
1007 let splash = self.render_splash(cx);
1008 let state = self.state.read(cx);
1063 let state = self.state.read(cx);
1009 let calendar_open = calendar_tab;
1064 let call_fullscreen = state.call_fullscreen();
1065 let window_width = f32::from(window.viewport_size().width);
1066 let panel_open = state
1067 .call
1068 .as_ref()
1069 .is_some_and(|call| call.chat_open || call.people_open || call.transcript_open);
1070 let calendar_open = calendar_tab && !state.viewing_call();
1010 let quick_view_open = chats_tab && state.quick_view.is_some();
1071 let quick_view_open = chats_tab && state.quick_view.is_some();
1011 let manage_team_open = !calendar_tab && !calls_tab && state.manage_team.is_some();
1072 let calls_open = calls_tab && !state.viewing_call();
1012 let calls_open = calls_tab;
1073 let show_sidebar = !calendar_open
1013 let show_sidebar = !calendar_open && !calls_open;
1074 && !calls_open
1014 let banner = state.connection_banner_text().filter(|_| !self.splash.is_up()).map(|banner| {
1075 && !(state.viewing_call()
1076 && !call_fullscreen
1077 && sidebar_hidden_in_call(window_width, panel_open));
1078 let island_width = window_width
1079 - RAIL_WIDTH
1080 - if show_sidebar {
1081 SIDEBAR_WIDTH + ISLAND_GAP
1082 } else {
1083 0.
1084 }
1085 - ISLAND_GAP;
1086 let call_view = render_call_view(
1087 &self.state,
1088 state,
1089 chat_panel,
1090 call_fullscreen,
1091 island_width,
1092 )
1093 .filter(|_| state.viewing_call())
1094 .or_else(|| render_call_end(&self.state, state));
1095 let (call_view, call_overlay) = match call_view {
1096 Some(view) if call_fullscreen => (None, Some(render_call_overlay(view))),
1097 view => (view, None),
1098 };
1099 self.sync_window_fullscreen(call_fullscreen, window);
1100 let call_mini = state
1101 .call
1102 .as_ref()
1103 .is_some_and(|call| !call.viewing)
1104 .then(|| self.call_mini.clone());
1105 let stage_overlay = render_stage_overlay(&self.state, state);
1106 let banner = state.connection_banner_text().map(|banner| {
1015 render_connection_banner(
1107 render_connection_banner(
1016 banner,
1108 banner,
1017 cx.listener(|this, _, _, cx| {
1109 cx.listener(|this, _, _, cx| this.state.update(cx, |state, _| state.retry_live())),
1018 this.state.update(cx, |state, _| state.retry_live())
1019 }),
1020 )
1110 )
1021 });
1111 });
1022 let title_bar = render_title_bar(
1112 let title_bar = render_title_bar(
@@ -1079,8 +1169,9 @@ impl Render for AppShell {
1079 }))
1169 }))
1080 .on_action(cx.listener(|this, _: &OpenSaved, window, cx| {
1170 .on_action(cx.listener(|this, _: &OpenSaved, window, cx| {
1081 this.close_image_viewer(window, cx);
1171 this.close_image_viewer(window, cx);
1082 this.sidebar
1172 this.sidebar.update(cx, |sidebar, cx| {
1083 .update(cx, |sidebar, cx| sidebar.open_quick_view(QuickView::Saved, cx));
1173 sidebar.open_quick_view(QuickView::Saved, cx)
1174 });
1084 }))
1175 }))
1085 .on_action(cx.listener(|this, _: &OpenCalendar, window, cx| {
1176 .on_action(cx.listener(|this, _: &OpenCalendar, window, cx| {
1086 this.close_image_viewer(window, cx);
1177 this.close_image_viewer(window, cx);
@@ -1116,20 +1207,24 @@ impl Render for AppShell {
1116 .update(cx, |sidebar, cx| sidebar.toggle_filter_box(window, cx));
1207 .update(cx, |sidebar, cx| sidebar.toggle_filter_box(window, cx));
1117 }))
1208 }))
1118 .on_action(cx.listener(|this, _: &FilterUnreadChats, _, cx| {
1209 .on_action(cx.listener(|this, _: &FilterUnreadChats, _, cx| {
1119 this.sidebar
1210 this.sidebar.update(cx, |sidebar, cx| {
1120 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Unread, cx));
1211 sidebar.toggle_pill(ChatFilterPill::Unread, cx)
1212 });
1121 }))
1213 }))
1122 .on_action(cx.listener(|this, _: &FilterNonMeetingChats, _, cx| {
1214 .on_action(cx.listener(|this, _: &FilterNonMeetingChats, _, cx| {
1123 this.sidebar
1215 this.sidebar.update(cx, |sidebar, cx| {
1124 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Chats, cx));
1216 sidebar.toggle_pill(ChatFilterPill::Chats, cx)
1217 });
1125 }))
1218 }))
1126 .on_action(cx.listener(|this, _: &FilterMeetingChats, _, cx| {
1219 .on_action(cx.listener(|this, _: &FilterMeetingChats, _, cx| {
1127 this.sidebar
1220 this.sidebar.update(cx, |sidebar, cx| {
1128 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Meetings, cx));
1221 sidebar.toggle_pill(ChatFilterPill::Meetings, cx)
1222 });
1129 }))
1223 }))
1130 .on_action(cx.listener(|this, _: &FilterMutedChats, _, cx| {
1224 .on_action(cx.listener(|this, _: &FilterMutedChats, _, cx| {
1131 this.sidebar
1225 this.sidebar.update(cx, |sidebar, cx| {
1132 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Muted, cx));
1226 sidebar.toggle_pill(ChatFilterPill::Muted, cx)
1227 });
1133 }))
1228 }))
1134 .on_action(cx.listener(|this, _: &ClearChatFilters, window, cx| {
1229 .on_action(cx.listener(|this, _: &ClearChatFilters, window, cx| {
1135 this.sidebar
1230 this.sidebar
@@ -1189,19 +1284,39 @@ impl Render for AppShell {
1189 .on_action(cx.listener(|this, _: &StartVideoCall, _, cx| {
1284 .on_action(cx.listener(|this, _: &StartVideoCall, _, cx| {
1190 this.start_call_in_open_chat(true, cx);
1285 this.start_call_in_open_chat(true, cx);
1191 }))
1286 }))
1192 .on_action(cx.listener(|this, _: &ZoomIn, _, cx| change_zoom(&this.state, WindowZoom::In, cx)))
1287 .on_action(cx.listener(|this, _: &ToggleCallFullscreen, _, cx| {
1193 .on_action(cx.listener(|this, _: &ZoomOut, _, cx| change_zoom(&this.state, WindowZoom::Out, cx)))
1288 if this.image_viewer.is_some() || !this.state.read(cx).viewing_call() {
1194 .on_action(cx.listener(|this, _: &ZoomReset, _, cx| change_zoom(&this.state, WindowZoom::Reset, cx)))
1289 cx.propagate();
1290 return;
1291 }
1292 this.state
1293 .update(cx, |state, cx| state.toggle_call_fullscreen(cx));
1294 }))
1295 .on_action(
1296 cx.listener(|this, _: &ZoomIn, _, cx| change_zoom(&this.state, WindowZoom::In, cx)),
1297 )
1298 .on_action(
1299 cx.listener(|this, _: &ZoomOut, _, cx| {
1300 change_zoom(&this.state, WindowZoom::Out, cx)
1301 }),
1302 )
1303 .on_action(cx.listener(|this, _: &ZoomReset, _, cx| {
1304 change_zoom(&this.state, WindowZoom::Reset, cx)
1305 }))
1195 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1306 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
1196 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1307 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
1197 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
1308 .on_action(zoom_listener::<ZoomShareReset>(
1309 &self.state,
1310 ZoomStep::Reset,
1311 ))
1198 .on_action(cx.listener(|this, _: &JumpToLastReadOrNewest, _, cx| {
1312 .on_action(cx.listener(|this, _: &JumpToLastReadOrNewest, _, cx| {
1199 if this.image_viewer.is_some() {
1313 if this.image_viewer.is_some() || this.state.read(cx).viewing_call() {
1200 cx.propagate();
1314 cx.propagate();
1201 return;
1315 return;
1202 }
1316 }
1203 this.conversation
1317 this.conversation.update(cx, |conversation, cx| {
1204 .update(cx, |conversation, cx| conversation.jump_to_last_read_or_newest(cx));
1318 conversation.jump_to_last_read_or_newest(cx)
1319 });
1205 }))
1320 }))
1206 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
1321 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
1207 this.close_image_viewer(window, cx);
1322 this.close_image_viewer(window, cx);
@@ -1223,9 +1338,17 @@ impl Render for AppShell {
1223 .size_full()
1338 .size_full()
1224 .child(title_bar)
1339 .child(title_bar)
1225 .children(banner)
1340 .children(banner)
1226 .child(rising_in(self.islands(show_sidebar, calendar_open, quick_view_open, calls_open, manage_team_open), &self.splash, cx)),
1341 .child(self.islands(
1342 call_view,
1343 show_sidebar,
1344 calendar_open,
1345 quick_view_open,
1346 calls_open,
1347 )),
1227 )
1348 )
1228 .children(splash)
1349 .children(call_mini)
1350 .children(call_overlay)
1351 .children(stage_overlay)
1229 .children(self.image_viewer.clone())
1352 .children(self.image_viewer.clone())
1230 .children(self.switcher.clone())
1353 .children(self.switcher.clone())
1231 .children(render_task_dialog(self.state.read(cx), cx))
1354 .children(render_task_dialog(self.state.read(cx), cx))
@@ -1239,27 +1362,17 @@ impl Render for AppShell {
1239 }
1362 }
1240}
1363}
1241
1364
1242fn rising_in(islands: Div, splash: &Splash, cx: &App) -> AnyElement {
1243 if splash.content_rising().is_none() || cx.reduce_motion() {
1244 return islands.into_any_element();
1245 }
1246 islands
1247 .relative()
1248 .with_animation("startup-content-rise", Animation::new(splash::CONTENT_RISE).with_easing(ease_out_quint()), |islands, delta| {
1249 islands.top(px(splash::CONTENT_RISE_OFFSET * (1. - delta))).opacity(delta)
1250 })
1251 .into_any_element()
1252}
1253
1254#[cfg(test)]
1365#[cfg(test)]
1255mod opening_link_tests {
1366mod opening_link_tests {
1256 use super::opening_link_text;
1367 use super::opening_link_text;
1257
1368
1258 #[test]
1369 #[test]
1259 fn the_notice_names_the_host() {
1370 fn the_notice_names_the_host() {
1260 assert_eq!(opening_link_text("https://example.com/a?b#c"), "Opening example.com...");
1371 assert_eq!(
1372 opening_link_text("https://example.com/a?b#c"),
1373 "Opening example.com..."
1374 );
1261 assert_eq!(opening_link_text("mailto:"), "Opening mailto:...");
1375 assert_eq!(opening_link_text("mailto:"), "Opening mailto:...");
1262 assert_eq!(opening_link_text(""), "Opening link...");
1376 assert_eq!(opening_link_text(""), "Opening link...");
1263 }
1377 }
1264}
1378}
1265
crates/app/src/views/shell/team_keys.rs +29 −14
@@ -33,8 +33,9 @@ impl AppShell {
33 33 shell
34 34 .on_action(cx.listener(|this, _: &GoToComposeBox, window, cx| {
35 35 this.close_image_viewer(window, cx);
36 this.conversation
37 .update(cx, |conversation, cx| conversation.focus_composer(window, cx));
36 this.conversation.update(cx, |conversation, cx| {
37 conversation.focus_composer(window, cx)
38 });
38 39 }))
39 40 .on_action(cx.listener(|this, _: &ReplyToLastMessage, window, cx| {
40 41 this.close_image_viewer(window, cx);
@@ -42,16 +43,24 @@ impl AppShell {
42 43 conversation.reply_to_latest_from_others(window, cx)
43 44 });
44 45 }))
45 .on_action(cx.listener(|this, _: &PreviousUnreadConversation, window, cx| {
46 this.close_image_viewer(window, cx);
47 this.select_unread(Step::Previous, cx);
48 }))
46 .on_action(
47 cx.listener(|this, _: &PreviousUnreadConversation, window, cx| {
48 this.close_image_viewer(window, cx);
49 this.select_unread(Step::Previous, cx);
50 }),
51 )
49 52 .on_action(cx.listener(|this, _: &NextUnreadConversation, window, cx| {
50 53 this.close_image_viewer(window, cx);
51 54 this.select_unread(Step::Next, cx);
52 55 }))
53 .on_action(presence_listener::<SetPresenceAvailable>(&self.state, ForcedKind::Available))
54 .on_action(presence_listener::<SetPresenceBusy>(&self.state, ForcedKind::Busy))
56 .on_action(presence_listener::<SetPresenceAvailable>(
57 &self.state,
58 ForcedKind::Available,
59 ))
60 .on_action(presence_listener::<SetPresenceBusy>(
61 &self.state,
62 ForcedKind::Busy,
63 ))
55 64 .on_action(presence_listener::<SetPresenceDoNotDisturb>(
56 65 &self.state,
57 66 ForcedKind::DoNotDisturb,
@@ -60,14 +69,19 @@ impl AppShell {
60 69 &self.state,
61 70 ForcedKind::BeRightBack,
62 71 ))
63 .on_action(presence_listener::<SetPresenceAway>(&self.state, ForcedKind::Away))
72 .on_action(presence_listener::<SetPresenceAway>(
73 &self.state,
74 ForcedKind::Away,
75 ))
64 76 .on_action(cx.listener(|this, _: &AcceptCall, _, cx| {
65 this.state
66 .update(cx, |state, cx| state.accept_ringing_call(AcceptMode::Video, cx));
77 this.state.update(cx, |state, cx| {
78 state.accept_ringing_call(AcceptMode::Video, cx)
79 });
67 80 }))
68 81 .on_action(cx.listener(|this, _: &AcceptAudioCall, _, cx| {
69 this.state
70 .update(cx, |state, cx| state.accept_ringing_call(AcceptMode::Audio, cx));
82 this.state.update(cx, |state, cx| {
83 state.accept_ringing_call(AcceptMode::Audio, cx)
84 });
71 85 }))
72 86 .on_action(cx.listener(|this, _: &ToggleBackgroundBlur, _, cx| {
73 87 this.state
@@ -82,7 +96,8 @@ impl AppShell {
82 96 fn select_unread(&mut self, step: Step, cx: &mut Context<Self>) {
83 97 let target = self.state.read(cx).adjacent_unread_chat_id(step);
84 98 if let Some(chat_id) = target {
85 self.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));
99 self.sidebar
100 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
86 101 self.state.update(cx, |state, cx| {
87 102 state.select(crate::app_state::Selection::Chat(chat_id), cx)
88 103 });
@@ -33,8 +33,9 @@ impl AppShell {
33 shell
33 shell
34 .on_action(cx.listener(|this, _: &GoToComposeBox, window, cx| {
34 .on_action(cx.listener(|this, _: &GoToComposeBox, window, cx| {
35 this.close_image_viewer(window, cx);
35 this.close_image_viewer(window, cx);
36 this.conversation
36 this.conversation.update(cx, |conversation, cx| {
37 .update(cx, |conversation, cx| conversation.focus_composer(window, cx));
37 conversation.focus_composer(window, cx)
38 });
38 }))
39 }))
39 .on_action(cx.listener(|this, _: &ReplyToLastMessage, window, cx| {
40 .on_action(cx.listener(|this, _: &ReplyToLastMessage, window, cx| {
40 this.close_image_viewer(window, cx);
41 this.close_image_viewer(window, cx);
@@ -42,16 +43,24 @@ impl AppShell {
42 conversation.reply_to_latest_from_others(window, cx)
43 conversation.reply_to_latest_from_others(window, cx)
43 });
44 });
44 }))
45 }))
45 .on_action(cx.listener(|this, _: &PreviousUnreadConversation, window, cx| {
46 .on_action(
46 this.close_image_viewer(window, cx);
47 cx.listener(|this, _: &PreviousUnreadConversation, window, cx| {
47 this.select_unread(Step::Previous, cx);
48 this.close_image_viewer(window, cx);
48 }))
49 this.select_unread(Step::Previous, cx);
50 }),
51 )
49 .on_action(cx.listener(|this, _: &NextUnreadConversation, window, cx| {
52 .on_action(cx.listener(|this, _: &NextUnreadConversation, window, cx| {
50 this.close_image_viewer(window, cx);
53 this.close_image_viewer(window, cx);
51 this.select_unread(Step::Next, cx);
54 this.select_unread(Step::Next, cx);
52 }))
55 }))
53 .on_action(presence_listener::<SetPresenceAvailable>(&self.state, ForcedKind::Available))
56 .on_action(presence_listener::<SetPresenceAvailable>(
54 .on_action(presence_listener::<SetPresenceBusy>(&self.state, ForcedKind::Busy))
57 &self.state,
58 ForcedKind::Available,
59 ))
60 .on_action(presence_listener::<SetPresenceBusy>(
61 &self.state,
62 ForcedKind::Busy,
63 ))
55 .on_action(presence_listener::<SetPresenceDoNotDisturb>(
64 .on_action(presence_listener::<SetPresenceDoNotDisturb>(
56 &self.state,
65 &self.state,
57 ForcedKind::DoNotDisturb,
66 ForcedKind::DoNotDisturb,
@@ -60,14 +69,19 @@ impl AppShell {
60 &self.state,
69 &self.state,
61 ForcedKind::BeRightBack,
70 ForcedKind::BeRightBack,
62 ))
71 ))
63 .on_action(presence_listener::<SetPresenceAway>(&self.state, ForcedKind::Away))
72 .on_action(presence_listener::<SetPresenceAway>(
73 &self.state,
74 ForcedKind::Away,
75 ))
64 .on_action(cx.listener(|this, _: &AcceptCall, _, cx| {
76 .on_action(cx.listener(|this, _: &AcceptCall, _, cx| {
65 this.state
77 this.state.update(cx, |state, cx| {
66 .update(cx, |state, cx| state.accept_ringing_call(AcceptMode::Video, cx));
78 state.accept_ringing_call(AcceptMode::Video, cx)
79 });
67 }))
80 }))
68 .on_action(cx.listener(|this, _: &AcceptAudioCall, _, cx| {
81 .on_action(cx.listener(|this, _: &AcceptAudioCall, _, cx| {
69 this.state
82 this.state.update(cx, |state, cx| {
70 .update(cx, |state, cx| state.accept_ringing_call(AcceptMode::Audio, cx));
83 state.accept_ringing_call(AcceptMode::Audio, cx)
84 });
71 }))
85 }))
72 .on_action(cx.listener(|this, _: &ToggleBackgroundBlur, _, cx| {
86 .on_action(cx.listener(|this, _: &ToggleBackgroundBlur, _, cx| {
73 this.state
87 this.state
@@ -82,7 +96,8 @@ impl AppShell {
82 fn select_unread(&mut self, step: Step, cx: &mut Context<Self>) {
96 fn select_unread(&mut self, step: Step, cx: &mut Context<Self>) {
83 let target = self.state.read(cx).adjacent_unread_chat_id(step);
97 let target = self.state.read(cx).adjacent_unread_chat_id(step);
84 if let Some(chat_id) = target {
98 if let Some(chat_id) = target {
85 self.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));
99 self.sidebar
100 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
86 self.state.update(cx, |state, cx| {
101 self.state.update(cx, |state, cx| {
87 state.select(crate::app_state::Selection::Chat(chat_id), cx)
102 state.select(crate::app_state::Selection::Chat(chat_id), cx)
88 });
103 });
crates/app/src/views/shortcuts.rs +4 −5
@@ -3,11 +3,10 @@ use gpui_kit::*;
3 3
4 4 use super::actions::{
5 5 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLastMessage, EditLink, InsertTableLine, NewChat,
6 OpenSwitcher, PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, ToggleBold,
7 ToggleCallMute, ToggleCode, ToggleFormatBar, ToggleItalic, ToggleStrike, ToggleSubscript,
8 ToggleSuperscript,
9 ToggleUnderline, SetParagraph, SetHeading1, SetHeading2, SetHeading3, ToggleCodeBlock,
10 ToggleQuote,
6 OpenSwitcher, PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, SetHeading1,
7 SetHeading2, SetHeading3, SetParagraph, ToggleBold, ToggleCallMute, ToggleCode,
8 ToggleCodeBlock, ToggleFormatBar, ToggleItalic, ToggleQuote, ToggleStrike, ToggleSubscript,
9 ToggleSuperscript, ToggleUnderline,
11 10 };
12 11
13 12 const TEXT_FIELD_CONTEXT: &str = "Input";
@@ -3,11 +3,10 @@ use gpui_kit::*;
3
3
4use super::actions::{
4use super::actions::{
5 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLastMessage, EditLink, InsertTableLine, NewChat,
5 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLastMessage, EditLink, InsertTableLine, NewChat,
6 OpenSwitcher, PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, ToggleBold,
6 OpenSwitcher, PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, SetHeading1,
7 ToggleCallMute, ToggleCode, ToggleFormatBar, ToggleItalic, ToggleStrike, ToggleSubscript,
7 SetHeading2, SetHeading3, SetParagraph, ToggleBold, ToggleCallMute, ToggleCode,
8 ToggleSuperscript,
8 ToggleCodeBlock, ToggleFormatBar, ToggleItalic, ToggleQuote, ToggleStrike, ToggleSubscript,
9 ToggleUnderline, SetParagraph, SetHeading1, SetHeading2, SetHeading3, ToggleCodeBlock,
9 ToggleSuperscript, ToggleUnderline,
10 ToggleQuote,
11};
10};
12
11
13const TEXT_FIELD_CONTEXT: &str = "Input";
12const TEXT_FIELD_CONTEXT: &str = "Input";
crates/app/src/views/sidebar.rs +32 −26
@@ -2,11 +2,11 @@ use std::cell::{Cell, RefCell};
2 2 use std::collections::{HashMap, HashSet};
3 3
4 4 use chrono::{Local, Offset, Utc};
5 use gpui_kit::component::scroll::ScrollableElement as _;
6 5 use gpui_kit::assets::IconName;
7 6 use gpui_kit::component::button::{Button, ButtonVariants as _};
8 7 use gpui_kit::component::dialog::DialogFooter;
9 8 use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
9 use gpui_kit::component::scroll::ScrollableElement as _;
10 10 use gpui_kit::component::{Icon, Sizable as _, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
11 11 use gpui_kit::prelude::FluentBuilder as _;
12 12 use gpui_kit::*;
@@ -18,14 +18,14 @@ use teams_core::team_avatar_key;
18 18
19 19 use super::activity_panel::ActivityPanel;
20 20 use super::avatar::{spec_avatar, team_avatar, with_presence};
21 use super::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
22 use super::scroll_edge::{scroll_offset, with_top_edge};
23 21 use super::channel_admin_dialogs::{confirm_delete_channel, open_edit_channel_dialog};
22 use super::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
24 23 use super::create_channel_dialog::open_create_channel_dialog;
24 use super::last_views::LastViews;
25 use super::scroll_edge::{scroll_offset, with_top_edge};
25 26 use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
26 27 use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
27 28 use crate::agents::AgentsPanel;
28 use super::last_views::LastViews;
29 29 use crate::app_state::{AppEvent, AppState, QuickView, Selection};
30 30 use crate::channel_menu::{
31 31 ChannelMenuItem, MenuEntry, TeamMenuItem, TeamMenuState, channel_menu_entries,
@@ -559,15 +559,12 @@ impl SidebarView {
559 559 self.last_views.remember(current);
560 560 }
561 561 let first_chat_id = state.sidebar.chats.first().map(|chat| chat.id.as_str());
562 if let Some(selection) =
563 self.last_views
564 .restore(
565 tab,
566 state.selection.as_ref(),
567 first_chat_id,
568 first_channel_id.as_deref(),
569 )
570 {
562 if let Some(selection) = self.last_views.restore(
563 tab,
564 state.selection.as_ref(),
565 first_chat_id,
566 first_channel_id.as_deref(),
567 ) {
571 568 self.state
572 569 .update(cx, |state, cx| state.select(selection, cx));
573 570 }
@@ -604,7 +601,9 @@ impl SidebarView {
604 601
605 602 fn first_channel_id(&self, cx: &App) -> Option<String> {
606 603 let input = self.channel_order_input(self.state.read(cx), None);
607 visible_channel_ids(&input).first().map(|id| (*id).to_owned())
604 visible_channel_ids(&input)
605 .first()
606 .map(|id| (*id).to_owned())
608 607 }
609 608
610 609 fn channel_order_input<'a>(
@@ -896,7 +895,8 @@ impl SidebarView {
896 895 let mut height = SECTION_GAP + SECTION_HEIGHT;
897 896 if !collapsed {
898 897 for (view, glyph) in QUICK_VIEWS {
899 section = section.child(self.quick_view_row(view, glyph, open_view == Some(view), cx));
898 section =
899 section.child(self.quick_view_row(view, glyph, open_view == Some(view), cx));
900 900 height += QUICK_ROW_HEIGHT;
901 901 }
902 902 }
@@ -1527,7 +1527,12 @@ impl SidebarView {
1527 1527 cx.notify();
1528 1528 }))
1529 1529 .context_menu(move |popup, _, _| {
1530 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_menu_flags)
1530 team_menu(
1531 popup,
1532 team_menu_state.clone(),
1533 &team_menu_id,
1534 team_menu_flags,
1535 )
1531 1536 }),
1532 1537 );
1533 1538 if !expanded {
@@ -1596,7 +1601,11 @@ impl SidebarView {
1596 1601 .hover(|row| row.bg(theme::row_hover()))
1597 1602 .text_size(px(13.5))
1598 1603 .text_color(theme::accent_text())
1599 .child(if open { SEE_FEWER_CHANNELS } else { SEE_ALL_CHANNELS })
1604 .child(if open {
1605 SEE_FEWER_CHANNELS
1606 } else {
1607 SEE_ALL_CHANNELS
1608 })
1600 1609 .on_click(on_click)
1601 1610 }
1602 1611
@@ -1682,11 +1691,11 @@ impl SidebarView {
1682 1691 .child(channel.name.clone()),
1683 1692 )
1684 1693 .when(is_private_channel(channel), |name| {
1685 name.child(
1686 div()
1687 .flex_none()
1688 .child(symbol("lock", 14., theme::text_muted())),
1689 )
1694 name.child(div().flex_none().child(symbol(
1695 "lock",
1696 14.,
1697 theme::text_muted(),
1698 )))
1690 1699 }),
1691 1700 )
1692 1701 .children(notification_badge(notifications.level))
@@ -2169,10 +2178,7 @@ impl Render for SidebarView {
2169 2178 mod tests {
2170 2179 use std::collections::HashSet;
2171 2180
2172 use super::{
2173 drop_target, parse_collapsed_teams, serialize_collapsed_teams,
2174 team_expanded,
2175 };
2181 use super::{drop_target, parse_collapsed_teams, serialize_collapsed_teams, team_expanded};
2176 2182 use crate::data::PENDING_FOLDER_PREFIX;
2177 2183 use crate::sidebar_model::{Section, SectionKind};
2178 2184
@@ -2,11 +2,11 @@ use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
2use std::collections::{HashMap, HashSet};
3
3
4use chrono::{Local, Offset, Utc};
4use chrono::{Local, Offset, Utc};
5use gpui_kit::component::scroll::ScrollableElement as _;
6use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
6use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::dialog::DialogFooter;
7use gpui_kit::component::dialog::DialogFooter;
9use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
8use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
9use gpui_kit::component::scroll::ScrollableElement as _;
10use gpui_kit::component::{Icon, Sizable as _, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
10use gpui_kit::component::{Icon, Sizable as _, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
12use gpui_kit::*;
@@ -18,14 +18,14 @@ use teams_core::team_avatar_key;
18
18
19use super::activity_panel::ActivityPanel;
19use super::activity_panel::ActivityPanel;
20use super::avatar::{spec_avatar, team_avatar, with_presence};
20use super::avatar::{spec_avatar, team_avatar, with_presence};
21use super::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
22use super::scroll_edge::{scroll_offset, with_top_edge};
23use super::channel_admin_dialogs::{confirm_delete_channel, open_edit_channel_dialog};
21use super::channel_admin_dialogs::{confirm_delete_channel, open_edit_channel_dialog};
22use super::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
24use super::create_channel_dialog::open_create_channel_dialog;
23use super::create_channel_dialog::open_create_channel_dialog;
24use super::last_views::LastViews;
25use super::scroll_edge::{scroll_offset, with_top_edge};
25use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
26use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
26use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
27use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
27use crate::agents::AgentsPanel;
28use crate::agents::AgentsPanel;
28use super::last_views::LastViews;
29use crate::app_state::{AppEvent, AppState, QuickView, Selection};
29use crate::app_state::{AppEvent, AppState, QuickView, Selection};
30use crate::channel_menu::{
30use crate::channel_menu::{
31 ChannelMenuItem, MenuEntry, TeamMenuItem, TeamMenuState, channel_menu_entries,
31 ChannelMenuItem, MenuEntry, TeamMenuItem, TeamMenuState, channel_menu_entries,
@@ -559,15 +559,12 @@ impl SidebarView {
559 self.last_views.remember(current);
559 self.last_views.remember(current);
560 }
560 }
561 let first_chat_id = state.sidebar.chats.first().map(|chat| chat.id.as_str());
561 let first_chat_id = state.sidebar.chats.first().map(|chat| chat.id.as_str());
562 if let Some(selection) =
562 if let Some(selection) = self.last_views.restore(
563 self.last_views
563 tab,
564 .restore(
564 state.selection.as_ref(),
565 tab,
565 first_chat_id,
566 state.selection.as_ref(),
566 first_channel_id.as_deref(),
567 first_chat_id,
567 ) {
568 first_channel_id.as_deref(),
569 )
570 {
571 self.state
568 self.state
572 .update(cx, |state, cx| state.select(selection, cx));
569 .update(cx, |state, cx| state.select(selection, cx));
573 }
570 }
@@ -604,7 +601,9 @@ impl SidebarView {
604
601
605 fn first_channel_id(&self, cx: &App) -> Option<String> {
602 fn first_channel_id(&self, cx: &App) -> Option<String> {
606 let input = self.channel_order_input(self.state.read(cx), None);
603 let input = self.channel_order_input(self.state.read(cx), None);
607 visible_channel_ids(&input).first().map(|id| (*id).to_owned())
604 visible_channel_ids(&input)
605 .first()
606 .map(|id| (*id).to_owned())
608 }
607 }
609
608
610 fn channel_order_input<'a>(
609 fn channel_order_input<'a>(
@@ -896,7 +895,8 @@ impl SidebarView {
896 let mut height = SECTION_GAP + SECTION_HEIGHT;
895 let mut height = SECTION_GAP + SECTION_HEIGHT;
897 if !collapsed {
896 if !collapsed {
898 for (view, glyph) in QUICK_VIEWS {
897 for (view, glyph) in QUICK_VIEWS {
899 section = section.child(self.quick_view_row(view, glyph, open_view == Some(view), cx));
898 section =
899 section.child(self.quick_view_row(view, glyph, open_view == Some(view), cx));
900 height += QUICK_ROW_HEIGHT;
900 height += QUICK_ROW_HEIGHT;
901 }
901 }
902 }
902 }
@@ -1527,7 +1527,12 @@ impl SidebarView {
1527 cx.notify();
1527 cx.notify();
1528 }))
1528 }))
1529 .context_menu(move |popup, _, _| {
1529 .context_menu(move |popup, _, _| {
1530 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_menu_flags)
1530 team_menu(
1531 popup,
1532 team_menu_state.clone(),
1533 &team_menu_id,
1534 team_menu_flags,
1535 )
1531 }),
1536 }),
1532 );
1537 );
1533 if !expanded {
1538 if !expanded {
@@ -1596,7 +1601,11 @@ impl SidebarView {
1596 .hover(|row| row.bg(theme::row_hover()))
1601 .hover(|row| row.bg(theme::row_hover()))
1597 .text_size(px(13.5))
1602 .text_size(px(13.5))
1598 .text_color(theme::accent_text())
1603 .text_color(theme::accent_text())
1599 .child(if open { SEE_FEWER_CHANNELS } else { SEE_ALL_CHANNELS })
1604 .child(if open {
1605 SEE_FEWER_CHANNELS
1606 } else {
1607 SEE_ALL_CHANNELS
1608 })
1600 .on_click(on_click)
1609 .on_click(on_click)
1601 }
1610 }
1602
1611
@@ -1682,11 +1691,11 @@ impl SidebarView {
1682 .child(channel.name.clone()),
1691 .child(channel.name.clone()),
1683 )
1692 )
1684 .when(is_private_channel(channel), |name| {
1693 .when(is_private_channel(channel), |name| {
1685 name.child(
1694 name.child(div().flex_none().child(symbol(
1686 div()
1695 "lock",
1687 .flex_none()
1696 14.,
1688 .child(symbol("lock", 14., theme::text_muted())),
1697 theme::text_muted(),
1689 )
1698 )))
1690 }),
1699 }),
1691 )
1700 )
1692 .children(notification_badge(notifications.level))
1701 .children(notification_badge(notifications.level))
@@ -2169,10 +2178,7 @@ impl Render for SidebarView {
2169mod tests {
2178mod tests {
2170 use std::collections::HashSet;
2179 use std::collections::HashSet;
2171
2180
2172 use super::{
2181 use super::{drop_target, parse_collapsed_teams, serialize_collapsed_teams, team_expanded};
2173 drop_target, parse_collapsed_teams, serialize_collapsed_teams,
2174 team_expanded,
2175 };
2176 use crate::data::PENDING_FOLDER_PREFIX;
2182 use crate::data::PENDING_FOLDER_PREFIX;
2177 use crate::sidebar_model::{Section, SectionKind};
2183 use crate::sidebar_model::{Section, SectionKind};
2178
2184
crates/app/src/views/sidebar/channel_filter_bar.rs +26 −6
@@ -43,11 +43,16 @@ impl SidebarView {
43 43 cx.notify();
44 44 }
45 45
46 fn channel_filter_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
46 fn channel_filter_input(
47 &mut self,
48 window: &mut Window,
49 cx: &mut Context<Self>,
50 ) -> Entity<InputState> {
47 51 if let Some(input) = &self.channel_filter_input {
48 52 return input.clone();
49 53 }
50 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CHANNEL_FILTER_PLACEHOLDER));
54 let input =
55 cx.new(|cx| InputState::new(window, cx).placeholder(CHANNEL_FILTER_PLACEHOLDER));
51 56 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
52 57 if matches!(event, InputEvent::Change) {
53 58 this.channel_filter.text = input.read(cx).value().to_string();
@@ -61,7 +66,11 @@ impl SidebarView {
61 66
62 67 pub(super) fn channel_filter_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
63 68 let open = self.channel_filter_open;
64 let label = if open { CLOSE_FILTER_TEXT } else { SHOW_FILTER_TEXT };
69 let label = if open {
70 CLOSE_FILTER_TEXT
71 } else {
72 SHOW_FILTER_TEXT
73 };
65 74 div()
66 75 .id("channel-filter-toggle")
67 76 .size(px(NEW_CHAT_BUTTON_SIZE))
@@ -77,7 +86,11 @@ impl SidebarView {
77 86 .child(icon(
78 87 IconName::Search,
79 88 16.,
80 if open { theme::accent_text() } else { theme::text_soft() },
89 if open {
90 theme::accent_text()
91 } else {
92 theme::text_soft()
93 },
81 94 ))
82 95 .on_click(cx.listener(|this, _, window, cx| this.toggle_channel_filter(window, cx)))
83 96 }
@@ -92,7 +105,12 @@ impl SidebarView {
92 105 .sidebar
93 106 .teams
94 107 .iter()
95 .find(|entry| entry.channels.iter().any(|channel| &channel.id == channel_id))
108 .find(|entry| {
109 entry
110 .channels
111 .iter()
112 .any(|channel| &channel.id == channel_id)
113 })
96 114 .filter(|entry| entry.rights.add_channel && !app.mode.read_only)
97 115 .map(|entry| entry.team.id.clone()),
98 116 _ => None,
@@ -154,7 +172,9 @@ impl SidebarView {
154 172 .rounded_full()
155 173 .text_size(px(12.))
156 174 .cursor_pointer()
157 .when(selected, |chip| chip.bg(theme::accent()).text_color(theme::on_accent()))
175 .when(selected, |chip| {
176 chip.bg(theme::accent()).text_color(theme::on_accent())
177 })
158 178 .when(!selected, |chip| {
159 179 chip.bg(theme::surface_raised())
160 180 .text_color(theme::text_soft())
@@ -43,11 +43,16 @@ impl SidebarView {
43 cx.notify();
43 cx.notify();
44 }
44 }
45
45
46 fn channel_filter_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
46 fn channel_filter_input(
47 &mut self,
48 window: &mut Window,
49 cx: &mut Context<Self>,
50 ) -> Entity<InputState> {
47 if let Some(input) = &self.channel_filter_input {
51 if let Some(input) = &self.channel_filter_input {
48 return input.clone();
52 return input.clone();
49 }
53 }
50 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CHANNEL_FILTER_PLACEHOLDER));
54 let input =
55 cx.new(|cx| InputState::new(window, cx).placeholder(CHANNEL_FILTER_PLACEHOLDER));
51 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
56 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
52 if matches!(event, InputEvent::Change) {
57 if matches!(event, InputEvent::Change) {
53 this.channel_filter.text = input.read(cx).value().to_string();
58 this.channel_filter.text = input.read(cx).value().to_string();
@@ -61,7 +66,11 @@ impl SidebarView {
61
66
62 pub(super) fn channel_filter_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
67 pub(super) fn channel_filter_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
63 let open = self.channel_filter_open;
68 let open = self.channel_filter_open;
64 let label = if open { CLOSE_FILTER_TEXT } else { SHOW_FILTER_TEXT };
69 let label = if open {
70 CLOSE_FILTER_TEXT
71 } else {
72 SHOW_FILTER_TEXT
73 };
65 div()
74 div()
66 .id("channel-filter-toggle")
75 .id("channel-filter-toggle")
67 .size(px(NEW_CHAT_BUTTON_SIZE))
76 .size(px(NEW_CHAT_BUTTON_SIZE))
@@ -77,7 +86,11 @@ impl SidebarView {
77 .child(icon(
86 .child(icon(
78 IconName::Search,
87 IconName::Search,
79 16.,
88 16.,
80 if open { theme::accent_text() } else { theme::text_soft() },
89 if open {
90 theme::accent_text()
91 } else {
92 theme::text_soft()
93 },
81 ))
94 ))
82 .on_click(cx.listener(|this, _, window, cx| this.toggle_channel_filter(window, cx)))
95 .on_click(cx.listener(|this, _, window, cx| this.toggle_channel_filter(window, cx)))
83 }
96 }
@@ -92,7 +105,12 @@ impl SidebarView {
92 .sidebar
105 .sidebar
93 .teams
106 .teams
94 .iter()
107 .iter()
95 .find(|entry| entry.channels.iter().any(|channel| &channel.id == channel_id))
108 .find(|entry| {
109 entry
110 .channels
111 .iter()
112 .any(|channel| &channel.id == channel_id)
113 })
96 .filter(|entry| entry.rights.add_channel && !app.mode.read_only)
114 .filter(|entry| entry.rights.add_channel && !app.mode.read_only)
97 .map(|entry| entry.team.id.clone()),
115 .map(|entry| entry.team.id.clone()),
98 _ => None,
116 _ => None,
@@ -154,7 +172,9 @@ impl SidebarView {
154 .rounded_full()
172 .rounded_full()
155 .text_size(px(12.))
173 .text_size(px(12.))
156 .cursor_pointer()
174 .cursor_pointer()
157 .when(selected, |chip| chip.bg(theme::accent()).text_color(theme::on_accent()))
175 .when(selected, |chip| {
176 chip.bg(theme::accent()).text_color(theme::on_accent())
177 })
158 .when(!selected, |chip| {
178 .when(!selected, |chip| {
159 chip.bg(theme::surface_raised())
179 chip.bg(theme::surface_raised())
160 .text_color(theme::text_soft())
180 .text_color(theme::text_soft())
crates/app/src/views/sidebar/chat_filter_bar.rs +2 −2
@@ -9,8 +9,8 @@ use gpui_kit::*;
9 9 use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
10 10 use crate::app_state::Selection;
11 11 use crate::chat_filter::{
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill,
13 FILTER_PLACEHOLDER, NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill, FILTER_PLACEHOLDER,
13 NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
14 14 };
15 15 use crate::theme;
16 16 use crate::views::widgets::icon;
@@ -9,8 +9,8 @@ use gpui_kit::*;
9use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
9use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
10use crate::app_state::Selection;
10use crate::app_state::Selection;
11use crate::chat_filter::{
11use crate::chat_filter::{
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill,
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill, FILTER_PLACEHOLDER,
13 FILTER_PLACEHOLDER, NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
13 NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
14};
14};
15use crate::theme;
15use crate::theme;
16use crate::views::widgets::icon;
16use crate::views::widgets::icon;
crates/app/src/views/status_menu.rs +7 −5
@@ -13,8 +13,8 @@ use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKin
13 13 use super::avatar::{person_avatar, status_glyph, with_presence, with_presence_badge};
14 14 use super::widgets::{menu_icon, symbol};
15 15 use crate::app_state::AppState;
16 use crate::notify::pause;
17 16 use crate::data::{Person, PresenceKind};
17 use crate::notify::pause;
18 18 use crate::own_status::{
19 19 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
20 20 presence_kind_for, state_summary, work_location_label,
@@ -234,10 +234,12 @@ fn pause_item(
234 234 let menu = STATUS_DURATIONS.iter().fold(menu, |menu, duration| {
235 235 let app = app.clone();
236 236 let duration = *duration;
237 menu.item(PopupMenuItem::new(duration.label()).on_click(move |_, _, cx| {
238 let until = duration.expires_at(Local::now());
239 app.update(cx, |state, cx| state.pause_notifications(until, cx));
240 }))
237 menu.item(
238 PopupMenuItem::new(duration.label()).on_click(move |_, _, cx| {
239 let until = duration.expires_at(Local::now());
240 app.update(cx, |state, cx| state.pause_notifications(until, cx));
241 }),
242 )
241 243 });
242 244 if !paused {
243 245 return menu;
@@ -13,8 +13,8 @@ use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKin
13use super::avatar::{person_avatar, status_glyph, with_presence, with_presence_badge};
13use super::avatar::{person_avatar, status_glyph, with_presence, with_presence_badge};
14use super::widgets::{menu_icon, symbol};
14use super::widgets::{menu_icon, symbol};
15use crate::app_state::AppState;
15use crate::app_state::AppState;
16use crate::notify::pause;
17use crate::data::{Person, PresenceKind};
16use crate::data::{Person, PresenceKind};
17use crate::notify::pause;
18use crate::own_status::{
18use crate::own_status::{
19 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
19 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
20 presence_kind_for, state_summary, work_location_label,
20 presence_kind_for, state_summary, work_location_label,
@@ -234,10 +234,12 @@ fn pause_item(
234 let menu = STATUS_DURATIONS.iter().fold(menu, |menu, duration| {
234 let menu = STATUS_DURATIONS.iter().fold(menu, |menu, duration| {
235 let app = app.clone();
235 let app = app.clone();
236 let duration = *duration;
236 let duration = *duration;
237 menu.item(PopupMenuItem::new(duration.label()).on_click(move |_, _, cx| {
237 menu.item(
238 let until = duration.expires_at(Local::now());
238 PopupMenuItem::new(duration.label()).on_click(move |_, _, cx| {
239 app.update(cx, |state, cx| state.pause_notifications(until, cx));
239 let until = duration.expires_at(Local::now());
240 }))
240 app.update(cx, |state, cx| state.pause_notifications(until, cx));
241 }),
242 )
241 });
243 });
242 if !paused {
244 if !paused {
243 return menu;
245 return menu;
crates/app/src/views/switcher.rs +8 −9
@@ -300,9 +300,10 @@ impl Switcher {
300 300 if !still_current {
301 301 return;
302 302 }
303 let receiver = runtime::spawn(async move {
304 engine.server_suggestions(&search_session, &query).await
305 });
303 let receiver =
304 runtime::spawn(
305 async move { engine.server_suggestions(&search_session, &query).await },
306 );
306 307 let suggestions = match receiver.await {
307 308 Ok(Ok(suggestions)) => suggestions,
308 309 _ => return,
@@ -380,8 +381,7 @@ impl Switcher {
380 381 cx.emit(SwitcherEvent::PickPerson {
381 382 user_id: person.user_id.clone(),
382 383 });
383 } else if let Some(message) = message_index.and_then(|index| self.messages.get(index))
384 {
384 } else if let Some(message) = message_index.and_then(|index| self.messages.get(index)) {
385 385 cx.emit(SwitcherEvent::PickMessage {
386 386 selection: message.selection.clone(),
387 387 message_id: message.message_id.clone(),
@@ -677,10 +677,9 @@ impl Render for Switcher {
677 677 .items_center()
678 678 .child(icon(IconName::Search, 14., theme::text_muted()))
679 679 .child(
680 div()
681 .flex_1()
682 .min_w_0()
683 .child(Input::new(&self.input).appearance(false).bordered(false)),
680 div().flex_1().min_w_0().child(
681 Input::new(&self.input).appearance(false).bordered(false),
682 ),
684 683 ),
685 684 )
686 685 .child(
@@ -300,9 +300,10 @@ impl Switcher {
300 if !still_current {
300 if !still_current {
301 return;
301 return;
302 }
302 }
303 let receiver = runtime::spawn(async move {
303 let receiver =
304 engine.server_suggestions(&search_session, &query).await
304 runtime::spawn(
305 });
305 async move { engine.server_suggestions(&search_session, &query).await },
306 );
306 let suggestions = match receiver.await {
307 let suggestions = match receiver.await {
307 Ok(Ok(suggestions)) => suggestions,
308 Ok(Ok(suggestions)) => suggestions,
308 _ => return,
309 _ => return,
@@ -380,8 +381,7 @@ impl Switcher {
380 cx.emit(SwitcherEvent::PickPerson {
381 cx.emit(SwitcherEvent::PickPerson {
381 user_id: person.user_id.clone(),
382 user_id: person.user_id.clone(),
382 });
383 });
383 } else if let Some(message) = message_index.and_then(|index| self.messages.get(index))
384 } else if let Some(message) = message_index.and_then(|index| self.messages.get(index)) {
384 {
385 cx.emit(SwitcherEvent::PickMessage {
385 cx.emit(SwitcherEvent::PickMessage {
386 selection: message.selection.clone(),
386 selection: message.selection.clone(),
387 message_id: message.message_id.clone(),
387 message_id: message.message_id.clone(),
@@ -677,10 +677,9 @@ impl Render for Switcher {
677 .items_center()
677 .items_center()
678 .child(icon(IconName::Search, 14., theme::text_muted()))
678 .child(icon(IconName::Search, 14., theme::text_muted()))
679 .child(
679 .child(
680 div()
680 div().flex_1().min_w_0().child(
681 .flex_1()
681 Input::new(&self.input).appearance(false).bordered(false),
682 .min_w_0()
682 ),
683 .child(Input::new(&self.input).appearance(false).bordered(false)),
684 ),
683 ),
685 )
684 )
686 .child(
685 .child(
crates/app/src/views/switcher_server.rs +15 −4
@@ -162,8 +162,12 @@ mod tests {
162 162 };
163 163 let today = NaiveDate::from_ymd_opt(2026, 11, 8).unwrap();
164 164 let offset = FixedOffset::east_opt(0).unwrap();
165 let results =
166 server_message_results(&[hit("19:a"), hit("19:unknown")], &conversations, today, offset);
165 let results = server_message_results(
166 &[hit("19:a"), hit("19:unknown")],
167 &conversations,
168 today,
169 offset,
170 );
167 171 assert_eq!(results.len(), 1);
168 172 assert_eq!(results[0].snippet, "the build is green");
169 173 assert_eq!(results[0].matches, [4..9]);
@@ -173,10 +177,17 @@ mod tests {
173 177 fn merged_messages_keep_local_first_without_duplicates() {
174 178 let merged = merge_messages(
175 179 &[message("1", "19:a")],
176 vec![message("1", "19:a"), message("2", "19:a"), message("3", "19:a")],
180 vec![
181 message("1", "19:a"),
182 message("2", "19:a"),
183 message("3", "19:a"),
184 ],
177 185 2,
178 186 );
179 let ids: Vec<&str> = merged.iter().map(|message| message.message_id.as_str()).collect();
187 let ids: Vec<&str> = merged
188 .iter()
189 .map(|message| message.message_id.as_str())
190 .collect();
180 191 assert_eq!(ids, ["1", "2"]);
181 192 }
182 193 }
@@ -162,8 +162,12 @@ mod tests {
162 };
162 };
163 let today = NaiveDate::from_ymd_opt(2026, 11, 8).unwrap();
163 let today = NaiveDate::from_ymd_opt(2026, 11, 8).unwrap();
164 let offset = FixedOffset::east_opt(0).unwrap();
164 let offset = FixedOffset::east_opt(0).unwrap();
165 let results =
165 let results = server_message_results(
166 server_message_results(&[hit("19:a"), hit("19:unknown")], &conversations, today, offset);
166 &[hit("19:a"), hit("19:unknown")],
167 &conversations,
168 today,
169 offset,
170 );
167 assert_eq!(results.len(), 1);
171 assert_eq!(results.len(), 1);
168 assert_eq!(results[0].snippet, "the build is green");
172 assert_eq!(results[0].snippet, "the build is green");
169 assert_eq!(results[0].matches, [4..9]);
173 assert_eq!(results[0].matches, [4..9]);
@@ -173,10 +177,17 @@ mod tests {
173 fn merged_messages_keep_local_first_without_duplicates() {
177 fn merged_messages_keep_local_first_without_duplicates() {
174 let merged = merge_messages(
178 let merged = merge_messages(
175 &[message("1", "19:a")],
179 &[message("1", "19:a")],
176 vec![message("1", "19:a"), message("2", "19:a"), message("3", "19:a")],
180 vec![
181 message("1", "19:a"),
182 message("2", "19:a"),
183 message("3", "19:a"),
184 ],
177 2,
185 2,
178 );
186 );
179 let ids: Vec<&str> = merged.iter().map(|message| message.message_id.as_str()).collect();
187 let ids: Vec<&str> = merged
188 .iter()
189 .map(|message| message.message_id.as_str())
190 .collect();
180 assert_eq!(ids, ["1", "2"]);
191 assert_eq!(ids, ["1", "2"]);
181 }
192 }
182}
193}
crates/app/src/views/transfer_picker.rs +19 −4
@@ -1,5 +1,5 @@
1 use gpui_kit::component::scroll::ScrollableElement as _;
2 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 3 use gpui_kit::component::{
4 4 button::{Button, ButtonVariants as _},
5 5 h_flex,
@@ -233,11 +233,26 @@ impl Render for TransferPicker {
233 233 )
234 234 .children(match self.mode {
235 235 PickerMode::Transfer => vec![
236 self.action("transfer-consult", "Consult first", false, AppState::start_consult),
237 self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind),
236 self.action(
237 "transfer-consult",
238 "Consult first",
239 false,
240 AppState::start_consult,
241 ),
242 self.action(
243 "transfer-now",
244 "Transfer now",
245 true,
246 AppState::transfer_call_blind,
247 ),
238 248 ],
239 249 PickerMode::Invite => {
240 vec![self.action("transfer-invite", "Invite", true, AppState::invite_call_person)]
250 vec![self.action(
251 "transfer-invite",
252 "Invite",
253 true,
254 AppState::invite_call_person,
255 )]
241 256 }
242 257 });
243 258 div()
@@ -1,5 +1,5 @@
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::component::{
3use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
4 button::{Button, ButtonVariants as _},
5 h_flex,
5 h_flex,
@@ -233,11 +233,26 @@ impl Render for TransferPicker {
233 )
233 )
234 .children(match self.mode {
234 .children(match self.mode {
235 PickerMode::Transfer => vec![
235 PickerMode::Transfer => vec![
236 self.action("transfer-consult", "Consult first", false, AppState::start_consult),
236 self.action(
237 self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind),
237 "transfer-consult",
238 "Consult first",
239 false,
240 AppState::start_consult,
241 ),
242 self.action(
243 "transfer-now",
244 "Transfer now",
245 true,
246 AppState::transfer_call_blind,
247 ),
238 ],
248 ],
239 PickerMode::Invite => {
249 PickerMode::Invite => {
240 vec![self.action("transfer-invite", "Invite", true, AppState::invite_call_person)]
250 vec![self.action(
251 "transfer-invite",
252 "Invite",
253 true,
254 AppState::invite_call_person,
255 )]
241 }
256 }
242 });
257 });
243 div()
258 div()
crates/mcp/Cargo.toml +1 −1
@@ -11,7 +11,7 @@ base64.workspace = true
11 11 chrono.workspace = true
12 12 percent-encoding.workspace = true
13 13 rand = "0.9"
14 rmcp = { version = "=3.5.1", features = ["server", "macros", "transport-streamable-http-server"] }
14 rmcp = { version = "=3.5.1", features = ["server", "client", "macros", "transport-streamable-http-server", "transport-streamable-http-client-reqwest"] }
15 15 serde.workspace = true
16 16 serde_json = { workspace = true, features = ["raw_value"] }
17 17 store.workspace = true
@@ -11,7 +11,7 @@ base64.workspace = true
11chrono.workspace = true
11chrono.workspace = true
12percent-encoding.workspace = true
12percent-encoding.workspace = true
13rand = "0.9"
13rand = "0.9"
14rmcp = { version = "=3.5.1", features = ["server", "macros", "transport-streamable-http-server"] }
14rmcp = { version = "=3.5.1", features = ["server", "client", "macros", "transport-streamable-http-server", "transport-streamable-http-client-reqwest"] }
15serde.workspace = true
15serde.workspace = true
16serde_json = { workspace = true, features = ["raw_value"] }
16serde_json = { workspace = true, features = ["raw_value"] }
17store.workspace = true
17store.workspace = true
crates/mcp/src/lib.rs +6 −4
@@ -1,25 +1,27 @@
1 1 mod auth;
2 2 mod hub;
3 mod meetings;
4 3 pub mod install;
5 4 mod policy;
5 mod remote;
6 6 mod server;
7 7 mod settings;
8 8 mod source;
9 9 mod tools;
10 10
11 11 pub use hub::{
12 AgentHub, CaptionLine, Event, EventKind, FreeWriting, FreeWritingAsk, MeetingOutcome, MeetingProposal, NewProposal, NewReactionProposal, Outcome, Proposal,
12 AgentHub, CaptionLine, Event, EventKind, NewProposal, NewReactionProposal, Outcome, Proposal,
13 13 ProposalImage, ProposalMention, ReactionOutcome, ReactionProposal, UiEvent,
14 14 };
15 15 pub use policy::{Access, AgentPolicy, ConversationKind, DEFAULT_PORT};
16 pub use remote::{ListedTool, ToolSession};
16 17 pub use server::{ServerError, ServerHandle, start};
17 18 pub use settings::{
18 19 load as load_policy, load_or_create_token, regenerate_token, save as save_policy,
19 20 };
20 21 pub use source::{
21 BusySlot, CreatedMeeting, EncodedImage, FileInfo, MeetingDraft, PersonAvailability, ForwardedInfo, ImageInfo, ImageKind, LinkInfo, Meeting, MentionInfo, MessageExtras,
22 QuoteInfo, ReactionInfo, SourceError, SourceFuture, TeamsSource, Transcript, TranscriptTurn,
22 EncodedImage, FileInfo, ForwardedInfo, ImageInfo, ImageKind, LinkInfo, Meeting, MentionInfo,
23 MessageExtras, QuoteInfo, ReactionInfo, SourceError, SourceFuture, TeamsSource, Transcript,
24 TranscriptTurn,
23 25 };
24 26
25 27 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -1,25 +1,27 @@
1mod auth;
1mod auth;
2mod hub;
2mod hub;
3mod meetings;
4pub mod install;
3pub mod install;
5mod policy;
4mod policy;
5mod remote;
6mod server;
6mod server;
7mod settings;
7mod settings;
8mod source;
8mod source;
9mod tools;
9mod tools;
10
10
11pub use hub::{
11pub use hub::{
12 AgentHub, CaptionLine, Event, EventKind, FreeWriting, FreeWritingAsk, MeetingOutcome, MeetingProposal, NewProposal, NewReactionProposal, Outcome, Proposal,
12 AgentHub, CaptionLine, Event, EventKind, NewProposal, NewReactionProposal, Outcome, Proposal,
13 ProposalImage, ProposalMention, ReactionOutcome, ReactionProposal, UiEvent,
13 ProposalImage, ProposalMention, ReactionOutcome, ReactionProposal, UiEvent,
14};
14};
15pub use policy::{Access, AgentPolicy, ConversationKind, DEFAULT_PORT};
15pub use policy::{Access, AgentPolicy, ConversationKind, DEFAULT_PORT};
16pub use remote::{ListedTool, ToolSession};
16pub use server::{ServerError, ServerHandle, start};
17pub use server::{ServerError, ServerHandle, start};
17pub use settings::{
18pub use settings::{
18 load as load_policy, load_or_create_token, regenerate_token, save as save_policy,
19 load as load_policy, load_or_create_token, regenerate_token, save as save_policy,
19};
20};
20pub use source::{
21pub use source::{
21 BusySlot, CreatedMeeting, EncodedImage, FileInfo, MeetingDraft, PersonAvailability, ForwardedInfo, ImageInfo, ImageKind, LinkInfo, Meeting, MentionInfo, MessageExtras,
22 EncodedImage, FileInfo, ForwardedInfo, ImageInfo, ImageKind, LinkInfo, Meeting, MentionInfo,
22 QuoteInfo, ReactionInfo, SourceError, SourceFuture, TeamsSource, Transcript, TranscriptTurn,
23 MessageExtras, QuoteInfo, ReactionInfo, SourceError, SourceFuture, TeamsSource, Transcript,
24 TranscriptTurn,
23};
25};
24
26
25#[derive(Debug, Clone, PartialEq, Eq)]
27#[derive(Debug, Clone, PartialEq, Eq)]
crates/mcp/src/remote.rs added +73 −0
@@ -0,0 +1,73 @@
1 use rmcp::ServiceExt;
2 use rmcp::model::{CallToolRequestParams, ClientConfig};
3 use rmcp::transport::StreamableHttpClientTransport;
4 use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
5 use serde_json::{Map, Value};
6
7 use crate::McpEndpoint;
8
9 #[derive(Clone, Debug, PartialEq)]
10 pub struct ListedTool {
11 pub name: String,
12 pub description: String,
13 pub parameters: Value,
14 }
15
16 pub struct ToolSession {
17 client: rmcp::service::RunningService<rmcp::RoleClient, ClientConfig>,
18 }
19
20 impl ToolSession {
21 pub async fn connect(endpoint: &McpEndpoint) -> Result<Self, String> {
22 let transport = StreamableHttpClientTransport::from_config(
23 StreamableHttpClientTransportConfig::with_uri(endpoint.url.clone())
24 .auth_header(endpoint.token.clone()),
25 );
26 let client = ClientConfig::default()
27 .serve(transport)
28 .await
29 .map_err(|error| error.to_string())?;
30 Ok(Self { client })
31 }
32
33 pub async fn tools(&self) -> Result<Vec<ListedTool>, String> {
34 let tools = self
35 .client
36 .list_all_tools()
37 .await
38 .map_err(|error| error.to_string())?;
39 Ok(tools
40 .into_iter()
41 .map(|tool| ListedTool {
42 name: tool.name.to_string(),
43 description: tool.description.unwrap_or_default().to_string(),
44 parameters: Value::Object(tool.input_schema.as_ref().clone()),
45 })
46 .collect())
47 }
48
49 pub async fn call(&self, name: &str, arguments: &str) -> Result<String, String> {
50 let parsed: Value = serde_json::from_str(arguments).unwrap_or(Value::Object(Map::new()));
51 let arguments = parsed.as_object().cloned().unwrap_or_default();
52 let params = CallToolRequestParams::new(name.to_owned()).with_arguments(arguments);
53 let result = self
54 .client
55 .call_tool(params)
56 .await
57 .map_err(|error| error.to_string())?;
58 let text = result
59 .content
60 .iter()
61 .filter_map(|content| content.as_text().map(|text| text.text.clone()))
62 .collect::<Vec<_>>()
63 .join("\n");
64 if result.is_error == Some(true) {
65 return Err(if text.is_empty() {
66 format!("{name} failed")
67 } else {
68 text
69 });
70 }
71 Ok(text)
72 }
73 }
@@ -0,0 +1,73 @@
1use rmcp::ServiceExt;
2use rmcp::model::{CallToolRequestParams, ClientConfig};
3use rmcp::transport::StreamableHttpClientTransport;
4use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
5use serde_json::{Map, Value};
6
7use crate::McpEndpoint;
8
9#[derive(Clone, Debug, PartialEq)]
10pub struct ListedTool {
11 pub name: String,
12 pub description: String,
13 pub parameters: Value,
14}
15
16pub struct ToolSession {
17 client: rmcp::service::RunningService<rmcp::RoleClient, ClientConfig>,
18}
19
20impl ToolSession {
21 pub async fn connect(endpoint: &McpEndpoint) -> Result<Self, String> {
22 let transport = StreamableHttpClientTransport::from_config(
23 StreamableHttpClientTransportConfig::with_uri(endpoint.url.clone())
24 .auth_header(endpoint.token.clone()),
25 );
26 let client = ClientConfig::default()
27 .serve(transport)
28 .await
29 .map_err(|error| error.to_string())?;
30 Ok(Self { client })
31 }
32
33 pub async fn tools(&self) -> Result<Vec<ListedTool>, String> {
34 let tools = self
35 .client
36 .list_all_tools()
37 .await
38 .map_err(|error| error.to_string())?;
39 Ok(tools
40 .into_iter()
41 .map(|tool| ListedTool {
42 name: tool.name.to_string(),
43 description: tool.description.unwrap_or_default().to_string(),
44 parameters: Value::Object(tool.input_schema.as_ref().clone()),
45 })
46 .collect())
47 }
48
49 pub async fn call(&self, name: &str, arguments: &str) -> Result<String, String> {
50 let parsed: Value = serde_json::from_str(arguments).unwrap_or(Value::Object(Map::new()));
51 let arguments = parsed.as_object().cloned().unwrap_or_default();
52 let params = CallToolRequestParams::new(name.to_owned()).with_arguments(arguments);
53 let result = self
54 .client
55 .call_tool(params)
56 .await
57 .map_err(|error| error.to_string())?;
58 let text = result
59 .content
60 .iter()
61 .filter_map(|content| content.as_text().map(|text| text.text.clone()))
62 .collect::<Vec<_>>()
63 .join("\n");
64 if result.is_error == Some(true) {
65 return Err(if text.is_empty() {
66 format!("{name} failed")
67 } else {
68 text
69 });
70 }
71 Ok(text)
72 }
73}
crates/mcp/tests/http.rs +3 −1
@@ -15,7 +15,9 @@ use rmcp::service::RunningService;
15 15 use rmcp::transport::StreamableHttpClientTransport;
16 16 use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
17 17 use serde_json::{Value, json};
18 use store::{ChannelReadState, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamRecord};
18 use store::{
19 ChannelReadState, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamRecord,
20 };
19 21 use tokio::io::{AsyncReadExt, AsyncWriteExt};
20 22 use tokio::net::TcpStream;
21 23
@@ -15,7 +15,9 @@ use rmcp::service::RunningService;
15use rmcp::transport::StreamableHttpClientTransport;
15use rmcp::transport::StreamableHttpClientTransport;
16use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
16use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
17use serde_json::{Value, json};
17use serde_json::{Value, json};
18use store::{ChannelReadState, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamRecord};
18use store::{
19 ChannelReadState, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamRecord,
20};
19use tokio::io::{AsyncReadExt, AsyncWriteExt};
21use tokio::io::{AsyncReadExt, AsyncWriteExt};
20use tokio::net::TcpStream;
22use tokio::net::TcpStream;
21
23