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
24 changes: 20 additions & 4 deletions apps/desktop/src-tauri/src/agent_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ pub fn spawn(app: AppHandle) {
loop {
thread::sleep(INTERVAL);
let state = app.state::<AppState>();
// Adaptador genérico: la actividad del PTY como `status_changed`.
for (terminal, activity) in state.activity.tick(Instant::now()) {
events.emit_generic(terminal, activity_event(activity));
}
let detected = match state.detect_agents.execute(state.session_id) {
Ok(detected) => detected,
Err(e) => {
Expand All @@ -59,6 +55,15 @@ pub fn spawn(app: AppHandle) {
.map(|a| a.id())
.collect();
let value = (agents, started_at);
if value.0.is_empty() {
state.activity.forget(terminal);
if last
.get(&terminal)
.is_some_and(|(prev_agents, _)| !prev_agents.is_empty())
{
state.agent_states.forget(terminal);
}
}
if last.get(&terminal) != Some(&value) {
let _ = app.emit(
TERMINAL_AGENT_EVENT,
Expand All @@ -71,6 +76,17 @@ pub fn spawn(app: AppHandle) {
}
current.insert(terminal, value);
}

// Adaptador genérico: la actividad del PTY como `status_changed`, solo en
// terminales donde efectivamente corre un agente.
for (terminal, activity) in state.activity.tick(Instant::now()) {
if current
.get(&terminal)
.is_some_and(|(agents, _)| !agents.is_empty())
{
events.emit_generic(terminal, activity_event(activity));
}
}
// Las terminales cerradas desaparecen solas del mapa.
last = current;
}
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export function App() {
const [focusedPaneId, setFocusedPaneId] = useState<string | null>(
() => workspaces[0].sessions[0].panes[0]?.id ?? null,
);
const [focusAckSeq, setFocusAckSeq] = useState(0);
const [maximizedPaneId, setMaximizedPaneId] = useState<string | null>(null);
const [statuses, setStatuses] = useState<Record<string, PaneStatus>>({});
const [meta, setMeta] = useState<Record<string, PaneMeta>>({});
Expand Down Expand Up @@ -285,6 +286,7 @@ export function App() {
const selectTerminal = (sessionId: string, paneId: string) => {
setActiveSessionByWs((m) => ({ ...m, [activeWorkspace.id]: sessionId }));
setFocusedPaneId(paneId);
setFocusAckSeq((n) => n + 1);
// Si había un panel maximizado, pasar a mostrar este.
if (maximizedPaneId) setMaximizedPaneId(paneId);
updateSession(sessionId, (s) => ({
Expand Down Expand Up @@ -517,6 +519,7 @@ export function App() {
initialAgent={pane.agent}
order={index}
focused={focusedPaneId === pane.id}
focusAckSeq={focusedPaneId === pane.id ? focusAckSeq : 0}
minimized={pane.minimized && soloPaneId !== pane.id}
maximized={soloPaneId === pane.id}
hidden={!inActiveSession || (soloPaneId !== null && soloPaneId !== pane.id)}
Expand Down
60 changes: 49 additions & 11 deletions apps/desktop/src/components/TerminalPane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ import {
localUser,
modKey,
parseOsc7,
shouldClearAttentionOnWatchChange,
statusLabel,
type ActivityState,
type AgentId,
type AgentState,
type PaneMeta,
type PaneStatus,
type WatchInputs,
} from "@opencollab/ui";
import { useGitBranch } from "../hooks/useGitBranch";
import { useWindowFocus } from "../hooks/useWindowFocus";
Expand All @@ -52,6 +54,8 @@ type Props = {
/// Agente a ejecutar dentro de la shell al abrir (`null` = solo la shell).
initialAgent: AgentId | null;
focused: boolean;
/// Secuencia que incrementa cuando el usuario selecciona explícitamente el panel en el sidebar.
focusAckSeq?: number;
minimized: boolean;
maximized: boolean;
/// Oculto (otra sesión activa u otro panel en foco): sigue montado para no perder el PTY.
Expand Down Expand Up @@ -87,22 +91,25 @@ export function TerminalPane(props: Props) {
const [info, setInfo] = useState<{ name: string; cwd: string | null } | null>(null);
/// El primero es el agente principal de la terminal; los siguientes son los que
/// ese agente tiene anidados.
const [agents, setAgents] = useState<AgentId[]>([]);
const [agents, setAgents] = useState<AgentId[]>(() => (initialAgent ? [initialAgent] : []));
const agentsRef = useRef<AgentId[]>(initialAgent ? [initialAgent] : []);
const [startedAt, setStartedAt] = useState<number | null>(null);
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);
const [activityState, setActivityState] = useState<ActivityState>(initialActivity);
const [agentState, setAgentState] = useState<AgentState | null>(null);
const windowFocused = useWindowFocus();
/// "Mirando" = enfocado, visible y con la ventana en primer plano; no basta con ser el
/// último panel clickeado.
const watching = isWatching({
const watchInputs: WatchInputs = {
focused: props.focused,
hidden: props.hidden,
minimized: props.minimized,
windowFocused,
});
};
/// "Mirando" = enfocado, visible y con la ventana en primer plano; no basta con ser el
/// último panel clickeado.
const watching = isWatching(watchInputs);
const prevWatchRef = useRef<WatchInputs>(watchInputs);
/// El handler de actividad se registra una vez: lee si se está mirando desde acá.
const focusedRef = useRef(watching);
focusedRef.current = watching;
Expand Down Expand Up @@ -131,11 +138,28 @@ export function TerminalPane(props: Props) {
}),
[paneId, info?.name, agents, cwd, 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.
// Solo limpia `attention` automáticamente cuando el panel en sí pasa a estar activo
// (cambio de panel, sesión o desminimizar), no cuando solo vuelve el foco de la ventana.
useEffect(() => {
const prev = prevWatchRef.current;
const next: WatchInputs = {
focused: props.focused,
hidden: props.hidden,
minimized: props.minimized,
windowFocused,
};
prevWatchRef.current = next;
if (shouldClearAttentionOnWatchChange(prev, next)) {
setActivityState(applyFocus);
}
}, [props.focused, props.hidden, props.minimized, windowFocused]);

useEffect(() => {
if (watching) setActivityState(applyFocus);
}, [watching]);
if (props.focusAckSeq && props.focusAckSeq > 0) {
setActivityState(applyFocus);
if (props.focused && !props.hidden && !props.minimized) termRef.current?.focus();
}
}, [props.focusAckSeq, props.focused, props.hidden, props.minimized]);

useEffect(() => {
const container = containerRef.current;
Expand All @@ -157,7 +181,11 @@ export function TerminalPane(props: Props) {
const fit = new FitAddon();
term.loadAddon(fit);
term.open(container);
term.attachCustomKeyEventHandler(createTerminalKeyEventHandler(term));
const keyClipboardHandler = createTerminalKeyEventHandler(term);
term.attachCustomKeyEventHandler((e) => {
if (e.type === "keydown") setActivityState(applyFocus);
return keyClipboardHandler(e);
});

const onContextMenu = (e: MouseEvent) => {
e.preventDefault();
Expand Down Expand Up @@ -209,17 +237,24 @@ export function TerminalPane(props: Props) {
// La shell terminó sola (p. ej. `exit`): se cierra igual que con el ✕.
onExit: () => {
setStatus("done");
agentsRef.current = [];
setAgents([]);
setStartedAt(null);
setActivityState(initialActivity);
setAgentState(null);
void closeRef.current();
},
onAgent: (newAgents, newStartedAt) => {
agentsRef.current = newAgents;
setAgents(newAgents);
setStartedAt(newStartedAt);
if (newAgents.length === 0) {
setActivityState(initialActivity);
setAgentState(null);
}
},
onAgentState: (next) => {
if (agentsRef.current.length === 0) return;
setAgentState(next);
// La "atención" es de UI: depende del foco del panel en este momento.
const status = next.status;
Expand Down Expand Up @@ -342,7 +377,10 @@ export function TerminalPane(props: Props) {
hidden={props.hidden}
style={{ order: props.order }}
// pointerdown y no mousedown: el arrastre cancela los eventos de mouse del header.
onPointerDown={props.onFocus}
onPointerDown={() => {
setActivityState(applyFocus);
props.onFocus();
}}
header={header}
bodyRef={containerRef}
bodyClassName="pane-body"
Expand Down
31 changes: 30 additions & 1 deletion packages/ui/src/activity.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { describe, expect, it } from "vitest";

import { applyActivity, applyFocus, initialActivity, isWatching } from "./activity";
import {
applyActivity,
applyFocus,
initialActivity,
isPaneActive,
isWatching,
shouldClearAttentionOnWatchChange,
} from "./activity";

describe("activity", () => {
it("starts unknown and without attention", () => {
Expand Down Expand Up @@ -54,4 +61,26 @@ describe("activity", () => {
expect(isWatching({ ...all, ...patch })).toBe(false);
});
});

describe("shouldClearAttentionOnWatchChange", () => {
const base = { focused: true, hidden: false, minimized: false, windowFocused: true };

it("does NOT clear attention when only windowFocused flips false -> true on an already-active pane", () => {
const prev = { ...base, windowFocused: false };
const next = { ...base, windowFocused: true };
expect(isPaneActive(prev)).toBe(true);
expect(shouldClearAttentionOnWatchChange(prev, next)).toBe(false);
});

it("clears attention when switching focus from another pane while window is focused", () => {
const prev = { ...base, focused: false };
const next = { ...base, focused: true };
expect(shouldClearAttentionOnWatchChange(prev, next)).toBe(true);
});

it("clears attention when un-hiding a session or un-minimizing a pane while window is focused", () => {
expect(shouldClearAttentionOnWatchChange({ ...base, hidden: true }, base)).toBe(true);
expect(shouldClearAttentionOnWatchChange({ ...base, minimized: true }, base)).toBe(true);
});
});
});
25 changes: 20 additions & 5 deletions packages/ui/src/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,28 @@ export function applyFocus(state: ActivityState): ActivityState {
return state.attention ? { ...state, attention: false } : state;
}

/// El usuario está mirando el panel: enfocado, visible (no oculto ni minimizado) y con
/// la ventana de la app en primer plano. Solo entonces un cambio de actividad cuenta como visto.
export function isWatching(v: {
export type WatchInputs = {
focused: boolean;
hidden: boolean;
minimized: boolean;
windowFocused: boolean;
}): boolean {
return v.focused && !v.hidden && !v.minimized && v.windowFocused;
};

/// El panel está activo dentro de la grilla (enfocado, visible y no minimizado).
export function isPaneActive(v: Pick<WatchInputs, "focused" | "hidden" | "minimized">): boolean {
return v.focused && !v.hidden && !v.minimized;
}

/// El usuario está mirando el panel: enfocado, visible (no oculto ni minimizado) y con
/// la ventana de la app en primer plano. Solo entonces un cambio de actividad cuenta como visto.
export function isWatching(v: WatchInputs): boolean {
return isPaneActive(v) && v.windowFocused;
}

/// Solo limpia `attention` automáticamente cuando el panel en sí pasa a estar activo
/// mientras la ventana tiene foco (cambiar de panel, de sesión o desminimizar).
/// Si el panel ya estaba activo y solo volvió el foco de la ventana (`windowFocused: false -> true`),
/// no se limpia hasta que el usuario interactúe con el panel o lo seleccione explícitamente.
export function shouldClearAttentionOnWatchChange(prev: WatchInputs, next: WatchInputs): boolean {
return !isPaneActive(prev) && isWatching(next);
}
Loading