fauna-api 1.0.759

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
use std::ops::Deref;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

use super::generative::{Content, Part, Reaction, Role, Tool, ToolsOrTool};
use super::share::{
    AppendOptions, AppendResult, ChatTarget, SteerOptions, append_room_message,
    list_room_attachments, page_messages, room_parts, set_room_repository, steer_room,
    unqueue_room_message,
};
use crate::authentification::{CredentialsOrApiKey, Profile};
use crate::billing::PageQuery;
use crate::error::Result;
use crate::groups::Group;
use crate::shared::server::{Authorization, Hooks, Presence, Room, connect};
use crate::termite::versioning::Repository;

pub use super::share::Attachment;

/// One durable message in a room transcript. Parts keep their file refs as
/// streaming `drive::File`s (no bytes over the socket); `download()` them when
/// you need the bytes. `author` is the sender's public Profile (USER turns only).
#[derive(Debug, Clone)]
pub struct RoomMessage {
    pub id: String,
    pub position: u32,
    pub role: Role,
    pub parts: Vec<Part>,
    pub author: Option<Profile>,
    pub reply_to: Option<String>,
    /// LLM id that produced a MODEL turn (for UI avatar / rehydrate).
    pub model: Option<String>,
    pub created: i64,
    /// The name of the API key an agent posted this with, for its author.
    pub via: Option<String>,
}

fn text(value: &Value) -> String {
    match value {
        Value::String(value) => value.clone(),
        Value::Null => String::new(),
        value => value.to_string(),
    }
}

fn optional(value: &Value) -> Option<String> {
    value.as_str().map(str::to_string)
}

impl RoomMessage {
    pub(crate) fn from_json(
        json: &Value,
        authorization: &CredentialsOrApiKey,
        target: &ChatTarget,
    ) -> RoomMessage {
        RoomMessage {
            id: text(&json["id"]),
            position: json["position"].as_f64().unwrap_or_default() as u32,
            role: serde_json::from_value(json["role"].clone()).unwrap_or(Role::User),
            parts: room_parts(&json["parts"], authorization, target),
            author: Profile::from_json(&json["author"]),
            reply_to: optional(&json["replyTo"]),
            model: optional(&json["model"]),
            created: json["created"].as_f64().unwrap_or_default() as i64,
            via: optional(&json["via"]).filter(|via| !via.is_empty()),
        }
    }
}

/// One buffered send in the shared room queue. When a member sends while the
/// model is replying, it lands here (visible to all members) instead of the
/// transcript, and drains FIFO into the transcript as replies complete. `id` is
/// the stable per-row key used for unqueue/steer targeting and orders the queue.
#[derive(Debug, Clone)]
pub struct RoomQueueItem {
    pub id: String,
    pub role: Role,
    pub parts: Vec<Part>,
    pub author: Option<Profile>,
    pub model: Option<String>,
    pub reasoning: Option<String>,
    pub reply_to: Option<String>,
    pub created: i64,
}

impl RoomQueueItem {
    pub(crate) fn from_json(
        json: &Value,
        authorization: &CredentialsOrApiKey,
        target: &ChatTarget,
    ) -> RoomQueueItem {
        RoomQueueItem {
            id: text(&json["id"]),
            role: serde_json::from_value(json["role"].clone()).unwrap_or(Role::User),
            parts: room_parts(&json["parts"], authorization, target),
            author: Profile::from_json(&json["author"]),
            model: optional(&json["model"]),
            reasoning: optional(&json["reasoning"]),
            reply_to: optional(&json["replyTo"]),
            created: json["created"].as_f64().unwrap_or_default() as i64,
        }
    }
}

/// `"running" | "success" | "error"` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolStatus {
    Running,
    Success,
    Error,
}

/// `"browser" | "desktop"` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolSessionKind {
    Browser,
    Desktop,
}

/// The live room a tool opened, to watch it: a browser, joined with its access
/// code, or a machine's desktop, joined by reference by the people who may use
/// the machine.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolSession {
    pub kind: ToolSessionKind,
    pub reference: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RoomToolState {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub args: Map<String, Value>,
    pub status: ToolStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,
    /// What a running tool is waiting on, like the machine starting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub progress: Option<String>,
    /// The live room the tool opened, to watch it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<ToolSession>,
}

fn tool_states(json: &Value) -> Vec<RoomToolState> {
    json.as_array()
        .into_iter()
        .flatten()
        .filter_map(|tool| serde_json::from_value(tool.clone()).ok())
        .collect()
}

/// The in-progress streamed model reply: `{ turn, text, tools, files }` in the
/// TypeScript SDK.
#[derive(Debug, Clone)]
pub struct StreamingReply {
    pub turn: String,
    pub text: String,
    pub tools: Vec<RoomToolState>,
    pub files: Vec<Attachment>,
}

/// An originator-only client tool call: `{ id, name, args, turn? }` in the
/// TypeScript SDK.
#[derive(Debug, Clone, PartialEq)]
pub struct RoomToolCall {
    pub id: String,
    pub name: String,
    pub args: Map<String, Value>,
    pub turn: Option<String>,
}

/// Chat room hooks. Every method defaults to a no-op, like the optional members
/// of the TypeScript `RoomHooks` object.
pub trait RoomHooks: Send + Sync {
    /// A new message landed (any member's send, or the server's model reply).
    fn on_message(&self, _room: &ChatRoom, _message: &RoomMessage) {}
    /// The shared queue changed (an item was buffered, released, or unqueued).
    fn on_queue(&self, _room: &ChatRoom) {}
    /// The room's model reply started (true) or finished (false).
    fn on_thinking(&self, _room: &ChatRoom, _thinking: bool) {}
    /// The room's model reply is streaming. `text` is the full reply so far;
    /// `delta` is the new portion since the last call. Fires as the reply grows.
    /// When the turn finishes, the finished reply also arrives via `on_message` (a
    /// durable row). `aborted` is true on the terminal call: the streamed turn
    /// finalized or was cancelled; drop the partial and rely on `on_message`.
    /// `files` are what the reply attached so far.
    #[allow(clippy::too_many_arguments)]
    fn on_delta(
        &self,
        _room: &ChatRoom,
        _turn: &str,
        _delta: &str,
        _text: &str,
        _aborted: bool,
        _tools: &[RoomToolState],
        _files: &[Attachment],
    ) {
    }
    /// Originator-only client tool call (evaluate locally, then send_tool_result).
    fn on_tool_call(&self, _room: &ChatRoom, _call: &RoomToolCall) {}
    /// The chat was renamed.
    fn on_renamed(&self, _room: &ChatRoom, _name: &str) {}
    /// The chat's repository was attached, swapped or detached.
    fn on_repository(&self, _room: &ChatRoom) {}
    /// The reply pointed everyone to a file (Parrot's `open`): show it.
    fn on_open_file(&self, _room: &ChatRoom, _attachment: &Attachment) {}
    /// The chat was deleted/closed by its owner (or the host disconnected).
    fn on_closed(&self, _room: &ChatRoom) {}
    /// The roster changed (someone joined/left or updated presence/status).
    fn on_presence(&self, _room: &ChatRoom) {}
}

impl RoomHooks for () {}

const OLDER_PAGE: u32 = 20;

type RepositoryWatcher = Arc<dyn Fn(Option<u64>) + Send + Sync>;

#[derive(Default)]
struct Chat {
    messages: Vec<RoomMessage>,
    queue: Vec<RoomQueueItem>,
    thinking: bool,
    name: String,
    system_prompt: String,
    human: bool,
    repository: Option<u64>,
    owner: String,
    write: bool,
    reference: String,
    has_more: bool,
    // The current streamed model turn so far (by turn id).
    streaming: Option<StreamingReply>,
}

struct ChatState {
    target: ChatTarget,
    chat: Mutex<Chat>,
    hooks: Mutex<Arc<dyn RoomHooks>>,
    client_tools: Mutex<Vec<Tool>>,
    repository_watchers: Mutex<Vec<(u64, RepositoryWatcher)>>,
    next_watcher: AtomicU64,
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// A live, domain-agnostic chat room. `ChatRoom` wraps `Room` and owns everything
/// chat-transcript-specific: a WINDOWED transcript (the last page hydrated on
/// connect), `load_older()` pagination for scroll-up backfill, the shared
/// queue, and the streamed model reply. It is NOT tied to a durable "chat":
/// Parrot, Extensions.Web, and Marmot's chat side all reuse it. The generic
/// `Room` stays domain-agnostic (presence + deltas) for non-chat rooms.
///
/// Sends go through the append edge (so file parts stream) and the server owns
/// turn-taking: once the room goes quiet it streams one model reply over the
/// whole transcript, billed to the room's host principal.
#[derive(Clone)]
pub struct ChatRoom {
    room: Room,
    inner: Arc<ChatState>,
}

impl Deref for ChatRoom {
    type Target = Room;
    fn deref(&self) -> &Room {
        &self.room
    }
}

impl ChatRoom {
    fn chat(&self) -> MutexGuard<'_, Chat> {
        lock(&self.inner.chat)
    }

    fn hooks(&self) -> Arc<dyn RoomHooks> {
        lock(&self.inner.hooks).clone()
    }

    /// The currently-loaded transcript window, in order.
    pub fn get_messages(&self) -> Vec<RoomMessage> {
        self.chat().messages.clone()
    }

    /// The current shared queue (buffered sends), in FIFO order.
    pub fn get_queue(&self) -> Vec<RoomQueueItem> {
        self.chat().queue.clone()
    }

    /// The chat's name.
    pub fn get_name(&self) -> String {
        self.chat().name.clone()
    }

    /// Room system prompt (not a transcript row). Empty when unset.
    pub fn get_system_prompt(&self) -> String {
        self.chat().system_prompt.clone()
    }

    /// True for a people only chat: no model ever replies, so sends never queue.
    pub fn is_human(&self) -> bool {
        self.chat().human
    }

    /// False when you joined with a share link that only lets you read along.
    pub fn can_write(&self) -> bool {
        self.chat().write
    }

    /// The chat's repository, by id. Kept current for everyone in the room.
    pub fn repository(&self) -> Option<u64> {
        self.chat().repository
    }

    /// The saved chat this room is bound to, by id, or None for an unbound room.
    pub fn chat_id(&self) -> Option<String> {
        let reference = self.chat().reference.clone();
        reference
            .strip_prefix("parrot:chat:")
            .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
            .map(str::to_string)
    }

    /// Who owns the chat: `credentials:{id}`, `group:{id}`, `friend:{id}` or `partnership:{id}`. Empty for an unbound room.
    pub fn owner(&self) -> String {
        self.chat().owner.clone()
    }

    /// The group that owns the chat, whose repositories it takes; None for anyone else's.
    pub fn group(&self) -> Option<Group> {
        let owner = self.owner();
        owner
            .strip_prefix("group:")
            .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
            .map(|id| Group::from_json(&json!({ "id": id })))
    }

    /// Attach a repository, or None to detach. Everyone in the room sees the change.
    pub async fn set_repository(&self, repository: Option<&Repository>) -> Result<()> {
        set_room_repository(
            self.get_authorization(),
            &self.inner.target,
            repository.map(|repository| repository.id),
        )
        .await
    }

    /// Hear about every repository change, from anyone in the room. Returns a function that stops listening.
    pub fn watch_repository(
        &self,
        listener: impl Fn(Option<u64>) + Send + Sync + 'static,
    ) -> Box<dyn FnOnce() + Send + Sync> {
        let id = self.inner.next_watcher.fetch_add(1, Ordering::Relaxed);
        lock(&self.inner.repository_watchers).push((id, Arc::new(listener)));
        let inner = Arc::downgrade(&self.inner);
        Box::new(move || {
            if let Some(inner) = inner.upgrade() {
                lock(&inner.repository_watchers).retain(|(other, _)| *other != id);
            }
        })
    }

    /// Every file in the chat, newest first: what people attached and what Parrot opened.
    pub async fn attachments(&self) -> Result<Vec<Attachment>> {
        list_room_attachments(self.get_authorization(), &self.inner.target).await
    }

    /// True while the server is streaming the room's model reply.
    pub fn is_thinking(&self) -> bool {
        self.chat().thinking
    }

    /// True while older transcript pages remain to be loaded (scroll-up).
    pub fn has_more(&self) -> bool {
        self.chat().has_more
    }

    /// The in-progress streamed model reply, or None when none is streaming.
    pub fn streaming_reply(&self) -> Option<StreamingReply> {
        self.chat().streaming.clone()
    }

    /// Send the reply under way (thinking, and the streamed turn so far) to the hooks
    /// again, for a UI that sets its hooks after connecting in the middle of a reply.
    pub fn replay_reply(&self) {
        let (thinking, streaming) = {
            let chat = self.chat();
            (chat.thinking, chat.streaming.clone())
        };
        let hooks = self.hooks();
        if thinking {
            hooks.on_thinking(self, true);
        }
        if let Some(s) = streaming {
            hooks.on_delta(self, &s.turn, &s.text, &s.text, false, &s.tools, &s.files);
        }
    }

    /// Load one older page of transcript messages and merge it into the window by
    /// position. The cursor is how many messages are already loaded, counted from
    /// the newest, so live messages that arrived since connect keep it correct.
    /// File parts stream lazily via their `drive::File`s.
    pub async fn load_older(&self) -> Result<Vec<RoomMessage>> {
        let cursor = self.chat().messages.len() as u32;
        let page = page_messages(
            self.get_authorization(),
            &self.inner.target,
            PageQuery {
                cursor,
                max: OLDER_PAGE,
            },
        )
        .await?;
        let mut chat = self.chat();
        let older: Vec<RoomMessage> = page
            .iter()
            .filter(|message| {
                !chat
                    .messages
                    .iter()
                    .any(|known| known.position == message.position)
            })
            .map(|message| RoomMessage {
                id: message.id.clone(),
                position: message.position,
                role: message.role,
                parts: message.parts.clone(),
                author: message.author.clone(),
                reply_to: message.reply_to.clone(),
                model: message.model.clone(),
                created: message.created,
                via: message.via.clone(),
            })
            .collect();
        let mut messages = older.clone();
        messages.append(&mut chat.messages);
        messages.sort_by_key(|message| message.position);
        chat.messages = messages;
        chat.has_more = page.len() as u32 == OLDER_PAGE;
        Ok(older)
    }

    /// Append a message to the shared transcript. USER sends are attributed to
    /// the caller and nudge the server's debounced model reply. If the room is
    /// currently replying the server buffers the send into the shared queue
    /// instead (drained FIFO when the reply finishes); the result says which
    /// happened. File parts stream their bytes with the message. `model`
    /// (optional) is the sender's selected model; the reply uses the last
    /// sender's choice.
    pub async fn send_message(
        &self,
        role: Role,
        parts: Vec<Part>,
        options: AppendOptions,
    ) -> Result<AppendResult> {
        append_room_message(
            self.get_authorization(),
            &self.inner.target,
            &Content {
                parts,
                role,
                created_at: Utc::now(),
                author: None,
                model: None,
                via: None,
            },
            options,
        )
        .await
    }

    /// React to the message at transcript `position`. A reaction is its own USER
    /// message (so in a chat with a model it prompts a reply like any send);
    /// `on: Some(false)` takes it back.
    pub async fn react(
        &self,
        position: u32,
        emoji: &str,
        on: Option<bool>,
    ) -> Result<AppendResult> {
        let reaction = Reaction {
            emoji: emoji.to_string(),
            position,
            on: on.unwrap_or(true),
        };
        self.send_message(
            Role::User,
            vec![Part::Reaction(reaction)],
            AppendOptions::default(),
        )
        .await
    }

    /// Reply to a client tool_call addressed to this originator.
    pub fn send_tool_result(&self, call_id: &str, result: &str) {
        self.post(&json!({ "event": "tool-result", "id": call_id, "result": result }));
    }

    /// Register Tool.evaluate handlers for originator-only room tool calls.
    /// When a chat-tool-call arrives, matching tools auto-evaluate and reply.
    pub fn set_client_tools(&self, tools: Option<ToolsOrTool>) {
        *lock(&self.inner.client_tools) = match tools {
            None => Vec::new(),
            Some(ToolsOrTool::Tools(tools)) => tools,
            Some(ToolsOrTool::Tool(tool)) => vec![tool],
        };
    }

    /// Remove one of your buffered messages from the shared queue. It never
    /// entered the transcript, so this is not an unsend: the server just drops
    /// the queue row and it fans out to every member.
    pub async fn unqueue(&self, queue_id: &str) -> Result<()> {
        unqueue_room_message(self.get_authorization(), &self.inner.target, queue_id).await
    }

    /// Steer the room: stop the in-progress model reply now and have the server
    /// re-answer after the normal debounce window. Any member may steer.
    /// `queue_id` releases just that one queued row into the transcript first
    /// (per-item steer); `all` flushes the whole queue in FIFO order (steer-all).
    /// Released rows behave like idle sends: the model does NOT reply immediately.
    /// `stop` cancels the current reply without scheduling a new one.
    pub async fn steer(&self, options: SteerOptions) -> Result<()> {
        steer_room(self.get_authorization(), &self.inner.target, options).await
    }

    /// Replace the room's event hooks after connection (e.g. once the UI
    /// that owns rendering is ready).
    pub fn set_hooks(&self, hooks: Arc<dyn RoomHooks>) {
        *lock(&self.inner.hooks) = hooks;
    }

    /// Fire on_closed using the latest hooks (set_hooks), not the connect-time ones.
    pub fn emit_closed(&self) {
        // Drop local roster so a remounted widget cannot paint stale peers.
        self.room.clear_presences();
        self.hooks().on_closed(self);
    }

    /// Broadcast this member's typing state to the room (presence status).
    pub fn set_typing(&self, me: &Presence, typing: bool) {
        me.set_status(if typing { "typing" } else { "" });
    }

    /// Members currently marked as typing (excludes the given self presence).
    pub fn typing_presences(&self, me: Option<&Presence>) -> Vec<Presence> {
        self.get_presences()
            .into_iter()
            .filter(|presence| {
                me.is_none_or(|me| presence.id() != me.id()) && presence.status() == "typing"
            })
            .collect()
    }

    pub fn hydrate(&self, state: &Value) {
        let authorization = self.get_authorization().clone();
        let target = &self.inner.target;
        let chat_state = &state["chat"];
        let stream = &state["stream"];
        let mut chat = self.chat();
        chat.name = chat_state["name"].as_str().unwrap_or_default().to_string();
        chat.system_prompt = chat_state["systemPrompt"]
            .as_str()
            .unwrap_or_default()
            .to_string();
        chat.human = chat_state["human"] == true;
        chat.repository = chat_state["repository"]
            .as_f64()
            .filter(|repository| *repository > 0.0)
            .map(|repository| repository as u64);
        chat.owner = chat_state["owner"].as_str().unwrap_or_default().to_string();
        chat.write = chat_state["write"] != false;
        chat.reference = state["room"]["reference"]
            .as_str()
            .unwrap_or_default()
            .to_string();
        chat.messages = state["messages"]
            .as_array()
            .into_iter()
            .flatten()
            .map(|message| RoomMessage::from_json(message, &authorization, target))
            .collect();
        chat.queue = state["queue"]
            .as_array()
            .into_iter()
            .flatten()
            .map(|item| RoomQueueItem::from_json(item, &authorization, target))
            .collect();
        chat.has_more = match &state["hasMore"] {
            Value::Bool(more) => *more,
            Value::Null => false,
            Value::Number(more) => more.as_f64().is_some_and(|more| more != 0.0),
            Value::String(more) => !more.is_empty(),
            _ => true,
        };
        chat.thinking = state["thinking"] == true;
        chat.streaming = stream["turn"]
            .as_str()
            .filter(|turn| !turn.is_empty())
            .map(|turn| StreamingReply {
                turn: turn.to_string(),
                text: match &stream["text"] {
                    Value::Null => String::new(),
                    value => text(value),
                },
                tools: tool_states(&stream["tools"]),
                files: attachments(&stream["files"], &authorization),
            });
    }

    pub fn handle_event(&self, packet: &Value) -> bool {
        let data = &packet["data"];
        let hooks = self.hooks();
        match packet["event"].as_str().unwrap_or_default() {
            "chat-message" => {
                if !data["message"].is_object() {
                    return true;
                }
                let message = RoomMessage::from_json(
                    &data["message"],
                    self.get_authorization(),
                    &self.inner.target,
                );
                {
                    let mut chat = self.chat();
                    if !chat.messages.iter().any(|known| known.id == message.id) {
                        chat.messages.push(message.clone());
                        chat.messages.sort_by_key(|message| message.position);
                    }
                    // A MODEL row finalizes any in-progress streamed turn.
                    if message.role == Role::Model {
                        chat.streaming = None;
                    }
                }
                hooks.on_message(self, &message);
                true
            }
            "chat-queue-add" => {
                if !data["item"].is_object() {
                    return true;
                }
                let item = RoomQueueItem::from_json(
                    &data["item"],
                    self.get_authorization(),
                    &self.inner.target,
                );
                {
                    let mut chat = self.chat();
                    if !chat.queue.iter().any(|queued| queued.id == item.id) {
                        chat.queue.push(item);
                        chat.queue
                            .sort_by_key(|queued| queued.id.parse::<i128>().unwrap_or_default());
                    }
                }
                hooks.on_queue(self);
                true
            }
            "chat-queue-remove" => {
                let id = match &data["id"] {
                    Value::Null => String::new(),
                    id => text(id),
                };
                if id.is_empty() {
                    return true;
                }
                self.chat().queue.retain(|queued| queued.id != id);
                hooks.on_queue(self);
                true
            }
            "chat-delta" => {
                // The server streams the in-progress reply as full text (fans out
                // to every replica). Compute the delta against what we last saw so
                // callers can append incrementally.
                let turn = match &data["turn"] {
                    Value::Null => String::new(),
                    turn => text(turn),
                };
                let full = match &data["text"] {
                    Value::Null => String::new(),
                    full => text(full),
                };
                if turn.is_empty() {
                    return true;
                }
                let tools = tool_states(&data["tools"]);
                let files = attachments(&data["files"], self.get_authorization());
                let delta = {
                    let mut chat = self.chat();
                    let previous = match &chat.streaming {
                        Some(streaming) if streaming.turn == turn => streaming.text.clone(),
                        _ => String::new(),
                    };
                    let delta = full
                        .strip_prefix(previous.as_str())
                        .unwrap_or(&full)
                        .to_string();
                    chat.streaming = Some(StreamingReply {
                        turn: turn.clone(),
                        text: full.clone(),
                        tools: tools.clone(),
                        files: files.clone(),
                    });
                    delta
                };
                hooks.on_delta(self, &turn, &delta, &full, false, &tools, &files);
                true
            }
            "chat-delta-done" => {
                // The stream row was cleared: the turn finalized (a durable
                // chat-message follows) or aborted. Either way, drop the partial;
                // the transcript's MODEL row (if any) is authoritative.
                let turn = match &data["turn"] {
                    Value::Null => String::new(),
                    turn => text(turn),
                };
                let done = {
                    let mut chat = self.chat();
                    match &chat.streaming {
                        Some(streaming) if turn.is_empty() || streaming.turn == turn => {
                            chat.streaming.take()
                        }
                        _ => None,
                    }
                };
                if let Some(done) = done {
                    hooks.on_delta(self, &done.turn, "", &done.text, true, &[], &[]);
                }
                true
            }
            "chat-status" => {
                let thinking = match &data["thinking"] {
                    Value::Bool(thinking) => *thinking,
                    Value::Null => false,
                    Value::Number(thinking) => {
                        thinking.as_f64().is_some_and(|thinking| thinking != 0.0)
                    }
                    Value::String(thinking) => !thinking.is_empty(),
                    _ => true,
                };
                self.chat().thinking = thinking;
                hooks.on_thinking(self, thinking);
                true
            }
            "chat-renamed" => {
                let name = {
                    let mut chat = self.chat();
                    if let Some(name) = data["name"].as_str() {
                        chat.name = name.to_string();
                    }
                    chat.name.clone()
                };
                hooks.on_renamed(self, &name);
                true
            }
            "chat-repository" => {
                let renamed = {
                    let mut chat = self.chat();
                    match data["name"].as_str() {
                        Some(name) if name != chat.name => {
                            chat.name = name.to_string();
                            Some(name.to_string())
                        }
                        _ => None,
                    }
                };
                if let Some(name) = renamed {
                    hooks.on_renamed(self, &name);
                }
                let repository = data["repository"]
                    .as_f64()
                    .filter(|repository| *repository > 0.0)
                    .map(|repository| repository as u64);
                let changed = {
                    let mut chat = self.chat();
                    let changed = chat.repository != repository;
                    chat.repository = repository;
                    changed
                };
                if changed {
                    hooks.on_repository(self);
                    let watchers: Vec<RepositoryWatcher> = lock(&self.inner.repository_watchers)
                        .iter()
                        .map(|(_, listener)| listener.clone())
                        .collect();
                    for listener in watchers {
                        listener(repository);
                    }
                }
                true
            }
            "chat-open-file" => {
                if !data["attachment"].is_null() {
                    hooks.on_open_file(
                        self,
                        &Attachment::from_json(&data["attachment"], self.get_authorization()),
                    );
                }
                true
            }
            "chat-tool-call" => {
                let pick = |key: &str| {
                    if data[key].is_null() {
                        packet[key].clone()
                    } else {
                        data[key].clone()
                    }
                };
                let id = match pick("id") {
                    Value::Null => String::new(),
                    id => text(&id),
                };
                let name = match pick("name") {
                    Value::Null => String::new(),
                    name => text(&name),
                };
                let args = match pick("args") {
                    Value::Object(args) => args,
                    _ => Map::new(),
                };
                let turn = match &data["turn"] {
                    Value::Null | Value::Bool(false) => None,
                    Value::String(turn) if turn.is_empty() => None,
                    turn => Some(text(turn)),
                };
                if id.is_empty() || name.is_empty() {
                    return true;
                }
                let tool = lock(&self.inner.client_tools)
                    .iter()
                    .find(|tool| tool.function.name == name)
                    .cloned();
                match tool {
                    Some(tool) => {
                        let room = self.clone();
                        tokio::spawn(async move {
                            let result = match (tool.evaluate)(Value::Object(args)).await {
                                Ok(result) => result,
                                Err(error) => format!("Error: {error}"),
                            };
                            room.send_tool_result(&id, &result);
                        });
                    }
                    None => hooks.on_tool_call(
                        self,
                        &RoomToolCall {
                            id,
                            name,
                            args,
                            turn,
                        },
                    ),
                }
                true
            }
            "chat-closed" | "server-closed" => {
                self.emit_closed();
                true
            }
            _ => false,
        }
    }
}

fn attachments(json: &Value, authorization: &CredentialsOrApiKey) -> Vec<Attachment> {
    json.as_array()
        .into_iter()
        .flatten()
        .map(|raw| Attachment::from_json(raw, authorization))
        .collect()
}

struct ChatHooks {
    inner: Arc<ChatState>,
}

impl ChatHooks {
    fn room(&self, room: &Room) -> ChatRoom {
        ChatRoom {
            room: room.clone(),
            inner: self.inner.clone(),
        }
    }
}

impl Hooks for ChatHooks {
    fn on_connection(&self, room: &Room, state: &Value) {
        self.room(room).hydrate(state);
    }

    fn on_event(&self, room: &Room, packet: &Value) -> bool {
        self.room(room).handle_event(packet)
    }

    // Use ChatRoom.emit_closed so set_hooks(on_closed) after UI mount is honored.
    fn on_closed(&self, room: &Room, _reason: Option<&str>) {
        self.room(room).emit_closed();
    }

    fn on_presence(&self, room: &Room) {
        let room = self.room(room);
        room.hooks().on_presence(&room);
    }
}

/// Connect to a live room as a `ChatRoom`. `target` is an access code or a room
/// reference (`parrot:chat:{chatId}` / `parrot:room:{uuid}`). Resolves with the
/// room and the caller's own `Presence` (use it to broadcast typing + position).
/// The connection snapshot carries only the last transcript window; scroll-up
/// backfill goes through `room.load_older()`.
pub async fn connect_room(
    authorization: &CredentialsOrApiKey,
    target: &ChatTarget,
    hooks: Option<Arc<dyn RoomHooks>>,
) -> Result<(ChatRoom, Presence)> {
    let auth = match target {
        ChatTarget::Code { code } => Authorization::AccessCode {
            authorization: authorization.clone(),
            access_code: code.clone(),
        },
        ChatTarget::Reference { reference } => Authorization::Server {
            authorization: authorization.clone(),
            server: reference.clone(),
            group: None,
        },
    };

    let inner = Arc::new(ChatState {
        target: target.clone(),
        chat: Mutex::new(Chat {
            write: true,
            ..Chat::default()
        }),
        hooks: Mutex::new(hooks.unwrap_or_else(|| Arc::new(()))),
        client_tools: Mutex::new(Vec::new()),
        repository_watchers: Mutex::new(Vec::new()),
        next_watcher: AtomicU64::new(0),
    });
    let me = connect(
        auth,
        &format!("{}/chat/live", super::get_url()),
        Arc::new(ChatHooks {
            inner: inner.clone(),
        }),
    )
    .await?;
    let room = ChatRoom {
        room: me.room().clone(),
        inner,
    };
    room.hooks().on_presence(&room);

    Ok((room, me))
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use serde_json::{Value, json};
    use tokio::sync::mpsc;
    use tokio_tungstenite::tungstenite::Message;

    use super::*;
    use crate::authentification::ApiKey;

    #[derive(Default)]
    struct Recorder {
        events: Mutex<Vec<String>>,
    }

    impl Recorder {
        fn push(&self, event: String) {
            self.events.lock().unwrap().push(event);
        }
    }

    impl RoomHooks for Recorder {
        fn on_message(&self, _room: &ChatRoom, message: &RoomMessage) {
            self.push(format!("message {}", message.id));
        }
        fn on_queue(&self, room: &ChatRoom) {
            let ids: Vec<String> = room.get_queue().into_iter().map(|item| item.id).collect();
            self.push(format!("queue {}", ids.join(",")));
        }
        fn on_thinking(&self, _room: &ChatRoom, thinking: bool) {
            self.push(format!("thinking {thinking}"));
        }
        fn on_delta(
            &self,
            _room: &ChatRoom,
            turn: &str,
            delta: &str,
            text: &str,
            aborted: bool,
            tools: &[RoomToolState],
            _files: &[Attachment],
        ) {
            self.push(format!(
                "delta {turn} [{delta}] [{text}] {aborted} {}",
                tools.len()
            ));
        }
        fn on_tool_call(&self, _room: &ChatRoom, call: &RoomToolCall) {
            self.push(format!("tool {} {}", call.id, call.name));
        }
        fn on_renamed(&self, _room: &ChatRoom, name: &str) {
            self.push(format!("renamed {name}"));
        }
        fn on_repository(&self, room: &ChatRoom) {
            self.push(format!("repository {:?}", room.repository()));
        }
        fn on_closed(&self, _room: &ChatRoom) {
            self.push("closed".to_string());
        }
    }

    fn chat_room(recorder: Arc<Recorder>) -> (ChatRoom, mpsc::UnboundedReceiver<Message>) {
        let (ws, outbox) = mpsc::unbounded_channel();
        let authorization = CredentialsOrApiKey::ApiKey(ApiKey {
            id: "key".to_string(),
            ..ApiKey::default()
        });
        let room = Room::new(
            "http://localhost/chat/live".to_string(),
            ws,
            Authorization::Server {
                authorization,
                server: "parrot:chat:9".to_string(),
                group: None,
            },
            "room".to_string(),
        );
        let inner = Arc::new(ChatState {
            target: ChatTarget::Reference {
                reference: "parrot:chat:9".to_string(),
            },
            chat: Mutex::new(Chat {
                write: true,
                ..Chat::default()
            }),
            hooks: Mutex::new(recorder),
            client_tools: Mutex::new(Vec::new()),
            repository_watchers: Mutex::new(Vec::new()),
            next_watcher: AtomicU64::new(0),
        });
        (ChatRoom { room, inner }, outbox)
    }

    fn message(id: &str, position: u32, role: &str) -> Value {
        json!({ "id": id, "position": position, "role": role, "parts": [{ "type": "TEXT", "text": id }], "created": 1 })
    }

    #[test]
    fn hydrate_reads_the_connection_snapshot() {
        let recorder = Arc::new(Recorder::default());
        let (room, _outbox) = chat_room(recorder);
        room.hydrate(&json!({
            "chat": { "name": "Plans", "systemPrompt": "Be brief", "human": false, "repository": 4, "owner": "group:12", "write": false },
            "room": { "reference": "parrot:chat:9" },
            "messages": [message("2", 2, "MODEL"), message("1", 1, "USER")],
            "queue": [{ "id": "5", "role": "USER", "parts": [], "created": 2 }],
            "hasMore": true,
            "thinking": true,
            "stream": { "turn": "t1", "text": "Half", "tools": [{ "id": "x", "name": "exec", "status": "running" }] }
        }));
        assert_eq!(room.get_name(), "Plans");
        assert_eq!(room.get_system_prompt(), "Be brief");
        assert_eq!(room.repository(), Some(4));
        assert!(!room.can_write());
        assert_eq!(room.chat_id().as_deref(), Some("9"));
        assert_eq!(room.group().unwrap().id, "12");
        assert_eq!(room.get_messages().len(), 2);
        assert_eq!(room.get_queue()[0].id, "5");
        assert!(room.has_more());
        assert!(room.is_thinking());
        let streaming = room.streaming_reply().unwrap();
        assert_eq!(streaming.text, "Half");
        assert_eq!(streaming.tools[0].status, ToolStatus::Running);
    }

    #[test]
    fn events_update_the_room_and_reach_the_hooks() {
        let recorder = Arc::new(Recorder::default());
        let (room, mut outbox) = chat_room(recorder.clone());
        let seen = Arc::new(Mutex::new(Vec::new()));
        let watched = seen.clone();
        let stop =
            room.watch_repository(move |repository| watched.lock().unwrap().push(repository));

        for packet in [
            json!({ "event": "chat-status", "data": { "thinking": true } }),
            json!({ "event": "chat-delta", "data": { "turn": "t1", "text": "Hel" } }),
            json!({ "event": "chat-delta", "data": { "turn": "t1", "text": "Hello", "tools": [{ "id": "x", "name": "exec", "status": "success" }] } }),
            json!({ "event": "chat-delta-done", "data": { "turn": "t1" } }),
            json!({ "event": "chat-message", "data": { "message": message("3", 3, "MODEL") } }),
            json!({ "event": "chat-message", "data": { "message": message("3", 3, "MODEL") } }),
            json!({ "event": "chat-queue-add", "data": { "item": { "id": "10", "role": "USER", "parts": [] } } }),
            json!({ "event": "chat-queue-add", "data": { "item": { "id": "9", "role": "USER", "parts": [] } } }),
            json!({ "event": "chat-queue-remove", "data": { "id": "10" } }),
            json!({ "event": "chat-repository", "data": { "repository": 7, "name": "Build" } }),
            json!({ "event": "chat-tool-call", "data": { "id": "c1", "name": "pick", "args": {} } }),
            json!({ "event": "chat-closed" }),
        ] {
            assert!(room.handle_event(&packet));
        }
        stop();
        room.handle_event(&json!({ "event": "chat-repository", "data": { "repository": 0 } }));
        assert!(!room.handle_event(&json!({ "event": "something-else" })));

        assert_eq!(
            *recorder.events.lock().unwrap(),
            vec![
                "thinking true",
                "delta t1 [Hel] [Hel] false 0",
                "delta t1 [lo] [Hello] false 1",
                "delta t1 [] [Hello] true 0",
                "message 3",
                "message 3",
                "queue 10",
                "queue 9,10",
                "queue 9",
                "renamed Build",
                "repository Some(7)",
                "tool c1 pick",
                "closed",
                "repository None",
            ]
        );
        assert_eq!(room.get_messages().len(), 1);
        assert_eq!(*seen.lock().unwrap(), vec![Some(7)]);

        room.send_tool_result("c1", "a");
        let Some(Message::Text(frame)) = outbox.blocking_recv() else {
            panic!("expected a frame");
        };
        assert_eq!(
            serde_json::from_str::<Value>(frame.as_str()).unwrap(),
            json!({ "event": "tool-result", "id": "c1", "result": "a" })
        );
    }
}