claudy 0.3.0

Modern multi-provider launcher for Claude CLI
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
use std::sync::Arc;

use crate::domain::channel_events::{
    Button, ChannelIdentity, ConversationId, IncomingEvent, OutboundMessage, TextMessage,
};
use crate::ports::channel_ports::ChannelPort;

use super::super::server::AppState;
use super::super::state::{ChannelState, with_write};
use super::formatting::*;
use super::handlers::handle_project_sessions;

/// Context passed to callback handlers.
pub struct CallbackContext {
    pub channel: Arc<dyn ChannelPort>,
    pub channel_id: ChannelIdentity,
    pub action: String,
    pub data: String,
    pub callback_message_id: Option<String>,
    pub original_text: Option<String>,
    pub scope: String,
    pub channel_state: Arc<tokio::sync::RwLock<ChannelState>>,
    pub app_state: Arc<AppState>,
}

/// Handle callback from inline keyboard buttons.
pub async fn handle_callback(ctx: CallbackContext) -> anyhow::Result<()> {
    let CallbackContext {
        channel,
        channel_id,
        action,
        data,
        callback_message_id,
        original_text,
        scope,
        channel_state,
        app_state,
    } = ctx;
    match action.as_str() {
        "sess" => {
            handle_session_callback(
                channel.as_ref(),
                &channel_id,
                &data,
                callback_message_id,
                original_text,
                &scope,
                &channel_state,
            )
            .await
        }
        "proj" => {
            handle_project_callback(channel.as_ref(), &channel_id, &data, callback_message_id).await
        }
        "model" => {
            handle_model_callback(
                channel.as_ref(),
                &channel_id,
                &data,
                callback_message_id,
                original_text,
                &scope,
                &channel_state,
            )
            .await
        }
        "new" => {
            handle_new_callback(
                channel.as_ref(),
                &channel_id,
                &data,
                callback_message_id,
                original_text,
                &scope,
                &channel_state,
            )
            .await
        }
        "reply" => {
            handle_reply_callback(
                channel.as_ref(),
                &channel_id,
                callback_message_id,
                original_text,
            )
            .await
        }
        "choice" => {
            handle_choice_callback(
                channel.as_ref(),
                &channel_id,
                &data,
                callback_message_id,
                original_text,
                app_state,
            )
            .await
        }
        _ => {
            tracing::warn!(action, data, "Unknown callback action");
            Ok(())
        }
    }
}

async fn handle_session_callback(
    channel: &dyn ChannelPort,
    channel_id: &ChannelIdentity,
    data: &str,
    callback_message_id: Option<String>,
    original_text: Option<String>,
    scope: &str,
    state: &Arc<tokio::sync::RwLock<ChannelState>>,
) -> anyhow::Result<()> {
    // Parse "project_dir:session_prefix" from callback data.
    let (project_dir, session_prefix) = match data.split_once(':') {
        Some((dir, prefix)) => (dir, prefix),
        None => {
            return dismiss_keyboard(
                channel,
                channel_id,
                callback_message_id,
                original_text,
                "Invalid session reference.",
            )
            .await;
        }
    };

    let Some(projects_dir) = super::super::sessions::claude_projects_dir() else {
        return dismiss_keyboard(
            channel,
            channel_id,
            callback_message_id,
            original_text,
            "No projects found.",
        )
        .await;
    };

    // Scope search to the originating project
    let sessions =
        super::super::sessions::discover_project_sessions(&projects_dir, project_dir, 50);
    let matched = sessions
        .iter()
        .find(|s| s.session_id.starts_with(session_prefix));

    let Some(session) = matched else {
        return dismiss_keyboard(
            channel,
            channel_id,
            callback_message_id,
            original_text,
            "Session not found.",
        )
        .await;
    };

    // Switch to this session
    {
        with_write(state, |cs| {
            cs.set_session_id(scope, &session.session_id);
            // Use the session's actual cwd from JSONL, fall back to project_path
            let cwd = session
                .cwd
                .as_deref()
                .or(session.project_path.as_deref())
                .unwrap_or("");
            if !cwd.is_empty() {
                cs.set_working_dir(scope, cwd);
            }
        })
        .await;
    }

    let preview = session.first_message.as_deref().unwrap_or("(no message)");
    let result = format!(
        "Switched to session {}...\nProject: {}\nFirst: {}",
        &session.session_id[..8],
        session.project_name,
        truncate_chars(preview, 80)
    );
    dismiss_keyboard(
        channel,
        channel_id,
        callback_message_id,
        original_text,
        &result,
    )
    .await
}

async fn handle_project_callback(
    channel: &dyn ChannelPort,
    channel_id: &ChannelIdentity,
    encoded_dir: &str,
    callback_message_id: Option<String>,
) -> anyhow::Result<()> {
    // Dismiss the project list keyboard
    dismiss_keyboard(channel, channel_id, callback_message_id, None, "Loading...").await?;

    // Show sessions for this project
    handle_project_sessions(channel, channel_id, encoded_dir).await
}

async fn handle_model_callback(
    channel: &dyn ChannelPort,
    channel_id: &ChannelIdentity,
    model: &str,
    callback_message_id: Option<String>,
    original_text: Option<String>,
    scope: &str,
    state: &Arc<tokio::sync::RwLock<ChannelState>>,
) -> anyhow::Result<()> {
    if !["sonnet", "opus", "haiku"].contains(&model) {
        return dismiss_keyboard(
            channel,
            channel_id,
            callback_message_id,
            original_text,
            "Unknown model.",
        )
        .await;
    }
    {
        with_write(state, |cs| cs.set_model(scope, model)).await;
    }
    dismiss_keyboard(
        channel,
        channel_id,
        callback_message_id,
        original_text,
        &format!("✅ Model set to: {model}"),
    )
    .await
}

/// Edit the message to remove inline keyboard buttons and append the result.
///
/// If `original_text` is provided the edited message will be:
///
/// ```text
/// <original question>
///
/// <result>
/// ```
///
/// This way the user can still see what they were asked before they tapped
/// the button.  When `original_text` is absent (e.g. Slack/Discord which
/// don't surface message text in interaction payloads yet) only `result` is
/// shown, preserving the previous behaviour.
async fn dismiss_keyboard(
    channel: &dyn ChannelPort,
    channel_id: &ChannelIdentity,
    callback_message_id: Option<String>,
    original_text: Option<String>,
    result: &str,
) -> anyhow::Result<()> {
    let text = match original_text.as_deref().filter(|t| !t.is_empty()) {
        Some(question) => format!("{question}\n\n{result}"),
        None => result.to_string(),
    };

    let Some(msg_id) = callback_message_id else {
        // Fallback: just send a new message
        return reply(channel, channel_id, &text).await;
    };
    channel
        .edit_message(&OutboundMessage {
            conversation_id: ConversationId::new(),
            channel: channel_id.clone(),
            text,
            message_ref: Some(msg_id),
            interaction: None,
        })
        .await
}

async fn handle_reply_callback(
    channel: &dyn ChannelPort,
    channel_id: &ChannelIdentity,
    callback_message_id: Option<String>,
    original_text: Option<String>,
) -> anyhow::Result<()> {
    dismiss_keyboard(
        channel,
        channel_id,
        callback_message_id,
        original_text,
        "Type your response below.",
    )
    .await
}

async fn handle_choice_callback(
    channel: &dyn ChannelPort,
    channel_id: &ChannelIdentity,
    data: &str,
    callback_message_id: Option<String>,
    original_text: Option<String>,
    app_state: Arc<AppState>,
) -> anyhow::Result<()> {
    // Reject if Claude is already running for this scope
    {
        let scope = crate::adapters::channel::state::scope_key(
            channel_id.platform.as_str(),
            &channel_id.channel_id,
            &channel_id.user_id,
        );
        let active = app_state.active_claude.try_lock();
        match active {
            Ok(guard) if guard.contains_key(&scope) => {
                return dismiss_keyboard(
                    channel,
                    channel_id,
                    callback_message_id,
                    original_text,
                    "Claude is busy — wait for the current response to finish.",
                )
                .await;
            }
            Err(_) => {
                return dismiss_keyboard(
                    channel,
                    channel_id,
                    callback_message_id,
                    original_text,
                    "Claude is busy — wait for the current response to finish.",
                )
                .await;
            }
            _ => {} // Lock held, not active for this scope — proceed
        }
    }
    dismiss_keyboard(
        channel,
        channel_id,
        callback_message_id,
        original_text,
        &format!("> {data}"),
    )
    .await?;
    let synthetic = IncomingEvent::TextMessage(TextMessage {
        conversation_id: ConversationId::new(),
        channel: channel_id.clone(),
        text: data.to_string(),
        reply_to_id: None,
    });
    super::super::server::spawn_process_event(app_state, synthetic);
    Ok(())
}

async fn handle_new_callback(
    channel: &dyn ChannelPort,
    channel_id: &ChannelIdentity,
    data: &str,
    callback_message_id: Option<String>,
    original_text: Option<String>,
    scope: &str,
    state: &Arc<tokio::sync::RwLock<ChannelState>>,
) -> anyhow::Result<()> {
    match data {
        "session" => {
            dismiss_keyboard(channel, channel_id, callback_message_id, original_text, "").await?;
            reply_with_buttons(
                channel,
                channel_id,
                "New session:".to_string(),
                "Choose scope",
                vec![
                    Button {
                        id: "new:current".to_string(),
                        label: "Current project".to_string(),
                    },
                    Button {
                        id: "new:project".to_string(),
                        label: "Other project".to_string(),
                    },
                ],
            )
            .await
        }
        "current" => {
            let cwd_info = with_write(state, |cs| {
                cs.clear_session(scope);
                cs.clear_waiting_for_dir(scope);
                cs.working_dir(scope)
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| "default workspace".to_string())
            })
            .await;
            dismiss_keyboard(
                channel,
                channel_id,
                callback_message_id,
                original_text,
                &format!("New session started.\nWorking dir: {}", cwd_info),
            )
            .await
        }
        "project" => {
            with_write(state, |cs| {
                cs.set_waiting_for_dir(scope);
            })
            .await;
            dismiss_keyboard(
                channel,
                channel_id,
                callback_message_id,
                original_text,
                "Enter the project folder path:",
            )
            .await
        }
        _ => {
            dismiss_keyboard(
                channel,
                channel_id,
                callback_message_id,
                original_text,
                "Unknown new-session option.",
            )
            .await
        }
    }
}