deepseek-tui 0.8.31

Terminal UI for DeepSeek
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
//! Slash commands for the persistent network allow/deny list.

use std::fs;
use std::path::Path;

use anyhow::{Context, bail};
use toml::Value;

use super::CommandResult;
use crate::network_policy::host_from_url;
use crate::tui::app::App;

pub fn network(_app: &mut App, arg: Option<&str>) -> CommandResult {
    match network_inner(arg) {
        Ok(message) => CommandResult::message(message),
        Err(err) => CommandResult::error(err.to_string()),
    }
}

fn network_inner(arg: Option<&str>) -> anyhow::Result<String> {
    let raw = arg.map(str::trim).unwrap_or("");
    if raw.is_empty() || raw.eq_ignore_ascii_case("list") {
        return list_policy();
    }

    let mut parts = raw.split_whitespace();
    let Some(command) = parts.next() else {
        return list_policy();
    };
    let command = command.to_ascii_lowercase();

    match command.as_str() {
        "allow" | "deny" | "remove" | "forget" => {
            let Some(host_arg) = parts.next() else {
                bail!("Usage: /network {command} <host>");
            };
            if parts.next().is_some() {
                bail!("Usage: /network {command} <host>");
            }
            let host = normalize_host_arg(host_arg)?;
            let edit = match command.as_str() {
                "allow" => NetworkEdit::Allow,
                "deny" => NetworkEdit::Deny,
                _ => NetworkEdit::Remove,
            };
            update_host(edit, &host)
        }
        "default" => {
            let Some(value) = parts.next() else {
                bail!("Usage: /network default <allow|deny|prompt>");
            };
            if parts.next().is_some() {
                bail!("Usage: /network default <allow|deny|prompt>");
            }
            update_default(value)
        }
        _ => bail!(usage()),
    }
}

fn usage() -> &'static str {
    "Usage: /network [list|allow <host>|deny <host>|remove <host>|default <allow|deny|prompt>]"
}

#[derive(Clone, Copy)]
enum NetworkEdit {
    Allow,
    Deny,
    Remove,
}

fn list_policy() -> anyhow::Result<String> {
    let path = super::config::config_toml_path()?;
    let doc = load_config_doc(&path)?;
    let network = doc.get("network").and_then(Value::as_table);
    let default = network
        .and_then(|table| table.get("default"))
        .and_then(Value::as_str)
        .unwrap_or("prompt");
    let allow = network
        .map(|table| string_array(table, "allow"))
        .unwrap_or_default();
    let deny = network
        .map(|table| string_array(table, "deny"))
        .unwrap_or_default();

    Ok(format!(
        "Network policy ({})\n\
         default = {default}\n\
         allow = {}\n\
         deny = {}\n\n\
         Use `/network allow <host>` to allow a host, `/network deny <host>` to block it, or `/network remove <host>` to clear an entry.",
        path.display(),
        display_list(&allow),
        display_list(&deny)
    ))
}

fn update_host(edit: NetworkEdit, host: &str) -> anyhow::Result<String> {
    let path = super::config::config_toml_path()?;
    let mut doc = load_config_doc(&path)?;
    let network = network_table_mut(&mut doc)?;

    match edit {
        NetworkEdit::Allow => {
            remove_host(network, "deny", host)?;
            add_host(network, "allow", host)?;
        }
        NetworkEdit::Deny => {
            remove_host(network, "allow", host)?;
            add_host(network, "deny", host)?;
        }
        NetworkEdit::Remove => {
            remove_host(network, "allow", host)?;
            remove_host(network, "deny", host)?;
        }
    }

    save_config_doc(&path, &doc)?;
    let action = match edit {
        NetworkEdit::Allow => "allowed",
        NetworkEdit::Deny => "denied",
        NetworkEdit::Remove => "removed",
    };
    Ok(format!(
        "Network host {action}: {host}\nSaved to {}. Retry the command now.",
        path.display()
    ))
}

fn update_default(value: &str) -> anyhow::Result<String> {
    let normalized = match value.trim().to_ascii_lowercase().as_str() {
        "allow" => "allow",
        "deny" | "block" => "deny",
        "prompt" | "ask" => "prompt",
        _ => bail!("Usage: /network default <allow|deny|prompt>"),
    };

    let path = super::config::config_toml_path()?;
    let mut doc = load_config_doc(&path)?;
    let network = network_table_mut(&mut doc)?;
    network.insert("default".to_string(), Value::String(normalized.to_string()));
    save_config_doc(&path, &doc)?;

    Ok(format!(
        "Network default set to {normalized}\nSaved to {}.",
        path.display()
    ))
}

fn load_config_doc(path: &Path) -> anyhow::Result<Value> {
    if !path.exists() {
        return Ok(Value::Table(toml::value::Table::new()));
    }
    let raw = fs::read_to_string(path)
        .with_context(|| format!("failed to read config at {}", path.display()))?;
    toml::from_str(&raw).with_context(|| format!("failed to parse config at {}", path.display()))
}

fn save_config_doc(path: &Path, doc: &Value) -> anyhow::Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("failed to create config directory {}", parent.display()))?;
    }
    let body = toml::to_string_pretty(doc).context("failed to serialize config.toml")?;
    fs::write(path, body).with_context(|| format!("failed to write config at {}", path.display()))
}

fn network_table_mut(doc: &mut Value) -> anyhow::Result<&mut toml::value::Table> {
    let root = doc
        .as_table_mut()
        .context("config.toml root must be a table")?;
    let entry = root
        .entry("network".to_string())
        .or_insert_with(|| Value::Table(toml::value::Table::new()));
    let table = entry
        .as_table_mut()
        .context("`network` section in config.toml must be a table")?;
    table
        .entry("default".to_string())
        .or_insert_with(|| Value::String("prompt".to_string()));
    table
        .entry("audit".to_string())
        .or_insert_with(|| Value::Boolean(true));
    Ok(table)
}

fn string_array(table: &toml::value::Table, key: &str) -> Vec<String> {
    table
        .get(key)
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
        .map(ToString::to_string)
        .collect()
}

fn string_array_mut<'a>(
    table: &'a mut toml::value::Table,
    key: &str,
) -> anyhow::Result<&'a mut Vec<Value>> {
    let value = table
        .entry(key.to_string())
        .or_insert_with(|| Value::Array(Vec::new()));
    value
        .as_array_mut()
        .with_context(|| format!("`network.{key}` must be an array of strings"))
}

fn add_host(table: &mut toml::value::Table, key: &str, host: &str) -> anyhow::Result<()> {
    let list = string_array_mut(table, key)?;
    if !list
        .iter()
        .filter_map(Value::as_str)
        .any(|existing| normalize_host_for_compare(existing) == host)
    {
        list.push(Value::String(host.to_string()));
    }
    Ok(())
}

fn remove_host(table: &mut toml::value::Table, key: &str, host: &str) -> anyhow::Result<()> {
    let list = string_array_mut(table, key)?;
    list.retain(|value| {
        value
            .as_str()
            .is_none_or(|existing| normalize_host_for_compare(existing) != host)
    });
    Ok(())
}

fn normalize_host_arg(input: &str) -> anyhow::Result<String> {
    let trimmed = input.trim();
    let host = if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
        host_from_url(trimmed).context("URL must include a host")?
    } else {
        if trimmed.contains("://") || trimmed.contains('/') {
            bail!("Pass a host like `github.com`, not a URL path");
        }
        trimmed.to_string()
    };

    let normalized = normalize_host_for_compare(&host);
    if normalized.is_empty() {
        bail!("host cannot be empty");
    }
    Ok(normalized)
}

fn normalize_host_for_compare(host: &str) -> String {
    let trimmed = host.trim().trim_end_matches('.').to_ascii_lowercase();
    if let Some(rest) = trimmed.strip_prefix("*.") {
        format!(".{rest}")
    } else {
        trimmed
    }
}

fn display_list(values: &[String]) -> String {
    if values.is_empty() {
        "[]".to_string()
    } else {
        format!("[{}]", values.join(", "))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::tui::app::{App, TuiOptions};
    use std::env;
    use std::ffi::OsString;
    use std::path::PathBuf;
    use std::time::{SystemTime, UNIX_EPOCH};

    struct EnvGuard {
        home: Option<OsString>,
        userprofile: Option<OsString>,
        deepseek_config_path: Option<OsString>,
        _lock: std::sync::MutexGuard<'static, ()>,
    }

    impl EnvGuard {
        fn new(home: &Path) -> Self {
            let lock = crate::test_support::lock_test_env();
            let config_path = home.join(".deepseek").join("config.toml");
            let home_prev = env::var_os("HOME");
            let userprofile_prev = env::var_os("USERPROFILE");
            let deepseek_config_prev = env::var_os("DEEPSEEK_CONFIG_PATH");

            // Safety: test-only environment mutation guarded by a global mutex.
            unsafe {
                env::set_var("HOME", home.as_os_str());
                env::set_var("USERPROFILE", home.as_os_str());
                env::set_var("DEEPSEEK_CONFIG_PATH", config_path.as_os_str());
            }

            Self {
                home: home_prev,
                userprofile: userprofile_prev,
                deepseek_config_path: deepseek_config_prev,
                _lock: lock,
            }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            restore_env("HOME", self.home.take());
            restore_env("USERPROFILE", self.userprofile.take());
            restore_env("DEEPSEEK_CONFIG_PATH", self.deepseek_config_path.take());
        }
    }

    fn restore_env(key: &str, value: Option<OsString>) {
        // Safety: test-only environment mutation guarded by a global mutex.
        unsafe {
            if let Some(value) = value {
                env::set_var(key, value);
            } else {
                env::remove_var(key);
            }
        }
    }

    fn temp_home(label: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let path = env::temp_dir().join(format!(
            "deepseek-network-{label}-{}-{nanos}",
            std::process::id()
        ));
        fs::create_dir_all(&path).unwrap();
        path
    }

    fn create_test_app(home: &Path) -> App {
        let options = TuiOptions {
            model: "test-model".to_string(),
            workspace: home.to_path_buf(),
            config_path: None,
            config_profile: None,
            allow_shell: false,
            use_alt_screen: true,
            use_mouse_capture: false,
            use_bracketed_paste: true,
            max_subagents: 1,
            skills_dir: home.join("skills"),
            memory_path: home.join("memory.md"),
            notes_path: home.join("notes.txt"),
            mcp_config_path: home.join("mcp.json"),
            use_memory: false,
            start_in_agent_mode: false,
            skip_onboarding: true,
            yolo: false,
            resume_session_id: None,
            initial_input: None,
        };
        App::new(options, &Config::default())
    }

    #[test]
    fn network_allow_persists_host_and_removes_exact_deny() {
        let home = temp_home("allow");
        let _guard = EnvGuard::new(&home);
        let config_path = home.join(".deepseek").join("config.toml");
        fs::create_dir_all(config_path.parent().unwrap()).unwrap();
        fs::write(
            &config_path,
            "[network]\ndefault = \"prompt\"\ndeny = [\"github.com\"]\n",
        )
        .unwrap();

        let mut app = create_test_app(&home);
        let result = network(&mut app, Some("allow GitHub.COM"));

        assert!(!result.is_error, "{:?}", result.message);
        let body = fs::read_to_string(config_path).unwrap();
        assert!(body.contains("allow = [\"github.com\"]"), "{body}");
        assert!(body.contains("deny = []"), "{body}");
    }

    #[test]
    fn network_allow_extracts_host_from_url() {
        let home = temp_home("url");
        let _guard = EnvGuard::new(&home);

        let mut app = create_test_app(&home);
        let result = network(&mut app, Some("allow https://github.com/obra/superpowers"));

        assert!(!result.is_error, "{:?}", result.message);
        let body = fs::read_to_string(home.join(".deepseek").join("config.toml")).unwrap();
        assert!(body.contains("allow = [\"github.com\"]"), "{body}");
    }

    #[test]
    fn network_default_rejects_unknown_value() {
        let home = temp_home("default");
        let _guard = EnvGuard::new(&home);

        let mut app = create_test_app(&home);
        let result = network(&mut app, Some("default maybe"));

        assert!(result.is_error);
        assert!(
            result
                .message
                .as_deref()
                .unwrap_or_default()
                .contains("/network default <allow|deny|prompt>")
        );
    }
}