Skip to main content

fauna_api/extensions/web/
session.rs

1use std::sync::Arc;
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5
6use super::tools::page_tools;
7use crate::authentification::CredentialsOrApiKey;
8use crate::error::{Error, Result};
9use crate::http::{client, encode, ok};
10use crate::marmot::web::{WebRoom, WebRoomHooks, WebTarget, connect_web_room};
11use crate::parrot::chat::{CreateChatOptions, create_chat, delete_chat};
12use crate::parrot::generative::Tool;
13use crate::parrot::room::{ChatRoom, RoomHooks, connect_room};
14use crate::parrot::share::{ChatTarget, OpenRoomOptions, open_room};
15use crate::shared::server::Presence;
16
17/// Public join URL for a web-room access code (chat joins via ensure, not the URL).
18/// `origin` defaults to `https://app.faunakit.com`.
19pub fn share_url(code: &str, origin: Option<&str>) -> String {
20    // Trailing slash is required: without it Vite (and many static hosts) serve
21    // the app root `index.html` instead of `extensions/web/index.html`.
22    let origin = origin.unwrap_or("https://app.faunakit.com");
23    format!(
24        "{}/extensions/web/?access-code={}",
25        origin.strip_suffix('/').unwrap_or(origin),
26        encode(code)
27    )
28}
29
30#[derive(Default, Clone)]
31pub struct SessionHooks {
32    pub web: Option<Arc<dyn WebRoomHooks>>,
33    pub chat: Option<Arc<dyn RoomHooks>>,
34}
35
36/// A paired live session: one `WebRoom` (live page DOM) + one `ChatRoom`.
37/// Share links carry only the web access code; chat uses ensure + Parrot code.
38#[derive(Clone)]
39pub struct ExtensionWebSession {
40    pub web: WebRoom,
41    pub chat: ChatRoom,
42    pub web_self: Presence,
43    pub chat_self: Presence,
44    /// Bare web access code used in the share URL.
45    pub code: String,
46    /// The temporary chat this session made as host, deleted when it closes.
47    made_chat: Option<(CredentialsOrApiKey, String)>,
48}
49
50impl ExtensionWebSession {
51    pub fn share_code(&self) -> String {
52        self.code.clone()
53    }
54
55    /// Page tools routed through the web room (host executes).
56    pub fn page_tools(&self) -> Vec<Tool> {
57        let web = self.web.clone();
58        page_tools(Arc::new(move |name, params| {
59            let web = web.clone();
60            Box::pin(async move {
61                let name = match serde_json::to_value(name)? {
62                    Value::String(name) => name,
63                    name => name.to_string(),
64                };
65                web.invoke_tool(&name, params, None).await
66            })
67        }))
68    }
69
70    pub fn close(&self) {
71        self.web.publish_closed();
72        self.web.disconnect();
73        self.chat.disconnect();
74        if let Some((authorization, chat_id)) = self.made_chat.clone() {
75            // A failed delete is left to the idle sweep.
76            tokio::spawn(async move {
77                let _ = delete_chat(&authorization, &chat_id, None).await;
78            });
79        }
80    }
81}
82
83/// Cached chat half of a share: a temporary Parrot chat. The content script only
84/// makes and opens it (`open_room`); the chat iframe owns the live `ChatRoom`
85/// socket so the host does not double-join presence.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "camelCase")]
88pub struct CachedChatRoom {
89    pub chat_id: String,
90    pub reference: String,
91    pub room_id: String,
92    pub code: String,
93}
94
95/// A share's temporary chat, opened with an access code.
96async fn open_share_chat(authorization: &CredentialsOrApiKey) -> Result<CachedChatRoom> {
97    let chat_id = create_chat(
98        authorization,
99        Some("Web share"),
100        None,
101        CreateChatOptions {
102            temporary: Some(true),
103            ..CreateChatOptions::default()
104        },
105    )
106    .await?;
107    let opened = open_room(
108        authorization,
109        &chat_id,
110        OpenRoomOptions {
111            share: Some(true),
112            ..OpenRoomOptions::default()
113        },
114    )
115    .await?;
116    Ok(CachedChatRoom {
117        chat_id,
118        reference: opened.reference,
119        room_id: opened.room_id,
120        code: opened.code.unwrap_or_default(),
121    })
122}
123
124/// Open (or return) this tab's shared chat, a temporary Parrot chat. Lives until
125/// the host leaves the page (`end_chat_room`): closing the panel keeps it. Does
126/// not connect a socket here; call `connect_room` from the chat UI with `code`.
127pub async fn ensure_chat_room(
128    authorization: &CredentialsOrApiKey,
129    cached: Option<&CachedChatRoom>,
130) -> Result<CachedChatRoom> {
131    if let Some(cached) = cached.filter(|cached| !cached.code.is_empty()) {
132        return Ok(cached.clone());
133    }
134    open_share_chat(authorization).await
135}
136
137/// Deletes a share's temporary chat once the host leaves.
138pub async fn end_chat_room(
139    authorization: &CredentialsOrApiKey,
140    chat: &CachedChatRoom,
141) -> Result<()> {
142    delete_chat(authorization, &chat.chat_id, None).await
143}
144
145/// `{ accessCode } | { reference }` in the TypeScript SDK: a web room as a guest
146/// joined it, or as its host opened it.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub enum AccessScope {
149    AccessCode { access_code: String },
150    Reference { reference: String },
151}
152
153/// The `opts` argument of `ensure_chat_from_web_access`.
154#[derive(Debug, Clone, Default)]
155pub struct EnsureOptions {
156    pub room: Option<String>,
157}
158
159/// `{ room, code }` in the TypeScript SDK.
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161pub struct EnsuredChat {
162    pub room: String,
163    pub code: String,
164}
165
166fn scoped(
167    request: reqwest::RequestBuilder,
168    authorization: &CredentialsOrApiKey,
169    scope: &AccessScope,
170) -> reqwest::RequestBuilder {
171    let request = request.header("Content-Type", "application/json").header(
172        "Authorization",
173        match authorization {
174            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
175            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
176        },
177    );
178    match scope {
179        AccessScope::AccessCode { access_code } => request.header("Access-Code", access_code),
180        AccessScope::Reference { reference } => request.header("Server", reference),
181    }
182}
183
184/// Bind (host) or open the Parrot room paired with a web room. The host binds a
185/// room it opened (`room` is its reference). Always returns a fresh Parrot access
186/// code for `connect_room(ChatTarget::Code { code })`.
187pub async fn ensure_chat_from_web_access(
188    authorization: &CredentialsOrApiKey,
189    scope: &AccessScope,
190    opts: EnsureOptions,
191) -> Result<EnsuredChat> {
192    let body = match opts.room.filter(|room| !room.is_empty()) {
193        Some(room) => json!({ "room": room }),
194        None => json!({}),
195    };
196    let response = scoped(
197        client().post(format!(
198            "{}/extensions/web/chat/ensure",
199            crate::marmot::get_url()
200        )),
201        authorization,
202        scope,
203    )
204    .json(&body)
205    .send()
206    .await?;
207    let json: Value = ok(response).await?.json().await?;
208    match (
209        json["room"].as_str().filter(|room| !room.is_empty()),
210        json["code"].as_str().filter(|code| !code.is_empty()),
211    ) {
212        (Some(room), Some(code)) => Ok(EnsuredChat {
213            room: room.to_string(),
214            code: code.to_string(),
215        }),
216        _ => Err(Error::Message(
217            "Invalid web chat ensure response.".to_string(),
218        )),
219    }
220}
221
222/// Opens a shared chat and a hosted web room paired with it. Page capture stays
223/// with the browser, so the session only carries the rooms.
224pub async fn open_session(
225    authorization: &CredentialsOrApiKey,
226    hooks: SessionHooks,
227) -> Result<ExtensionWebSession> {
228    let opened_chat = open_share_chat(authorization).await?;
229    let chat_code = opened_chat.code.clone();
230
231    let reference = format!("web:{}", uuid::Uuid::new_v4());
232    let (web, web_self) = connect_web_room(
233        authorization,
234        &WebTarget::Reference {
235            reference: reference.clone(),
236        },
237        hooks.web,
238    )
239    .await?;
240    let web_code = web.generate_access_code().await?;
241    ensure_chat_from_web_access(
242        authorization,
243        &AccessScope::Reference { reference },
244        EnsureOptions {
245            room: Some(opened_chat.reference),
246        },
247    )
248    .await?;
249
250    let (chat, chat_self) = connect_room(
251        authorization,
252        &ChatTarget::Code { code: chat_code },
253        hooks.chat,
254    )
255    .await?;
256
257    Ok(ExtensionWebSession {
258        web,
259        chat,
260        web_self,
261        chat_self,
262        code: web_code,
263        made_chat: Some((authorization.clone(), opened_chat.chat_id)),
264    })
265}
266
267/// Joins a shared page by its web access code, with the chat paired with it.
268pub async fn join_room(
269    authorization: &CredentialsOrApiKey,
270    web_code: &str,
271    hooks: SessionHooks,
272) -> Result<ExtensionWebSession> {
273    let (web, web_self) = connect_web_room(
274        authorization,
275        &WebTarget::Code {
276            code: web_code.to_string(),
277        },
278        hooks.web,
279    )
280    .await?;
281
282    let ensured = ensure_chat_from_web_access(
283        authorization,
284        &AccessScope::AccessCode {
285            access_code: web_code.to_string(),
286        },
287        EnsureOptions::default(),
288    )
289    .await?;
290    let (chat, chat_self) = connect_room(
291        authorization,
292        &ChatTarget::Code { code: ensured.code },
293        hooks.chat,
294    )
295    .await?;
296
297    Ok(ExtensionWebSession {
298        web,
299        chat,
300        web_self,
301        chat_self,
302        code: web_code.to_string(),
303        made_chat: None,
304    })
305}
306
307pub async fn invite(
308    authorization: &CredentialsOrApiKey,
309    email: &str,
310    join_url: &str,
311    scope: &AccessScope,
312) -> Result<()> {
313    let response = scoped(
314        client().post(format!(
315            "{}/extensions/web/invite",
316            crate::marmot::get_url()
317        )),
318        authorization,
319        scope,
320    )
321    .json(&json!({ "email": email, "joinUrl": join_url }))
322    .send()
323    .await?;
324    ok(response).await?;
325    Ok(())
326}