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