gent-link 0.2.2

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
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
//! Typed desktop actions. Both native views submit the same commands on a private pipe.
use crate::{auth, configure, enrollment, node, node_home, owner, pairing, setup, update};
use anyhow::{Context, Result};
use gent_daemon::config;
use gent_protocol::{
    ConfigurationEdit, Effect, OwnerOp, Permission, Rule, Selector, administration::RuleDecision,
};
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::Path;
use uuid::Uuid;

#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub(super) enum Request {
    Manage { action: Action },
}

#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(super) enum Action {
    CheckUpdate,
    SignIn,
    SignOut,
    Create {
        name: String,
    },
    Join {
        code: String,
    },
    FinishSetup,
    Invite {
        name: String,
        role: Role,
    },
    RenameNode {
        id: Uuid,
        name: String,
    },
    RemoveNode {
        id: Uuid,
    },
    RenameChat {
        id: Uuid,
        name: String,
        expected_generation: u64,
    },
    Unregister {
        id: Uuid,
    },
    NodeRole {
        id: Uuid,
        role: Role,
    },
    SetRule {
        actor: String,
        peer: String,
        permission: Permission,
        decision: RuleDecision,
    },
}

#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum Role {
    Admin,
    Member,
}
impl Action {
    fn page(&self) -> &'static str {
        match self {
            Self::CheckUpdate => "about",
            Self::Invite { .. }
            | Self::RenameNode { .. }
            | Self::RemoveNode { .. }
            | Self::NodeRole { .. } => "nodes",
            Self::RenameChat { .. } | Self::Unregister { .. } => "chats",
            Self::SetRule { .. } => "permissions",
            _ => "cluster",
        }
    }
    pub(super) fn error(&self, error: &str) -> Value {
        json!({"page":self.page(),"operation":true,"error":error})
    }
    pub(super) async fn respond(self, home: &Path) -> Value {
        let page = self.page();
        match self.run(home).await {
            Ok(mut value) => {
                value["page"] = json!(page);
                value["operation"] = json!(true);
                value
            }
            Err(error) => json!({"page":page,"operation":true,"error":format!("{error:#}")}),
        }
    }
    async fn run(self, home: &Path) -> Result<Value> {
        let notice = match self {
            Self::CheckUpdate => {
                let result = update::desktop_check(home).await?;
                let channel = result["channel"]
                    .as_str()
                    .context("missing release channel")?;
                let commit = result["blessed_commit"]
                    .as_str()
                    .context("missing release revision")?;
                if result["update_available"] == true {
                    format!(
                        "Update available · {channel} {}",
                        &commit[..commit.len().min(12)]
                    )
                } else {
                    format!("You’re running the current {channel} release.")
                }
            }
            Self::SignIn => {
                auth::desktop_login(home).await?;
                "Signed in to Gent.".into()
            }
            Self::SignOut => {
                let result = auth::execute(home, auth::Command::Logout).await?;
                if result["status"] == "signed_out" {
                    "Signed out.".into()
                } else {
                    "Sign-out pending. Retry when the service is reachable.".into()
                }
            }
            Self::Create { name } => {
                node_home::provision::install(
                    home,
                    None,
                    setup::Options::desktop(Some(name)),
                    false,
                )
                .await?;
                "Cluster created and daemon installed.".into()
            }
            Self::Join { code } => {
                let mut args = pairing::JoinArgs::code(
                    (!code.trim().is_empty()).then(|| code.trim().to_owned()),
                );
                args.no_input = true;
                enrollment::join(home, args).await?;
                "Joined the cluster and installed the daemon.".into()
            }
            Self::FinishSetup => {
                node_home::provision::install(home, None, setup::Options::desktop(None), false)
                    .await?;
                "Daemon setup complete.".into()
            }
            Self::Invite { name, role } => {
                let directory = tempfile::tempdir()?;
                let file = directory.path().join("invite");
                let options = enrollment::AddArgs::invitation(
                    name.clone(),
                    matches!(role, Role::Admin),
                    file.clone(),
                );
                enrollment::add(home, options).await?;
                return Ok(json!({"notice":format!("Invitation for {name}"),
                    "private_code":std::fs::read_to_string(&file)?}));
            }
            Self::RenameNode { id, name } => {
                let result =
                    node::rename(home, &Uuid::new_v4().to_string(), &id.to_string(), &name).await?;
                return change_result(&result);
            }
            Self::RemoveNode { id } => {
                let result = node::remove(home, id.to_string()).await?;
                if result["state"] == "queued" {
                    "Removal queued for cluster approval.".into()
                } else if result["service_status"] == "pending" {
                    "Membership removed. Service revocation is pending.".into()
                } else {
                    "Node removed from the cluster.".into()
                }
            }
            Self::NodeRole { id, role } => {
                let result = configure(
                    home,
                    &Uuid::new_v4().to_string(),
                    ConfigurationEdit::DelegateNode {
                        node_id: id.to_string(),
                        allow: matches!(role, Role::Admin),
                    },
                )
                .await?;
                return change_result(&result);
            }
            Self::RenameChat {
                id,
                name,
                expected_generation,
            } => {
                let result =
                    crate::agent::rename(home, id.to_string(), name, Some(expected_generation))
                        .await?;
                return rename_result(&result);
            }
            Self::Unregister { id } => {
                let result = owner(
                    home,
                    OwnerOp::Revoke {
                        agent_id: id.to_string(),
                    },
                )
                .await?;
                if result["revoked"] == true {
                    "Chat unregistered.".into()
                } else if result["state"] == "queued" {
                    return Ok(
                        json!({"notice":"Unregistration queued for the hosting node. Refresh to check its registration.", "queued_unregister":id}),
                    );
                } else {
                    anyhow::bail!(
                        "Missing unregistration status. Refresh Chats to check its registration."
                    );
                }
            }
            Self::SetRule {
                actor,
                peer,
                permission,
                decision,
            } => {
                let effect = match decision {
                    RuleDecision::Allow => Some(Effect::Allow),
                    RuleDecision::Deny => Some(Effect::Deny),
                    RuleDecision::Inherit => None,
                };
                let id = Uuid::new_v4().to_string();
                let result = configure(
                    home,
                    &id,
                    ConfigurationEdit::SetPermissionRule {
                        actor: crate::selector(actor)?,
                        peer: crate::selector(peer)?,
                        permission,
                        effect,
                    },
                )
                .await?;
                return change_result(&result);
            }
        };
        Ok(json!({"notice":notice}))
    }
}

fn rename_result(result: &Value) -> Result<Value> {
    match result["state"].as_str() {
        Some("applied") => Ok(json!({"notice":"Chat renamed."})),
        Some("queued") => {
            Ok(json!({"notice":"Rename queued for the hosting node.", "queued_rename":true}))
        }
        Some("unconfirmed") => anyhow::bail!(
            "Rename unconfirmed: {}",
            result["reason"]
                .as_str()
                .unwrap_or("No decision received from the hosting node.")
        ),
        Some("rejected") => anyhow::bail!(
            "Rename rejected: {}",
            result["reason"]
                .as_str()
                .unwrap_or("Hosting node declined the change.")
        ),
        _ => anyhow::bail!("Missing chat rename status. Refresh Chats to check its name."),
    }
}

fn change_result(result: &Value) -> Result<Value> {
    let state = result["state"]
        .as_str()
        .context("missing configuration request status")?;
    anyhow::ensure!(
        state != "rejected",
        "Change rejected: {}",
        result["reason"].as_str().unwrap_or("unknown reason")
    );
    Ok(json!({"notice":format!("Configuration change: {state}")}))
}

pub(super) fn cluster(home: &Path) -> Result<Value> {
    let account = auth::desktop_account(home)?;
    let state = account["state"].as_str().unwrap_or("Unknown");
    let mut actions = Vec::new();
    if state != "Signed in" && state != "Sign-out pending" {
        actions.push(json!({"kind":"sign_in","title":"Sign in with GitHub"}));
    }
    if state != "Signed out" {
        actions.push(json!({"kind":"sign_out","title":"Sign out","confirm":"Sign out of the Gent account on this machine?"}));
    }
    let title = if config::path(home).try_exists()? {
        actions.push(json!({"kind":"finish_setup","title":"Install or repair daemon…","confirm":"Install and start the user service for this node?"}));
        "Account"
    } else {
        actions.push(json!({"kind":"create","title":"Create cluster…","submit":"Create cluster",
            "fields":[{"key":"name","title":"Cluster name"}],"hint":"Create a cluster with your Gent account and start this node’s daemon."}));
        actions.push(json!({"kind":"join","title":"Join with invitation…","submit":"Join cluster",
            "fields":[{"key":"code","title":"Invitation code","secret":true}],
            "hint":"Use the one-time code from Add node on an enrolled machine. Sign in to the same Gent account first."}));
        if enrollment::pending(home)?.is_some() {
            actions.push(json!({"kind":"join","title":"Resume pending join","values":{"code":""}}));
        }
        "Set up this node"
    };
    let login = account["login"]
        .as_str()
        .map(|s| format!(" · @{s}"))
        .unwrap_or_default();
    Ok(json!({"title":title,"detail":format!("Gent account: {state}{login}"),"actions":actions}))
}

fn role_field() -> Value {
    json!({"key":"role","title":"Node permissions","choices":[["admin","Admin"],["member","Messaging only"]]})
}

pub(super) fn directory_actions(chats: bool) -> Value {
    if chats {
        return json!([{"kind":"rename_chat","title":"Rename chat…","row":true,"submit":"Rename",
            "fields":[{"key":"name","title":"New chat name"}]},
            {"kind":"unregister","title":"Unregister chat…","row":true,"destructive":true,"submit":"Unregister chat",
        "confirm":"Unregister this conversation? Its Gent binding will lose access. The conversation stays in its host app."}]);
    }
    json!([{"kind":"invite","title":"Add node…","submit":"Create invitation",
        "hint":"Adding a new node requires Gent Pro. Give the one-time code to that node within 15 minutes.",
        "fields":[{"key":"name","title":"New node name"},role_field()]},
        {"kind":"rename_node","title":"Rename node…","row":true,"submit":"Rename",
        "fields":[{"key":"name","title":"New node name"}]},
        {"kind":"node_role","title":"Change role…","row":true,"submit":"Change role","fields":[role_field()],
        "hint":"Admin nodes can change cluster configuration and permissions."},
        {"kind":"remove_node","title":"Remove node…","row":true,"destructive":true,"submit":"Remove node",
        "confirm":"Remove this node from membership and revoke its cluster access?"}])
}

fn selector_key(selector: &Selector) -> String {
    match selector {
        Selector::All => "*".into(),
        Selector::SameNode => "same-node".into(),
        Selector::Agent(id) => id.clone(),
        Selector::Node(id) => format!("node:{id}"),
        Selector::Group(name) => format!("group:{name}"),
    }
}

pub(super) async fn permissions(home: &Path) -> Result<Value> {
    anyhow::ensure!(
        config::path(home).try_exists()?,
        "Set up this node in Status to view cluster permissions."
    );
    let snapshot = match owner(home, OwnerOp::PermissionRules).await {
        Err(error) if error.to_string() == "invalid request" => {
            anyhow::bail!("Update the local daemon to view cluster permissions.")
        }
        result => result?,
    };
    let nodes = owner(home, OwnerOp::Nodes).await?;
    let chats = owner(home, OwnerOp::Agents).await?;
    permission_view(snapshot, nodes, chats)
}

fn permission_view(snapshot: Value, nodes: Value, chats: Value) -> Result<Value> {
    let mut choices = vec![
        [String::new(), "Choose chats…".to_owned()],
        ["*".to_owned(), "All chats".to_owned()],
        ["same-node".into(), "Chats on the same node".into()],
    ];
    let nodes = nodes.as_array().context("invalid node directory")?;
    let read_only = nodes.iter().any(|n| {
        n["status"] == "local"
            && n.get("is_owner").is_some()
            && n["is_owner"] != true
            && n["can_configure"] == false
    });
    for node in nodes {
        if let (Some(id), Some(name)) = (node["id"].as_str(), node["name"].as_str()) {
            let short_id: String = id.chars().take(8).collect();
            choices.push([format!("node:{id}"), format!("Node · {name} · {short_id}")]);
        }
    }
    for group in snapshot["groups"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
    {
        choices.push([format!("group:{group}"), format!("Group · {group}")]);
    }
    let mut entries: Vec<gent_protocol::directory::Entry> = serde_json::from_value(chats)?;
    entries.sort_by_cached_key(|e| e.agent.name.to_lowercase());
    for entry in entries {
        if !entry.retired && !entry.agent.revoked {
            choices.push([
                entry.agent.id.clone(),
                format!(
                    "{} · {} · {}",
                    entry.agent.name,
                    entry.node_name.unwrap_or(entry.agent.node_id),
                    entry.agent.id.chars().take(8).collect::<String>()
                ),
            ]);
        }
    }
    let rules: Vec<Rule> = serde_json::from_value(snapshot["rules"].clone())?;
    // A rule can outlive its directory entry. Keep its scope selectable so
    // Inherit can remove the same actor/peer override.
    let mut known: std::collections::HashSet<_> =
        choices.iter().map(|[key, _]| key.clone()).collect();
    for selector in rules.iter().flat_map(|r| [&r.actor, &r.peer]) {
        let key = selector_key(selector);
        if known.insert(key.clone()) {
            let label = format!("Existing rule · {key}");
            choices.push([key, label]);
        }
    }
    let labels: std::collections::HashMap<_, _> = choices.iter().map(|[k, v]| (k, v)).collect();
    let name = |s: &Selector| {
        let key = selector_key(s);
        labels.get(&key).map_or(key.clone(), |s| (*s).clone())
    };
    let lines: Vec<_> = rules
        .iter()
        .map(|r| {
            let relationship = match r.permission {
                Permission::Send => "Send to",
                Permission::Receive => "Receive from",
                Permission::Enumerate => "Discover",
            };
            format!(
                "{:?} · {} · {relationship} {}",
                r.effect,
                name(&r.actor),
                name(&r.peer)
            )
        })
        .collect();
    let detail = if lines.is_empty() {
        "No explicit permission rules.".into()
    } else {
        lines.join("\n")
    };
    if read_only {
        return Ok(json!({"title":"Cluster permissions","actions":[],
            "detail":format!("This node has read-only access to cluster permissions.\n\n{detail}")}));
    }
    Ok(
        json!({"title":"Cluster permissions","detail":detail,"actions":[{"kind":"set_rule","title":"Edit permission…",
        "submit":"Apply rule","hint":"This replaces the selected rule across the cluster. Inherit removes that override. Any other matching deny still applies.",
        "fields":[{"key":"actor","title":"Acting chats","choices":choices},{"key":"peer","title":"Peer chats","choices":choices},
        {"key":"permission","title":"Permission","choices":[["send","Send to peer"],["receive","Receive from peer"],["enumerate","Discover peer"]]},
        {"key":"decision","title":"Decision","choices":[["","Choose a decision…"],["deny","Deny"],["allow","Allow"],["inherit","Inherit"]]}]}]}),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_receive_rule_names_its_peer_and_remains_editable_after_the_chat_leaves() {
        let former_chat = Uuid::new_v4().to_string();
        let snapshot = json!({"groups": [], "rules": [Rule {
            actor: Selector::All,
            peer: Selector::Agent(former_chat.clone()),
            permission: Permission::Receive,
            effect: Effect::Deny,
        }]});
        let page = permission_view(snapshot, json!([]), json!([])).unwrap();
        let label = format!("Existing rule · {former_chat}");
        assert_eq!(
            page["detail"],
            format!("Deny · All chats · Receive from {label}")
        );
        let fields = page["actions"][0]["fields"].as_array().unwrap();
        for field in fields {
            if field["key"] != "permission" {
                assert_eq!(field["choices"][0][0], "");
            }
            if field["key"] == "peer" {
                assert!(
                    field["choices"]
                        .as_array()
                        .unwrap()
                        .contains(&json!([former_chat, label]))
                );
            }
        }
    }

    #[test]
    fn a_messaging_only_node_can_read_the_rules() {
        let nodes = json!([{"status":"local","is_owner":null,"can_configure":false}]);
        let page = permission_view(json!({"rules":[]}), nodes, json!([])).unwrap();
        assert_eq!(page["actions"], json!([]));
        assert!(
            page["detail"]
                .as_str()
                .unwrap()
                .contains("No explicit permission rules.")
        );
    }
}