Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions apps/desktop/core/application/src/agent_detection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! catálogo de agentes conocidos es solo un detalle de presentación.

use std::collections::HashMap;
use std::path::PathBuf;

/// Agentes que la app sabe reconocer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -79,6 +80,8 @@ pub struct ProcessInfo {
pub args: Vec<String>,
/// Instante de arranque, en segundos desde la época Unix (`None` si no se conoce).
pub started_at: Option<u64>,
/// Directorio de trabajo actual del proceso (`None` si el SO no lo expone).
pub cwd: Option<PathBuf>,
}

const SCRIPT_RUNTIMES: [&str; 3] = ["node", "bun", "deno"];
Expand Down Expand Up @@ -129,6 +132,9 @@ pub struct AgentTree {
/// Agentes conocidos por debajo del principal, del más cercano al shell al
/// más profundo, sin repetir.
pub nested: Vec<KnownAgent>,
/// Directorio de trabajo activo del agente o de su subproceso/subagente más
/// profundo (p. ej. cuando trabaja dentro de un git worktree).
pub active_cwd: Option<PathBuf>,
}

/// Busca los agentes conocidos entre los descendientes de `root` (la shell de la
Expand Down Expand Up @@ -157,6 +163,8 @@ pub fn detect_agents_within(processes: &[ProcessInfo], root: u32, stop_at: &[Str
// Acumula en orden de anchura (menor profundidad primero) y sin repetir.
let mut found: Vec<KnownAgent> = Vec::new();
let mut primary_started_at = None;
let mut primary_cwd: Option<PathBuf> = None;
let mut active_cwd: Option<PathBuf> = None;
let mut level = vec![root];
let mut visited = std::collections::HashSet::from([root]);
while !level.is_empty() {
Expand All @@ -171,10 +179,19 @@ pub fn detect_agents_within(processes: &[ProcessInfo], root: u32, stop_at: &[Str
if !found.contains(&agent) {
if found.is_empty() {
primary_started_at = child.started_at;
primary_cwd = child.cwd.clone();
active_cwd = child.cwd.clone();
}
found.push(agent);
}
}
if !found.is_empty() {
if let Some(cwd) = &child.cwd {
if primary_cwd.as_ref() != Some(cwd) || active_cwd.is_none() {
active_cwd = Some(cwd.clone());
}
}
}
// Aunque sea un agente, sigue bajando: puede tener otros debajo.
if visited.insert(child.pid) {
next.push(child.pid);
Expand All @@ -189,6 +206,7 @@ pub fn detect_agents_within(processes: &[ProcessInfo], root: u32, stop_at: &[Str
primary: found.next(),
primary_started_at,
nested: found.collect(),
active_cwd,
}
}

Expand Down Expand Up @@ -220,9 +238,15 @@ mod tests {
name: name.into(),
args: args.iter().map(|a| a.to_string()).collect(),
started_at: None,
cwd: None,
}
}

fn with_cwd(mut process: ProcessInfo, path: &str) -> ProcessInfo {
process.cwd = Some(PathBuf::from(path));
process
}

fn started(mut process: ProcessInfo, at: u64) -> ProcessInfo {
process.started_at = Some(at);
process
Expand Down Expand Up @@ -328,6 +352,7 @@ mod tests {
primary: Some(KnownAgent::ClaudeCode),
primary_started_at: None,
nested: vec![KnownAgent::Codex],
active_cwd: None,
}
);
}
Expand All @@ -353,6 +378,7 @@ mod tests {
KnownAgent::OpenCode,
KnownAgent::AntigravityCli,
],
active_cwd: None,
}
);
}
Expand All @@ -372,6 +398,7 @@ mod tests {
primary: Some(KnownAgent::ClaudeCode),
primary_started_at: None,
nested: vec![KnownAgent::Codex],
active_cwd: None,
}
);
}
Expand Down Expand Up @@ -481,4 +508,32 @@ mod tests {
);
assert_eq!(detect_agents(&list, SHELL).nested, vec![KnownAgent::Codex]);
}

#[test]
fn reports_active_cwd_of_primary_agent_and_prefers_subagent_worktree_cwd() {
let primary_only = vec![
with_cwd(proc(SHELL, 1, "powershell.exe", &[]), "/repo"),
with_cwd(proc(200, SHELL, "claude.exe", &[]), "/repo"),
];
assert_eq!(
detect_agents(&primary_only, SHELL).active_cwd,
Some(PathBuf::from("/repo"))
);

// Cuando un subagente o proceso hijo trabaja en un git worktree, su CWD
// prevalece sobre el CWD raíz del agente principal o de otros helpers.
let with_worktree = vec![
with_cwd(proc(SHELL, 1, "powershell.exe", &[]), "/repo"),
with_cwd(proc(200, SHELL, "claude.exe", &[]), "/repo"),
with_cwd(
proc(300, 200, "codex.exe", &[]),
"/repo-worktrees/feature-a",
),
with_cwd(proc(301, 200, "node.exe", &["mcp-server.js"]), "/repo"),
];
assert_eq!(
detect_agents(&with_worktree, SHELL).active_cwd,
Some(PathBuf::from("/repo-worktrees/feature-a"))
);
}
}
6 changes: 6 additions & 0 deletions apps/desktop/core/application/src/use_cases.rs
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,7 @@ mod tests {
name: "claude.exe".into(),
args: vec![],
started_at: Some(1_700_000_000),
cwd: None,
}]));

let detected = DetectTerminalAgents::new(w.repo.clone(), w.pty.clone(), inspector)
Expand All @@ -457,6 +458,7 @@ mod tests {
primary: Some(KnownAgent::ClaudeCode),
primary_started_at: Some(1_700_000_000),
nested: vec![],
active_cwd: None,
}
),
(second, AgentTree::default()),
Expand All @@ -475,13 +477,15 @@ mod tests {
name: "claude.exe".into(),
args: vec![],
started_at: None,
cwd: None,
},
crate::agent_detection::ProcessInfo {
pid: 2001,
parent: Some(2000),
name: "codex.exe".into(),
args: vec![],
started_at: None,
cwd: None,
},
]));

Expand All @@ -497,6 +501,7 @@ mod tests {
primary: Some(KnownAgent::ClaudeCode),
primary_started_at: None,
nested: vec![KnownAgent::Codex],
active_cwd: None,
}
)]
);
Expand All @@ -511,6 +516,7 @@ mod tests {
name: name.into(),
args: vec![],
started_at: None,
cwd: None,
};
let inspector = Arc::new(FakeInspector(vec![
p(2000, 1000, "claude.exe"),
Expand Down
8 changes: 6 additions & 2 deletions apps/desktop/core/infrastructure/src/process_inspector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,13 @@ impl ProcessInspector for SysinfoProcessInspector {
.system
.lock()
.map_err(|e| PortError::new(e.to_string()))?;
// Solo lo que la detección usa: sin CPU, memoria ni disco.
// Solo lo que la detección usa: comando, CWD actual y arranque (sin CPU, memoria ni disco).
system.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing().with_cmd(UpdateKind::OnlyIfNotSet),
ProcessRefreshKind::nothing()
.with_cmd(UpdateKind::OnlyIfNotSet)
.with_cwd(UpdateKind::Always),
);
Ok(system
.processes()
Expand All @@ -50,6 +52,7 @@ impl ProcessInspector for SysinfoProcessInspector {
.collect(),
// sysinfo informa 0 cuando no pudo leerlo.
started_at: Some(p.start_time()).filter(|&t| t > 0),
cwd: p.cwd().map(|path| path.to_path_buf()),
})
.collect())
}
Expand All @@ -67,6 +70,7 @@ mod tests {
.find(|p| p.pid == std::process::id())
.expect("el proceso del test debería aparecer");
assert!(me.parent.is_some());
assert_eq!(me.cwd, std::env::current_dir().ok());
// El proceso del test arrancó hace poco, pero ya.
let started = me.started_at.expect("sysinfo debería informar el arranque");
let now = std::time::SystemTime::now()
Expand Down
31 changes: 25 additions & 6 deletions apps/desktop/src-tauri/src/agent_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,23 @@ struct TerminalAgentPayload {
/// Arranque del proceso del agente principal (segundos desde la época Unix);
/// `null` si no corre ninguno.
started_at: Option<u64>,
/// Directorio de trabajo actual del agente o subagente activo (`null` si no
/// corre ningún agente o el SO no lo expone).
cwd: Option<String>,
}

#[derive(Clone, PartialEq, Eq)]
struct AgentObservation {
agents: Vec<&'static str>,
started_at: Option<u64>,
cwd: Option<String>,
}

pub fn spawn(app: AppHandle) {
thread::spawn(move || {
let events =
TauriAgentEvents::new(app.clone(), app.state::<AppState>().agent_states.clone());
let mut last: HashMap<TerminalId, (Vec<&'static str>, Option<u64>)> = HashMap::new();
let mut last: HashMap<TerminalId, AgentObservation> = HashMap::new();
loop {
thread::sleep(INTERVAL);
let state = app.state::<AppState>();
Expand All @@ -52,24 +62,33 @@ pub fn spawn(app: AppHandle) {
for (terminal, tree) in detected {
// El principal primero, después los que ese agente tiene anidados.
let started_at = tree.primary.and(tree.primary_started_at);
let cwd = tree
.primary
.and(tree.active_cwd)
.map(|p| p.to_string_lossy().into_owned());
let agents: Vec<&'static str> = tree
.primary
.into_iter()
.chain(tree.nested)
.map(|a| a.id())
.collect();
let value = (agents, started_at);
if last.get(&terminal) != Some(&value) {
let observation = AgentObservation {
agents,
started_at,
cwd,
};
if last.get(&terminal) != Some(&observation) {
let _ = app.emit(
TERMINAL_AGENT_EVENT,
TerminalAgentPayload {
terminal_id: terminal.to_string(),
agents: value.0.clone(),
started_at,
agents: observation.agents.clone(),
started_at: observation.started_at,
cwd: observation.cwd.clone(),
},
);
}
current.insert(terminal, value);
current.insert(terminal, observation);
}
// Las terminales cerradas desaparecen solas del mapa.
last = current;
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/src/components/CwdSwitcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export function CwdSwitcher({ cwd, disabledReason, onNavigate }: Props) {
onClick={() => void copyPath()}
>
{copied ? <Check /> : <VscCopy />}
<span className="cwd-item-path">{copied ? "Copied!" : "Copy path"}</span>
<span className="cwd-item-label">{copied ? "Copied!" : "Copy path"}</span>
</button>

{/* Hacia adelante: subcarpetas del directorio actual. */}
Expand Down
25 changes: 17 additions & 8 deletions apps/desktop/src/components/TerminalPane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ export function TerminalPane(props: Props) {
const agent = agents[0] ?? null;
/// Directorio actual, según lo reporta la shell con OSC 7 en cada prompt.
const [cwd, setCwd] = useState<string | null>(null);
/// Directorio de trabajo real del proceso del agente o subagente activo (p. ej. un git worktree).
const [agentCwd, setAgentCwd] = useState<string | null>(null);
const effectiveCwd = agentCwd ?? cwd;
const [activityState, setActivityState] = useState<ActivityState>(initialActivity);
const [agentState, setAgentState] = useState<AgentState | null>(null);
const windowFocused = useWindowFocus();
Expand All @@ -106,8 +109,8 @@ export function TerminalPane(props: Props) {
/// El handler de actividad se registra una vez: lee si se está mirando desde acá.
const focusedRef = useRef(watching);
focusedRef.current = watching;
// Se vuelve a leer al quedar inactivo: un agente pudo cambiar de rama.
const branch = useGitBranch(cwd, activityState.activity === "idle");
// Se vuelve a leer al cambiar el directorio efectivo (shell o worktree del agente) o al quedar inactivo.
const branch = useGitBranch(effectiveCwd, activityState.activity === "idle");
const [status, setStatus] = useState<PaneStatus>("starting");
const [error, setError] = useState<string | null>(null);
const [contextMenu, setContextMenu] = useState<{
Expand All @@ -122,14 +125,14 @@ export function TerminalPane(props: Props) {
onMeta(paneId, {
shellName: info?.name ?? null,
agents,
cwd,
cwd: effectiveCwd,
startedAt,
branch,
agentState,
activity: activityState.activity,
attention: activityState.attention,
}),
[paneId, info?.name, agents, cwd, startedAt, branch, agentState, activityState, onMeta],
[paneId, info?.name, agents, effectiveCwd, startedAt, branch, agentState, activityState, onMeta],
);
// Mirar el panel (enfocarlo, volver a la ventana, a su sesión o restaurarlo): lo que
// pedía atención ya se vio.
Expand Down Expand Up @@ -211,13 +214,19 @@ export function TerminalPane(props: Props) {
setStatus("done");
setAgents([]);
setStartedAt(null);
setAgentCwd(null);
setActivityState(initialActivity);
setAgentState(null);
void closeRef.current();
},
onAgent: (newAgents, newStartedAt) => {
onAgent: (newAgents, newStartedAt, newAgentCwd) => {
setAgents(newAgents);
setStartedAt(newStartedAt);
setAgentCwd(newAgentCwd);
if (newAgents.length === 0) {
setActivityState(initialActivity);
setAgentState(null);
}
},
onAgentState: (next) => {
setAgentState(next);
Expand Down Expand Up @@ -313,9 +322,9 @@ export function TerminalPane(props: Props) {
<span className="pane-name" title={detected ? `${name} · en ${shellName}` : undefined}>
{name}
</span>
{cwd && (
{effectiveCwd && (
<span className="pane-cwd">
<CwdSwitcher cwd={cwd} disabledReason={cwdDisabledReason} onNavigate={navigate} />
<CwdSwitcher cwd={effectiveCwd} disabledReason={cwdDisabledReason} onNavigate={navigate} />
</span>
)}
<span className={`pane-status pane-status--${status}`} title={error ?? undefined}>
Expand All @@ -326,7 +335,7 @@ export function TerminalPane(props: Props) {
{localUser.initials}
</span>
<span className="pane-controls">
<NewTerminalMenu cwd={cwd} onOpen={props.onNewTerminal} />
<NewTerminalMenu cwd={effectiveCwd} onOpen={props.onNewTerminal} />
<IconButton icon={<Minus />} title="Minimize" onClick={props.onToggleMinimize} />
<IconButton icon={<Maximize />} title="Maximize" onClick={props.onToggleMaximize} />
<IconButton icon={<Close />} title="Close" onClick={() => void close()} />
Expand Down
Loading
Loading