Skip to main content

subspace_client_github/copilot_agents/
browser.rs

1//! The browser routes used by `gh agent-task view --web`.
2
3use serde_json::Value;
4use subspace_core::http::plain_https_url;
5
6use super::{PullRequestArtifact, validate_task_id};
7
8// qual:api
9pub const COPILOT_AGENTS_HOME_URL: &str = "https://github.com/copilot/agents";
10
11/// The pull request's sessions, optionally focused on one known run.
12pub fn session_browser_url(pull_url: &str, session_id: Option<&str>) -> Option<String> {
13    let pull = plain_https_url(pull_url).ok()?;
14    let suffix = session_id.filter(|id| validate_task_id(id).is_ok());
15    Some(match suffix {
16        Some(id) => format!("{pull}/agent-sessions/{id}"),
17        None => format!("{pull}/agent-sessions"),
18    })
19}
20
21pub(super) fn task_browser_url(raw: &Value, pull: Option<&PullRequestArtifact>) -> String {
22    raw.get("html_url")
23        .and_then(Value::as_str)
24        .and_then(|url| plain_https_url(url).ok())
25        .or_else(|| session_browser_url(&pull?.url, last_session_id(raw)))
26        .unwrap_or_default()
27}
28
29fn last_session_id(raw: &Value) -> Option<&str> {
30    raw.get("sessions")?.as_array()?.last()?.get("id")?.as_str()
31}
32
33#[cfg(test)]
34mod tests {
35    use super::session_browser_url;
36
37    #[test]
38    fn session_routes_do_not_append_untrusted_paths_or_use_unsafe_origins() {
39        let pull = "https://github.com/o/r/pull/7/";
40        assert_eq!(
41            session_browser_url(pull, Some("../other")).as_deref(),
42            Some("https://github.com/o/r/pull/7/agent-sessions")
43        );
44        for url in ["javascript:alert(1)", "https://user@github.com/o/r/pull/7"] {
45            assert!(session_browser_url(url, Some("s1")).is_none());
46        }
47    }
48}