Skip to main content

subspace_agent/
runtime.rs

1//! One SDK client on a dedicated runtime. The UI never waits for SDK startup.
2#[path = "runtime/acp.rs"]
3mod acp;
4#[path = "runtime/child.rs"]
5mod child;
6#[path = "config.rs"]
7mod config;
8#[path = "runtime/persistence.rs"]
9mod persistence;
10#[path = "runtime/pi.rs"]
11mod pi;
12#[path = "runtime/selection.rs"]
13mod selection;
14#[path = "runtime/startup.rs"]
15mod startup;
16use crate::ChatPreferences;
17use persistence::parse_session_id;
18#[path = "runtime/export.rs"]
19mod export;
20#[path = "runtime/library.rs"]
21mod library;
22pub use export::export_file_name;
23#[path = "runtime/display.rs"]
24mod display;
25#[path = "runtime/names.rs"]
26mod names;
27#[path = "runtime/supervisor.rs"]
28mod supervisor;
29#[path = "runtime/tabs.rs"]
30mod tabs;
31#[path = "runtime/watchdog.rs"]
32mod watchdog;
33use display::{bridge_event, history_entries, prompt, publish_sessions, refresh};
34
35mod transcript;
36use transcript::Transcript;
37#[path = "runtime/builtins.rs"]
38mod builtins;
39#[path = "runtime/canvas.rs"]
40mod canvas;
41#[path = "runtime/canvas_negotiation.rs"]
42mod canvas_negotiation;
43#[path = "runtime/catalog.rs"]
44mod catalog;
45#[path = "runtime/chat.rs"]
46mod chat;
47#[path = "runtime/chat_session.rs"]
48mod chat_session;
49#[path = "runtime/choices.rs"]
50mod choices;
51#[path = "runtime/commands.rs"]
52mod commands;
53#[path = "runtime/evidence.rs"]
54mod evidence;
55#[path = "runtime/refusal.rs"]
56mod refusal;
57#[path = "runtime/remote.rs"]
58mod remote;
59use catalog::load_agents;
60#[path = "runtime/sdk_tools.rs"]
61mod sdk_tools;
62#[path = "runtime/session.rs"]
63mod session;
64#[path = "runtime/setup.rs"]
65mod setup;
66use session::{
67    configure_sandbox, ensure_managed_policy, reset_permissions, verify_identity,
68    verify_local_session,
69};
70use startup::validate_command;
71
72use std::collections::{HashMap, HashSet};
73use std::fs;
74use std::path::{Path, PathBuf};
75use std::sync::atomic::{AtomicU64, Ordering};
76use std::sync::{Arc, Mutex, MutexGuard};
77use std::time::Duration;
78
79use github_copilot_sdk::rpc::{
80    AgentSelectRequest, AgentsDiscoverRequest, EventLogReadRequest, EventsReadDirection,
81    ModeSetRequest, NameSetAutoRequest, NameSetRequest, PermissionMode, PermissionsSetModeRequest,
82    SandboxConfig, SandboxConfigAuth, SandboxConfigSource, SessionUpdateOptionsParams,
83    SessionsReadPersistedEventsRequest, ToolsListRequest,
84};
85use github_copilot_sdk::session::Session;
86use github_copilot_sdk::types::{
87    CustomAgentConfig, ResumeSessionConfig, SessionConfig, SessionEvent, SessionId,
88};
89use github_copilot_sdk::{Client, ClientMode, ClientOptions, Transport};
90use serde_json::Value;
91use subspace_core::{
92    Secret,
93    config::{ChatEngine, Config},
94    credentials::Credentials,
95    features::{ACP_CHAT, FeatureStage, PI_CHAT},
96    state,
97};
98use tokio::sync::mpsc;
99
100use crate::{
101    ATTACHMENT_MARKER, ChatCommand, ChatEvent, ChatId, ChatMode, Choice, Command, ContextRef,
102    Entry, EntryKind, Event, MAX_CHATS, ModelChoice, SessionSummary, SlashCommand, ToolStatus,
103    TranscriptEntry, Usage,
104};
105use actor::run;
106use decisions::Decisions;
107#[cfg(test)]
108use files::copy_attachment;
109use files::{contains_secret, copy_attachment_checked, private_directory, read_regular_file};
110use interaction::EventQueue;
111use setup::SessionSetup;
112use subspace_agent_tools::{Catalog, ChatToolServer};
113
114const EVENT_LIMIT: usize = 256;
115const DELTA_LIMIT: usize = 64 * 1024;
116const FILE_LIMIT: u64 = 2 * 1024 * 1024;
117const WORKSPACE_LIMIT: u64 = 20 * 1024 * 1024;
118const PROMPT_LIMIT: usize = 256 * 1024;
119const APPROVAL_LIMIT: usize = 16;
120const COMMAND_LIMIT: usize = 64;
121const MAX_AGENT_FILES: usize = 64;
122const SESSION_ID_LIMIT: usize = 128;
123const APPROVAL_TIMEOUT: Duration = Duration::from_secs(300);
124static NEXT_ID: AtomicU64 = AtomicU64::new(1);
125
126const CHAT_OFF: &str = "Chat is off. Choose an engine in Settings > Chat.";
127
128/// Offline runtime boundary for consumer tests. No thread, process or service starts.
129#[cfg(any(test, feature = "test-support"))]
130impl AgentHandle {
131    // qual:test_helper
132    pub fn test_offline(
133        workspace: PathBuf,
134        events: Vec<Event>,
135    ) -> (AgentHandle, mpsc::Receiver<Command>) {
136        let (commands, receiver) = mpsc::channel(COMMAND_LIMIT);
137        let queue = EventQueue::default();
138        lock(&queue.items).extend(events);
139        let handle = AgentHandle {
140            inner: Arc::new(HandleInner {
141                commands,
142                events: Arc::new(queue),
143                workspace,
144                attachment_lock: Mutex::new(()),
145                engine: ChatEngine::Copilot,
146                _stop: supervisor::stop_pair().0,
147            }),
148        };
149        (handle, receiver)
150    }
151}
152
153pub(super) fn read_attachment_image(path: &Path, limit: u64) -> Result<Vec<u8>, String> {
154    files::reject_sensitive_path(path, contains_secret)?;
155    read_regular_file(path, limit, "image")
156}
157
158fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
159    mutex
160        .lock()
161        .unwrap_or_else(std::sync::PoisonError::into_inner)
162}
163
164#[derive(Clone)]
165pub struct AgentHandle {
166    inner: Arc<HandleInner>,
167}
168
169struct HandleInner {
170    commands: mpsc::Sender<Command>,
171    events: Arc<EventQueue>,
172    workspace: PathBuf,
173    attachment_lock: Mutex<()>,
174    engine: ChatEngine,
175    /// Dropped with the last handle, which stops the runtime even when it
176    /// waits on a call that never returns (see `supervisor.rs`).
177    _stop: supervisor::Stop,
178}
179
180impl AgentHandle {
181    /// Starts chat with the agent tools of the product's selected boards.
182    pub fn start(
183        config: Arc<Config>,
184        credentials: Arc<Credentials>,
185        tools: Catalog,
186    ) -> Result<Self, String> {
187        Self::start_with_preferences(config, credentials, tools, ChatPreferences::default(), None)
188    }
189
190    /// `chat_tools` serves the app's tools to ACP agents, which speak MCP
191    /// themselves; Copilot and Pi call `tools` directly.
192    pub fn start_with_preferences(
193        config: Arc<Config>,
194        credentials: Arc<Credentials>,
195        tools: Catalog,
196        preferences: ChatPreferences,
197        chat_tools: Option<Arc<dyn ChatToolServer>>,
198    ) -> Result<Self, String> {
199        if config.chat.engine == ChatEngine::Pi && !config.feature_enabled(&PI_CHAT) {
200            return Err(pi_disabled_message(PI_CHAT.stage));
201        }
202        if config.chat.engine == ChatEngine::Acp && !config.feature_enabled(&ACP_CHAT) {
203            return Err(acp_disabled_message(ACP_CHAT.stage));
204        }
205        let engine = config.chat.engine;
206        let workspace_name = match engine {
207            ChatEngine::Off => return Err(CHAT_OFF.into()),
208            ChatEngine::Copilot => "copilot-workspace",
209            ChatEngine::Pi => "pi-workspace",
210            ChatEngine::Acp => "acp-workspace",
211        };
212        let workspace = state::sibling(workspace_name)
213            .ok_or_else(|| "Cannot find the Subspace state directory.".to_string())?;
214        let (commands, receiver) = mpsc::channel(COMMAND_LIMIT);
215        let events = Arc::new(EventQueue::default());
216        remember_secrets(&events, &config, engine);
217        let (stop, stopped) = supervisor::stop_pair();
218        launch_runtime(RuntimeLaunch {
219            engine,
220            acp: config.chat.acp.clone(),
221            credentials,
222            tools,
223            chat_tools,
224            workspace: workspace.clone(),
225            receiver,
226            events: events.clone(),
227            preferences,
228            stopped,
229        })?;
230        Ok(AgentHandle {
231            inner: Arc::new(HandleInner {
232                commands,
233                events,
234                workspace,
235                attachment_lock: Mutex::new(()),
236                engine,
237                _stop: stop,
238            }),
239        })
240    }
241
242    pub fn send(&self, command: Command) -> Result<(), String> {
243        if self.is_stopped() {
244            return Err(stopped_message(
245                self.engine().label(),
246                self.inner.events.failure(),
247            ));
248        }
249        self.inner.commands.try_send(command).map_err(|_| {
250            format!(
251                "{}'s command queue is full or closed. Try again.",
252                self.engine().label()
253            )
254        })
255    }
256
257    pub fn take_events(&self) -> Vec<Event> {
258        let events = lock(&self.inner.events.items).drain(..).collect();
259        self.inner.events.space.notify_one();
260        events
261    }
262
263    pub fn attach_file(&self, path: &Path) -> Result<ContextRef, String> {
264        let _guard = lock(&self.inner.attachment_lock);
265        copy_attachment_checked(path, &self.inner.workspace, |content| {
266            self.inner.events.has_secret(content)
267        })
268    }
269
270    /// Reads a dropped image through the same regular-file, symlink, path and
271    /// open-race boundary as text attachments. The caller still validates the
272    /// image format and decoded dimensions.
273    pub fn read_attachment_image(&self, path: &Path, limit: u64) -> Result<Vec<u8>, String> {
274        let _guard = lock(&self.inner.attachment_lock);
275        files::reject_sensitive_path(path, |value| self.inner.events.has_secret(value))?;
276        read_regular_file(path, limit, "image")
277    }
278
279    pub fn same_runtime(&self, other: &Self) -> bool {
280        Arc::ptr_eq(&self.inner, &other.inner)
281    }
282
283    pub fn engine(&self) -> ChatEngine {
284        self.inner.engine
285    }
286
287    /// Whether the runtime has stopped, after a startup failure or a
288    /// shutdown. Reconnect starts a new one.
289    pub fn is_stopped(&self) -> bool {
290        self.inner.events.stopped.load(Ordering::Acquire)
291    }
292}
293
294/// What a command to a stopped runtime says: the failure that stopped it,
295/// which a later chat error would otherwise hide, else how to start again.
296fn stopped_message(engine: &str, failure: Option<String>) -> String {
297    match failure {
298        Some(failure) => format!("{engine} is not running. {failure}"),
299        None => format!("{engine} is not running. Click Reconnect to start it again."),
300    }
301}
302
303fn pi_disabled_message(stage: FeatureStage) -> String {
304    match stage {
305        FeatureStage::Experimental => "Pi chat is experimental and disabled. Enable Pi chat in Settings > Experiments or choose another engine.",
306        FeatureStage::Stable => "Pi chat is disabled. Enable Pi chat in Settings > General under regular features or choose another engine.",
307        FeatureStage::Removed => "Pi chat is unavailable. Choose another engine in Settings > Chat.",
308    }
309    .into()
310}
311
312fn acp_disabled_message(stage: FeatureStage) -> String {
313    match stage {
314        FeatureStage::Experimental => "ACP agent chat is experimental and disabled. Enable ACP agent chat in Settings > Experiments or choose another engine.",
315        FeatureStage::Stable => "ACP agent chat is disabled. Enable it in Settings > General or choose another engine.",
316        FeatureStage::Removed => "ACP agent chat is unavailable. Choose another engine in Settings > Chat.",
317    }
318    .into()
319}
320
321fn remember_secrets(events: &EventQueue, config: &Config, engine: ChatEngine) {
322    events.remember_secrets(config.github.token.clone());
323    const SERVICE_SECRETS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
324    const PI_PROVIDER_SECRETS: [&str; 17] = [
325        "ANTHROPIC_AUTH_TOKEN",
326        "ANTHROPIC_API_KEY",
327        "ANTHROPIC_OAUTH_TOKEN",
328        "OPENAI_API_KEY",
329        "AZURE_OPENAI_API_KEY",
330        "DEEPSEEK_API_KEY",
331        "GEMINI_API_KEY",
332        "GROQ_API_KEY",
333        "XAI_API_KEY",
334        "OPENROUTER_API_KEY",
335        "AI_GATEWAY_API_KEY",
336        "ZAI_API_KEY",
337        "MISTRAL_API_KEY",
338        "OPENCODE_API_KEY",
339        "KIMI_API_KEY",
340        "AWS_ACCESS_KEY_ID",
341        "AWS_SECRET_ACCESS_KEY",
342    ];
343    events.remember_secrets(
344        SERVICE_SECRETS
345            .into_iter()
346            .filter_map(|name| std::env::var(name).ok().map(Secret::new)),
347    );
348    if engine == ChatEngine::Acp {
349        events.remember_secrets(
350            config
351                .chat
352                .acp
353                .env
354                .iter()
355                .filter(|(name, _)| {
356                    ["KEY", "TOKEN", "SECRET", "PASSWORD"]
357                        .iter()
358                        .any(|marker| name.contains(marker))
359                })
360                .map(|(_, value)| Secret::new(value.clone())),
361        );
362    }
363    if engine != ChatEngine::Copilot {
364        events.remember_secrets(
365            PI_PROVIDER_SECRETS
366                .into_iter()
367                .filter_map(|name| std::env::var(name).ok().map(Secret::new)),
368        );
369    }
370}
371
372struct RuntimeLaunch {
373    engine: ChatEngine,
374    acp: subspace_core::config::AcpConfig,
375    credentials: Arc<Credentials>,
376    tools: Catalog,
377    chat_tools: Option<Arc<dyn ChatToolServer>>,
378    workspace: PathBuf,
379    receiver: mpsc::Receiver<Command>,
380    events: Arc<EventQueue>,
381    preferences: ChatPreferences,
382    stopped: supervisor::Stopped,
383}
384
385struct RuntimeContext {
386    commands: mpsc::Receiver<Command>,
387    events: Arc<EventQueue>,
388    preferences: ChatPreferences,
389}
390
391fn launch_runtime(launch: RuntimeLaunch) -> Result<(), String> {
392    let engine = launch.engine;
393    let thread_name = format!("subspace-{}", engine.label().to_ascii_lowercase());
394    std::thread::Builder::new()
395        .name(thread_name)
396        .spawn(move || run_engine(launch))
397        .map_err(|_| format!("Cannot start the {} worker thread.", engine.label()))?;
398    Ok(())
399}
400
401fn run_engine(launch: RuntimeLaunch) {
402    let engine = launch.engine;
403    let events = launch.events.clone();
404    let runtime = tokio::runtime::Builder::new_multi_thread()
405        .worker_threads(2)
406        .enable_all()
407        .build();
408    match runtime {
409        Ok(runtime) => runtime.block_on(async {
410            let result = match engine_work(launch) {
411                Ok((work, stopped)) => {
412                    supervisor::supervised(work, stopped, supervisor::SHUTDOWN_GRACE).await
413                }
414                Err(error) => Err(error),
415            };
416            if let Err(message) = result {
417                events.fail(&message).await;
418            }
419        }),
420        Err(_) => {
421            events.push_initial_error(&format!("Cannot start the {} runtime.", engine.label()))
422        }
423    }
424    events.stopped.store(true, Ordering::Release);
425}
426
427/// The selected engine's work, and the signal that stops it.
428fn engine_work(launch: RuntimeLaunch) -> Result<(supervisor::Work, supervisor::Stopped), String> {
429    let RuntimeLaunch {
430        engine,
431        acp,
432        credentials,
433        tools,
434        chat_tools,
435        workspace,
436        receiver,
437        events,
438        preferences,
439        stopped,
440    } = launch;
441    let work: supervisor::Work = match engine {
442        ChatEngine::Off => return Err(CHAT_OFF.into()),
443        ChatEngine::Copilot => Box::pin(run(
444            credentials,
445            tools,
446            workspace,
447            RuntimeContext {
448                commands: receiver,
449                events,
450                preferences,
451            },
452        )),
453        ChatEngine::Pi => Box::pin(pi::run(tools, workspace, receiver, events, preferences)),
454        ChatEngine::Acp => Box::pin(acp::run(
455            acp::AcpRun {
456                config: acp,
457                workspace,
458                tools: chat_tools,
459            },
460            receiver,
461            events,
462            preferences,
463        )),
464    };
465    Ok((work, stopped))
466}
467
468#[path = "runtime/decisions.rs"]
469mod decisions;
470#[path = "runtime/interaction.rs"]
471mod interaction;
472#[path = "runtime/permissions.rs"]
473mod permissions;
474
475fn next_id() -> u64 {
476    NEXT_ID.fetch_add(1, Ordering::Relaxed)
477}
478
479#[path = "runtime/actor.rs"]
480mod actor;
481mod attachments;
482#[cfg(test)]
483mod batch_fixture;
484#[cfg(test)]
485mod replay_fixture;
486
487#[path = "runtime/files.rs"]
488mod files;
489
490pub(crate) fn redact(text: &str) -> String {
491    let mut result = text.to_owned();
492    for prefix in ["github_pat_", "ghp_", "gho_", "ghu_", "ghs_", "ghr_"] {
493        while let Some(start) = result.find(prefix) {
494            let end = result[start..]
495                .find(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_')
496                .map_or(result.len(), |end| start + end);
497            result.replace_range(start..end, "[redacted]");
498        }
499    }
500    result
501}
502
503#[cfg(test)]
504mod tests {
505    use super::{
506        AgentHandle, EventQueue, contains_secret, copy_attachment, pi_disabled_message, prompt,
507        verify_identity,
508    };
509    use crate::{ChatEvent, ContextRef, EntryKind, Event};
510    use std::fs;
511    use std::sync::{Arc, Mutex};
512    use std::time::Duration;
513    use subspace_agent_tools::{Catalog, test_support};
514    use subspace_core::{
515        Secret,
516        config::{ChatEngine, Config},
517        features::FeatureStage,
518    };
519
520    fn offline_handle(workspace: std::path::PathBuf) -> super::AgentHandle {
521        super::AgentHandle::test_offline(workspace, Vec::new()).0
522    }
523
524    fn decisions(events: Arc<EventQueue>) -> super::Decisions {
525        super::Decisions {
526            events,
527            pending: Mutex::new(Default::default()),
528            chats: Mutex::new(Default::default()),
529            workspace: std::path::PathBuf::from("/no/such/workspace"),
530        }
531    }
532
533    #[tokio::test]
534    async fn handle_drains_events_and_copies_files_without_starting_sdk() {
535        let dir = tempfile::tempdir().unwrap();
536        let source = dir.path().join("reference.txt");
537        fs::write(&source, "Reference evidence").unwrap();
538        let handle = offline_handle(dir.path().join("workspace"));
539        let reference = handle.attach_file(&source).unwrap();
540        assert_eq!(reference.content, "Reference evidence");
541        handle
542            .inner
543            .events
544            .push(Event::of(1, ChatEvent::TurnDone))
545            .await;
546        assert!(matches!(
547            handle.take_events().as_slice(),
548            [Event::Chat {
549                chat: 1,
550                event: ChatEvent::TurnDone
551            }]
552        ));
553        assert!(handle.take_events().is_empty());
554    }
555
556    #[tokio::test]
557    async fn a_command_to_a_stopped_runtime_repeats_the_failure_that_stopped_it() {
558        let dir = tempfile::tempdir().unwrap();
559        let handle = offline_handle(dir.path().join("workspace"));
560        handle
561            .inner
562            .events
563            .fail("GitHub rejected the gh CLI token for octo-dev.")
564            .await;
565        handle
566            .inner
567            .events
568            .stopped
569            .store(true, std::sync::atomic::Ordering::Release);
570        assert!(handle.is_stopped());
571        assert_eq!(
572            handle.send(super::Command::Refresh).unwrap_err(),
573            "Copilot is not running. GitHub rejected the gh CLI token for octo-dev."
574        );
575        assert!(
576            super::stopped_message("Copilot", None).contains("Click Reconnect"),
577            "a runtime that shut down cleanly says how to start it again"
578        );
579    }
580
581    #[test]
582    fn authentication_does_not_fall_back_to_another_identity() {
583        assert!(verify_identity(true, Some("work"), "WORK").is_ok());
584        assert!(verify_identity(true, None, "work").is_ok());
585        assert!(verify_identity(true, Some("personal"), "work").is_err());
586        assert!(verify_identity(false, Some("work"), "work").is_err());
587        assert!(verify_identity(false, None, "work").is_err());
588    }
589
590    #[test]
591    fn default_chat_config_cannot_start_a_runtime() {
592        let config = Config::default();
593        let credentials = test_support::credentials(&config);
594        let error = AgentHandle::start(Arc::new(config), credentials, Catalog::default())
595            .err()
596            .unwrap();
597        assert_eq!(error, "Chat is off. Choose an engine in Settings > Chat.");
598    }
599
600    #[test]
601    fn disabled_pi_is_rejected_before_workspace_or_process_startup() {
602        let mut config = Config::default();
603        config.chat.engine = ChatEngine::Pi;
604        let credentials = test_support::credentials(&config);
605
606        let error = AgentHandle::start(Arc::new(config), credentials, Catalog::default())
607            .err()
608            .unwrap();
609
610        assert!(error.contains("Settings > Experiments"), "{error}");
611        assert!(error.contains("choose another engine"), "{error}");
612    }
613
614    #[test]
615    fn pi_gate_guidance_follows_the_feature_lifecycle() {
616        let experimental = pi_disabled_message(FeatureStage::Experimental);
617        let stable = pi_disabled_message(FeatureStage::Stable);
618        let removed = pi_disabled_message(FeatureStage::Removed);
619
620        assert!(experimental.contains("Settings > Experiments"));
621        assert!(experimental.contains("experimental"));
622        assert!(stable.contains("Settings > General"));
623        assert!(stable.contains("regular features"));
624        assert!(!stable.contains("Experiments"));
625        assert!(removed.contains("unavailable"));
626        assert!(removed.contains("Choose another engine"));
627        assert!(!removed.contains("Enable Pi chat"));
628    }
629
630    #[test]
631    fn attachments_are_private_copies_not_parent_directory_grants() {
632        let dir = tempfile::tempdir().unwrap();
633        let source = dir.path().join("notes.md");
634        let workspace = dir.path().join("workspace");
635        fs::write(&source, "Reference evidence").unwrap();
636        let attached = copy_attachment(&source, &workspace).unwrap();
637        assert_eq!(attached.content, "Reference evidence");
638        let destination = attached.key.strip_prefix("file:").unwrap();
639        assert!(std::path::Path::new(destination).starts_with(workspace.join("attachments")));
640        assert_eq!(
641            fs::read_to_string(destination).unwrap(),
642            "Reference evidence"
643        );
644        #[cfg(unix)]
645        {
646            use std::os::unix::fs::PermissionsExt;
647            assert_eq!(
648                fs::metadata(destination).unwrap().permissions().mode() & 0o777,
649                0o600
650            );
651        }
652    }
653
654    #[test]
655    fn credential_files_and_content_are_rejected() {
656        let dir = tempfile::tempdir().unwrap();
657        let workspace = dir.path().join("workspace");
658        let source = dir.path().join("notes.md");
659        fs::write(&source, "github_pat_do_not_disclose").unwrap();
660        assert!(copy_attachment(&source, &workspace).is_err());
661        let env = dir.path().join(".env.local");
662        fs::write(&env, "arbitrary secret").unwrap();
663        assert!(copy_attachment(&env, &workspace).is_err());
664        assert!(!workspace.exists());
665        assert!(contains_secret(concat!("-----BEGIN ", "PRIVATE KEY-----")));
666    }
667
668    #[cfg(unix)]
669    #[test]
670    fn symlink_attachments_are_rejected() {
671        let dir = tempfile::tempdir().unwrap();
672        let source = dir.path().join("notes.md");
673        fs::write(&source, "notes").unwrap();
674        let link = dir.path().join("link.md");
675        std::os::unix::fs::symlink(source, &link).unwrap();
676        assert!(copy_attachment(&link, &dir.path().join("workspace")).is_err());
677    }
678
679    #[test]
680    fn image_reads_reject_directories_sensitive_paths_and_oversize_files() {
681        let dir = tempfile::tempdir().unwrap();
682        let handle = offline_handle(dir.path().join("workspace"));
683        assert!(handle.read_attachment_image(dir.path(), 16).is_err());
684        let secret = dir.path().join(".env-image.png");
685        fs::write(&secret, [1, 2, 3]).unwrap();
686        assert!(handle.read_attachment_image(&secret, 16).is_err());
687        let large = dir.path().join("large.png");
688        fs::write(&large, [0; 17]).unwrap();
689        assert!(handle.read_attachment_image(&large, 16).is_err());
690    }
691
692    #[cfg(unix)]
693    #[test]
694    fn image_reads_reject_symlinks() {
695        let dir = tempfile::tempdir().unwrap();
696        let source = dir.path().join("image.png");
697        fs::write(&source, [1, 2, 3]).unwrap();
698        let link = dir.path().join("linked.png");
699        std::os::unix::fs::symlink(source, &link).unwrap();
700        let handle = offline_handle(dir.path().join("workspace"));
701        assert!(handle.read_attachment_image(&link, 16).is_err());
702    }
703
704    #[test]
705    fn actual_read_stops_if_a_file_grows_after_inspection() {
706        use std::io::Write as _;
707
708        let dir = tempfile::tempdir().unwrap();
709        let path = dir.path().join("growing.png");
710        fs::write(&path, [1, 2]).unwrap();
711        let opened = fs::File::open(&path).unwrap();
712        let inspected_len = opened.metadata().unwrap().len();
713        std::fs::OpenOptions::new()
714            .append(true)
715            .open(&path)
716            .unwrap()
717            .write_all(&[3, 4, 5])
718            .unwrap();
719        let result = super::files::read_limited(opened, inspected_len, 4, "image");
720        assert!(
721            result.is_err(),
722            "the fifth byte must be observed and rejected"
723        );
724    }
725
726    #[test]
727    fn context_is_deduplicated_and_bounded() {
728        let item = ContextRef {
729            key: "same".into(),
730            label: "evidence".into(),
731            content: "unique evidence".into(),
732        };
733        let text = prompt("question", &[item.clone(), item]).unwrap();
734        assert_eq!(text.matches("unique evidence").count(), 1);
735        assert!(prompt(&"x".repeat(256 * 1024 + 1), &[]).is_err());
736    }
737
738    #[test]
739    fn only_the_sdk_session_id_is_persisted() {
740        let dir = tempfile::tempdir().unwrap();
741        let file = dir.path().join("tabs.json");
742        super::tabs::save_tabs(
743            &file,
744            &super::tabs::SavedTabs {
745                sessions: vec!["abc-123".into()],
746                active: Some("abc-123".into()),
747            },
748        )
749        .unwrap();
750        assert_eq!(
751            fs::read_to_string(&file).unwrap(),
752            r#"{"sessions":["abc-123"],"active":"abc-123"}"#
753        );
754    }
755
756    #[tokio::test]
757    async fn flooded_deltas_cannot_displace_approvals_or_final_events() {
758        let queue = EventQueue::default();
759        for _ in 0..1000 {
760            queue.delta(1, EntryKind::Assistant, "x ".repeat(512));
761        }
762        queue
763            .push(Event::of(
764                1,
765                ChatEvent::Approval {
766                    request_id: "one".into(),
767                    summary: "exact write".into(),
768                },
769            ))
770            .await;
771        queue.push(Event::of(1, ChatEvent::TurnDone)).await;
772        let entries = super::lock(&queue.items);
773        assert!(entries.len() <= super::EVENT_LIMIT);
774        assert!(entries.iter().any(|event| matches!(
775            event,
776            Event::Chat {
777                event: ChatEvent::Approval { .. },
778                ..
779            }
780        )));
781        assert!(entries.iter().any(|event| matches!(
782            event,
783            Event::Chat {
784                event: ChatEvent::TurnDone,
785                ..
786            }
787        )));
788    }
789
790    #[tokio::test]
791    async fn one_chats_stream_never_mixes_into_another_tab() {
792        let queue = EventQueue::default();
793        queue.delta(1, EntryKind::Assistant, "first ".into());
794        queue.delta(2, EntryKind::Assistant, "second ".into());
795        queue.delta(1, EntryKind::Assistant, "again ".into());
796        let entries = super::lock(&queue.items);
797        let deltas: Vec<(u64, String)> = entries
798            .iter()
799            .filter_map(|event| match event {
800                Event::Chat {
801                    chat,
802                    event: ChatEvent::Delta { text, .. },
803                } => Some((*chat, text.clone())),
804                _ => None,
805            })
806            .collect();
807        assert_eq!(
808            deltas,
809            vec![
810                (1, "first ".to_owned()),
811                (2, "second ".to_owned()),
812                (1, "again ".to_owned())
813            ]
814        );
815    }
816
817    #[tokio::test]
818    async fn approval_callback_waits_without_blocking_command_responses() {
819        let events = Arc::new(EventQueue::default());
820        let decisions = Arc::new(decisions(events.clone()));
821        let callback = decisions.clone();
822        let task = tokio::spawn(async move {
823            callback
824                .approval(
825                    3,
826                    "write-1".into(),
827                    "Set work item 42 title to reviewed".into(),
828                )
829                .await
830        });
831        let request = tokio::time::timeout(Duration::from_secs(1), async {
832            loop {
833                let event = super::lock(&events.items).pop_front();
834                if let Some(Event::Chat {
835                    chat,
836                    event:
837                        ChatEvent::Approval {
838                            request_id,
839                            summary,
840                        },
841                }) = event
842                {
843                    break (chat, request_id, summary);
844                }
845                tokio::task::yield_now().await;
846            }
847        })
848        .await
849        .unwrap();
850        assert_eq!(request.0, 3, "the asking tab shows the approval");
851        assert_eq!(request.2, "Set work item 42 title to reviewed");
852        assert!(!task.is_finished());
853        decisions.approve(&request.1, true);
854        assert!(task.await.unwrap().unwrap());
855        assert!(super::lock(&decisions.pending).is_empty());
856        decisions.approve(&request.1, true);
857        assert!(super::lock(&decisions.pending).is_empty());
858    }
859
860    #[tokio::test]
861    async fn cancelling_one_chat_leaves_another_chats_request_pending() {
862        let events = Arc::new(EventQueue::default());
863        let decisions = Arc::new(decisions(events.clone()));
864        let first = decisions.clone();
865        let second = decisions.clone();
866        let one = tokio::spawn(async move { first.approval(1, "a".into(), "one".into()).await });
867        let two = tokio::spawn(async move { second.approval(2, "b".into(), "two".into()).await });
868        tokio::time::timeout(Duration::from_secs(1), async {
869            while super::lock(&decisions.pending).len() < 2 {
870                tokio::task::yield_now().await;
871            }
872        })
873        .await
874        .unwrap();
875        decisions.cancel(1);
876        assert_eq!(super::lock(&decisions.pending).len(), 1);
877        decisions.approve("b", true);
878        assert!(two.await.unwrap().unwrap());
879        assert!(
880            !tokio::time::timeout(Duration::from_secs(1), one)
881                .await
882                .unwrap()
883                .unwrap()
884                .unwrap(),
885            "cancelling the first chat must resolve its approval as denied"
886        );
887    }
888
889    #[tokio::test]
890    async fn credential_like_operations_are_not_offered_for_approval() {
891        let events = Arc::new(EventQueue::default());
892        events.remember_secrets([Secret::new("opaque-service-credential")]);
893        let decisions = decisions(events.clone());
894        assert!(
895            decisions
896                .approval(
897                    1,
898                    "unsafe".into(),
899                    "Post opaque-service-credential as a comment".into()
900                )
901                .await
902                .is_err()
903        );
904        assert!(super::lock(&events.items).is_empty());
905    }
906
907    #[test]
908    fn streaming_never_exposes_a_pat_split_across_chunks() {
909        let events = EventQueue::default();
910        events.delta(1, EntryKind::Assistant, "Result gh".into());
911        events.delta(1, EntryKind::Assistant, "p_do_not_disclose".into());
912        events.delta(1, EntryKind::Assistant, " done ".into());
913        let text = super::lock(&events.items)
914            .iter()
915            .filter_map(|event| {
916                if let Event::Chat {
917                    event: ChatEvent::Delta { text, .. },
918                    ..
919                } = event
920                {
921                    Some(text.clone())
922                } else {
923                    None
924                }
925            })
926            .collect::<String>();
927        assert!(!text.contains("do_not_disclose"));
928        assert!(text.contains("[redacted]"));
929    }
930}