beam-worker 0.12.1

Per-session worker process for beam that owns terminal backends and CLI adapters
Documentation
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
434
435
436
437
//! Shared test helpers for the opencode adapter module.

use super::*;
use crate::backend::SessionBackend;
use async_trait::async_trait;
use std::path::Path;
use std::process::Command;
use std::sync::{Arc, Mutex};
use uuid::Uuid;

// ---------------------------------------------------------------------------
// Temp dir
// ---------------------------------------------------------------------------

pub(crate) fn temp_dir(name: &str) -> PathBuf {
    std::env::temp_dir().join(format!("beam-opencode-{}-{}", name, Uuid::new_v4()))
}

// ---------------------------------------------------------------------------
// DB creation helpers
// ---------------------------------------------------------------------------

pub(crate) fn create_test_db(db_path: &Path) {
    let mut script = String::from(
        r#"
import sqlite3
conn = sqlite3.connect(__DB_PATH__)
conn.executescript("""
CREATE TABLE session (
  id TEXT PRIMARY KEY,
  directory TEXT,
  time_updated INTEGER,
  time_archived INTEGER,
  parent_id TEXT
);
CREATE TABLE message (
  id TEXT PRIMARY KEY,
  session_id TEXT,
  time_created INTEGER,
  time_updated INTEGER,
  data TEXT
);
CREATE TABLE part (
  id TEXT PRIMARY KEY,
  message_id TEXT,
  session_id TEXT,
  time_created INTEGER,
  time_updated INTEGER,
  data TEXT
);
""")
conn.execute(
    "INSERT INTO session (id, directory, time_updated) VALUES (?, ?, ?)",
    ("sess-1", "/repo/opencode", 1500),
)
conn.execute(
    "INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)",
    ("msg-user", "sess-1", 1000, 1001, '{"role":"user","id":"msg-user"}'),
)
conn.execute(
    "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)",
    ("part-user", "msg-user", "sess-1", 1002, 1002, '{"type":"text","text":"hello"}'),
)
conn.execute(
    "INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)",
    ("msg-asst", "sess-1", 1300, 1500, '{"role":"assistant","id":"msg-asst"}'),
)
conn.execute(
    "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)",
    ("part-step", "msg-asst", "sess-1", 1400, 1400, '{"type":"step-start"}'),
)
conn.execute(
    "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)",
    ("part-text", "msg-asst", "sess-1", 1490, 1490, '{"type":"text","text":"hi there"}'),
)
conn.commit()
"#,
    );
    script = script.replace("__DB_PATH__", &json_string(&db_path.display().to_string()));
    let status = Command::new("python3")
        .args(["-c", &script])
        .status()
        .expect("python3 available");
    assert!(status.success(), "failed to create sqlite db");
}

pub(crate) fn append_user_submit(
    db_path: &Path,
    session_id: &str,
    text: &str,
    time_created: u64,
    time_updated: u64,
) {
    let message_id = format!("msg-{}", Uuid::new_v4());
    let part_id = format!("part-{}", Uuid::new_v4());
    let mut script = String::from(
        r#"
import sqlite3
conn = sqlite3.connect(__DB_PATH__)
conn.execute(
    "INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)",
    (__MESSAGE_ID__, __SESSION_ID__, __TIME_CREATED__, __TIME_UPDATED__, __MESSAGE_DATA__),
)
conn.execute(
    "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)",
    (__PART_ID__, __MESSAGE_ID__, __SESSION_ID__, __PART_CREATED__, __PART_UPDATED__, __PART_DATA__),
)
conn.commit()
"#,
    );
    script = script.replace("__DB_PATH__", &json_string(&db_path.display().to_string()));
    script = script.replace("__MESSAGE_ID__", &json_string(&message_id));
    script = script.replace("__PART_ID__", &json_string(&part_id));
    script = script.replace("__SESSION_ID__", &json_string(session_id));
    script = script.replace("__TIME_CREATED__", &time_created.to_string());
    script = script.replace("__TIME_UPDATED__", &time_updated.to_string());
    script = script.replace(
        "__MESSAGE_DATA__",
        &json_string(r#"{"role":"user","id":"submit"}"#),
    );
    script = script.replace("__PART_CREATED__", &(time_created + 1).to_string());
    script = script.replace("__PART_UPDATED__", &time_updated.to_string());
    script = script.replace(
        "__PART_DATA__",
        &json_string(&format!(
            r#"{{"type":"text","text":{}}}"#,
            json_string(text)
        )),
    );
    let status = Command::new("python3")
        .args(["-c", &script])
        .status()
        .expect("python3 available");
    assert!(status.success(), "failed to append submit row");
}

// ---------------------------------------------------------------------------
// Mock backend
// ---------------------------------------------------------------------------

#[derive(Clone)]
pub(crate) struct RecordingBackend {
    db_path: PathBuf,
    buffer: Arc<Mutex<String>>,
    append_on_enter: bool,
    next_time: Arc<Mutex<u64>>,
    calls: Arc<Mutex<Vec<String>>>,
    screen_content: Arc<Mutex<String>>,
    target_session_id: String,
}

impl RecordingBackend {
    pub(crate) fn new(db_path: PathBuf, append_on_enter: bool, start_time: u64) -> Self {
        Self {
            db_path,
            buffer: Arc::new(Mutex::new(String::new())),
            append_on_enter,
            next_time: Arc::new(Mutex::new(start_time)),
            calls: Arc::new(Mutex::new(Vec::new())),
            screen_content: Arc::new(Mutex::new(String::new())),
            target_session_id: "sess-1".to_string(),
        }
    }

    pub(crate) fn calls(&self) -> Vec<String> {
        self.calls.lock().unwrap().clone()
    }

    pub(crate) fn with_screen(self, content: String) -> Self {
        Self {
            screen_content: Arc::new(Mutex::new(content)),
            ..self
        }
    }

    pub(crate) fn with_target_session(mut self, id: impl Into<String>) -> Self {
        self.target_session_id = id.into();
        self
    }
}

#[async_trait]
impl SessionBackend for RecordingBackend {
    async fn spawn(
        &self,
        _bin: &str,
        _args: &[String],
        _opts: crate::backend::SpawnOpts,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    async fn send_text(&self, text: &str) -> anyhow::Result<()> {
        self.calls.lock().unwrap().push(format!("text:{text}"));
        self.buffer.lock().unwrap().push_str(text);
        Ok(())
    }

    async fn send_enter(&self) -> anyhow::Result<()> {
        self.calls.lock().unwrap().push("enter".to_string());
        if self.append_on_enter {
            let content = {
                let mut buffer = self.buffer.lock().unwrap();
                let content = buffer.clone();
                buffer.clear();
                content
            };
            if !content.is_empty() {
                let mut next_time = self.next_time.lock().unwrap();
                let created = *next_time + 1;
                let updated = created + 1;
                *next_time = updated;
                append_user_submit(
                    &self.db_path,
                    &self.target_session_id,
                    &content,
                    created,
                    updated,
                );
            }
        }
        Ok(())
    }

    async fn send_special_keys(&self, _keys: &[String]) -> anyhow::Result<()> {
        Ok(())
    }

    async fn paste_text(&self, text: &str) -> anyhow::Result<()> {
        self.send_text(text).await
    }

    async fn write_raw(&self, _text: &str) -> anyhow::Result<()> {
        Ok(())
    }

    async fn raw_input(&self, _text: &str) -> anyhow::Result<()> {
        Ok(())
    }

    async fn capture_viewport(&self) -> anyhow::Result<String> {
        Ok(self.screen_content.lock().unwrap().clone())
    }

    async fn capture_current_screen(&self) -> anyhow::Result<String> {
        self.capture_viewport().await
    }

    async fn is_alive(&self) -> anyhow::Result<bool> {
        Ok(true)
    }

    async fn child_pid(&self) -> anyhow::Result<Option<u32>> {
        Ok(None)
    }

    async fn kill(&self) -> anyhow::Result<()> {
        Ok(())
    }

    async fn destroy_session(&self) -> anyhow::Result<()> {
        Ok(())
    }

    async fn cursor_position(&self) -> anyhow::Result<Option<(u16, u16)>> {
        Ok(None)
    }

    fn subscribe(&self) -> tokio::sync::broadcast::Receiver<String> {
        let (_tx, rx) = tokio::sync::broadcast::channel(1);
        rx
    }
}

// ---------------------------------------------------------------------------
// Multi-session DB helpers
// ---------------------------------------------------------------------------

pub(crate) fn create_db_with_sessions(db_path: &Path, sessions: &[(&str, &str, u64)]) {
    let mut script = String::from(
        r#"
import sqlite3
conn = sqlite3.connect(__DB_PATH__)
conn.executescript("""
CREATE TABLE session (
  id TEXT PRIMARY KEY,
  directory TEXT,
  time_updated INTEGER,
  time_archived INTEGER,
  parent_id TEXT
);
CREATE TABLE message (
  id TEXT PRIMARY KEY,
  session_id TEXT,
  time_created INTEGER,
  time_updated INTEGER,
  data TEXT
);
CREATE TABLE part (
  id TEXT PRIMARY KEY,
  message_id TEXT,
  session_id TEXT,
  time_created INTEGER,
  time_updated INTEGER,
  data TEXT
);
""")
"#,
    );
    script = script.replace("__DB_PATH__", &json_string(&db_path.display().to_string()));
    for &(id, directory, time_updated) in sessions {
        script.push_str(&format!(
            "conn.execute(\"INSERT INTO session (id, directory, time_updated) VALUES (?, ?, ?)\", (\"{}\", \"{}\", {}))\n",
            id, directory, time_updated
        ));
    }
    script.push_str("conn.commit()\n");
    let status = Command::new("python3")
        .args(["-c", &script])
        .status()
        .expect("python3 available");
    assert!(status.success(), "failed to create multi-session sqlite db");
}

#[allow(clippy::type_complexity)]
pub(crate) fn create_db_with_session_rows(
    db_path: &Path,
    sessions: &[(&str, &str, u64, Option<u64>, Option<&str>)],
) {
    let mut script = String::from(
        r#"
import sqlite3
conn = sqlite3.connect(__DB_PATH__)
conn.executescript("""
CREATE TABLE session (
  id TEXT PRIMARY KEY,
  directory TEXT,
  time_updated INTEGER,
  time_archived INTEGER,
  parent_id TEXT
);
CREATE TABLE message (
  id TEXT PRIMARY KEY,
  session_id TEXT,
  time_created INTEGER,
  time_updated INTEGER,
  data TEXT
);
CREATE TABLE part (
  id TEXT PRIMARY KEY,
  message_id TEXT,
  session_id TEXT,
  time_created INTEGER,
  time_updated INTEGER,
  data TEXT
);
""")
"#,
    );
    script = script.replace("__DB_PATH__", &json_string(&db_path.display().to_string()));
    for &(id, directory, time_updated, time_archived, parent_id) in sessions {
        let time_archived = time_archived
            .map(|value| value.to_string())
            .unwrap_or_else(|| "None".to_string());
        let parent_id = parent_id
            .map(json_string)
            .unwrap_or_else(|| "None".to_string());
        script.push_str(&format!(
            "conn.execute(\"INSERT INTO session (id, directory, time_updated, time_archived, parent_id) VALUES (?, ?, ?, ?, ?)\", ({}, {}, {}, {}, {}))\n",
            json_string(id),
            json_string(directory),
            time_updated,
            time_archived,
            parent_id
        ));
    }
    script.push_str("conn.commit()\n");
    let status = Command::new("python3")
        .args(["-c", &script])
        .status()
        .expect("python3 available");
    assert!(
        status.success(),
        "failed to create sqlite db with session rows"
    );
}

pub(crate) fn insert_message_with_text(
    db_path: &Path,
    session_id: &str,
    message_id: &str,
    role: &str,
    text: &str,
    time_created: u64,
    time_updated: u64,
) {
    let part_id = format!("{}-part", message_id);
    let mut script = String::from(
        r#"
import sqlite3
conn = sqlite3.connect(__DB_PATH__)
conn.execute(
    "INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)",
    (__MESSAGE_ID__, __SESSION_ID__, __TIME_CREATED__, __TIME_UPDATED__, __MESSAGE_DATA__),
)
conn.execute(
    "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)",
    (__PART_ID__, __MESSAGE_ID__, __SESSION_ID__, __PART_CREATED__, __PART_UPDATED__, __PART_DATA__),
)
conn.commit()
"#,
    );
    script = script.replace("__DB_PATH__", &json_string(&db_path.display().to_string()));
    script = script.replace("__MESSAGE_ID__", &json_string(message_id));
    script = script.replace("__PART_ID__", &json_string(&part_id));
    script = script.replace("__SESSION_ID__", &json_string(session_id));
    script = script.replace("__TIME_CREATED__", &time_created.to_string());
    script = script.replace("__TIME_UPDATED__", &time_updated.to_string());
    script = script.replace(
        "__MESSAGE_DATA__",
        &json_string(&format!(r#"{{"role":"{}","id":"{}"}}"#, role, message_id)),
    );
    script = script.replace("__PART_CREATED__", &(time_created + 1).to_string());
    script = script.replace("__PART_UPDATED__", &time_updated.to_string());
    script = script.replace(
        "__PART_DATA__",
        &json_string(&format!(
            r#"{{"type":"text","text":{}}}"#,
            json_string(text)
        )),
    );
    let status = Command::new("python3")
        .args(["-c", &script])
        .status()
        .expect("python3 available");
    assert!(status.success(), "failed to insert message with text");
}