telekinesis-gui 0.2.2

Telekinesis companion — floating GPUI overlay for general computer use, powered by rx4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use crepuscularity_gpui::prelude::*;
use crepuscularity_macros::view_file;
use gpui::{ClickEvent, *};

use crate::agent::{setup_agents, AgentSetup};
use crate::view::overlay::CursorOverlay;
use crate::view::session::{AgentSession, CompanionEvent, MessageItem, SessionKind};
use rx4::agent::ToolCall;
use rx4::permissions::Decision;

#[cfg(target_os = "macos")]
use crate::platform::macos::with_ns_window;

#[derive(Clone, Copy, PartialEq, Debug)]
pub enum PanelKind {
    Cursor,
    Desktop,
}

pub struct CompanionView {
    input: String,
    sessions: Vec<AgentSession>,
    active_session: usize,
    event_rx: Option<tokio::sync::mpsc::UnboundedReceiver<CompanionEvent>>,
    rt_handle: Option<tokio::runtime::Handle>,
    event_tx: Option<tokio::sync::mpsc::UnboundedSender<CompanionEvent>>,
    approval_rx: Option<std::sync::mpsc::Receiver<(ToolCall, std::sync::mpsc::Sender<Decision>)>>,
    permission_respond: Option<std::sync::mpsc::Sender<Decision>>,
    permission_pending: bool,
    overlay: Option<Entity<CursorOverlay>>,
    panel_kind: PanelKind,
    pub cursor_panel_window: Option<gpui::WindowHandle<CompanionView>>,
    /// Desktop sidebar expanded
    #[allow(dead_code)]
    sidebar_expanded: bool,
    /// Sessions section expanded
    #[allow(dead_code)]
    sessions_expanded: bool,
    /// Recent section expanded
    #[allow(dead_code)]
    recent_expanded: bool,
}

impl CompanionView {
    pub fn new(
        _cx: &mut Context<Self>,
        overlay: Option<Entity<CursorOverlay>>,
        panel_kind: PanelKind,
    ) -> Self {
        let mut view = Self {
            input: String::new(),
            sessions: Vec::new(),
            active_session: 0,
            event_rx: None,
            rt_handle: None,
            event_tx: None,
            approval_rx: None,
            permission_respond: None,
            permission_pending: false,
            overlay,
            panel_kind,
            cursor_panel_window: None,
            sidebar_expanded: true,
            sessions_expanded: true,
            recent_expanded: false,
        };

        if let Some(AgentSetup {
            computer_use,
            coding,
            model,
            event_rx,
            rt_handle,
            event_tx,
            approval_rx,
        }) = setup_agents()
        {
            view.sessions.push(AgentSession::new(
                "computer use",
                SessionKind::ComputerUse,
                Some(computer_use),
                &model,
            ));
            view.sessions.push(AgentSession::new(
                "coding",
                SessionKind::Coding,
                Some(coding),
                &model,
            ));
            view.event_rx = Some(event_rx);
            view.rt_handle = Some(rt_handle);
            view.event_tx = Some(event_tx);
            view.approval_rx = Some(approval_rx);
        } else {
            let mut session =
                AgentSession::new("login required", SessionKind::Coding, None, "not connected");
            session.messages.push(MessageItem::new(
                "system",
                "Log in to start coding. Run `tk login grok`, then reopen Telekinesis.",
            ));
            view.sessions.push(session);
        }

        // Note: GPUI's cx.spawn() foreground executor doesn't drive tasks in this version.
        // Event polling is handled by the App-level spawn loop in main().
        // Shake-to-show is handled by a std thread with raw NSWindow pointers in main().

        view
    }

    fn active_session(&self) -> Option<&AgentSession> {
        self.sessions.get(self.active_session)
    }

    fn active_session_mut(&mut self) -> Option<&mut AgentSession> {
        self.sessions.get_mut(self.active_session)
    }

    /// Toggle sidebar expand/collapse (desktop only)
    #[allow(dead_code)]
    fn toggle_sidebar(&mut self, _: &ClickEvent, _window: &mut Window, cx: &mut Context<Self>) {
        self.sidebar_expanded = !self.sidebar_expanded;
        cx.notify();
    }

    /// Toggle sessions section
    #[allow(dead_code)]
    fn toggle_sessions(&mut self, _: &ClickEvent, _window: &mut Window, cx: &mut Context<Self>) {
        self.sessions_expanded = !self.sessions_expanded;
        cx.notify();
    }

    /// Toggle recent section
    #[allow(dead_code)]
    fn toggle_recent(&mut self, _: &ClickEvent, _window: &mut Window, cx: &mut Context<Self>) {
        self.recent_expanded = !self.recent_expanded;
        cx.notify();
    }

    /// Close the desktop window
    fn close_window(&mut self, _: &ClickEvent, window: &mut Window, _cx: &mut Context<Self>) {
        window.remove_window();
    }

    /// Minimize the desktop window
    fn minimize_window(&mut self, _: &ClickEvent, _window: &mut Window, cx: &mut Context<Self>) {
        #[cfg(target_os = "macos")]
        {
            use objc2::msg_send;
            let _ = with_ns_window(_window, |ns_window| unsafe {
                let _: () = msg_send![ns_window, miniaturize: ns_window];
            });
        }
        let _ = cx;
    }

    /// Toggle maximize/restore the desktop window
    fn maximize_window(&mut self, _: &ClickEvent, _window: &mut Window, cx: &mut Context<Self>) {
        #[cfg(target_os = "macos")]
        {
            use objc2::msg_send;
            let _ = with_ns_window(_window, |ns_window| unsafe {
                let _: () = msg_send![ns_window, toggleFullScreen: ns_window];
            });
        }
        let _ = cx;
    }

    fn poll_events(&mut self, _cx: &mut Context<Self>) -> bool {
        let mut pending = Vec::new();
        if let Some(ref mut rx) = self.event_rx {
            while let Ok(event) = rx.try_recv() {
                pending.push(event);
            }
        }
        let had_events = !pending.is_empty();
        for event in pending {
            match event {
                CompanionEvent::Session(idx, e) => {
                    let _overlay = self.overlay.clone();
                    if let Some(session) = self.sessions.get_mut(idx) {
                        session.handle_rx4_event(e);
                    }
                }
                CompanionEvent::SessionError(msg) => {
                    if let Some(session) = self.active_session_mut() {
                        session
                            .messages
                            .push(MessageItem::new("error", format!("Error: {msg}")));
                    }
                }
            }
        }
        had_events
    }

    fn send_prompt(&mut self, _: &ClickEvent, _window: &mut Window, cx: &mut Context<Self>) {
        self.do_send_prompt(cx);
    }

    fn do_send_prompt(&mut self, cx: &mut Context<Self>) {
        let Some(ref handle) = self.rt_handle else {
            return;
        };
        let Some(ref tx) = self.event_tx else {
            return;
        };

        let text = self.input.trim().to_string();
        if text.is_empty() {
            return;
        }

        let session_idx = self.active_session;
        let Some(session) = self.sessions.get_mut(session_idx) else {
            return;
        };
        if session.busy {
            return;
        }
        let Some(ref agent) = session.agent else {
            return;
        };

        session
            .messages
            .push(MessageItem::new("user", text.clone()));
        self.input.clear();
        session.busy = true;

        let agent = agent.clone();
        let tx = tx.clone();
        handle.spawn(async move {
            let mut agent = agent.lock().await;
            if let Err(e) = agent.prompt(&text).await {
                let _ = tx.send(CompanionEvent::SessionError(e.to_string()));
            }
        });

        cx.notify();
    }

    pub fn capture_screen(&mut self, _: &ClickEvent, _window: &mut Window, cx: &mut Context<Self>) {
        let Some(ref handle) = self.rt_handle else {
            return;
        };
        let Some(ref tx) = self.event_tx else {
            return;
        };

        let session_idx = self.active_session;
        let Some(session) = self.sessions.get_mut(session_idx) else {
            return;
        };
        if session.busy {
            return;
        }
        let Some(ref agent) = session.agent else {
            return;
        };

        let prompt = "Use cu_see to capture my screen, then tell me what you see. Wait for my next instruction.";
        session
            .messages
            .push(MessageItem::new("user", "see screen"));
        session.busy = true;

        let agent = agent.clone();
        let tx = tx.clone();
        handle.spawn(async move {
            let mut agent = agent.lock().await;
            if let Err(e) = agent.prompt(prompt).await {
                let _ = tx.send(CompanionEvent::SessionError(e.to_string()));
            }
        });

        cx.notify();
    }

    fn interrupt(&mut self, _: &ClickEvent, _window: &mut Window, cx: &mut Context<Self>) {
        if let Some(session) = self.active_session_mut() {
            session.busy = false;
            session.streaming_role = None;
            session.streaming_content.clear();
        }
        cx.notify();
    }

    fn hide_panel(&mut self, _: &ClickEvent, _window: &mut Window, cx: &mut Context<Self>) {
        if let Some(ref handle) = self.cursor_panel_window {
            #[cfg(target_os = "macos")]
            {
                use objc2::msg_send;
                let _ = handle.update(cx, |_, window, _cx| {
                    let _ = with_ns_window(window, |ns_window| unsafe {
                        let _: () = msg_send![ns_window, orderOut: ns_window];
                    });
                });
            }
        }
        cx.notify();
    }

    fn poll_approvals(&mut self, cx: &mut Context<Self>) {
        let mut pending = Vec::new();
        if let Some(rx) = self.approval_rx.as_ref() {
            while let Ok(item) = rx.try_recv() {
                pending.push(item);
            }
        }
        for (call, respond) in pending {
            self.permission_pending = true;
            self.permission_respond = Some(respond);
            if let Some(s) = self.active_session_mut() {
                s.messages.push(MessageItem::new(
                    "system",
                    format!(
                        "Approval required: {}\nargs: {}\n[y] allow  [n] deny",
                        call.name,
                        call.arguments.chars().take(200).collect::<String>()
                    ),
                ));
            }
            cx.notify();
        }
    }

    fn resolve_permission(&mut self, allow: bool, cx: &mut Context<Self>) {
        if let Some(tx) = self.permission_respond.take() {
            let _ = tx.send(if allow {
                Decision::Allow
            } else {
                Decision::Deny
            });
        }
        self.permission_pending = false;
        cx.notify();
    }

    fn handle_key(&mut self, event: &KeyDownEvent, _window: &mut Window, cx: &mut Context<Self>) {
        self.poll_approvals(cx);
        let key = &event.keystroke;
        if self.permission_pending {
            if key.key == "y" {
                self.resolve_permission(true, cx);
                return;
            }
            if key.key == "n" || key.key == "escape" {
                self.resolve_permission(false, cx);
                return;
            }
            return;
        }
        if key.key == "enter" {
            self.do_send_prompt(cx);
        } else if key.key == "backspace" {
            self.input.pop();
            cx.notify();
        } else if let Some(ch) = key.key_char.as_deref() {
            if !key.modifiers.control && !key.modifiers.alt {
                self.input.push_str(ch);
                cx.notify();
            }
        }
    }
}

impl Render for CompanionView {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        // Poll events on every render — GPUI's async spawn doesn't drive futures,
        // so we use render as our periodic callback. If events were processed,
        // notify to trigger another render.
        let had_events = self.poll_events(cx);
        self.poll_approvals(cx);
        if had_events {
            cx.notify();
        }

        let session = self.active_session();
        let model = session
            .map(|s| s.model.clone())
            .unwrap_or_else(|| "no-model".into());
        let busy = session.map(|s| s.busy).unwrap_or(false);
        let context_pct = session.map(|s| s.context_pct).unwrap_or(0);
        let connected = session.and_then(|s| s.agent.as_ref()).is_some();
        let status: SharedString = if connected {
            if busy {
                "working".into()
            } else {
                "ready".into()
            }
        } else {
            "login required".into()
        };

        let input: SharedString = if self.input.is_empty() {
            if self.panel_kind == PanelKind::Cursor {
                "ask anything...".into()
            } else if connected {
                "Describe what to change...".into()
            } else {
                "Run tk login grok to connect".into()
            }
        } else {
            self.input.clone().into()
        };

        // Build messages from the active session
        let mut all_messages: Vec<MessageItem> =
            session.map(|s| s.messages.clone()).unwrap_or_default();
        if let Some(s) = self.active_session() {
            if let Some(role) = &s.streaming_role {
                all_messages.push(MessageItem::new(role, s.streaming_content.clone()));
            }
        }

        // Desktop sidebar/section state
        let _sidebar_expanded = self.sidebar_expanded;
        let _sessions_expanded = self.sessions_expanded;
        let _recent_expanded = self.recent_expanded;

        match self.panel_kind {
            PanelKind::Cursor => {
                let messages = all_messages.iter();
                view_file!("cursor_panel.crepus").on_key_down(cx.listener(Self::handle_key))
            }
            PanelKind::Desktop => {
                let messages = all_messages.iter();
                view_file!("desktop.crepus").on_key_down(cx.listener(Self::handle_key))
            }
        }
    }
}