BlueGit

ict rusty-teams

refactor(app): extract app-state crate

- State, models and actions move from `app` to the new `app-state` crate (lib `state`)
- `app` keeps only views, windows and main
- Agent run test fixture moves to `agents/fixtures.rs` (feature `test-support`)
- Card input tests move next to the views
- Dead-code warning in call report storage gated to non-test builds

Windows release build after a one-line change:

| Changed crate | Rebuild |
|---|---|
| `app` (views) | 22 s |
| `app-state` | 45 s |

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-15 · 6 weeks ago

Hash
d39bdfed04f6589e95cdb23854430df9cdf89649
Parent
2f39a9c0
91 files changed +746 −652
Cargo.lock +30 −0
@@ -278,6 +278,7 @@ dependencies = [
278 278 "agents",
279 279 "app-base",
280 280 "app-call-model",
281 "app-state",
281 282 "app-ui-kit",
282 283 "calling",
283 284 "chatsvc",
@@ -355,6 +356,35 @@ dependencies = [
355 356 "uuid",
356 357 ]
357 358
359 [[package]]
360 name = "app-state"
361 version = "0.1.0"
362 dependencies = [
363 "agents",
364 "app-base",
365 "app-call-model",
366 "app-ui-kit",
367 "calling",
368 "chatsvc",
369 "chrono",
370 "directories",
371 "gpui-kit",
372 "graph",
373 "image",
374 "log",
375 "mcp",
376 "regex",
377 "serde",
378 "serde_json",
379 "session",
380 "store",
381 "teams-core",
382 "tempfile",
383 "tokio",
384 "uuid",
385 "webview",
386 ]
387
358 388 [[package]]
359 389 name = "app-ui-kit"
360 390 version = "0.1.0"
@@ -278,6 +278,7 @@ dependencies = [
278 "agents",
278 "agents",
279 "app-base",
279 "app-base",
280 "app-call-model",
280 "app-call-model",
281 "app-state",
281 "app-ui-kit",
282 "app-ui-kit",
282 "calling",
283 "calling",
283 "chatsvc",
284 "chatsvc",
@@ -355,6 +356,35 @@ dependencies = [
355 "uuid",
356 "uuid",
356]
357]
357
358
359[[package]]
360name = "app-state"
361version = "0.1.0"
362dependencies = [
363 "agents",
364 "app-base",
365 "app-call-model",
366 "app-ui-kit",
367 "calling",
368 "chatsvc",
369 "chrono",
370 "directories",
371 "gpui-kit",
372 "graph",
373 "image",
374 "log",
375 "mcp",
376 "regex",
377 "serde",
378 "serde_json",
379 "session",
380 "store",
381 "teams-core",
382 "tempfile",
383 "tokio",
384 "uuid",
385 "webview",
386]
387
358[[package]]
388[[package]]
359name = "app-ui-kit"
389name = "app-ui-kit"
360version = "0.1.0"
390version = "0.1.0"
Cargo.toml +4 −0
@@ -30,6 +30,7 @@ uuid = { version = "1", default-features = false, features = ["v4"] }
30 30
31 31 app-base = { path = "crates/app-base" }
32 32 app-call-model = { path = "crates/app-call-model" }
33 app-state = { path = "crates/app-state" }
33 34 app-ui-kit = { path = "crates/app-ui-kit" }
34 35 agents = { path = "crates/agents" }
35 36 session = { path = "crates/session" }
@@ -66,3 +67,6 @@ opt-level = 1
66 67
67 68 [profile.release.package.app-ui-kit]
68 69 opt-level = 1
70
71 [profile.release.package.app-state]
72 opt-level = 1
@@ -30,6 +30,7 @@ uuid = { version = "1", default-features = false, features = ["v4"] }
30
30
31app-base = { path = "crates/app-base" }
31app-base = { path = "crates/app-base" }
32app-call-model = { path = "crates/app-call-model" }
32app-call-model = { path = "crates/app-call-model" }
33app-state = { path = "crates/app-state" }
33app-ui-kit = { path = "crates/app-ui-kit" }
34app-ui-kit = { path = "crates/app-ui-kit" }
34agents = { path = "crates/agents" }
35agents = { path = "crates/agents" }
35session = { path = "crates/session" }
36session = { path = "crates/session" }
@@ -66,3 +67,6 @@ opt-level = 1
66
67
67[profile.release.package.app-ui-kit]
68[profile.release.package.app-ui-kit]
68opt-level = 1
69opt-level = 1
70
71[profile.release.package.app-state]
72opt-level = 1
crates/app-call-model/src/report/storage.rs +1 −0
@@ -4,6 +4,7 @@ use std::path::{Path, PathBuf};
4 4
5 5 use super::Document;
6 6
7 #[cfg(not(test))]
7 8 const REPORT_DIRECTORY: &str = "call-reports";
8 9 const KEEP_REPORTS: usize = 30;
9 10 const JSON_EXTENSION: &str = "json";
@@ -4,6 +4,7 @@ use std::path::{Path, PathBuf};
4
4
5use super::Document;
5use super::Document;
6
6
7#[cfg(not(test))]
7const REPORT_DIRECTORY: &str = "call-reports";
8const REPORT_DIRECTORY: &str = "call-reports";
8const KEEP_REPORTS: usize = 30;
9const KEEP_REPORTS: usize = 30;
9const JSON_EXTENSION: &str = "json";
10const JSON_EXTENSION: &str = "json";
crates/app-state/Cargo.toml added +42 −0
@@ -0,0 +1,42 @@
1 [package]
2 name = "app-state"
3 edition.workspace = true
4 version.workspace = true
5 license.workspace = true
6 publish.workspace = true
7
8 [features]
9 test-support = []
10
11 [lib]
12 name = "state"
13
14 [dev-dependencies]
15 gpui-kit = { workspace = true, features = ["test-support"] }
16 tempfile.workspace = true
17
18 [dependencies]
19 agents.workspace = true
20 app-base.workspace = true
21 app-call-model.workspace = true
22 app-ui-kit.workspace = true
23 calling.workspace = true
24 chatsvc.workspace = true
25 chrono.workspace = true
26 directories.workspace = true
27 gpui-kit.workspace = true
28 graph.workspace = true
29 log = "0.4"
30 mcp.workspace = true
31 regex.workspace = true
32 serde.workspace = true
33 serde_json.workspace = true
34 session.workspace = true
35 store.workspace = true
36 teams-core.workspace = true
37 tokio.workspace = true
38 uuid.workspace = true
39 image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
40
41 [target.'cfg(windows)'.dependencies]
42 webview.workspace = true
@@ -0,0 +1,42 @@
1[package]
2name = "app-state"
3edition.workspace = true
4version.workspace = true
5license.workspace = true
6publish.workspace = true
7
8[features]
9test-support = []
10
11[lib]
12name = "state"
13
14[dev-dependencies]
15gpui-kit = { workspace = true, features = ["test-support"] }
16tempfile.workspace = true
17
18[dependencies]
19agents.workspace = true
20app-base.workspace = true
21app-call-model.workspace = true
22app-ui-kit.workspace = true
23calling.workspace = true
24chatsvc.workspace = true
25chrono.workspace = true
26directories.workspace = true
27gpui-kit.workspace = true
28graph.workspace = true
29log = "0.4"
30mcp.workspace = true
31regex.workspace = true
32serde.workspace = true
33serde_json.workspace = true
34session.workspace = true
35store.workspace = true
36teams-core.workspace = true
37tokio.workspace = true
38uuid.workspace = true
39image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
40
41[target.'cfg(windows)'.dependencies]
42webview.workspace = true
crates/app/src/activity/feed.rs crates/app-state/src/activity/feed.rs renamed +0 −0
crates/app/src/activity/mod.rs crates/app-state/src/activity/mod.rs renamed +3 −3
@@ -1,6 +1,6 @@
1 mod feed;
2 mod reactions;
3 mod service;
1 pub mod feed;
2 pub mod reactions;
3 pub mod service;
4 4
5 5 pub use feed::{Actor, Entry, Filter, Kind};
6 6 pub use service::ActivityCenter;
@@ -1,6 +1,6 @@
1mod feed;
1pub mod feed;
2mod reactions;
2pub mod reactions;
3mod service;
3pub mod service;
4
4
5pub use feed::{Actor, Entry, Filter, Kind};
5pub use feed::{Actor, Entry, Filter, Kind};
6pub use service::ActivityCenter;
6pub use service::ActivityCenter;
crates/app/src/activity/reactions.rs crates/app-state/src/activity/reactions.rs renamed +0 −0
crates/app/src/activity/service.rs crates/app-state/src/activity/service.rs renamed +0 −0
crates/app/src/agent_api/body.rs crates/app-state/src/agent_api/body.rs renamed +0 −0
crates/app/src/agent_api/bridge.rs crates/app-state/src/agent_api/bridge.rs renamed +0 −0
crates/app/src/agent_api/mod.rs crates/app-state/src/agent_api/mod.rs renamed +2 −2
@@ -1,6 +1,6 @@
1 mod bridge;
1 pub mod bridge;
2 2 pub mod body;
3 mod source;
3 pub mod source;
4 4
5 5 use std::collections::{BTreeSet, HashMap};
6 6 use std::sync::Arc;
@@ -1,6 +1,6 @@
1mod bridge;
1pub mod bridge;
2pub mod body;
2pub mod body;
3mod source;
3pub mod source;
4
4
5use std::collections::{BTreeSet, HashMap};
5use std::collections::{BTreeSet, HashMap};
6use std::sync::Arc;
6use std::sync::Arc;
crates/app/src/agent_api/source.rs crates/app-state/src/agent_api/source.rs renamed +0 −0
crates/app/src/agents/demo.rs crates/app-state/src/agents/demo.rs renamed +0 −0
crates/app-state/src/agents/fixtures.rs added +35 −0
@@ -0,0 +1,35 @@
1 use std::time::Duration;
2
3 use chrono::{TimeZone, Utc};
4
5 use super::runs::{AgentRun, RunState};
6
7 pub fn finished_run(id: u64) -> AgentRun {
8 AgentRun {
9 id,
10 action_id: "answer-this".to_owned(),
11 action_label: "Answer this".to_owned(),
12 agent_id: "claude".to_owned(),
13 agent_name: "Claude Code".to_owned(),
14 conversation_id: "19:chat".to_owned(),
15 message_id: format!("m{id}"),
16 chat_title: "Ops".to_owned(),
17 sender_name: "Ada".to_owned(),
18 session_id: format!("session-{id}"),
19 working_dir: "~".to_owned(),
20 extra: String::new(),
21 state: RunState::Done,
22 current_step: "Done".to_owned(),
23 steps: vec![(Duration::from_secs(3), "Read a.rs".to_owned())],
24 final_text: "ok".to_owned(),
25 started_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
26 ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),
27 expanded: false,
28 dismissed: false,
29 process_id: None,
30 pending_prompt: None,
31 sent_to: None,
32 launch_session_id: None,
33 launched: true,
34 }
35 }
@@ -0,0 +1,35 @@
1use std::time::Duration;
2
3use chrono::{TimeZone, Utc};
4
5use super::runs::{AgentRun, RunState};
6
7pub fn finished_run(id: u64) -> AgentRun {
8 AgentRun {
9 id,
10 action_id: "answer-this".to_owned(),
11 action_label: "Answer this".to_owned(),
12 agent_id: "claude".to_owned(),
13 agent_name: "Claude Code".to_owned(),
14 conversation_id: "19:chat".to_owned(),
15 message_id: format!("m{id}"),
16 chat_title: "Ops".to_owned(),
17 sender_name: "Ada".to_owned(),
18 session_id: format!("session-{id}"),
19 working_dir: "~".to_owned(),
20 extra: String::new(),
21 state: RunState::Done,
22 current_step: "Done".to_owned(),
23 steps: vec![(Duration::from_secs(3), "Read a.rs".to_owned())],
24 final_text: "ok".to_owned(),
25 started_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
26 ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),
27 expanded: false,
28 dismissed: false,
29 process_id: None,
30 pending_prompt: None,
31 sent_to: None,
32 launch_session_id: None,
33 launched: true,
34 }
35}
crates/app/src/agents/kills.rs crates/app-state/src/agents/kills.rs renamed +0 −0
crates/app/src/agents/mcp_bridge.rs crates/app-state/src/agents/mcp_bridge.rs renamed +0 −0
crates/app/src/agents/message_context.rs crates/app-state/src/agents/message_context.rs renamed +0 −0
crates/app-state/src/agents/mod.rs added +207 −0
@@ -0,0 +1,207 @@
1 pub mod demo;
2 #[cfg(any(test, feature = "test-support"))]
3 pub mod fixtures;
4 pub mod kills;
5 pub mod mcp_bridge;
6 pub mod message_context;
7 pub mod runs;
8 pub mod session_options;
9 pub mod store;
10
11 use std::path::PathBuf;
12 use std::time::Duration;
13
14 pub use app_base::agents::{lanes, settings_problems};
15 pub use app_ui_kit::{settings_controls, spinner};
16 use agents::{AgentAction, Environment};
17 use directories::ProjectDirs;
18 use gpui_kit::*;
19
20 pub use runs::{
21 AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions, StartRequest, needs_dialog,
22 };
23
24 use crate::app_state::{AppHandle, AppState};
25
26 pub fn install(app: Entity<AppState>, cx: &mut App) {
27 let runs = cx.new(|cx| AgentRuns::new(app, cx));
28 cx.set_global(AgentRunsHandle(runs));
29 }
30
31 const MCP_POLL_INTERVAL: Duration = Duration::from_millis(100);
32 const MCP_WAIT_LIMIT: Duration = Duration::from_secs(5);
33 const MCP_CONFIG_FOLDER: &str = "agent-mcp";
34
35 fn mcp_config_directory() -> Option<PathBuf> {
36 ProjectDirs::from("", "", ::store::DATA_DIR_NAME)
37 .map(|directories| directories.data_local_dir().join(MCP_CONFIG_FOLDER))
38 }
39
40 pub fn runs_handle(cx: &App) -> Option<Entity<AgentRuns>> {
41 cx.try_global::<AgentRunsHandle>()
42 .map(|handle| handle.0.clone())
43 }
44
45 pub fn raise_notice(text: String, cx: &mut App) {
46 let Some(handle) = cx.try_global::<AppHandle>() else {
47 return;
48 };
49 handle
50 .0
51 .clone()
52 .update(cx, |state, cx| state.raise_notice(text, None, cx));
53 }
54
55 pub fn start_run(
56 action_id: &str,
57 conversation_id: &str,
58 message_id: &str,
59 extra: &str,
60 options: StartOptions,
61 cx: &mut App,
62 ) {
63 let Some(runs) = runs_handle(cx) else {
64 return;
65 };
66 let started = runs.update(cx, |runs, cx| {
67 runs.start_with(action_id, conversation_id, message_id, extra, options, cx)
68 });
69 if let Err(error) = started {
70 raise_notice(format!("Agent could not start: {error}"), cx);
71 }
72 }
73
74 pub fn start_run_when_mcp_ready(
75 action_id: String,
76 conversation_id: String,
77 message_id: String,
78 extra: String,
79 options: StartOptions,
80 cx: &mut App,
81 ) {
82 cx.spawn(async move |cx| {
83 let mut waited = Duration::ZERO;
84 while waited < MCP_WAIT_LIMIT && !cx.update(|cx| mcp_bridge::endpoint(cx).is_some()) {
85 cx.background_executor().timer(MCP_POLL_INTERVAL).await;
86 waited += MCP_POLL_INTERVAL;
87 }
88 cx.update(|cx| {
89 if mcp_bridge::endpoint(cx).is_none() {
90 raise_notice(
91 "MCP server is not running - the agent cannot propose a reply".to_owned(),
92 cx,
93 );
94 }
95 start_run(
96 &action_id,
97 &conversation_id,
98 &message_id,
99 &extra,
100 options,
101 cx,
102 );
103 });
104 })
105 .detach();
106 }
107
108 pub fn retry_run(run_id: u64, cx: &mut App) {
109 let Some(runs) = runs_handle(cx) else {
110 return;
111 };
112 let retried = runs.update(cx, |runs, cx| runs.retry(run_id, cx));
113 if let Err(error) = retried {
114 raise_notice(format!("Agent could not start: {error}"), cx);
115 }
116 }
117
118 pub fn delegate(request: StartRequest, cx: &mut App) {
119 let Some(runs) = runs_handle(cx) else {
120 return;
121 };
122 let action = runs
123 .read(cx)
124 .settings()
125 .actions
126 .iter()
127 .find(|action| action.id == request.action_id)
128 .cloned();
129 let Some(action) = action else {
130 return;
131 };
132 let allowed = mcp_bridge::chat_allowed(&request.conversation_id, cx);
133 if needs_dialog(&action, allowed) {
134 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::StartRequested(request)));
135 } else {
136 start_run(
137 &request.action_id,
138 &request.conversation_id,
139 &request.message_id,
140 "",
141 StartOptions::default(),
142 cx,
143 );
144 }
145 }
146
147 pub fn open_settings(cx: &mut App) {
148 if let Some(runs) = runs_handle(cx) {
149 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::OpenSettings));
150 }
151 }
152
153 pub fn has_session(session_id: &str, cx: &App) -> bool {
154 runs_handle(cx).is_some_and(|runs| runs.read(cx).by_session(session_id).is_some())
155 }
156
157 pub fn open_session(session_id: &str, cx: &mut App) {
158 let run = runs_handle(cx).and_then(|runs| runs.read(cx).by_session(session_id).cloned());
159 match run {
160 Some(run) => open_run_session(&run, cx),
161 None => raise_notice(
162 "This session was not started from this app, open it in your terminal".to_owned(),
163 cx,
164 ),
165 }
166 }
167
168 fn open_run_session(run: &AgentRun, cx: &mut App) {
169 let Some(handle) = cx.try_global::<AppHandle>() else {
170 return;
171 };
172 let settings = store::load_settings(&handle.0.read(cx).store);
173 let Some(profile) = settings
174 .agents
175 .iter()
176 .find(|profile| profile.id == run.agent_id)
177 else {
178 raise_notice("The agent of this run no longer exists".to_owned(), cx);
179 return;
180 };
181 let action = AgentAction {
182 working_dir: run.working_dir.clone(),
183 ..AgentAction::default()
184 };
185 let spawned = agents::open_session_invocation(profile, &action, &run.session_id)
186 .map_err(|error| error.to_string())
187 .and_then(|invocation| {
188 std::process::Command::new(&invocation.program)
189 .args(&invocation.args)
190 .spawn()
191 .map(drop)
192 .map_err(|error| error.to_string())
193 });
194 if let Err(error) = spawned {
195 raise_notice(format!("Could not open the session: {error}"), cx);
196 }
197 }
198
199 pub fn environment_label(environment: &Environment) -> String {
200 match environment {
201 Environment::Host => "Windows".to_owned(),
202 Environment::Wsl { distro: None } => "WSL".to_owned(),
203 Environment::Wsl {
204 distro: Some(distro),
205 } => format!("WSL - {distro}"),
206 }
207 }
@@ -0,0 +1,207 @@
1pub mod demo;
2#[cfg(any(test, feature = "test-support"))]
3pub mod fixtures;
4pub mod kills;
5pub mod mcp_bridge;
6pub mod message_context;
7pub mod runs;
8pub mod session_options;
9pub mod store;
10
11use std::path::PathBuf;
12use std::time::Duration;
13
14pub use app_base::agents::{lanes, settings_problems};
15pub use app_ui_kit::{settings_controls, spinner};
16use agents::{AgentAction, Environment};
17use directories::ProjectDirs;
18use gpui_kit::*;
19
20pub use runs::{
21 AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions, StartRequest, needs_dialog,
22};
23
24use crate::app_state::{AppHandle, AppState};
25
26pub fn install(app: Entity<AppState>, cx: &mut App) {
27 let runs = cx.new(|cx| AgentRuns::new(app, cx));
28 cx.set_global(AgentRunsHandle(runs));
29}
30
31const MCP_POLL_INTERVAL: Duration = Duration::from_millis(100);
32const MCP_WAIT_LIMIT: Duration = Duration::from_secs(5);
33const MCP_CONFIG_FOLDER: &str = "agent-mcp";
34
35fn mcp_config_directory() -> Option<PathBuf> {
36 ProjectDirs::from("", "", ::store::DATA_DIR_NAME)
37 .map(|directories| directories.data_local_dir().join(MCP_CONFIG_FOLDER))
38}
39
40pub fn runs_handle(cx: &App) -> Option<Entity<AgentRuns>> {
41 cx.try_global::<AgentRunsHandle>()
42 .map(|handle| handle.0.clone())
43}
44
45pub fn raise_notice(text: String, cx: &mut App) {
46 let Some(handle) = cx.try_global::<AppHandle>() else {
47 return;
48 };
49 handle
50 .0
51 .clone()
52 .update(cx, |state, cx| state.raise_notice(text, None, cx));
53}
54
55pub fn start_run(
56 action_id: &str,
57 conversation_id: &str,
58 message_id: &str,
59 extra: &str,
60 options: StartOptions,
61 cx: &mut App,
62) {
63 let Some(runs) = runs_handle(cx) else {
64 return;
65 };
66 let started = runs.update(cx, |runs, cx| {
67 runs.start_with(action_id, conversation_id, message_id, extra, options, cx)
68 });
69 if let Err(error) = started {
70 raise_notice(format!("Agent could not start: {error}"), cx);
71 }
72}
73
74pub fn start_run_when_mcp_ready(
75 action_id: String,
76 conversation_id: String,
77 message_id: String,
78 extra: String,
79 options: StartOptions,
80 cx: &mut App,
81) {
82 cx.spawn(async move |cx| {
83 let mut waited = Duration::ZERO;
84 while waited < MCP_WAIT_LIMIT && !cx.update(|cx| mcp_bridge::endpoint(cx).is_some()) {
85 cx.background_executor().timer(MCP_POLL_INTERVAL).await;
86 waited += MCP_POLL_INTERVAL;
87 }
88 cx.update(|cx| {
89 if mcp_bridge::endpoint(cx).is_none() {
90 raise_notice(
91 "MCP server is not running - the agent cannot propose a reply".to_owned(),
92 cx,
93 );
94 }
95 start_run(
96 &action_id,
97 &conversation_id,
98 &message_id,
99 &extra,
100 options,
101 cx,
102 );
103 });
104 })
105 .detach();
106}
107
108pub fn retry_run(run_id: u64, cx: &mut App) {
109 let Some(runs) = runs_handle(cx) else {
110 return;
111 };
112 let retried = runs.update(cx, |runs, cx| runs.retry(run_id, cx));
113 if let Err(error) = retried {
114 raise_notice(format!("Agent could not start: {error}"), cx);
115 }
116}
117
118pub fn delegate(request: StartRequest, cx: &mut App) {
119 let Some(runs) = runs_handle(cx) else {
120 return;
121 };
122 let action = runs
123 .read(cx)
124 .settings()
125 .actions
126 .iter()
127 .find(|action| action.id == request.action_id)
128 .cloned();
129 let Some(action) = action else {
130 return;
131 };
132 let allowed = mcp_bridge::chat_allowed(&request.conversation_id, cx);
133 if needs_dialog(&action, allowed) {
134 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::StartRequested(request)));
135 } else {
136 start_run(
137 &request.action_id,
138 &request.conversation_id,
139 &request.message_id,
140 "",
141 StartOptions::default(),
142 cx,
143 );
144 }
145}
146
147pub fn open_settings(cx: &mut App) {
148 if let Some(runs) = runs_handle(cx) {
149 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::OpenSettings));
150 }
151}
152
153pub fn has_session(session_id: &str, cx: &App) -> bool {
154 runs_handle(cx).is_some_and(|runs| runs.read(cx).by_session(session_id).is_some())
155}
156
157pub fn open_session(session_id: &str, cx: &mut App) {
158 let run = runs_handle(cx).and_then(|runs| runs.read(cx).by_session(session_id).cloned());
159 match run {
160 Some(run) => open_run_session(&run, cx),
161 None => raise_notice(
162 "This session was not started from this app, open it in your terminal".to_owned(),
163 cx,
164 ),
165 }
166}
167
168fn open_run_session(run: &AgentRun, cx: &mut App) {
169 let Some(handle) = cx.try_global::<AppHandle>() else {
170 return;
171 };
172 let settings = store::load_settings(&handle.0.read(cx).store);
173 let Some(profile) = settings
174 .agents
175 .iter()
176 .find(|profile| profile.id == run.agent_id)
177 else {
178 raise_notice("The agent of this run no longer exists".to_owned(), cx);
179 return;
180 };
181 let action = AgentAction {
182 working_dir: run.working_dir.clone(),
183 ..AgentAction::default()
184 };
185 let spawned = agents::open_session_invocation(profile, &action, &run.session_id)
186 .map_err(|error| error.to_string())
187 .and_then(|invocation| {
188 std::process::Command::new(&invocation.program)
189 .args(&invocation.args)
190 .spawn()
191 .map(drop)
192 .map_err(|error| error.to_string())
193 });
194 if let Err(error) = spawned {
195 raise_notice(format!("Could not open the session: {error}"), cx);
196 }
197}
198
199pub fn environment_label(environment: &Environment) -> String {
200 match environment {
201 Environment::Host => "Windows".to_owned(),
202 Environment::Wsl { distro: None } => "WSL".to_owned(),
203 Environment::Wsl {
204 distro: Some(distro),
205 } => format!("WSL - {distro}"),
206 }
207}
crates/app/src/agents/runs.rs crates/app-state/src/agents/runs.rs renamed +1 −30
@@ -1146,6 +1146,7 @@ pub(super) mod tests {
1146 1146
1147 1147 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1148 1148
1149 use super::super::fixtures::finished_run;
1149 1150 use super::{
1150 1151 AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, api_retry_text,
1151 1152 format_elapsed, needs_dialog, run_store,
@@ -1161,36 +1162,6 @@ pub(super) mod tests {
1161 1162 assert!(needs_dialog(&asking, true));
1162 1163 }
1163 1164
1164 pub fn finished_run(id: u64) -> AgentRun {
1165 AgentRun {
1166 id,
1167 action_id: "answer-this".to_owned(),
1168 action_label: "Answer this".to_owned(),
1169 agent_id: "claude".to_owned(),
1170 agent_name: "Claude Code".to_owned(),
1171 conversation_id: "19:chat".to_owned(),
1172 message_id: format!("m{id}"),
1173 chat_title: "Ops".to_owned(),
1174 sender_name: "Ada".to_owned(),
1175 session_id: format!("session-{id}"),
1176 working_dir: "~".to_owned(),
1177 extra: String::new(),
1178 state: RunState::Done,
1179 current_step: "Done".to_owned(),
1180 steps: vec![(Duration::from_secs(3), "Read a.rs".to_owned())],
1181 final_text: "ok".to_owned(),
1182 started_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
1183 ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),
1184 expanded: false,
1185 dismissed: false,
1186 process_id: None,
1187 pending_prompt: None,
1188 sent_to: None,
1189 launch_session_id: None,
1190 launched: true,
1191 }
1192 }
1193
1194 1165 fn fake_settings(command: &str) -> AgentSettings {
1195 1166 let profile = AgentProfile {
1196 1167 id: "fake".to_owned(),
@@ -1146,6 +1146,7 @@ pub(super) mod tests {
1146
1146
1147 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1147 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1148
1148
1149 use super::super::fixtures::finished_run;
1149 use super::{
1150 use super::{
1150 AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, api_retry_text,
1151 AgentRun, AgentRuns, RunState, SessionTarget, StartOptions, Utc, api_retry_text,
1151 format_elapsed, needs_dialog, run_store,
1152 format_elapsed, needs_dialog, run_store,
@@ -1161,36 +1162,6 @@ pub(super) mod tests {
1161 assert!(needs_dialog(&asking, true));
1162 assert!(needs_dialog(&asking, true));
1162 }
1163 }
1163
1164
1164 pub fn finished_run(id: u64) -> AgentRun {
1165 AgentRun {
1166 id,
1167 action_id: "answer-this".to_owned(),
1168 action_label: "Answer this".to_owned(),
1169 agent_id: "claude".to_owned(),
1170 agent_name: "Claude Code".to_owned(),
1171 conversation_id: "19:chat".to_owned(),
1172 message_id: format!("m{id}"),
1173 chat_title: "Ops".to_owned(),
1174 sender_name: "Ada".to_owned(),
1175 session_id: format!("session-{id}"),
1176 working_dir: "~".to_owned(),
1177 extra: String::new(),
1178 state: RunState::Done,
1179 current_step: "Done".to_owned(),
1180 steps: vec![(Duration::from_secs(3), "Read a.rs".to_owned())],
1181 final_text: "ok".to_owned(),
1182 started_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
1183 ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),
1184 expanded: false,
1185 dismissed: false,
1186 process_id: None,
1187 pending_prompt: None,
1188 sent_to: None,
1189 launch_session_id: None,
1190 launched: true,
1191 }
1192 }
1193
1194 fn fake_settings(command: &str) -> AgentSettings {
1165 fn fake_settings(command: &str) -> AgentSettings {
1195 let profile = AgentProfile {
1166 let profile = AgentProfile {
1196 id: "fake".to_owned(),
1167 id: "fake".to_owned(),
crates/app/src/agents/session_options.rs crates/app-state/src/agents/session_options.rs renamed +3 −3
@@ -282,11 +282,11 @@ mod tests {
282 282 std::sync::Arc::new(store::Store::open_in_memory().unwrap()),
283 283 crate::app_state::Mode::default(),
284 284 );
285 let mut created = crate::agents::runs::tests::finished_run(1);
285 let mut created = crate::agents::fixtures::finished_run(1);
286 286 created.launched = true;
287 let mut never_started = crate::agents::runs::tests::finished_run(2);
287 let mut never_started = crate::agents::fixtures::finished_run(2);
288 288 never_started.launched = false;
289 let mut sent = crate::agents::runs::tests::finished_run(3);
289 let mut sent = crate::agents::fixtures::finished_run(3);
290 290 sent.launched = false;
291 291 sent.sent_to = Some(crate::agents::runs::SessionTarget {
292 292 session_id: sent.session_id.clone(),
@@ -282,11 +282,11 @@ mod tests {
282 std::sync::Arc::new(store::Store::open_in_memory().unwrap()),
282 std::sync::Arc::new(store::Store::open_in_memory().unwrap()),
283 crate::app_state::Mode::default(),
283 crate::app_state::Mode::default(),
284 );
284 );
285 let mut created = crate::agents::runs::tests::finished_run(1);
285 let mut created = crate::agents::fixtures::finished_run(1);
286 created.launched = true;
286 created.launched = true;
287 let mut never_started = crate::agents::runs::tests::finished_run(2);
287 let mut never_started = crate::agents::fixtures::finished_run(2);
288 never_started.launched = false;
288 never_started.launched = false;
289 let mut sent = crate::agents::runs::tests::finished_run(3);
289 let mut sent = crate::agents::fixtures::finished_run(3);
290 sent.launched = false;
290 sent.launched = false;
291 sent.sent_to = Some(crate::agents::runs::SessionTarget {
291 sent.sent_to = Some(crate::agents::runs::SessionTarget {
292 session_id: sent.session_id.clone(),
292 session_id: sent.session_id.clone(),
crates/app/src/agents/store.rs crates/app-state/src/agents/store.rs renamed +1 −1
@@ -51,7 +51,7 @@ mod tests {
51 51 use agents::AgentAction;
52 52
53 53 use super::*;
54 use crate::agents::runs::tests::finished_run;
54 use crate::agents::fixtures::finished_run;
55 55
56 56 #[test]
57 57 fn settings_round_trip_and_default_when_missing() {
@@ -51,7 +51,7 @@ mod tests {
51 use agents::AgentAction;
51 use agents::AgentAction;
52
52
53 use super::*;
53 use super::*;
54 use crate::agents::runs::tests::finished_run;
54 use crate::agents::fixtures::finished_run;
55
55
56 #[test]
56 #[test]
57 fn settings_round_trip_and_default_when_missing() {
57 fn settings_round_trip_and_default_when_missing() {
crates/app/src/app_state.rs crates/app-state/src/app_state.rs renamed +0 −0
crates/app/src/backend.rs crates/app-state/src/backend.rs renamed +0 −0
crates/app/src/call/actions.rs crates/app-state/src/call/actions.rs renamed +0 −0
crates/app/src/call/calendar.rs crates/app-state/src/call/calendar.rs renamed +0 −0
crates/app/src/call/consult.rs crates/app-state/src/call/consult.rs renamed +0 −0
crates/app/src/call/features.rs crates/app-state/src/call/features.rs renamed +0 −0
crates/app/src/call/history.rs crates/app-state/src/call/history.rs renamed +0 −0
crates/app/src/call/join.rs crates/app-state/src/call/join.rs renamed +0 −0
crates/app/src/call/launcher.rs crates/app-state/src/call/launcher.rs renamed +0 −0
crates/app/src/call/list.rs crates/app-state/src/call/list.rs renamed +0 −0
crates/app-state/src/call/mod.rs added +68 −0
@@ -0,0 +1,68 @@
1 pub mod actions;
2 pub mod calendar;
3 pub mod consult;
4 pub mod features;
5 pub mod history;
6 pub mod join;
7 pub mod launcher;
8 pub mod list;
9 pub mod overlay_layout;
10 pub mod people_actions;
11 pub mod prejoin;
12 pub mod record_load;
13 pub mod reminder;
14 pub mod share_actions;
15 pub mod schedule;
16 pub mod target;
17 pub mod view_actions;
18
19 pub use app_call_model::{
20 agenda, background, bubbles, caption_style, demo, fullscreen, health, media, mic,
21 model, options_dialog, people, preview, record_rights,
22 recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,
23 };
24
25 pub use actions::{load_camera, load_camera_effects, load_input, load_output, load_share_sound};
26 pub use mic::load_mic;
27 pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
28 pub use caption_style::{CaptionPosition, CaptionSize};
29 pub use background::{
30 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
31 load_custom_backgrounds,
32 };
33 pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};
34 pub use demo::DemoScene;
35 pub use features::TransferCandidate;
36 pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};
37 pub use history::CallRow;
38 pub use launcher::CallLauncher;
39 pub use list::{
40 AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
41 SECTION_HEIGHT,
42 };
43 pub use media::CallMedia;
44 pub use model::{
45 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
46 TileState,
47 };
48 pub use model::ConsultCall;
49 pub use options_dialog::OptionsDialog;
50 pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
51 pub use people::{PeopleSections, PersonRow, people_sections};
52 pub use share_actions::ZoomStep;
53 pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, ShareStage, load_flag, load_strip_width};
54 pub use preview::{CameraPreview, preview_backgrounds};
55 pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
56 pub use ring::{MissedCall, RingEntry, Rings};
57 pub use stage_split::{
58 GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP, gallery_split,
59 measured_stage, speaker_split, strip_split, video_wants,
60 };
61 pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};
62 pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
63 pub use record_rights::{RecordBlock, RecordFeature};
64 pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
65 pub use report::load_enabled as load_report_enabled;
66 pub use target::plan_for_chat;
67 pub use transcript::clock_label;
68 pub use view_settings::{CallLayout, ViewSettings};
@@ -0,0 +1,68 @@
1pub mod actions;
2pub mod calendar;
3pub mod consult;
4pub mod features;
5pub mod history;
6pub mod join;
7pub mod launcher;
8pub mod list;
9pub mod overlay_layout;
10pub mod people_actions;
11pub mod prejoin;
12pub mod record_load;
13pub mod reminder;
14pub mod share_actions;
15pub mod schedule;
16pub mod target;
17pub mod view_actions;
18
19pub use app_call_model::{
20 agenda, background, bubbles, caption_style, demo, fullscreen, health, media, mic,
21 model, options_dialog, people, preview, record_rights,
22 recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,
23};
24
25pub use actions::{load_camera, load_camera_effects, load_input, load_output, load_share_sound};
26pub use mic::load_mic;
27pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
28pub use caption_style::{CaptionPosition, CaptionSize};
29pub use background::{
30 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
31 load_custom_backgrounds,
32};
33pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};
34pub use demo::DemoScene;
35pub use features::TransferCandidate;
36pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};
37pub use history::CallRow;
38pub use launcher::CallLauncher;
39pub use list::{
40 AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
41 SECTION_HEIGHT,
42};
43pub use media::CallMedia;
44pub use model::{
45 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
46 TileState,
47};
48pub use model::ConsultCall;
49pub use options_dialog::OptionsDialog;
50pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
51pub use people::{PeopleSections, PersonRow, people_sections};
52pub use share_actions::ZoomStep;
53pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, ShareStage, load_flag, load_strip_width};
54pub use preview::{CameraPreview, preview_backgrounds};
55pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
56pub use ring::{MissedCall, RingEntry, Rings};
57pub use stage_split::{
58 GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP, gallery_split,
59 measured_stage, speaker_split, strip_split, video_wants,
60};
61pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};
62pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
63pub use record_rights::{RecordBlock, RecordFeature};
64pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
65pub use report::load_enabled as load_report_enabled;
66pub use target::plan_for_chat;
67pub use transcript::clock_label;
68pub use view_settings::{CallLayout, ViewSettings};
crates/app/src/call/overlay_layout.rs crates/app-state/src/call/overlay_layout.rs renamed +0 −0
crates/app/src/call/people_actions.rs crates/app-state/src/call/people_actions.rs renamed +0 −0
crates/app/src/call/prejoin.rs crates/app-state/src/call/prejoin.rs renamed +0 −0
crates/app/src/call/record_load.rs crates/app-state/src/call/record_load.rs renamed +0 −0
crates/app/src/call/reminder.rs crates/app-state/src/call/reminder.rs renamed +0 −0
crates/app/src/call/schedule.rs crates/app-state/src/call/schedule.rs renamed +0 −0
crates/app/src/call/share_actions.rs crates/app-state/src/call/share_actions.rs renamed +0 −0
crates/app/src/call/target.rs crates/app-state/src/call/target.rs renamed +0 −0
crates/app/src/call/view_actions.rs crates/app-state/src/call/view_actions.rs renamed +0 −0
crates/app/src/card_actions.rs crates/app-state/src/card_actions.rs renamed +2 −2
@@ -222,12 +222,12 @@ impl AppState {
222 222 .detach();
223 223 }
224 224
225 pub(crate) fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
225 pub fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
226 226 cx.emit(AppEvent::Cards(scope.conversation_id.clone()));
227 227 cx.notify();
228 228 }
229 229
230 pub(crate) fn replace_card(
230 pub fn replace_card(
231 231 &mut self,
232 232 scope: &CardScope,
233 233 json: &str,
@@ -222,12 +222,12 @@ impl AppState {
222 .detach();
222 .detach();
223 }
223 }
224
224
225 pub(crate) fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
225 pub fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
226 cx.emit(AppEvent::Cards(scope.conversation_id.clone()));
226 cx.emit(AppEvent::Cards(scope.conversation_id.clone()));
227 cx.notify();
227 cx.notify();
228 }
228 }
229
229
230 pub(crate) fn replace_card(
230 pub fn replace_card(
231 &mut self,
231 &mut self,
232 scope: &CardScope,
232 scope: &CardScope,
233 json: &str,
233 json: &str,
crates/app/src/card_inputs.rs crates/app-state/src/card_inputs.rs renamed +0 −259
@@ -569,262 +569,3 @@ impl AppState {
569 569 })
570 570 }
571 571 }
572
573 #[cfg(test)]
574 mod tests {
575 use std::sync::Arc;
576
577 use gpui_kit::{
578 AppContext as _, Context, Entity, IntoElement, Render, TestAppContext, VisualTestContext,
579 Window,
580 };
581 use serde_json::json;
582 use store::Store;
583 use teams_core::AdaptiveCard;
584
585 use super::InputField;
586 use crate::app_state::{AppHandle, AppState, Mode};
587 use crate::card_actions::CardTask;
588 use crate::card_state::{CardScope, Surface};
589 use crate::views::adaptive_card::card_view;
590
591 struct Harness {
592 app: Entity<AppState>,
593 scope: CardScope,
594 card: AdaptiveCard,
595 }
596
597 impl Render for Harness {
598 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
599 self.app.update(cx, |state, cx| {
600 state.ensure_card_inputs(&self.scope, &self.card, window, cx)
601 });
602 card_view(&self.card, &self.scope, cx)
603 }
604 }
605
606 fn form_card() -> AdaptiveCard {
607 let card = json!({
608 "body": [
609 {"type": "Input.Text", "id": "name", "label": "Name", "isRequired": true, "errorMessage": "Name needed"},
610 {"type": "Input.Toggle", "id": "agree", "title": "Agree"}
611 ],
612 "actions": [
613 {"type": "Action.Submit", "title": "Save", "data": {"action": "save"}},
614 {"type": "Action.Submit", "title": "Skip", "associatedInputs": "none", "data": {"action": "skip"}}
615 ]
616 });
617 AdaptiveCard::parse(&card.to_string()).unwrap()
618 }
619
620 fn typed_card() -> AdaptiveCard {
621 let card = json!({
622 "body": [
623 {"type": "Input.Text", "id": "code", "maxLength": 3, "regex": "^[a-z]+$", "errorMessage": "Letters only"},
624 {"type": "Input.Date", "id": "day", "value": "2026-11-02", "min": "2026-10-01", "max": "2026-12-31"},
625 {"type": "Input.Time", "id": "hour", "value": "09:30", "min": "10:00", "errorMessage": "Too early"},
626 {"type": "Input.Number", "id": "count", "value": 4},
627 {"type": "Input.Rating", "id": "stars", "value": 2, "allowHalf": true}
628 ],
629 "actions": [{"type": "Action.Submit", "title": "Save", "data": {"action": "save"}}]
630 });
631 AdaptiveCard::parse(&card.to_string()).unwrap()
632 }
633
634 fn open(
635 cx: &mut TestAppContext,
636 surface: Surface,
637 ) -> (
638 &mut VisualTestContext,
639 Entity<AppState>,
640 CardScope,
641 AdaptiveCard,
642 ) {
643 open_card(cx, surface, form_card())
644 }
645
646 fn open_card(
647 cx: &mut TestAppContext,
648 surface: Surface,
649 card: AdaptiveCard,
650 ) -> (
651 &mut VisualTestContext,
652 Entity<AppState>,
653 CardScope,
654 AdaptiveCard,
655 ) {
656 cx.update(gpui_kit::init);
657 let store = Arc::new(Store::open_in_memory().unwrap());
658 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
659 cx.update(|cx| cx.set_global(AppHandle(app.clone())));
660 let scope = CardScope {
661 surface,
662 ..CardScope::message("19:chat@thread.v2", "m1", 0)
663 };
664 let (_, window_cx) = cx.add_window_view({
665 let (app, scope, card) = (app.clone(), scope.clone(), card.clone());
666 move |_, _| Harness { app, scope, card }
667 });
668 window_cx.update(|window, cx| window.draw(cx).clear(cx));
669 (window_cx, app, scope, card)
670 }
671
672 fn focus_name_field(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
673 let key = scope.input_key("name");
674 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
675 let Some(InputField::Line(line)) = field else {
676 panic!("name is a single line field");
677 };
678 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
679 }
680
681 fn task_for(
682 cx: &mut VisualTestContext,
683 app: &Entity<AppState>,
684 scope: &CardScope,
685 card: &AdaptiveCard,
686 action_index: usize,
687 ) -> Option<CardTask> {
688 let action = card.actions[action_index].clone();
689 let inputs = card.own_inputs();
690 cx.update(|_, cx| app.update(cx, |state, cx| state.card_task(scope, action, &inputs, cx)))
691 }
692
693 fn object(pairs: &[(&str, &str)]) -> serde_json::Value {
694 serde_json::Value::Object(
695 pairs
696 .iter()
697 .map(|(key, value)| ((*key).to_owned(), serde_json::Value::from(*value)))
698 .collect(),
699 )
700 }
701
702 fn error_of(cx: &mut VisualTestContext, app: &Entity<AppState>, key: &str) -> Option<String> {
703 cx.update(|_, cx| app.read(cx).cards.input_error(key).map(str::to_owned))
704 }
705
706 fn type_name(
707 cx: &mut VisualTestContext,
708 app: &Entity<AppState>,
709 scope: &CardScope,
710 text: &str,
711 ) {
712 focus_name_field(cx, app, scope);
713 cx.simulate_input(text);
714 }
715
716 fn switch_agree(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
717 let key = scope.input_key("agree");
718 cx.update(|_, cx| {
719 app.update(cx, |state, cx| {
720 state.pick_card_input(scope, &key, "true".into(), cx)
721 })
722 });
723 }
724
725 fn sent_value(task: Option<CardTask>) -> serde_json::Value {
726 match task {
727 Some(CardTask::Action(action)) => action.invoke_payload().unwrap().value,
728 Some(CardTask::Submit(data)) => data,
729 None => serde_json::Value::Null,
730 }
731 }
732
733 #[gpui_kit::test]
734 fn typed_text_and_toggle_are_sent_with_the_action_data(cx: &mut TestAppContext) {
735 let (cx, app, scope, card) = open(cx, Surface::Message);
736 type_name(cx, &app, &scope, "Ada");
737 switch_agree(cx, &app, &scope);
738 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
739 assert_eq!(
740 sent,
741 object(&[("action", "save"), ("name", "Ada"), ("agree", "true")])
742 );
743 }
744
745 #[gpui_kit::test]
746 fn an_empty_required_input_blocks_the_send_until_it_changes(cx: &mut TestAppContext) {
747 let (cx, app, scope, card) = open(cx, Surface::Message);
748 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
749 let key = scope.input_key("name");
750 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Name needed"));
751 type_name(cx, &app, &scope, "A");
752 assert_eq!(error_of(cx, &app, &key), None);
753 assert!(task_for(cx, &app, &scope, &card, 0).is_some());
754 }
755
756 #[gpui_kit::test]
757 fn associated_inputs_none_skips_collection_and_validation(cx: &mut TestAppContext) {
758 let (cx, app, scope, card) = open(cx, Surface::Message);
759 let sent = sent_value(task_for(cx, &app, &scope, &card, 1));
760 assert_eq!(sent, object(&[("action", "skip")]));
761 }
762
763 #[gpui_kit::test]
764 fn a_dialog_submit_carries_the_collected_values(cx: &mut TestAppContext) {
765 let (cx, app, scope, card) = open(cx, Surface::Dialog);
766 type_name(cx, &app, &scope, "Ada");
767 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
768 assert_eq!(
769 sent,
770 object(&[("action", "save"), ("name", "Ada"), ("agree", "false")])
771 );
772 }
773
774 #[gpui_kit::test]
775 fn typing_past_the_max_length_is_ignored(cx: &mut TestAppContext) {
776 let (cx, app, scope, _) = open_card(cx, Surface::Message, typed_card());
777 let key = scope.input_key("code");
778 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
779 let Some(InputField::Line(line)) = field else {
780 panic!("code is a single line field");
781 };
782 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
783 cx.simulate_input("abcdef");
784 assert_eq!(
785 cx.update(|_, cx| app.read(cx).cards.input_text(&key, cx)),
786 "abc"
787 );
788 }
789
790 #[gpui_kit::test]
791 fn blur_validation_shows_the_error_message(cx: &mut TestAppContext) {
792 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
793 let key = scope.input_key("code");
794 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
795 let Some(InputField::Line(line)) = field else {
796 panic!("code is a single line field");
797 };
798 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
799 cx.simulate_input("AB");
800 let input = card.own_inputs().remove(0);
801 cx.update(|_, cx| {
802 app.update(cx, |state, cx| {
803 state.validate_card_input(&scope, &key, &input, cx)
804 })
805 });
806 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Letters only"));
807 }
808
809 #[gpui_kit::test]
810 fn date_time_and_rating_values_are_collected_with_their_types(cx: &mut TestAppContext) {
811 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
812 let hour_key = scope.input_key("hour");
813 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
814 assert_eq!(error_of(cx, &app, &hour_key).as_deref(), Some("Too early"));
815 cx.update(|_, cx| {
816 app.update(cx, |state, cx| {
817 state.pick_card_input(&scope, &hour_key, "10:15".into(), cx);
818 state.pick_card_input(&scope, &scope.input_key("stars"), "3.5".into(), cx);
819 })
820 });
821 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
822 assert_eq!(
823 sent,
824 json!({
825 "action": "save", "code": "", "day": "2026-11-02", "hour": "10:15",
826 "count": "4", "stars": 3.5
827 })
828 );
829 }
830 }
@@ -569,262 +569,3 @@ impl AppState {
569 })
569 })
570 }
570 }
571}
571}
572
573#[cfg(test)]
574mod tests {
575 use std::sync::Arc;
576
577 use gpui_kit::{
578 AppContext as _, Context, Entity, IntoElement, Render, TestAppContext, VisualTestContext,
579 Window,
580 };
581 use serde_json::json;
582 use store::Store;
583 use teams_core::AdaptiveCard;
584
585 use super::InputField;
586 use crate::app_state::{AppHandle, AppState, Mode};
587 use crate::card_actions::CardTask;
588 use crate::card_state::{CardScope, Surface};
589 use crate::views::adaptive_card::card_view;
590
591 struct Harness {
592 app: Entity<AppState>,
593 scope: CardScope,
594 card: AdaptiveCard,
595 }
596
597 impl Render for Harness {
598 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
599 self.app.update(cx, |state, cx| {
600 state.ensure_card_inputs(&self.scope, &self.card, window, cx)
601 });
602 card_view(&self.card, &self.scope, cx)
603 }
604 }
605
606 fn form_card() -> AdaptiveCard {
607 let card = json!({
608 "body": [
609 {"type": "Input.Text", "id": "name", "label": "Name", "isRequired": true, "errorMessage": "Name needed"},
610 {"type": "Input.Toggle", "id": "agree", "title": "Agree"}
611 ],
612 "actions": [
613 {"type": "Action.Submit", "title": "Save", "data": {"action": "save"}},
614 {"type": "Action.Submit", "title": "Skip", "associatedInputs": "none", "data": {"action": "skip"}}
615 ]
616 });
617 AdaptiveCard::parse(&card.to_string()).unwrap()
618 }
619
620 fn typed_card() -> AdaptiveCard {
621 let card = json!({
622 "body": [
623 {"type": "Input.Text", "id": "code", "maxLength": 3, "regex": "^[a-z]+$", "errorMessage": "Letters only"},
624 {"type": "Input.Date", "id": "day", "value": "2026-11-02", "min": "2026-10-01", "max": "2026-12-31"},
625 {"type": "Input.Time", "id": "hour", "value": "09:30", "min": "10:00", "errorMessage": "Too early"},
626 {"type": "Input.Number", "id": "count", "value": 4},
627 {"type": "Input.Rating", "id": "stars", "value": 2, "allowHalf": true}
628 ],
629 "actions": [{"type": "Action.Submit", "title": "Save", "data": {"action": "save"}}]
630 });
631 AdaptiveCard::parse(&card.to_string()).unwrap()
632 }
633
634 fn open(
635 cx: &mut TestAppContext,
636 surface: Surface,
637 ) -> (
638 &mut VisualTestContext,
639 Entity<AppState>,
640 CardScope,
641 AdaptiveCard,
642 ) {
643 open_card(cx, surface, form_card())
644 }
645
646 fn open_card(
647 cx: &mut TestAppContext,
648 surface: Surface,
649 card: AdaptiveCard,
650 ) -> (
651 &mut VisualTestContext,
652 Entity<AppState>,
653 CardScope,
654 AdaptiveCard,
655 ) {
656 cx.update(gpui_kit::init);
657 let store = Arc::new(Store::open_in_memory().unwrap());
658 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
659 cx.update(|cx| cx.set_global(AppHandle(app.clone())));
660 let scope = CardScope {
661 surface,
662 ..CardScope::message("19:chat@thread.v2", "m1", 0)
663 };
664 let (_, window_cx) = cx.add_window_view({
665 let (app, scope, card) = (app.clone(), scope.clone(), card.clone());
666 move |_, _| Harness { app, scope, card }
667 });
668 window_cx.update(|window, cx| window.draw(cx).clear(cx));
669 (window_cx, app, scope, card)
670 }
671
672 fn focus_name_field(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
673 let key = scope.input_key("name");
674 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
675 let Some(InputField::Line(line)) = field else {
676 panic!("name is a single line field");
677 };
678 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
679 }
680
681 fn task_for(
682 cx: &mut VisualTestContext,
683 app: &Entity<AppState>,
684 scope: &CardScope,
685 card: &AdaptiveCard,
686 action_index: usize,
687 ) -> Option<CardTask> {
688 let action = card.actions[action_index].clone();
689 let inputs = card.own_inputs();
690 cx.update(|_, cx| app.update(cx, |state, cx| state.card_task(scope, action, &inputs, cx)))
691 }
692
693 fn object(pairs: &[(&str, &str)]) -> serde_json::Value {
694 serde_json::Value::Object(
695 pairs
696 .iter()
697 .map(|(key, value)| ((*key).to_owned(), serde_json::Value::from(*value)))
698 .collect(),
699 )
700 }
701
702 fn error_of(cx: &mut VisualTestContext, app: &Entity<AppState>, key: &str) -> Option<String> {
703 cx.update(|_, cx| app.read(cx).cards.input_error(key).map(str::to_owned))
704 }
705
706 fn type_name(
707 cx: &mut VisualTestContext,
708 app: &Entity<AppState>,
709 scope: &CardScope,
710 text: &str,
711 ) {
712 focus_name_field(cx, app, scope);
713 cx.simulate_input(text);
714 }
715
716 fn switch_agree(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
717 let key = scope.input_key("agree");
718 cx.update(|_, cx| {
719 app.update(cx, |state, cx| {
720 state.pick_card_input(scope, &key, "true".into(), cx)
721 })
722 });
723 }
724
725 fn sent_value(task: Option<CardTask>) -> serde_json::Value {
726 match task {
727 Some(CardTask::Action(action)) => action.invoke_payload().unwrap().value,
728 Some(CardTask::Submit(data)) => data,
729 None => serde_json::Value::Null,
730 }
731 }
732
733 #[gpui_kit::test]
734 fn typed_text_and_toggle_are_sent_with_the_action_data(cx: &mut TestAppContext) {
735 let (cx, app, scope, card) = open(cx, Surface::Message);
736 type_name(cx, &app, &scope, "Ada");
737 switch_agree(cx, &app, &scope);
738 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
739 assert_eq!(
740 sent,
741 object(&[("action", "save"), ("name", "Ada"), ("agree", "true")])
742 );
743 }
744
745 #[gpui_kit::test]
746 fn an_empty_required_input_blocks_the_send_until_it_changes(cx: &mut TestAppContext) {
747 let (cx, app, scope, card) = open(cx, Surface::Message);
748 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
749 let key = scope.input_key("name");
750 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Name needed"));
751 type_name(cx, &app, &scope, "A");
752 assert_eq!(error_of(cx, &app, &key), None);
753 assert!(task_for(cx, &app, &scope, &card, 0).is_some());
754 }
755
756 #[gpui_kit::test]
757 fn associated_inputs_none_skips_collection_and_validation(cx: &mut TestAppContext) {
758 let (cx, app, scope, card) = open(cx, Surface::Message);
759 let sent = sent_value(task_for(cx, &app, &scope, &card, 1));
760 assert_eq!(sent, object(&[("action", "skip")]));
761 }
762
763 #[gpui_kit::test]
764 fn a_dialog_submit_carries_the_collected_values(cx: &mut TestAppContext) {
765 let (cx, app, scope, card) = open(cx, Surface::Dialog);
766 type_name(cx, &app, &scope, "Ada");
767 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
768 assert_eq!(
769 sent,
770 object(&[("action", "save"), ("name", "Ada"), ("agree", "false")])
771 );
772 }
773
774 #[gpui_kit::test]
775 fn typing_past_the_max_length_is_ignored(cx: &mut TestAppContext) {
776 let (cx, app, scope, _) = open_card(cx, Surface::Message, typed_card());
777 let key = scope.input_key("code");
778 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
779 let Some(InputField::Line(line)) = field else {
780 panic!("code is a single line field");
781 };
782 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
783 cx.simulate_input("abcdef");
784 assert_eq!(
785 cx.update(|_, cx| app.read(cx).cards.input_text(&key, cx)),
786 "abc"
787 );
788 }
789
790 #[gpui_kit::test]
791 fn blur_validation_shows_the_error_message(cx: &mut TestAppContext) {
792 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
793 let key = scope.input_key("code");
794 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
795 let Some(InputField::Line(line)) = field else {
796 panic!("code is a single line field");
797 };
798 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
799 cx.simulate_input("AB");
800 let input = card.own_inputs().remove(0);
801 cx.update(|_, cx| {
802 app.update(cx, |state, cx| {
803 state.validate_card_input(&scope, &key, &input, cx)
804 })
805 });
806 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Letters only"));
807 }
808
809 #[gpui_kit::test]
810 fn date_time_and_rating_values_are_collected_with_their_types(cx: &mut TestAppContext) {
811 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
812 let hour_key = scope.input_key("hour");
813 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
814 assert_eq!(error_of(cx, &app, &hour_key).as_deref(), Some("Too early"));
815 cx.update(|_, cx| {
816 app.update(cx, |state, cx| {
817 state.pick_card_input(&scope, &hour_key, "10:15".into(), cx);
818 state.pick_card_input(&scope, &scope.input_key("stars"), "3.5".into(), cx);
819 })
820 });
821 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
822 assert_eq!(
823 sent,
824 json!({
825 "action": "save", "code": "", "day": "2026-11-02", "hour": "10:15",
826 "count": "4", "stars": 3.5
827 })
828 );
829 }
830}
crates/app/src/card_refresh.rs crates/app-state/src/card_refresh.rs renamed +0 −0
crates/app/src/card_state.rs crates/app-state/src/card_state.rs renamed +0 −0
crates/app/src/chat_actions.rs crates/app-state/src/chat_actions.rs renamed +3 −3
@@ -215,7 +215,7 @@ impl AppState {
215 215 }
216 216
217 217 /// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
218 pub(crate) fn chat_action_engine(
218 pub fn chat_action_engine(
219 219 &mut self,
220 220 cx: &mut Context<Self>,
221 221 ) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
@@ -254,7 +254,7 @@ impl AppState {
254 254 }
255 255 }
256 256
257 pub(crate) fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
257 pub fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
258 258 let selected = match &self.selection {
259 259 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
260 260 _ => None,
@@ -309,7 +309,7 @@ impl AppState {
309 309 build_sections(&input)
310 310 }
311 311
312 pub(crate) fn run_chat_action(
312 pub fn run_chat_action(
313 313 &mut self,
314 314 label: &'static str,
315 315 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
@@ -215,7 +215,7 @@ impl AppState {
215 }
215 }
216
216
217 /// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
217 /// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
218 pub(crate) fn chat_action_engine(
218 pub fn chat_action_engine(
219 &mut self,
219 &mut self,
220 cx: &mut Context<Self>,
220 cx: &mut Context<Self>,
221 ) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
221 ) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
@@ -254,7 +254,7 @@ impl AppState {
254 }
254 }
255 }
255 }
256
256
257 pub(crate) fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
257 pub fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
258 let selected = match &self.selection {
258 let selected = match &self.selection {
259 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
259 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
260 _ => None,
260 _ => None,
@@ -309,7 +309,7 @@ impl AppState {
309 build_sections(&input)
309 build_sections(&input)
310 }
310 }
311
311
312 pub(crate) fn run_chat_action(
312 pub fn run_chat_action(
313 &mut self,
313 &mut self,
314 label: &'static str,
314 label: &'static str,
315 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
315 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
crates/app/src/data.rs crates/app-state/src/data.rs renamed +9 −9
@@ -129,15 +129,15 @@ pub struct Directory {
129 129 pub section_settings: ChatSectionSettings,
130 130 pub pinned_channels: Vec<String>,
131 131 pub unread_counts: HashMap<String, u32>,
132 pub(crate) avatars: HashMap<String, AvatarState>,
133 pub(crate) presence: HashMap<String, (PresenceKind, Instant)>,
134 pub(crate) activity: HashMap<String, Activity>,
135 pub(crate) presence_cached: HashMap<String, PresenceKind>,
136 pub(crate) presence_requested: HashMap<String, Instant>,
137 pub(crate) presence_pending: HashSet<String>,
138 pub(crate) images: HashMap<String, ImageEntry>,
139 pub(crate) images_requested: HashSet<String>,
140 pub(crate) images_failed: HashMap<String, Instant>,
132 pub avatars: HashMap<String, AvatarState>,
133 pub presence: HashMap<String, (PresenceKind, Instant)>,
134 pub activity: HashMap<String, Activity>,
135 pub presence_cached: HashMap<String, PresenceKind>,
136 pub presence_requested: HashMap<String, Instant>,
137 pub presence_pending: HashSet<String>,
138 pub images: HashMap<String, ImageEntry>,
139 pub images_requested: HashSet<String>,
140 pub images_failed: HashMap<String, Instant>,
141 141 }
142 142
143 143 const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
@@ -129,15 +129,15 @@ pub struct Directory {
129 pub section_settings: ChatSectionSettings,
129 pub section_settings: ChatSectionSettings,
130 pub pinned_channels: Vec<String>,
130 pub pinned_channels: Vec<String>,
131 pub unread_counts: HashMap<String, u32>,
131 pub unread_counts: HashMap<String, u32>,
132 pub(crate) avatars: HashMap<String, AvatarState>,
132 pub avatars: HashMap<String, AvatarState>,
133 pub(crate) presence: HashMap<String, (PresenceKind, Instant)>,
133 pub presence: HashMap<String, (PresenceKind, Instant)>,
134 pub(crate) activity: HashMap<String, Activity>,
134 pub activity: HashMap<String, Activity>,
135 pub(crate) presence_cached: HashMap<String, PresenceKind>,
135 pub presence_cached: HashMap<String, PresenceKind>,
136 pub(crate) presence_requested: HashMap<String, Instant>,
136 pub presence_requested: HashMap<String, Instant>,
137 pub(crate) presence_pending: HashSet<String>,
137 pub presence_pending: HashSet<String>,
138 pub(crate) images: HashMap<String, ImageEntry>,
138 pub images: HashMap<String, ImageEntry>,
139 pub(crate) images_requested: HashSet<String>,
139 pub images_requested: HashSet<String>,
140 pub(crate) images_failed: HashMap<String, Instant>,
140 pub images_failed: HashMap<String, Instant>,
141}
141}
142
142
143const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
143const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
crates/app/src/demo.rs crates/app-state/src/demo.rs renamed +0 −0
crates/app/src/demo_profiles.rs crates/app-state/src/demo_profiles.rs renamed +0 −0
crates/app/src/emoji/mod.rs crates/app-state/src/emoji/mod.rs renamed +2 −2
@@ -1,4 +1,4 @@
1 mod recent;
1 pub mod recent;
2 2
3 3 use app_base::emoji::typing;
4 4 use std::ops::Range;
@@ -7,7 +7,7 @@ use std::sync::OnceLock;
7 7 pub use recent::Recent;
8 8 pub use typing::{active_query, closing_code, smiley_before_space, trailing_smiley, typed_char};
9 9
10 const INDEX: &str = include_str!("../../assets/emoji/emoji.tsv");
10 const INDEX: &str = include_str!("../../../app/assets/emoji/emoji.tsv");
11 11
12 12 #[derive(Debug)]
13 13 pub struct Emoji {
@@ -1,4 +1,4 @@
1mod recent;
1pub mod recent;
2
2
3use app_base::emoji::typing;
3use app_base::emoji::typing;
4use std::ops::Range;
4use std::ops::Range;
@@ -7,7 +7,7 @@ use std::sync::OnceLock;
7pub use recent::Recent;
7pub use recent::Recent;
8pub use typing::{active_query, closing_code, smiley_before_space, trailing_smiley, typed_char};
8pub use typing::{active_query, closing_code, smiley_before_space, trailing_smiley, typed_char};
9
9
10const INDEX: &str = include_str!("../../assets/emoji/emoji.tsv");
10const INDEX: &str = include_str!("../../../app/assets/emoji/emoji.tsv");
11
11
12#[derive(Debug)]
12#[derive(Debug)]
13pub struct Emoji {
13pub struct Emoji {
crates/app/src/emoji/recent.rs crates/app-state/src/emoji/recent.rs renamed +0 −0
crates/app/src/gifs.rs crates/app-state/src/gifs.rs renamed +0 −0
crates/app-state/src/lib.rs added +46 −0
@@ -0,0 +1,46 @@
1 pub mod activity;
2 pub mod agent_api;
3 pub mod agents;
4 pub mod app_state;
5 pub mod backend;
6 pub mod call;
7 pub mod card_actions;
8 pub mod card_inputs;
9 pub mod card_refresh;
10 pub mod card_state;
11 pub mod chat_actions;
12 pub mod data;
13 pub mod demo;
14 pub mod demo_profiles;
15 pub mod emoji;
16 pub mod gifs;
17 pub mod image_view_gallery;
18 pub mod local_previews;
19 pub mod message_actions;
20 pub mod notice;
21 pub mod notify;
22 pub mod outbox;
23 pub mod outgoing;
24 pub mod own_status;
25 pub mod pending_rows;
26 pub mod people;
27 pub mod profile_model;
28 pub mod profile_state;
29 pub mod reaction_model;
30 pub mod rows;
31 pub mod scheduled;
32 pub mod scheduled_rows;
33 pub mod section_actions;
34 pub mod sidebar_model;
35 pub mod stored_outgoing;
36 pub mod task_dialog;
37 pub mod translation_actions;
38 pub mod typing;
39
40 pub use app_ui_kit::render;
41 pub use app_base::{
42 APP_NAME, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
43 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
44 image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
45 single_instance, stickers, theme, translation, updater, user_activity,
46 };
@@ -0,0 +1,46 @@
1pub mod activity;
2pub mod agent_api;
3pub mod agents;
4pub mod app_state;
5pub mod backend;
6pub mod call;
7pub mod card_actions;
8pub mod card_inputs;
9pub mod card_refresh;
10pub mod card_state;
11pub mod chat_actions;
12pub mod data;
13pub mod demo;
14pub mod demo_profiles;
15pub mod emoji;
16pub mod gifs;
17pub mod image_view_gallery;
18pub mod local_previews;
19pub mod message_actions;
20pub mod notice;
21pub mod notify;
22pub mod outbox;
23pub mod outgoing;
24pub mod own_status;
25pub mod pending_rows;
26pub mod people;
27pub mod profile_model;
28pub mod profile_state;
29pub mod reaction_model;
30pub mod rows;
31pub mod scheduled;
32pub mod scheduled_rows;
33pub mod section_actions;
34pub mod sidebar_model;
35pub mod stored_outgoing;
36pub mod task_dialog;
37pub mod translation_actions;
38pub mod typing;
39
40pub use app_ui_kit::render;
41pub use app_base::{
42 APP_NAME, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
43 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
44 image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
45 single_instance, stickers, theme, translation, updater, user_activity,
46};
crates/app/src/local_previews.rs crates/app-state/src/local_previews.rs renamed +0 −0
crates/app/src/message_actions.rs crates/app-state/src/message_actions.rs renamed +1 −1
@@ -80,7 +80,7 @@ fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {
80 80 }
81 81
82 82 impl AppState {
83 pub(crate) fn message_record(
83 pub fn message_record(
84 84 &self,
85 85 conversation_id: &str,
86 86 message_id: &str,
@@ -80,7 +80,7 @@ fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {
80}
80}
81
81
82impl AppState {
82impl AppState {
83 pub(crate) fn message_record(
83 pub fn message_record(
84 &self,
84 &self,
85 conversation_id: &str,
85 conversation_id: &str,
86 message_id: &str,
86 message_id: &str,
crates/app/src/notice.rs crates/app-state/src/notice.rs renamed +0 −0
crates/app/src/notify/incoming.rs crates/app-state/src/notify/incoming.rs renamed +0 −0
crates/app/src/notify/layout.rs crates/app-state/src/notify/layout.rs renamed +0 −0
crates/app-state/src/notify/mod.rs added +12 −0
@@ -0,0 +1,12 @@
1 pub mod incoming;
2 pub mod layout;
3 pub mod rules;
4 pub mod settings;
5 pub mod stack;
6 pub mod text;
7
8 pub use app_base::notify::{badge, platform, ring_tone};
9 pub use incoming::{IncomingTracker, preview_of};
10 #[cfg(windows)]
11 pub use platform::native_handle;
12 pub use rules::{ChatKind, Incoming, Preview, channel_alerts};
@@ -0,0 +1,12 @@
1pub mod incoming;
2pub mod layout;
3pub mod rules;
4pub mod settings;
5pub mod stack;
6pub mod text;
7
8pub use app_base::notify::{badge, platform, ring_tone};
9pub use incoming::{IncomingTracker, preview_of};
10#[cfg(windows)]
11pub use platform::native_handle;
12pub use rules::{ChatKind, Incoming, Preview, channel_alerts};
crates/app/src/notify/rules.rs crates/app-state/src/notify/rules.rs renamed +0 −0
crates/app/src/notify/settings.rs crates/app-state/src/notify/settings.rs renamed +0 −0
crates/app/src/notify/stack.rs crates/app-state/src/notify/stack.rs renamed +0 −0
crates/app/src/notify/text.rs crates/app-state/src/notify/text.rs renamed +0 −0
crates/app/src/outbox.rs crates/app-state/src/outbox.rs renamed +0 −0
crates/app/src/outgoing.rs crates/app-state/src/outgoing.rs renamed +0 −0
crates/app/src/own_status.rs crates/app-state/src/own_status.rs renamed +0 −0
crates/app/src/pending_rows.rs crates/app-state/src/pending_rows.rs renamed +0 −0
crates/app/src/people.rs crates/app-state/src/people.rs renamed +0 −0
crates/app/src/profile_model.rs crates/app-state/src/profile_model.rs renamed +0 −0
crates/app/src/profile_state.rs crates/app-state/src/profile_state.rs renamed +0 −0
crates/app/src/reaction_model.rs crates/app-state/src/reaction_model.rs renamed +0 −0
crates/app/src/rows.rs crates/app-state/src/rows.rs renamed +0 −0
crates/app/src/scheduled.rs crates/app-state/src/scheduled.rs renamed +0 −0
crates/app/src/scheduled_rows.rs crates/app-state/src/scheduled_rows.rs renamed +0 −0
crates/app/src/section_actions.rs crates/app-state/src/section_actions.rs renamed +1 −1
@@ -143,7 +143,7 @@ impl AppState {
143 143 }
144 144 }
145 145
146 pub(crate) fn reapply_section_changes(&mut self) {
146 pub fn reapply_section_changes(&mut self) {
147 147 self.section_changes.reapply(&mut self.directory);
148 148 }
149 149
@@ -143,7 +143,7 @@ impl AppState {
143 }
143 }
144 }
144 }
145
145
146 pub(crate) fn reapply_section_changes(&mut self) {
146 pub fn reapply_section_changes(&mut self) {
147 self.section_changes.reapply(&mut self.directory);
147 self.section_changes.reapply(&mut self.directory);
148 }
148 }
149
149
crates/app/src/sidebar_model.rs crates/app-state/src/sidebar_model.rs renamed +0 −0
crates/app/src/stored_outgoing.rs crates/app-state/src/stored_outgoing.rs renamed +0 −0
crates/app/src/task_dialog.rs crates/app-state/src/task_dialog.rs renamed +1 −1
@@ -6,7 +6,7 @@ use crate::backend::Engine;
6 6 use crate::card_state::CardScope;
7 7
8 8 #[cfg(windows)]
9 mod hosted;
9 pub mod hosted;
10 10 #[cfg(windows)]
11 11 use app_base::task_dialog::sdk;
12 12
@@ -6,7 +6,7 @@ use crate::backend::Engine;
6use crate::card_state::CardScope;
6use crate::card_state::CardScope;
7
7
8#[cfg(windows)]
8#[cfg(windows)]
9mod hosted;
9pub mod hosted;
10#[cfg(windows)]
10#[cfg(windows)]
11use app_base::task_dialog::sdk;
11use app_base::task_dialog::sdk;
12
12
crates/app/src/task_dialog/hosted.rs crates/app-state/src/task_dialog/hosted.rs renamed +0 −0
crates/app/src/translation_actions.rs crates/app-state/src/translation_actions.rs renamed +0 −0
crates/app/src/typing.rs crates/app-state/src/typing.rs renamed +0 −0
crates/app/Cargo.toml +2 −0
@@ -14,12 +14,14 @@ chrono.workspace = true
14 14 embed-resource = "3"
15 15
16 16 [dev-dependencies]
17 app-state = { workspace = true, features = ["test-support"] }
17 18 gpui-kit = { workspace = true, features = ["test-support"] }
18 19 tempfile.workspace = true
19 20
20 21 [dependencies]
21 22 app-base.workspace = true
22 23 app-call-model.workspace = true
24 app-state.workspace = true
23 25 app-ui-kit.workspace = true
24 26 agents.workspace = true
25 27 calling.workspace = true
@@ -14,12 +14,14 @@ chrono.workspace = true
14embed-resource = "3"
14embed-resource = "3"
15
15
16[dev-dependencies]
16[dev-dependencies]
17app-state = { workspace = true, features = ["test-support"] }
17gpui-kit = { workspace = true, features = ["test-support"] }
18gpui-kit = { workspace = true, features = ["test-support"] }
18tempfile.workspace = true
19tempfile.workspace = true
19
20
20[dependencies]
21[dependencies]
21app-base.workspace = true
22app-base.workspace = true
22app-call-model.workspace = true
23app-call-model.workspace = true
24app-state.workspace = true
23app-ui-kit.workspace = true
25app-ui-kit.workspace = true
24agents.workspace = true
26agents.workspace = true
25calling.workspace = true
27calling.workspace = true
crates/app/src/agents/mod.rs +1 −204
@@ -1,215 +1,12 @@
1 mod demo;
2 mod kills;
3 mod mcp_bridge;
4 mod message_context;
5 1 mod run_chip;
6 mod runs;
7 2 mod runs_popover;
8 mod session_options;
9 3 mod settings_forms;
10 4 mod settings_section;
11 5 mod start_dialog;
12 6 mod start_dialog_pickers;
13 mod store;
14
15 use std::path::PathBuf;
16 use std::time::Duration;
17
18 use app_base::agents::{lanes, settings_problems};
19 use app_ui_kit::{settings_controls, spinner};
20 use agents::{AgentAction, Environment};
21 use directories::ProjectDirs;
22 use gpui_kit::*;
23 7
8 pub use state::agents::*;
24 9 pub use run_chip::run_chip;
25 pub use runs::{
26 AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions, StartRequest, needs_dialog,
27 };
28 10 pub use runs_popover::RunsPopover;
29 11 pub use settings_section::AgentsSettings;
30 12 pub use start_dialog::{StartDialog, StartDialogEvent};
31
32 use crate::app_state::{AppHandle, AppState};
33
34 pub fn install(app: Entity<AppState>, cx: &mut App) {
35 let runs = cx.new(|cx| AgentRuns::new(app, cx));
36 cx.set_global(AgentRunsHandle(runs));
37 }
38
39 const MCP_POLL_INTERVAL: Duration = Duration::from_millis(100);
40 const MCP_WAIT_LIMIT: Duration = Duration::from_secs(5);
41 const MCP_CONFIG_FOLDER: &str = "agent-mcp";
42
43 fn mcp_config_directory() -> Option<PathBuf> {
44 ProjectDirs::from("", "", ::store::DATA_DIR_NAME)
45 .map(|directories| directories.data_local_dir().join(MCP_CONFIG_FOLDER))
46 }
47
48 pub fn runs_handle(cx: &App) -> Option<Entity<AgentRuns>> {
49 cx.try_global::<AgentRunsHandle>()
50 .map(|handle| handle.0.clone())
51 }
52
53 fn raise_notice(text: String, cx: &mut App) {
54 let Some(handle) = cx.try_global::<AppHandle>() else {
55 return;
56 };
57 handle
58 .0
59 .clone()
60 .update(cx, |state, cx| state.raise_notice(text, None, cx));
61 }
62
63 pub fn start_run(
64 action_id: &str,
65 conversation_id: &str,
66 message_id: &str,
67 extra: &str,
68 options: StartOptions,
69 cx: &mut App,
70 ) {
71 let Some(runs) = runs_handle(cx) else {
72 return;
73 };
74 let started = runs.update(cx, |runs, cx| {
75 runs.start_with(action_id, conversation_id, message_id, extra, options, cx)
76 });
77 if let Err(error) = started {
78 raise_notice(format!("Agent could not start: {error}"), cx);
79 }
80 }
81
82 pub fn start_run_when_mcp_ready(
83 action_id: String,
84 conversation_id: String,
85 message_id: String,
86 extra: String,
87 options: StartOptions,
88 cx: &mut App,
89 ) {
90 cx.spawn(async move |cx| {
91 let mut waited = Duration::ZERO;
92 while waited < MCP_WAIT_LIMIT && !cx.update(|cx| mcp_bridge::endpoint(cx).is_some()) {
93 cx.background_executor().timer(MCP_POLL_INTERVAL).await;
94 waited += MCP_POLL_INTERVAL;
95 }
96 cx.update(|cx| {
97 if mcp_bridge::endpoint(cx).is_none() {
98 raise_notice(
99 "MCP server is not running - the agent cannot propose a reply".to_owned(),
100 cx,
101 );
102 }
103 start_run(
104 &action_id,
105 &conversation_id,
106 &message_id,
107 &extra,
108 options,
109 cx,
110 );
111 });
112 })
113 .detach();
114 }
115
116 pub fn retry_run(run_id: u64, cx: &mut App) {
117 let Some(runs) = runs_handle(cx) else {
118 return;
119 };
120 let retried = runs.update(cx, |runs, cx| runs.retry(run_id, cx));
121 if let Err(error) = retried {
122 raise_notice(format!("Agent could not start: {error}"), cx);
123 }
124 }
125
126 pub fn delegate(request: StartRequest, cx: &mut App) {
127 let Some(runs) = runs_handle(cx) else {
128 return;
129 };
130 let action = runs
131 .read(cx)
132 .settings()
133 .actions
134 .iter()
135 .find(|action| action.id == request.action_id)
136 .cloned();
137 let Some(action) = action else {
138 return;
139 };
140 let allowed = mcp_bridge::chat_allowed(&request.conversation_id, cx);
141 if needs_dialog(&action, allowed) {
142 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::StartRequested(request)));
143 } else {
144 start_run(
145 &request.action_id,
146 &request.conversation_id,
147 &request.message_id,
148 "",
149 StartOptions::default(),
150 cx,
151 );
152 }
153 }
154
155 pub fn open_settings(cx: &mut App) {
156 if let Some(runs) = runs_handle(cx) {
157 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::OpenSettings));
158 }
159 }
160
161 pub fn has_session(session_id: &str, cx: &App) -> bool {
162 runs_handle(cx).is_some_and(|runs| runs.read(cx).by_session(session_id).is_some())
163 }
164
165 pub fn open_session(session_id: &str, cx: &mut App) {
166 let run = runs_handle(cx).and_then(|runs| runs.read(cx).by_session(session_id).cloned());
167 match run {
168 Some(run) => open_run_session(&run, cx),
169 None => raise_notice(
170 "This session was not started from this app, open it in your terminal".to_owned(),
171 cx,
172 ),
173 }
174 }
175
176 fn open_run_session(run: &AgentRun, cx: &mut App) {
177 let Some(handle) = cx.try_global::<AppHandle>() else {
178 return;
179 };
180 let settings = store::load_settings(&handle.0.read(cx).store);
181 let Some(profile) = settings
182 .agents
183 .iter()
184 .find(|profile| profile.id == run.agent_id)
185 else {
186 raise_notice("The agent of this run no longer exists".to_owned(), cx);
187 return;
188 };
189 let action = AgentAction {
190 working_dir: run.working_dir.clone(),
191 ..AgentAction::default()
192 };
193 let spawned = agents::open_session_invocation(profile, &action, &run.session_id)
194 .map_err(|error| error.to_string())
195 .and_then(|invocation| {
196 std::process::Command::new(&invocation.program)
197 .args(&invocation.args)
198 .spawn()
199 .map(drop)
200 .map_err(|error| error.to_string())
201 });
202 if let Err(error) = spawned {
203 raise_notice(format!("Could not open the session: {error}"), cx);
204 }
205 }
206
207 pub fn environment_label(environment: &Environment) -> String {
208 match environment {
209 Environment::Host => "Windows".to_owned(),
210 Environment::Wsl { distro: None } => "WSL".to_owned(),
211 Environment::Wsl {
212 distro: Some(distro),
213 } => format!("WSL - {distro}"),
214 }
215 }
@@ -1,215 +1,12 @@
1mod demo;
2mod kills;
3mod mcp_bridge;
4mod message_context;
5mod run_chip;
1mod run_chip;
6mod runs;
7mod runs_popover;
2mod runs_popover;
8mod session_options;
9mod settings_forms;
3mod settings_forms;
10mod settings_section;
4mod settings_section;
11mod start_dialog;
5mod start_dialog;
12mod start_dialog_pickers;
6mod start_dialog_pickers;
13mod store;
14
15use std::path::PathBuf;
16use std::time::Duration;
17
18use app_base::agents::{lanes, settings_problems};
19use app_ui_kit::{settings_controls, spinner};
20use agents::{AgentAction, Environment};
21use directories::ProjectDirs;
22use gpui_kit::*;
23
7
8pub use state::agents::*;
24pub use run_chip::run_chip;
9pub use run_chip::run_chip;
25pub use runs::{
26 AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState, StartOptions, StartRequest, needs_dialog,
27};
28pub use runs_popover::RunsPopover;
10pub use runs_popover::RunsPopover;
29pub use settings_section::AgentsSettings;
11pub use settings_section::AgentsSettings;
30pub use start_dialog::{StartDialog, StartDialogEvent};
12pub use start_dialog::{StartDialog, StartDialogEvent};
31
32use crate::app_state::{AppHandle, AppState};
33
34pub fn install(app: Entity<AppState>, cx: &mut App) {
35 let runs = cx.new(|cx| AgentRuns::new(app, cx));
36 cx.set_global(AgentRunsHandle(runs));
37}
38
39const MCP_POLL_INTERVAL: Duration = Duration::from_millis(100);
40const MCP_WAIT_LIMIT: Duration = Duration::from_secs(5);
41const MCP_CONFIG_FOLDER: &str = "agent-mcp";
42
43fn mcp_config_directory() -> Option<PathBuf> {
44 ProjectDirs::from("", "", ::store::DATA_DIR_NAME)
45 .map(|directories| directories.data_local_dir().join(MCP_CONFIG_FOLDER))
46}
47
48pub fn runs_handle(cx: &App) -> Option<Entity<AgentRuns>> {
49 cx.try_global::<AgentRunsHandle>()
50 .map(|handle| handle.0.clone())
51}
52
53fn raise_notice(text: String, cx: &mut App) {
54 let Some(handle) = cx.try_global::<AppHandle>() else {
55 return;
56 };
57 handle
58 .0
59 .clone()
60 .update(cx, |state, cx| state.raise_notice(text, None, cx));
61}
62
63pub fn start_run(
64 action_id: &str,
65 conversation_id: &str,
66 message_id: &str,
67 extra: &str,
68 options: StartOptions,
69 cx: &mut App,
70) {
71 let Some(runs) = runs_handle(cx) else {
72 return;
73 };
74 let started = runs.update(cx, |runs, cx| {
75 runs.start_with(action_id, conversation_id, message_id, extra, options, cx)
76 });
77 if let Err(error) = started {
78 raise_notice(format!("Agent could not start: {error}"), cx);
79 }
80}
81
82pub fn start_run_when_mcp_ready(
83 action_id: String,
84 conversation_id: String,
85 message_id: String,
86 extra: String,
87 options: StartOptions,
88 cx: &mut App,
89) {
90 cx.spawn(async move |cx| {
91 let mut waited = Duration::ZERO;
92 while waited < MCP_WAIT_LIMIT && !cx.update(|cx| mcp_bridge::endpoint(cx).is_some()) {
93 cx.background_executor().timer(MCP_POLL_INTERVAL).await;
94 waited += MCP_POLL_INTERVAL;
95 }
96 cx.update(|cx| {
97 if mcp_bridge::endpoint(cx).is_none() {
98 raise_notice(
99 "MCP server is not running - the agent cannot propose a reply".to_owned(),
100 cx,
101 );
102 }
103 start_run(
104 &action_id,
105 &conversation_id,
106 &message_id,
107 &extra,
108 options,
109 cx,
110 );
111 });
112 })
113 .detach();
114}
115
116pub fn retry_run(run_id: u64, cx: &mut App) {
117 let Some(runs) = runs_handle(cx) else {
118 return;
119 };
120 let retried = runs.update(cx, |runs, cx| runs.retry(run_id, cx));
121 if let Err(error) = retried {
122 raise_notice(format!("Agent could not start: {error}"), cx);
123 }
124}
125
126pub fn delegate(request: StartRequest, cx: &mut App) {
127 let Some(runs) = runs_handle(cx) else {
128 return;
129 };
130 let action = runs
131 .read(cx)
132 .settings()
133 .actions
134 .iter()
135 .find(|action| action.id == request.action_id)
136 .cloned();
137 let Some(action) = action else {
138 return;
139 };
140 let allowed = mcp_bridge::chat_allowed(&request.conversation_id, cx);
141 if needs_dialog(&action, allowed) {
142 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::StartRequested(request)));
143 } else {
144 start_run(
145 &request.action_id,
146 &request.conversation_id,
147 &request.message_id,
148 "",
149 StartOptions::default(),
150 cx,
151 );
152 }
153}
154
155pub fn open_settings(cx: &mut App) {
156 if let Some(runs) = runs_handle(cx) {
157 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::OpenSettings));
158 }
159}
160
161pub fn has_session(session_id: &str, cx: &App) -> bool {
162 runs_handle(cx).is_some_and(|runs| runs.read(cx).by_session(session_id).is_some())
163}
164
165pub fn open_session(session_id: &str, cx: &mut App) {
166 let run = runs_handle(cx).and_then(|runs| runs.read(cx).by_session(session_id).cloned());
167 match run {
168 Some(run) => open_run_session(&run, cx),
169 None => raise_notice(
170 "This session was not started from this app, open it in your terminal".to_owned(),
171 cx,
172 ),
173 }
174}
175
176fn open_run_session(run: &AgentRun, cx: &mut App) {
177 let Some(handle) = cx.try_global::<AppHandle>() else {
178 return;
179 };
180 let settings = store::load_settings(&handle.0.read(cx).store);
181 let Some(profile) = settings
182 .agents
183 .iter()
184 .find(|profile| profile.id == run.agent_id)
185 else {
186 raise_notice("The agent of this run no longer exists".to_owned(), cx);
187 return;
188 };
189 let action = AgentAction {
190 working_dir: run.working_dir.clone(),
191 ..AgentAction::default()
192 };
193 let spawned = agents::open_session_invocation(profile, &action, &run.session_id)
194 .map_err(|error| error.to_string())
195 .and_then(|invocation| {
196 std::process::Command::new(&invocation.program)
197 .args(&invocation.args)
198 .spawn()
199 .map(drop)
200 .map_err(|error| error.to_string())
201 });
202 if let Err(error) = spawned {
203 raise_notice(format!("Could not open the session: {error}"), cx);
204 }
205}
206
207pub fn environment_label(environment: &Environment) -> String {
208 match environment {
209 Environment::Host => "Windows".to_owned(),
210 Environment::Wsl { distro: None } => "WSL".to_owned(),
211 Environment::Wsl {
212 distro: Some(distro),
213 } => format!("WSL - {distro}"),
214 }
215}
crates/app/src/agents/runs_popover.rs +1 −1
@@ -173,7 +173,7 @@ impl Render for RunsPopover {
173 173 mod tests {
174 174 use super::split_runs;
175 175 use crate::agents::runs::RunState;
176 use crate::agents::runs::tests::finished_run;
176 use crate::agents::fixtures::finished_run;
177 177
178 178 #[test]
179 179 fn running_runs_go_first_and_done_is_capped_at_ten() {
@@ -173,7 +173,7 @@ impl Render for RunsPopover {
173mod tests {
173mod tests {
174 use super::split_runs;
174 use super::split_runs;
175 use crate::agents::runs::RunState;
175 use crate::agents::runs::RunState;
176 use crate::agents::runs::tests::finished_run;
176 use crate::agents::fixtures::finished_run;
177
177
178 #[test]
178 #[test]
179 fn running_runs_go_first_and_done_is_capped_at_ten() {
179 fn running_runs_go_first_and_done_is_capped_at_ten() {
crates/app/src/call/mod.rs +1 −68
@@ -1,71 +1,4 @@
1 mod actions;
2 mod calendar;
3 mod consult;
4 mod features;
5 mod history;
6 mod join;
7 mod launcher;
8 mod list;
9 1 mod overlay;
10 mod overlay_layout;
11 mod people_actions;
12 mod prejoin;
13 mod record_load;
14 mod reminder;
15 mod share_actions;
16 mod schedule;
17 mod target;
18 mod view_actions;
19 2
20 use app_call_model::{
21 agenda, background, bubbles, caption_style, demo, fullscreen, health, media, mic,
22 model, options_dialog, people, preview, record_rights,
23 recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,
24 };
25
26 pub use actions::{load_camera, load_camera_effects, load_input, load_output, load_share_sound};
27 pub use mic::load_mic;
28 pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
29 pub use caption_style::{CaptionPosition, CaptionSize};
30 pub use background::{
31 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
32 load_custom_backgrounds,
33 };
34 pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};
35 pub use demo::DemoScene;
36 pub use features::TransferCandidate;
37 pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};
38 pub use history::CallRow;
39 pub use launcher::CallLauncher;
40 pub use list::{
41 AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
42 SECTION_HEIGHT,
43 };
44 pub use media::CallMedia;
45 pub use model::{
46 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
47 TileState,
48 };
49 #[cfg(test)]
50 pub use model::ConsultCall;
51 pub use options_dialog::OptionsDialog;
3 pub use state::call::*;
52 4 pub use overlay::CallWindows;
53 pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
54 pub use people::{PeopleSections, PersonRow, people_sections};
55 pub use share_actions::ZoomStep;
56 pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, ShareStage, load_flag, load_strip_width};
57 pub use preview::{CameraPreview, preview_backgrounds};
58 pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
59 pub use ring::{MissedCall, RingEntry, Rings};
60 pub use stage_split::{
61 GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP, gallery_split,
62 measured_stage, speaker_split, strip_split, video_wants,
63 };
64 pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};
65 pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
66 pub use record_rights::{RecordBlock, RecordFeature};
67 pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
68 pub use report::load_enabled as load_report_enabled;
69 pub use target::plan_for_chat;
70 pub use transcript::clock_label;
71 pub use view_settings::{CallLayout, ViewSettings};
@@ -1,71 +1,4 @@
1mod actions;
2mod calendar;
3mod consult;
4mod features;
5mod history;
6mod join;
7mod launcher;
8mod list;
9mod overlay;
1mod overlay;
10mod overlay_layout;
11mod people_actions;
12mod prejoin;
13mod record_load;
14mod reminder;
15mod share_actions;
16mod schedule;
17mod target;
18mod view_actions;
19
2
20use app_call_model::{
3pub use state::call::*;
21 agenda, background, bubbles, caption_style, demo, fullscreen, health, media, mic,
22 model, options_dialog, people, preview, record_rights,
23 recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,
24};
25
26pub use actions::{load_camera, load_camera_effects, load_input, load_output, load_share_sound};
27pub use mic::load_mic;
28pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
29pub use caption_style::{CaptionPosition, CaptionSize};
30pub use background::{
31 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
32 load_custom_backgrounds,
33};
34pub use bubbles::{BUBBLE_SHOWN, shown_bubbles};
35pub use demo::DemoScene;
36pub use features::TransferCandidate;
37pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};
38pub use history::CallRow;
39pub use launcher::CallLauncher;
40pub use list::{
41 AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
42 SECTION_HEIGHT,
43};
44pub use media::CallMedia;
45pub use model::{
46 ActiveCall, CAPTION_SHOWN, CallKind, CallModel, Focus, REACTION_SHOWN, Tile, TileSize,
47 TileState,
48};
49#[cfg(test)]
50pub use model::ConsultCall;
51pub use options_dialog::OptionsDialog;
52pub use overlay::CallWindows;
4pub use overlay::CallWindows;
53pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
54pub use people::{PeopleSections, PersonRow, people_sections};
55pub use share_actions::ZoomStep;
56pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, ShareStage, load_flag, load_strip_width};
57pub use preview::{CameraPreview, preview_backgrounds};
58pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
59pub use ring::{MissedCall, RingEntry, Rings};
60pub use stage_split::{
61 GRID_PADDING, STRIP_GAP, SpeakerSplit, StripSplit, TILE_GAP, gallery_split,
62 measured_stage, speaker_split, strip_split, video_wants,
63};
64pub use stage_layout::{contain_size, focus_stage_size, gallery_grid};
65pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
66pub use record_rights::{RecordBlock, RecordFeature};
67pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
68pub use report::load_enabled as load_report_enabled;
69pub use target::plan_for_chat;
70pub use transcript::clock_label;
71pub use view_settings::{CallLayout, ViewSettings};
crates/app/src/layout_guard.rs +3 −2
@@ -838,9 +838,10 @@ mod frames {
838 838
839 839 #[test]
840 840 fn lines_are_solid() {
841 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
842 841 let mut files = Vec::new();
843 source_files(&root, &mut files);
842 for root in source_roots() {
843 source_files(&root, &mut files);
844 }
844 845 let violations: Vec<String> = files
845 846 .iter()
846 847 .filter(|file| !file.ends_with("layout_guard.rs"))
@@ -838,9 +838,10 @@ mod frames {
838
838
839#[test]
839#[test]
840fn lines_are_solid() {
840fn lines_are_solid() {
841 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
842 let mut files = Vec::new();
841 let mut files = Vec::new();
843 source_files(&root, &mut files);
842 for root in source_roots() {
843 source_files(&root, &mut files);
844 }
844 let violations: Vec<String> = files
845 let violations: Vec<String> = files
845 .iter()
846 .iter()
846 .filter(|file| !file.ends_with("layout_guard.rs"))
847 .filter(|file| !file.ends_with("layout_guard.rs"))
crates/app/src/main.rs +6 −47
@@ -3,55 +3,14 @@
3 3 windows_subsystem = "windows"
4 4 )]
5 5
6 mod activity;
7 mod agent_api;
8 mod agents;
9 mod app_state;
10 mod backend;
11 mod call;
12 mod card_actions;
13 mod card_inputs;
14 mod card_refresh;
15 mod card_state;
16 mod chat_actions;
17 mod data;
18 mod demo;
19 mod demo_profiles;
20 mod emoji;
21 mod gifs;
22 mod image_view_gallery;
6 pub mod agents;
7 pub mod call;
23 8 #[cfg(test)]
24 9 mod layout_guard;
25 mod local_previews;
26 mod message_actions;
27 mod notice;
28 mod notify;
29 mod outbox;
30 mod outgoing;
31 mod own_status;
32 mod pending_rows;
33 mod people;
34 mod profile_model;
35 mod profile_state;
36 mod reaction_model;
37 mod rows;
38 mod scheduled;
39 mod scheduled_rows;
40 mod section_actions;
41 mod sidebar_model;
42 mod stored_outgoing;
43 mod task_dialog;
44 mod translation_actions;
45 mod typing;
10 pub mod notify;
46 11 mod views;
47 12
48 pub use app_ui_kit::render;
49 pub use app_base::{
50 APP_NAME, assets, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
51 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
52 image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
53 single_instance, stickers, theme, translation, updater, user_activity,
54 };
13 pub use state::*;
55 14
56 15 use std::path::PathBuf;
57 16 use std::sync::Arc;
@@ -62,7 +21,7 @@ use gpui_kit::component::TitleBar;
62 21 use gpui_kit::*;
63 22 use store::Store;
64 23
65 use app_state::{AppState, Mode};
24 use crate::app_state::{AppState, Mode};
66 25 use views::shell::{AppShell, OpenTarget, Startup, bind_keys};
67 26
68 27 const VERSION_MARKER: &str = concat!("teams-build:", env!("TEAMS_BUILD_VERSION"));
@@ -222,7 +181,7 @@ fn main() {
222 181 application = application.with_http_client(Arc::new(http_client));
223 182 }
224 183
225 application.with_assets(assets::AppAssets).run(move |cx| {
184 application.with_assets(app_base::assets::AppAssets).run(move |cx| {
226 185 gpui_kit::init(cx);
227 186 cx.on_app_quit(|_| {
228 187 updater::exit_after_grace();
@@ -3,55 +3,14 @@
3 windows_subsystem = "windows"
3 windows_subsystem = "windows"
4)]
4)]
5
5
6mod activity;
6pub mod agents;
7mod agent_api;
7pub mod call;
8mod agents;
9mod app_state;
10mod backend;
11mod call;
12mod card_actions;
13mod card_inputs;
14mod card_refresh;
15mod card_state;
16mod chat_actions;
17mod data;
18mod demo;
19mod demo_profiles;
20mod emoji;
21mod gifs;
22mod image_view_gallery;
23#[cfg(test)]
8#[cfg(test)]
24mod layout_guard;
9mod layout_guard;
25mod local_previews;
10pub mod notify;
26mod message_actions;
27mod notice;
28mod notify;
29mod outbox;
30mod outgoing;
31mod own_status;
32mod pending_rows;
33mod people;
34mod profile_model;
35mod profile_state;
36mod reaction_model;
37mod rows;
38mod scheduled;
39mod scheduled_rows;
40mod section_actions;
41mod sidebar_model;
42mod stored_outgoing;
43mod task_dialog;
44mod translation_actions;
45mod typing;
46mod views;
11mod views;
47
12
48pub use app_ui_kit::render;
13pub use state::*;
49pub use app_base::{
50 APP_NAME, assets, avatar_image, channel_files, crash_log, demo_cards, demo_chart_cards, demo_gifs,
51 demo_input_cards, demo_library, demo_recap, diagnostics, downloads, format, frame_log, fuzzy,
52 image_view_math, inline_image, presence_link, read_state, recap, remote_image, runtime, schedule_time,
53 single_instance, stickers, theme, translation, updater, user_activity,
54};
55
14
56use std::path::PathBuf;
15use std::path::PathBuf;
57use std::sync::Arc;
16use std::sync::Arc;
@@ -62,7 +21,7 @@ use gpui_kit::component::TitleBar;
62use gpui_kit::*;
21use gpui_kit::*;
63use store::Store;
22use store::Store;
64
23
65use app_state::{AppState, Mode};
24use crate::app_state::{AppState, Mode};
66use views::shell::{AppShell, OpenTarget, Startup, bind_keys};
25use views::shell::{AppShell, OpenTarget, Startup, bind_keys};
67
26
68const VERSION_MARKER: &str = concat!("teams-build:", env!("TEAMS_BUILD_VERSION"));
27const VERSION_MARKER: &str = concat!("teams-build:", env!("TEAMS_BUILD_VERSION"));
@@ -222,7 +181,7 @@ fn main() {
222 application = application.with_http_client(Arc::new(http_client));
181 application = application.with_http_client(Arc::new(http_client));
223 }
182 }
224
183
225 application.with_assets(assets::AppAssets).run(move |cx| {
184 application.with_assets(app_base::assets::AppAssets).run(move |cx| {
226 gpui_kit::init(cx);
185 gpui_kit::init(cx);
227 cx.on_app_quit(|_| {
186 cx.on_app_quit(|_| {
228 updater::exit_after_grace();
187 updater::exit_after_grace();
crates/app/src/notify/mod.rs +1 −13
@@ -1,23 +1,11 @@
1 1 mod agent_toast;
2 2 mod center;
3 mod incoming;
4 mod layout;
5 3 mod meeting_view;
6 4 mod ring_view;
7 mod rules;
8 mod settings;
9 5 mod settings_mcp;
10 6 mod settings_view;
11 mod stack;
12 mod text;
13 7 mod toast;
14 8
15 pub use app_base::notify::{badge, platform, ring_tone};
9 pub use state::notify::*;
16 10 pub use center::NotificationCenter;
17 pub use incoming::{IncomingTracker, preview_of};
18 #[cfg(windows)]
19 pub use platform::native_handle;
20 #[cfg(test)]
21 pub use rules::ChatKind;
22 pub use rules::{Incoming, Preview, channel_alerts};
23 11 pub(crate) use settings_view::switch;
@@ -1,23 +1,11 @@
1mod agent_toast;
1mod agent_toast;
2mod center;
2mod center;
3mod incoming;
4mod layout;
5mod meeting_view;
3mod meeting_view;
6mod ring_view;
4mod ring_view;
7mod rules;
8mod settings;
9mod settings_mcp;
5mod settings_mcp;
10mod settings_view;
6mod settings_view;
11mod stack;
12mod text;
13mod toast;
7mod toast;
14
8
15pub use app_base::notify::{badge, platform, ring_tone};
9pub use state::notify::*;
16pub use center::NotificationCenter;
10pub use center::NotificationCenter;
17pub use incoming::{IncomingTracker, preview_of};
18#[cfg(windows)]
19pub use platform::native_handle;
20#[cfg(test)]
21pub use rules::ChatKind;
22pub use rules::{Incoming, Preview, channel_alerts};
23pub(crate) use settings_view::switch;
11pub(crate) use settings_view::switch;
crates/app/src/views/card_input_tests.rs added +255 −0
@@ -0,0 +1,255 @@
1 use std::sync::Arc;
2
3 use gpui_kit::{
4 AppContext as _, Context, Entity, IntoElement, Render, TestAppContext, VisualTestContext,
5 Window,
6 };
7 use serde_json::json;
8 use store::Store;
9 use teams_core::AdaptiveCard;
10
11 use crate::card_inputs::InputField;
12 use crate::app_state::{AppHandle, AppState, Mode};
13 use crate::card_actions::CardTask;
14 use crate::card_state::{CardScope, Surface};
15 use crate::views::adaptive_card::card_view;
16
17 struct Harness {
18 app: Entity<AppState>,
19 scope: CardScope,
20 card: AdaptiveCard,
21 }
22
23 impl Render for Harness {
24 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
25 self.app.update(cx, |state, cx| {
26 state.ensure_card_inputs(&self.scope, &self.card, window, cx)
27 });
28 card_view(&self.card, &self.scope, cx)
29 }
30 }
31
32 fn form_card() -> AdaptiveCard {
33 let card = json!({
34 "body": [
35 {"type": "Input.Text", "id": "name", "label": "Name", "isRequired": true, "errorMessage": "Name needed"},
36 {"type": "Input.Toggle", "id": "agree", "title": "Agree"}
37 ],
38 "actions": [
39 {"type": "Action.Submit", "title": "Save", "data": {"action": "save"}},
40 {"type": "Action.Submit", "title": "Skip", "associatedInputs": "none", "data": {"action": "skip"}}
41 ]
42 });
43 AdaptiveCard::parse(&card.to_string()).unwrap()
44 }
45
46 fn typed_card() -> AdaptiveCard {
47 let card = json!({
48 "body": [
49 {"type": "Input.Text", "id": "code", "maxLength": 3, "regex": "^[a-z]+$", "errorMessage": "Letters only"},
50 {"type": "Input.Date", "id": "day", "value": "2026-11-02", "min": "2026-10-01", "max": "2026-12-31"},
51 {"type": "Input.Time", "id": "hour", "value": "09:30", "min": "10:00", "errorMessage": "Too early"},
52 {"type": "Input.Number", "id": "count", "value": 4},
53 {"type": "Input.Rating", "id": "stars", "value": 2, "allowHalf": true}
54 ],
55 "actions": [{"type": "Action.Submit", "title": "Save", "data": {"action": "save"}}]
56 });
57 AdaptiveCard::parse(&card.to_string()).unwrap()
58 }
59
60 fn open(
61 cx: &mut TestAppContext,
62 surface: Surface,
63 ) -> (
64 &mut VisualTestContext,
65 Entity<AppState>,
66 CardScope,
67 AdaptiveCard,
68 ) {
69 open_card(cx, surface, form_card())
70 }
71
72 fn open_card(
73 cx: &mut TestAppContext,
74 surface: Surface,
75 card: AdaptiveCard,
76 ) -> (
77 &mut VisualTestContext,
78 Entity<AppState>,
79 CardScope,
80 AdaptiveCard,
81 ) {
82 cx.update(gpui_kit::init);
83 let store = Arc::new(Store::open_in_memory().unwrap());
84 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
85 cx.update(|cx| cx.set_global(AppHandle(app.clone())));
86 let scope = CardScope {
87 surface,
88 ..CardScope::message("19:chat@thread.v2", "m1", 0)
89 };
90 let (_, window_cx) = cx.add_window_view({
91 let (app, scope, card) = (app.clone(), scope.clone(), card.clone());
92 move |_, _| Harness { app, scope, card }
93 });
94 window_cx.update(|window, cx| window.draw(cx).clear(cx));
95 (window_cx, app, scope, card)
96 }
97
98 fn focus_name_field(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
99 let key = scope.input_key("name");
100 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
101 let Some(InputField::Line(line)) = field else {
102 panic!("name is a single line field");
103 };
104 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
105 }
106
107 fn task_for(
108 cx: &mut VisualTestContext,
109 app: &Entity<AppState>,
110 scope: &CardScope,
111 card: &AdaptiveCard,
112 action_index: usize,
113 ) -> Option<CardTask> {
114 let action = card.actions[action_index].clone();
115 let inputs = card.own_inputs();
116 cx.update(|_, cx| app.update(cx, |state, cx| state.card_task(scope, action, &inputs, cx)))
117 }
118
119 fn object(pairs: &[(&str, &str)]) -> serde_json::Value {
120 serde_json::Value::Object(
121 pairs
122 .iter()
123 .map(|(key, value)| ((*key).to_owned(), serde_json::Value::from(*value)))
124 .collect(),
125 )
126 }
127
128 fn error_of(cx: &mut VisualTestContext, app: &Entity<AppState>, key: &str) -> Option<String> {
129 cx.update(|_, cx| app.read(cx).cards.input_error(key).map(str::to_owned))
130 }
131
132 fn type_name(
133 cx: &mut VisualTestContext,
134 app: &Entity<AppState>,
135 scope: &CardScope,
136 text: &str,
137 ) {
138 focus_name_field(cx, app, scope);
139 cx.simulate_input(text);
140 }
141
142 fn switch_agree(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
143 let key = scope.input_key("agree");
144 cx.update(|_, cx| {
145 app.update(cx, |state, cx| {
146 state.pick_card_input(scope, &key, "true".into(), cx)
147 })
148 });
149 }
150
151 fn sent_value(task: Option<CardTask>) -> serde_json::Value {
152 match task {
153 Some(CardTask::Action(action)) => action.invoke_payload().unwrap().value,
154 Some(CardTask::Submit(data)) => data,
155 None => serde_json::Value::Null,
156 }
157 }
158
159 #[gpui_kit::test]
160 fn typed_text_and_toggle_are_sent_with_the_action_data(cx: &mut TestAppContext) {
161 let (cx, app, scope, card) = open(cx, Surface::Message);
162 type_name(cx, &app, &scope, "Ada");
163 switch_agree(cx, &app, &scope);
164 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
165 assert_eq!(
166 sent,
167 object(&[("action", "save"), ("name", "Ada"), ("agree", "true")])
168 );
169 }
170
171 #[gpui_kit::test]
172 fn an_empty_required_input_blocks_the_send_until_it_changes(cx: &mut TestAppContext) {
173 let (cx, app, scope, card) = open(cx, Surface::Message);
174 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
175 let key = scope.input_key("name");
176 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Name needed"));
177 type_name(cx, &app, &scope, "A");
178 assert_eq!(error_of(cx, &app, &key), None);
179 assert!(task_for(cx, &app, &scope, &card, 0).is_some());
180 }
181
182 #[gpui_kit::test]
183 fn associated_inputs_none_skips_collection_and_validation(cx: &mut TestAppContext) {
184 let (cx, app, scope, card) = open(cx, Surface::Message);
185 let sent = sent_value(task_for(cx, &app, &scope, &card, 1));
186 assert_eq!(sent, object(&[("action", "skip")]));
187 }
188
189 #[gpui_kit::test]
190 fn a_dialog_submit_carries_the_collected_values(cx: &mut TestAppContext) {
191 let (cx, app, scope, card) = open(cx, Surface::Dialog);
192 type_name(cx, &app, &scope, "Ada");
193 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
194 assert_eq!(
195 sent,
196 object(&[("action", "save"), ("name", "Ada"), ("agree", "false")])
197 );
198 }
199
200 #[gpui_kit::test]
201 fn typing_past_the_max_length_is_ignored(cx: &mut TestAppContext) {
202 let (cx, app, scope, _) = open_card(cx, Surface::Message, typed_card());
203 let key = scope.input_key("code");
204 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
205 let Some(InputField::Line(line)) = field else {
206 panic!("code is a single line field");
207 };
208 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
209 cx.simulate_input("abcdef");
210 assert_eq!(
211 cx.update(|_, cx| app.read(cx).cards.input_text(&key, cx)),
212 "abc"
213 );
214 }
215
216 #[gpui_kit::test]
217 fn blur_validation_shows_the_error_message(cx: &mut TestAppContext) {
218 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
219 let key = scope.input_key("code");
220 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
221 let Some(InputField::Line(line)) = field else {
222 panic!("code is a single line field");
223 };
224 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
225 cx.simulate_input("AB");
226 let input = card.own_inputs().remove(0);
227 cx.update(|_, cx| {
228 app.update(cx, |state, cx| {
229 state.validate_card_input(&scope, &key, &input, cx)
230 })
231 });
232 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Letters only"));
233 }
234
235 #[gpui_kit::test]
236 fn date_time_and_rating_values_are_collected_with_their_types(cx: &mut TestAppContext) {
237 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
238 let hour_key = scope.input_key("hour");
239 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
240 assert_eq!(error_of(cx, &app, &hour_key).as_deref(), Some("Too early"));
241 cx.update(|_, cx| {
242 app.update(cx, |state, cx| {
243 state.pick_card_input(&scope, &hour_key, "10:15".into(), cx);
244 state.pick_card_input(&scope, &scope.input_key("stars"), "3.5".into(), cx);
245 })
246 });
247 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
248 assert_eq!(
249 sent,
250 json!({
251 "action": "save", "code": "", "day": "2026-11-02", "hour": "10:15",
252 "count": "4", "stars": 3.5
253 })
254 );
255 }
@@ -0,0 +1,255 @@
1use std::sync::Arc;
2
3use gpui_kit::{
4 AppContext as _, Context, Entity, IntoElement, Render, TestAppContext, VisualTestContext,
5 Window,
6};
7use serde_json::json;
8use store::Store;
9use teams_core::AdaptiveCard;
10
11use crate::card_inputs::InputField;
12use crate::app_state::{AppHandle, AppState, Mode};
13use crate::card_actions::CardTask;
14use crate::card_state::{CardScope, Surface};
15use crate::views::adaptive_card::card_view;
16
17struct Harness {
18 app: Entity<AppState>,
19 scope: CardScope,
20 card: AdaptiveCard,
21}
22
23impl Render for Harness {
24 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
25 self.app.update(cx, |state, cx| {
26 state.ensure_card_inputs(&self.scope, &self.card, window, cx)
27 });
28 card_view(&self.card, &self.scope, cx)
29 }
30}
31
32fn form_card() -> AdaptiveCard {
33 let card = json!({
34 "body": [
35 {"type": "Input.Text", "id": "name", "label": "Name", "isRequired": true, "errorMessage": "Name needed"},
36 {"type": "Input.Toggle", "id": "agree", "title": "Agree"}
37 ],
38 "actions": [
39 {"type": "Action.Submit", "title": "Save", "data": {"action": "save"}},
40 {"type": "Action.Submit", "title": "Skip", "associatedInputs": "none", "data": {"action": "skip"}}
41 ]
42 });
43 AdaptiveCard::parse(&card.to_string()).unwrap()
44}
45
46fn typed_card() -> AdaptiveCard {
47 let card = json!({
48 "body": [
49 {"type": "Input.Text", "id": "code", "maxLength": 3, "regex": "^[a-z]+$", "errorMessage": "Letters only"},
50 {"type": "Input.Date", "id": "day", "value": "2026-11-02", "min": "2026-10-01", "max": "2026-12-31"},
51 {"type": "Input.Time", "id": "hour", "value": "09:30", "min": "10:00", "errorMessage": "Too early"},
52 {"type": "Input.Number", "id": "count", "value": 4},
53 {"type": "Input.Rating", "id": "stars", "value": 2, "allowHalf": true}
54 ],
55 "actions": [{"type": "Action.Submit", "title": "Save", "data": {"action": "save"}}]
56 });
57 AdaptiveCard::parse(&card.to_string()).unwrap()
58}
59
60fn open(
61 cx: &mut TestAppContext,
62 surface: Surface,
63) -> (
64 &mut VisualTestContext,
65 Entity<AppState>,
66 CardScope,
67 AdaptiveCard,
68) {
69 open_card(cx, surface, form_card())
70}
71
72fn open_card(
73 cx: &mut TestAppContext,
74 surface: Surface,
75 card: AdaptiveCard,
76) -> (
77 &mut VisualTestContext,
78 Entity<AppState>,
79 CardScope,
80 AdaptiveCard,
81) {
82 cx.update(gpui_kit::init);
83 let store = Arc::new(Store::open_in_memory().unwrap());
84 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
85 cx.update(|cx| cx.set_global(AppHandle(app.clone())));
86 let scope = CardScope {
87 surface,
88 ..CardScope::message("19:chat@thread.v2", "m1", 0)
89 };
90 let (_, window_cx) = cx.add_window_view({
91 let (app, scope, card) = (app.clone(), scope.clone(), card.clone());
92 move |_, _| Harness { app, scope, card }
93 });
94 window_cx.update(|window, cx| window.draw(cx).clear(cx));
95 (window_cx, app, scope, card)
96}
97
98fn focus_name_field(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
99 let key = scope.input_key("name");
100 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
101 let Some(InputField::Line(line)) = field else {
102 panic!("name is a single line field");
103 };
104 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
105}
106
107fn task_for(
108 cx: &mut VisualTestContext,
109 app: &Entity<AppState>,
110 scope: &CardScope,
111 card: &AdaptiveCard,
112 action_index: usize,
113) -> Option<CardTask> {
114 let action = card.actions[action_index].clone();
115 let inputs = card.own_inputs();
116 cx.update(|_, cx| app.update(cx, |state, cx| state.card_task(scope, action, &inputs, cx)))
117}
118
119fn object(pairs: &[(&str, &str)]) -> serde_json::Value {
120 serde_json::Value::Object(
121 pairs
122 .iter()
123 .map(|(key, value)| ((*key).to_owned(), serde_json::Value::from(*value)))
124 .collect(),
125 )
126}
127
128fn error_of(cx: &mut VisualTestContext, app: &Entity<AppState>, key: &str) -> Option<String> {
129 cx.update(|_, cx| app.read(cx).cards.input_error(key).map(str::to_owned))
130}
131
132fn type_name(
133 cx: &mut VisualTestContext,
134 app: &Entity<AppState>,
135 scope: &CardScope,
136 text: &str,
137) {
138 focus_name_field(cx, app, scope);
139 cx.simulate_input(text);
140}
141
142fn switch_agree(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
143 let key = scope.input_key("agree");
144 cx.update(|_, cx| {
145 app.update(cx, |state, cx| {
146 state.pick_card_input(scope, &key, "true".into(), cx)
147 })
148 });
149}
150
151fn sent_value(task: Option<CardTask>) -> serde_json::Value {
152 match task {
153 Some(CardTask::Action(action)) => action.invoke_payload().unwrap().value,
154 Some(CardTask::Submit(data)) => data,
155 None => serde_json::Value::Null,
156 }
157}
158
159#[gpui_kit::test]
160fn typed_text_and_toggle_are_sent_with_the_action_data(cx: &mut TestAppContext) {
161 let (cx, app, scope, card) = open(cx, Surface::Message);
162 type_name(cx, &app, &scope, "Ada");
163 switch_agree(cx, &app, &scope);
164 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
165 assert_eq!(
166 sent,
167 object(&[("action", "save"), ("name", "Ada"), ("agree", "true")])
168 );
169}
170
171#[gpui_kit::test]
172fn an_empty_required_input_blocks_the_send_until_it_changes(cx: &mut TestAppContext) {
173 let (cx, app, scope, card) = open(cx, Surface::Message);
174 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
175 let key = scope.input_key("name");
176 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Name needed"));
177 type_name(cx, &app, &scope, "A");
178 assert_eq!(error_of(cx, &app, &key), None);
179 assert!(task_for(cx, &app, &scope, &card, 0).is_some());
180}
181
182#[gpui_kit::test]
183fn associated_inputs_none_skips_collection_and_validation(cx: &mut TestAppContext) {
184 let (cx, app, scope, card) = open(cx, Surface::Message);
185 let sent = sent_value(task_for(cx, &app, &scope, &card, 1));
186 assert_eq!(sent, object(&[("action", "skip")]));
187}
188
189#[gpui_kit::test]
190fn a_dialog_submit_carries_the_collected_values(cx: &mut TestAppContext) {
191 let (cx, app, scope, card) = open(cx, Surface::Dialog);
192 type_name(cx, &app, &scope, "Ada");
193 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
194 assert_eq!(
195 sent,
196 object(&[("action", "save"), ("name", "Ada"), ("agree", "false")])
197 );
198}
199
200#[gpui_kit::test]
201fn typing_past_the_max_length_is_ignored(cx: &mut TestAppContext) {
202 let (cx, app, scope, _) = open_card(cx, Surface::Message, typed_card());
203 let key = scope.input_key("code");
204 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
205 let Some(InputField::Line(line)) = field else {
206 panic!("code is a single line field");
207 };
208 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
209 cx.simulate_input("abcdef");
210 assert_eq!(
211 cx.update(|_, cx| app.read(cx).cards.input_text(&key, cx)),
212 "abc"
213 );
214}
215
216#[gpui_kit::test]
217fn blur_validation_shows_the_error_message(cx: &mut TestAppContext) {
218 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
219 let key = scope.input_key("code");
220 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
221 let Some(InputField::Line(line)) = field else {
222 panic!("code is a single line field");
223 };
224 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
225 cx.simulate_input("AB");
226 let input = card.own_inputs().remove(0);
227 cx.update(|_, cx| {
228 app.update(cx, |state, cx| {
229 state.validate_card_input(&scope, &key, &input, cx)
230 })
231 });
232 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Letters only"));
233}
234
235#[gpui_kit::test]
236fn date_time_and_rating_values_are_collected_with_their_types(cx: &mut TestAppContext) {
237 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
238 let hour_key = scope.input_key("hour");
239 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
240 assert_eq!(error_of(cx, &app, &hour_key).as_deref(), Some("Too early"));
241 cx.update(|_, cx| {
242 app.update(cx, |state, cx| {
243 state.pick_card_input(&scope, &hour_key, "10:15".into(), cx);
244 state.pick_card_input(&scope, &scope.input_key("stars"), "3.5".into(), cx);
245 })
246 });
247 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
248 assert_eq!(
249 sent,
250 json!({
251 "action": "save", "code": "", "day": "2026-11-02", "hour": "10:15",
252 "count": "4", "stars": 3.5
253 })
254 );
255}
crates/app/src/views/mod.rs +2 −0
@@ -22,6 +22,8 @@ pub mod call_view;
22 22 pub mod call_view_menu;
23 23 pub mod calls_tab;
24 24 pub mod card_carousel;
25 #[cfg(test)]
26 mod card_input_tests;
25 27 pub mod card_code_block;
26 28 pub mod card_icon;
27 29 pub mod card_input;
@@ -22,6 +22,8 @@ pub mod call_view;
22pub mod call_view_menu;
22pub mod call_view_menu;
23pub mod calls_tab;
23pub mod calls_tab;
24pub mod card_carousel;
24pub mod card_carousel;
25#[cfg(test)]
26mod card_input_tests;
25pub mod card_code_block;
27pub mod card_code_block;
26pub mod card_icon;
28pub mod card_icon;
27pub mod card_input;
29pub mod card_input;