gent-link 0.2.3

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
//! Account inbox publisher and passive desktop watch. Only the pinned login
//! authority sees its bearer. Local device cursors are independent per account.
use super::*;
#[cfg(target_os = "macos")]
use crate::desktop::notification_delivery::Destination;
#[cfg(not(target_os = "macos"))]
type Destination = Path;
use futures_util::StreamExt;
use gent_protocol::{
    OwnerOp,
    notifications::{Event, Failure, Notice},
};
use std::path::PathBuf;
use tokio_tungstenite::{
    connect_async_with_config,
    tungstenite::{Message, client::IntoClientRequest, protocol::WebSocketConfig},
};
use uuid::Uuid;

fn active(home: &Path) -> Result<Option<Saved>> {
    Ok(
        read(&source::directory(home)?.join("session.json"))?.filter(|s| {
            s.phase == Phase::Active
                && s.session
                    .as_ref()
                    .is_some_and(|a| a.expires_at > gent_daemon::store::now() as u64)
        }),
    )
}

pub(crate) fn scope(home: &Path) -> Option<gent_protocol::notifications::Scope> {
    let saved = active(home).ok()??;
    Some(gent_protocol::notifications::Scope {
        account: saved.session?.account_id,
        origin: saved.service,
    })
}
async fn directory_name(home: &Path, op: OwnerOp, id: uuid::Uuid) -> String {
    let id = id.to_string();
    let directory = tokio::time::timeout(Duration::from_secs(2), crate::owner(home, op)).await;
    directory
        .ok()
        .and_then(Result::ok)
        .and_then(|value| {
            value.as_array()?.iter().find(|row| row["id"] == id)?["name"]
                .as_str()
                .map(str::to_owned)
        })
        .unwrap_or(id)
}

async fn details(home: &Path, notice: &Notice) -> (&'static str, String) {
    match &notice.event {
        Event::GoalResumed { chat, reason, .. } => {
            let name = directory_name(home, OwnerOp::Agents, *chat).await;
            (
                "Gent Babysitter resumed a goal",
                format!("{name} resumed after {}.", reason.label()),
            )
        }
        Event::UpdateInstalled { node, commit } => {
            let name = directory_name(home, OwnerOp::Nodes, *node).await;
            (
                "Gent updated",
                format!(
                    "{name} updated to {}.",
                    commit.chars().take(12).collect::<String>()
                ),
            )
        }
    }
}

async fn display(
    _home: &Path,
    destination: &Destination,
    _id: Uuid,
    title: &str,
    message: String,
) -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        destination.display(_id, title, message).await
    }
    #[cfg(not(target_os = "macos"))]
    let mut command = {
        let mut c = tokio::process::Command::new("notify-send");
        c.arg("--app-name=Gent");
        #[cfg(target_os = "linux")]
        c.arg(format!(
            "--hint=string:desktop-entry:{}",
            crate::desktop::desktop_entry_id(_home)
        ));
        c.arg("--icon")
            .arg(destination)
            .args(["--", title, &message]);
        c
    };
    #[cfg(not(target_os = "macos"))]
    {
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            command
                .kill_on_drop(true)
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status(),
        )
        .await??;
        ensure!(result.success(), "desktop notification unavailable");
        Ok(())
    }
}

async fn publish(home: &Path) -> Result<()> {
    let Some(login) = active(home)? else {
        return Ok(());
    };
    let scope = gent_protocol::notifications::Scope {
        account: login
            .session
            .as_ref()
            .context("missing session")?
            .account_id
            .clone(),
        origin: login.service.clone(),
    };
    let pending = crate::owner(home, OwnerOp::NotificationPending { scope }).await?;
    let pending: Vec<Notice> = serde_json::from_value(pending)?;
    if pending.is_empty() {
        return Ok(());
    }
    let url = account_endpoint(home, &login.service)?.join("v1/notifications")?;
    let client = client()?;
    for notice in pending {
        if !still_signed_in(home, &login)? {
            break;
        }
        if notice.created_at >= now()? as i64 - 7 * 86400 {
            let (status, value) = response(
                client
                    .post(url.clone())
                    .bearer_auth(&login.token)
                    .json(&notice),
            )
            .await?;
            ensure!(
                success(status, value)?["accepted"] == true,
                "account notification pending"
            );
        }
        crate::owner(home, OwnerOp::NotificationSent { id: notice.id }).await?;
    }
    Ok(())
}

pub(crate) async fn publish_loop(home: &Path) {
    let mut pause = 5;
    loop {
        pause = if publish(home).await.is_ok() {
            15
        } else {
            (pause * 2).min(300)
        };
        tokio::time::sleep(Duration::from_secs(pause)).await;
    }
}

fn cursor_file(directory: &Path, origin: &Url, account: &str) -> PathBuf {
    directory.join(format!(
        "notification-cursor-{}",
        crate::babysitter::fingerprint(&[origin.as_str(), account])
    ))
}

fn cursor_paths(home: &Path, saved: &Saved) -> Result<(PathBuf, Option<PathBuf>)> {
    let account = &saved
        .session
        .as_ref()
        .context("missing session")?
        .account_id;
    let directory = source::directory(home)?;
    let pin = account_pin(&saved.service)?;
    let current = cursor_file(&directory, &pin, account);
    // Older clients allowed an explicit beta login and keyed its cursor to that URL.
    let beta = if ACCOUNT.contains(&pin) {
        Some(cursor_file(&directory, &origin(ACCOUNT.beta)?, account))
    } else {
        None
    };
    Ok((current, beta))
}

fn read_cursor(path: &Path) -> Result<u64> {
    let snapshot = Snapshot::read(path)?;
    snapshot.private()?;
    Ok(snapshot
        .text
        .as_deref()
        .map(str::trim)
        .unwrap_or("0")
        .parse()?)
}
fn still_signed_in(home: &Path, login: &Saved) -> Result<bool> {
    Ok(active(home)?.is_some_and(|s| s.token == login.token && s.service == login.service))
}
// An older desktop can advance its cursor past a newly introduced event kind.
fn supported(value: &Value) -> Result<Option<Notice>> {
    match value["event"]["kind"]
        .as_str()
        .context("missing notification kind")?
    {
        "goal_resumed"
            if value["event"]["reason"].is_string()
                && serde_json::from_value::<Failure>(value["event"]["reason"].clone()).is_err() =>
        {
            Ok(None)
        }
        "goal_resumed" | "update_installed" => Ok(Some(serde_json::from_value(value.clone())?)),
        _ => Ok(None),
    }
}
fn cursor_position(path: &Path, legacy: Option<&Path>) -> Result<u64> {
    let old = legacy.map(read_cursor).transpose()?.unwrap_or(0);
    Ok(old.max(read_cursor(path)?))
}

// The account inbox retains 512 rows and serves at most 64 per page.
const PAGE_SIZE: usize = 64;
const RETAINED_ROWS: usize = 512;
const SUMMARY_THRESHOLD: usize = 3;

fn summary(notices: &[(u64, Notice)]) -> (&'static str, String) {
    let recoveries = notices
        .iter()
        .filter(|(_, notice)| matches!(notice.event, Event::GoalResumed { .. }))
        .count();
    let updates = notices.len() - recoveries;
    let recovery_text = format!(
        "{recoveries} Babysitter {}",
        if recoveries == 1 {
            "recovery"
        } else {
            "recoveries"
        }
    );
    let update_text = format!(
        "{updates} {} installed",
        if updates == 1 { "update" } else { "updates" }
    );
    match (recoveries, updates) {
        (0, _) => ("Gent updates", update_text),
        (_, 0) => ("Gent Babysitter", recovery_text),
        _ => ("Gent activity", format!("{recovery_text} · {update_text}")),
    }
}

fn advance_cursor(path: &Path, sequence: u64) -> Result<()> {
    let snapshot = Snapshot::read(path)?;
    snapshot.private()?;
    if snapshot
        .text
        .as_deref()
        .unwrap_or("0")
        .trim()
        .parse::<u64>()?
        < sequence
    {
        snapshot.write(&sequence.to_string())?;
    }
    Ok(())
}

async fn collect(home: &Path, login: &Saved, destination: &Destination) -> Result<()> {
    let (path, legacy) = cursor_paths(home, login)?;
    let mut after = cursor_position(&path, legacy.as_deref())?;
    let start = after;
    let url = account_endpoint(home, &login.service)?.join("v1/notifications")?;
    let client = client()?;
    let mut notices = Vec::new();
    for _ in 0..RETAINED_ROWS / PAGE_SIZE {
        if !still_signed_in(home, login)? {
            return Ok(());
        }
        let (status, value) = response(
            client
                .get(url.clone())
                .bearer_auth(&login.token)
                .header("X-Gent-After", after.to_string()),
        )
        .await?;
        let value = success(status, value)?;
        let rows = value.as_array().context("invalid inbox page")?;
        ensure!(rows.len() <= PAGE_SIZE, "oversized inbox page");
        for row in rows {
            let seq = row["sequence"].as_u64().context("invalid inbox sequence")?;
            ensure!(seq > after, "invalid inbox order");
            if let Some(notice) = supported(&row["notice"])? {
                notices.push((seq, notice));
            }
            after = seq;
        }
        if rows.len() < PAGE_SIZE {
            break;
        }
    }

    if after == start {
        return Ok(());
    }
    let previous_end = read_cursor(&path.with_extension("summary-through"))?;
    let remaining = if start < previous_end && previous_end < after {
        let split = notices.partition_point(|(seq, _)| *seq <= previous_end);
        deliver(
            home,
            login,
            destination,
            &path,
            &notices[..split],
            previous_end,
        )
        .await?;
        &notices[split..]
    } else {
        &notices[..]
    };
    deliver(home, login, destination, &path, remaining, after).await
}

async fn deliver(
    home: &Path,
    login: &Saved,
    destination: &Destination,
    path: &Path,
    notices: &[(u64, Notice)],
    through: u64,
) -> Result<()> {
    if !still_signed_in(home, login)? {
        return Ok(());
    }
    if let Some((_, last)) = notices
        .last()
        .filter(|_| notices.len() >= SUMMARY_THRESHOLD)
    {
        let (title, body) = summary(notices);
        // Save the range before native submission. After a lost acknowledgment,
        // reuse the same banner ID and handle newer arrivals separately.
        advance_cursor(&path.with_extension("summary-through"), through)?;
        display(home, destination, last.id, title, body).await?;
    } else {
        for (sequence, notice) in notices {
            let (title, body) = details(home, notice).await;
            if !still_signed_in(home, login)? {
                return Ok(());
            }
            display(home, destination, notice.id, title, body).await?;
            if !still_signed_in(home, login)? {
                return Ok(());
            }
            advance_cursor(path, *sequence)?;
        }
    }
    // Includes unsupported rows so a future event kind cannot stall a reader.
    if still_signed_in(home, login)? {
        advance_cursor(path, through)?;
    }
    Ok(())
}

async fn watch(home: &Path, login: &Saved, destination: &Destination) -> Result<()> {
    let endpoint = account_endpoint(home, &login.service)?;
    let mut url = endpoint.join("v1/notifications/watch")?;
    url.set_scheme(if url.scheme() == "https" { "wss" } else { "ws" })
        .map_err(|_| anyhow::anyhow!("invalid watch URL"))?;
    let mut request = url.as_str().into_client_request()?;
    request
        .headers_mut()
        .insert("Authorization", format!("Bearer {}", login.token).parse()?);
    let config = WebSocketConfig::default()
        .max_message_size(Some(1024))
        .max_frame_size(Some(1024));
    let (mut socket, _) = tokio::time::timeout(
        Duration::from_secs(10),
        connect_async_with_config(request, Some(config), true),
    )
    .await??;
    collect(home, login, destination).await?;
    let mut auth_tick = tokio::time::interval(Duration::from_secs(15));
    loop {
        tokio::select! {
            frame=socket.next()=>match frame.context("watch closed")??{
                Message::Text(text) if text=="changed"=>collect(home,login,destination).await?,
                Message::Ping(_) | Message::Pong(_)=>{},
                _=>anyhow::bail!("account watch ended"),
            },
            _=auth_tick.tick()=>if !still_signed_in(home,login)? || account_endpoint(home, &login.service)? != endpoint {return Ok(())},
        }
    }
}
pub(crate) async fn desktop_loop(home: &Path, destination: &Destination) {
    let mut backoff = 1;
    loop {
        if let Ok(Some(login)) = active(home) {
            let since = std::time::Instant::now();
            let result = watch(home, &login, destination).await;
            backoff = if result.is_ok() || since.elapsed().as_secs() > 60 {
                1
            } else {
                (backoff * 2).min(300)
            };
        } else {
            backoff = 10;
        }
        tokio::time::sleep(Duration::from_secs(backoff)).await;
    }
}

#[cfg(all(test, target_os = "macos"))]
mod macos_tests;

#[cfg(all(test, target_os = "linux"))]
mod tests;