Skip to content

Commit be4f591

Browse files
feat(owpenbot): add send command and sidecar integration (anomalyco#309)
- Add 'send' command for testing message delivery to WhatsApp/Telegram - Create build script at packages/owpenbot/script/build.ts - Add build:binary script to package.json - Update prepare-sidecar.mjs to compile owpenbot alongside server - Add owpenbot to externalBin in tauri.conf.json - Create Tauri owpenbot module with manager and spawn logic - Add owpenbot_start, owpenbot_stop, owpenbot_info, owpenbot_qr commands - Register OwpenbotManager and commands in lib.rs
1 parent e893a51 commit be4f591

12 files changed

Lines changed: 537 additions & 4 deletions

File tree

‎packages/desktop/scripts/prepare-sidecar.mjs‎

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ const DOWNLOAD_URL =
1010

1111
const __dirname = dirname(fileURLToPath(import.meta.url));
1212
const sidecarDir = join(__dirname, "..", "src-tauri", "sidecars");
13-
const openworkServerName = process.platform === "win32" ? "openwork-server.exe" : "openwork-server";
14-
const openworkServerPath = join(sidecarDir, openworkServerName);
15-
const openworkServerTargetTriple = (() => {
13+
14+
// Target triple for native platform binaries
15+
const nativeTargetTriple = (() => {
1616
if (process.platform === "darwin") {
1717
return process.arch === "arm64" ? "aarch64-apple-darwin" : "x86_64-apple-darwin";
1818
}
@@ -21,11 +21,26 @@ const openworkServerTargetTriple = (() => {
2121
}
2222
return null;
2323
})();
24+
25+
// openwork-server paths
26+
const openworkServerName = process.platform === "win32" ? "openwork-server.exe" : "openwork-server";
27+
const openworkServerPath = join(sidecarDir, openworkServerName);
28+
const openworkServerTargetTriple = nativeTargetTriple;
2429
const openworkServerTargetPath = openworkServerTargetTriple
2530
? join(sidecarDir, `openwork-server-${openworkServerTargetTriple}`)
2631
: null;
2732

2833
const openworkServerDir = resolve(__dirname, "..", "..", "server");
34+
35+
// owpenbot paths
36+
const owpenbotName = process.platform === "win32" ? "owpenbot.exe" : "owpenbot";
37+
const owpenbotPath = join(sidecarDir, owpenbotName);
38+
const owpenbotTargetTriple = nativeTargetTriple;
39+
const owpenbotTargetPath = owpenbotTargetTriple
40+
? join(sidecarDir, `owpenbot-${owpenbotTargetTriple}`)
41+
: null;
42+
43+
const owpenbotDir = resolve(__dirname, "..", "..", "owpenbot");
2944
const targetSidecarPath = join(sidecarDir, `opencode-${TARGET_TRIPLE}.exe`);
3045
const devSidecarPath = join(sidecarDir, "opencode.exe");
3146

@@ -79,6 +94,43 @@ if (openworkServerTargetPath) {
7994
}
8095
}
8196

97+
// Build owpenbot
98+
const shouldBuildOwpenbot = !existsSync(owpenbotPath) || isStubBinary(owpenbotPath);
99+
100+
if (shouldBuildOwpenbot) {
101+
mkdirSync(sidecarDir, { recursive: true });
102+
if (existsSync(owpenbotPath)) {
103+
try {
104+
unlinkSync(owpenbotPath);
105+
} catch {
106+
// ignore
107+
}
108+
}
109+
const owpenbotBuildResult = spawnSync(
110+
"bun",
111+
["./script/build.ts", "--outdir", sidecarDir, "--filename", "owpenbot"],
112+
{ cwd: owpenbotDir, stdio: "inherit" }
113+
);
114+
115+
if (owpenbotBuildResult.status !== 0) {
116+
process.exit(owpenbotBuildResult.status ?? 1);
117+
}
118+
}
119+
120+
if (owpenbotTargetPath) {
121+
const shouldCopyOwpenbotTarget = !existsSync(owpenbotTargetPath) || isStubBinary(owpenbotTargetPath);
122+
if (shouldCopyOwpenbotTarget && existsSync(owpenbotPath)) {
123+
try {
124+
if (existsSync(owpenbotTargetPath)) {
125+
unlinkSync(owpenbotTargetPath);
126+
}
127+
} catch {
128+
// ignore
129+
}
130+
copyFileSync(owpenbotPath, owpenbotTargetPath);
131+
}
132+
}
133+
82134
if (process.platform !== "win32") {
83135
console.log("Skipping Windows sidecar download (non-Windows host).");
84136
process.exit(0);

‎packages/desktop/src-tauri/src/commands/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pub mod engine;
44
pub mod misc;
55
pub mod openwork_server;
66
pub mod opkg;
7+
pub mod owpenbot;
78
pub mod skills;
89
pub mod updater;
910
pub mod workspace;
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
use tauri::{AppHandle, State};
2+
use tauri_plugin_shell::process::CommandEvent;
3+
4+
use crate::owpenbot::manager::OwpenbotManager;
5+
use crate::owpenbot::spawn::spawn_owpenbot;
6+
use crate::types::OwpenbotInfo;
7+
use crate::utils::truncate_output;
8+
9+
#[tauri::command]
10+
pub fn owpenbot_info(manager: State<OwpenbotManager>) -> OwpenbotInfo {
11+
let mut state = manager.inner.lock().expect("owpenbot mutex poisoned");
12+
OwpenbotManager::snapshot_locked(&mut state)
13+
}
14+
15+
#[tauri::command]
16+
pub fn owpenbot_start(
17+
app: AppHandle,
18+
manager: State<OwpenbotManager>,
19+
workspace_path: String,
20+
opencode_url: Option<String>,
21+
) -> Result<OwpenbotInfo, String> {
22+
let mut state = manager
23+
.inner
24+
.lock()
25+
.map_err(|_| "owpenbot mutex poisoned".to_string())?;
26+
OwpenbotManager::stop_locked(&mut state);
27+
28+
let (mut rx, child) = spawn_owpenbot(&app, &workspace_path, opencode_url.as_deref())?;
29+
30+
state.child = Some(child);
31+
state.child_exited = false;
32+
state.workspace_path = Some(workspace_path);
33+
state.opencode_url = opencode_url;
34+
state.last_stdout = None;
35+
state.last_stderr = None;
36+
37+
let state_handle = manager.inner.clone();
38+
39+
tauri::async_runtime::spawn(async move {
40+
while let Some(event) = rx.recv().await {
41+
match event {
42+
CommandEvent::Stdout(line_bytes) => {
43+
let line = String::from_utf8_lossy(&line_bytes).to_string();
44+
if let Ok(mut state) = state_handle.try_lock() {
45+
let next = state
46+
.last_stdout
47+
.as_deref()
48+
.unwrap_or_default()
49+
.to_string()
50+
+ &line;
51+
state.last_stdout = Some(truncate_output(&next, 8000));
52+
53+
// Check for WhatsApp linked status in output
54+
if line.contains("WhatsApp linked") {
55+
state.whatsapp_linked = true;
56+
}
57+
}
58+
}
59+
CommandEvent::Stderr(line_bytes) => {
60+
let line = String::from_utf8_lossy(&line_bytes).to_string();
61+
if let Ok(mut state) = state_handle.try_lock() {
62+
let next = state
63+
.last_stderr
64+
.as_deref()
65+
.unwrap_or_default()
66+
.to_string()
67+
+ &line;
68+
state.last_stderr = Some(truncate_output(&next, 8000));
69+
}
70+
}
71+
CommandEvent::Terminated(payload) => {
72+
if let Ok(mut state) = state_handle.try_lock() {
73+
state.child_exited = true;
74+
if let Some(code) = payload.code {
75+
let next = format!("Owpenbot exited (code {code}).");
76+
state.last_stderr = Some(truncate_output(&next, 8000));
77+
}
78+
}
79+
}
80+
CommandEvent::Error(message) => {
81+
if let Ok(mut state) = state_handle.try_lock() {
82+
state.child_exited = true;
83+
let next = state
84+
.last_stderr
85+
.as_deref()
86+
.unwrap_or_default()
87+
.to_string()
88+
+ &message;
89+
state.last_stderr = Some(truncate_output(&next, 8000));
90+
}
91+
}
92+
_ => {}
93+
}
94+
}
95+
});
96+
97+
Ok(OwpenbotManager::snapshot_locked(&mut state))
98+
}
99+
100+
#[tauri::command]
101+
pub fn owpenbot_stop(manager: State<OwpenbotManager>) -> Result<OwpenbotInfo, String> {
102+
let mut state = manager
103+
.inner
104+
.lock()
105+
.map_err(|_| "owpenbot mutex poisoned".to_string())?;
106+
OwpenbotManager::stop_locked(&mut state);
107+
Ok(OwpenbotManager::snapshot_locked(&mut state))
108+
}
109+
110+
#[tauri::command]
111+
pub async fn owpenbot_qr(app: AppHandle) -> Result<String, String> {
112+
use tauri_plugin_shell::ShellExt;
113+
114+
let command = match app.shell().sidecar("owpenbot") {
115+
Ok(command) => command,
116+
Err(_) => app.shell().command("owpenbot"),
117+
};
118+
119+
let output = command
120+
.args(["whatsapp", "qr", "--format", "base64", "--json"])
121+
.output()
122+
.await
123+
.map_err(|e| format!("Failed to get QR code: {e}"))?;
124+
125+
if !output.status.success() {
126+
let stderr = String::from_utf8_lossy(&output.stderr);
127+
return Err(format!("Failed to get QR code: {stderr}"));
128+
}
129+
130+
let stdout = String::from_utf8_lossy(&output.stdout);
131+
132+
// Parse JSON response
133+
#[derive(serde::Deserialize)]
134+
struct QrResponse {
135+
qr: Option<String>,
136+
error: Option<String>,
137+
}
138+
139+
let response: QrResponse =
140+
serde_json::from_str(&stdout).map_err(|e| format!("Failed to parse QR response: {e}"))?;
141+
142+
if let Some(error) = response.error {
143+
return Err(error);
144+
}
145+
146+
response.qr.ok_or_else(|| "No QR code returned".to_string())
147+
}

‎packages/desktop/src-tauri/src/lib.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ mod engine;
44
mod fs;
55
mod opkg;
66
mod openwork_server;
7+
mod owpenbot;
78
mod paths;
89
mod platform;
910
mod types;
@@ -21,6 +22,7 @@ use commands::engine::{engine_doctor, engine_info, engine_install, engine_start,
2122
use commands::misc::{opencode_mcp_auth, reset_opencode_cache, reset_openwork_state};
2223
use commands::openwork_server::openwork_server_info;
2324
use commands::opkg::{import_skill, opkg_install};
25+
use commands::owpenbot::{owpenbot_info, owpenbot_qr, owpenbot_start, owpenbot_stop};
2426
use commands::skills::{install_skill_template, list_local_skills, uninstall_skill};
2527
use commands::updater::updater_environment;
2628
use commands::workspace::{
@@ -30,6 +32,7 @@ use commands::workspace::{
3032
};
3133
use engine::manager::EngineManager;
3234
use openwork_server::manager::OpenworkServerManager;
35+
use owpenbot::manager::OwpenbotManager;
3336
use workspace::watch::WorkspaceWatchState;
3437

3538
pub fn run() {
@@ -46,6 +49,7 @@ pub fn run() {
4649
builder
4750
.manage(EngineManager::default())
4851
.manage(OpenworkServerManager::default())
52+
.manage(OwpenbotManager::default())
4953
.manage(WorkspaceWatchState::default())
5054
.invoke_handler(tauri::generate_handler![
5155
engine_start,
@@ -54,6 +58,10 @@ pub fn run() {
5458
engine_doctor,
5559
engine_install,
5660
openwork_server_info,
61+
owpenbot_info,
62+
owpenbot_start,
63+
owpenbot_stop,
64+
owpenbot_qr,
5765
workspace_bootstrap,
5866
workspace_set_active,
5967
workspace_create,
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
use std::sync::{Arc, Mutex};
2+
3+
use tauri_plugin_shell::process::CommandChild;
4+
5+
use crate::types::OwpenbotInfo;
6+
7+
#[derive(Default)]
8+
pub struct OwpenbotManager {
9+
pub inner: Arc<Mutex<OwpenbotState>>,
10+
}
11+
12+
#[derive(Default)]
13+
pub struct OwpenbotState {
14+
pub child: Option<CommandChild>,
15+
pub child_exited: bool,
16+
pub workspace_path: Option<String>,
17+
pub opencode_url: Option<String>,
18+
pub qr_data: Option<String>,
19+
pub whatsapp_linked: bool,
20+
pub telegram_configured: bool,
21+
pub last_stdout: Option<String>,
22+
pub last_stderr: Option<String>,
23+
}
24+
25+
impl OwpenbotManager {
26+
pub fn snapshot_locked(state: &mut OwpenbotState) -> OwpenbotInfo {
27+
let (running, pid) = match state.child.as_ref() {
28+
None => (false, None),
29+
Some(_child) if state.child_exited => {
30+
state.child = None;
31+
(false, None)
32+
}
33+
Some(child) => (true, Some(child.pid())),
34+
};
35+
36+
OwpenbotInfo {
37+
running,
38+
workspace_path: state.workspace_path.clone(),
39+
opencode_url: state.opencode_url.clone(),
40+
qr_data: state.qr_data.clone(),
41+
whatsapp_linked: state.whatsapp_linked,
42+
telegram_configured: state.telegram_configured,
43+
pid,
44+
last_stdout: state.last_stdout.clone(),
45+
last_stderr: state.last_stderr.clone(),
46+
}
47+
}
48+
49+
pub fn stop_locked(state: &mut OwpenbotState) {
50+
if let Some(child) = state.child.take() {
51+
let _ = child.kill();
52+
}
53+
state.child_exited = true;
54+
state.workspace_path = None;
55+
state.opencode_url = None;
56+
state.qr_data = None;
57+
state.whatsapp_linked = false;
58+
state.telegram_configured = false;
59+
state.last_stdout = None;
60+
state.last_stderr = None;
61+
}
62+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
pub mod manager;
2+
pub mod spawn;
3+
4+
pub use manager::*;
5+
pub use spawn::*;

0 commit comments

Comments
 (0)