Skip to main content

subspace_agent/
runtime.rs

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