use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
use uuid::Uuid;
use crate::config::{ProjectConfig, ServeMode};
use crate::mcp::McpClient;
const SCHEMA_VERSION: u32 = 2;
const ROJO_PORT_MIN: u16 = 40_000;
const ROJO_PORT_COUNT: u16 = 10_000;
#[derive(Clone, Debug)]
pub struct GeneratedPaths {
pub state: PathBuf,
pub lock: PathBuf,
pub build_project: PathBuf,
pub serve_project: PathBuf,
pub artifact: PathBuf,
pub rojo_log: PathBuf,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct SessionState {
pub schema_version: Option<u32>,
pub worktree_id: Option<String>,
pub worktree_root: Option<String>,
pub updated_at: Option<f64>,
pub session_token: Option<String>,
pub port: Option<u16>,
pub project_name: Option<String>,
pub project_source_digest: Option<String>,
pub artifact_digest: Option<String>,
pub artifact_built_at: Option<f64>,
pub rojo_pid: Option<u32>,
pub rojo_birth: Option<String>,
pub rojo_start_ticks: Option<u64>,
pub rojo_started_at: Option<f64>,
pub instance_id: Option<String>,
pub studio_started_at: Option<f64>,
pub studio_process_pid: Option<u32>,
pub studio_process_started: Option<u64>,
pub validated_at: Option<f64>,
pub manifest_verified_at: Option<f64>,
}
pub struct OperationLock(File);
impl Drop for OperationLock {
fn drop(&mut self) {
let _ = FileExt::unlock(&self.0);
}
}
pub struct StudioSession {
pub config: ProjectConfig,
pub mcp: McpClient,
pub paths: GeneratedPaths,
}
fn now() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
pub fn worktree_identity(root: &Path) -> String {
let resolved = root.to_string_lossy();
let raw = root
.file_name()
.and_then(|value| value.to_str())
.unwrap_or("worktree")
.to_lowercase();
let mut readable = String::new();
let mut separating = false;
for character in raw.chars() {
if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
readable.push(character);
separating = false;
} else if !separating && !readable.is_empty() {
readable.push('-');
separating = true;
}
}
let readable = readable.trim_matches('-');
let readable = if readable.is_empty() {
"worktree"
} else {
readable
};
let digest = Sha256::digest(resolved.as_bytes());
format!("{readable}-{:x}", digest)[..readable.len() + 11].to_owned()
}
fn sha256(path: &Path) -> Result<String> {
let mut file =
File::open(path).with_context(|| format!("Could not open {}", path.display()))?;
let mut digest = Sha256::new();
std::io::copy(&mut file, &mut digest)
.with_context(|| format!("Could not hash {}", path.display()))?;
Ok(format!("{:x}", digest.finalize()))
}
fn replace_file(temporary: &Path, target: &Path) -> Result<()> {
#[cfg(windows)]
if target.exists() {
fs::remove_file(target)
.with_context(|| format!("Could not replace {}", target.display()))?;
}
fs::rename(temporary, target).with_context(|| {
format!(
"Could not move {} to {}",
temporary.display(),
target.display()
)
})
}
fn atomic_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("Could not create {}", parent.display()))?;
}
let temporary = path.with_extension(format!(
"{}.next",
path.extension()
.and_then(|value| value.to_str())
.unwrap_or("json")
));
let mut bytes = serde_json::to_vec_pretty(value).context("Could not encode JSON")?;
bytes.push(b'\n');
fs::write(&temporary, bytes)
.with_context(|| format!("Could not write {}", temporary.display()))?;
replace_file(&temporary, path)
}
fn rebase_project_paths(value: &mut Value, project_dir: &Path, generated_dir: &Path) {
match value {
Value::Array(values) => {
for value in values {
rebase_project_paths(value, project_dir, generated_dir);
}
}
Value::Object(object) => {
if let Some(Value::String(path)) = object.get_mut("$path") {
let original = Path::new(path);
if !original.is_absolute() {
if let Some(relative) =
pathdiff::diff_paths(project_dir.join(original), generated_dir)
{
*path = relative.to_string_lossy().into_owned();
}
}
}
for (key, value) in object.iter_mut() {
if key != "$path" {
rebase_project_paths(value, project_dir, generated_dir);
}
}
}
_ => {}
}
}
fn is_port_free(port: u16) -> bool {
TcpListener::bind(("127.0.0.1", port)).is_ok()
}
pub fn choose_port(identity: &str, unavailable: &BTreeSet<u16>) -> Result<u16> {
let digest = Sha256::digest(identity.as_bytes());
let seed = u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]]);
let start = ROJO_PORT_MIN + (seed % u32::from(ROJO_PORT_COUNT)) as u16;
for offset in 0..ROJO_PORT_COUNT {
let port = ROJO_PORT_MIN + ((start - ROJO_PORT_MIN + offset) % ROJO_PORT_COUNT);
if !unavailable.contains(&port) && is_port_free(port) {
return Ok(port);
}
}
bail!("No free loopback port is available for this worktree's Rojo server")
}
impl StudioSession {
pub fn new(config: ProjectConfig, mcp: McpClient) -> Self {
let state_dir = &config.state_dir;
Self {
paths: GeneratedPaths {
state: state_dir.join("session.json"),
lock: state_dir.join("operation.lock"),
build_project: state_dir.join("build.project.json"),
serve_project: state_dir.join("serve.project.json"),
artifact: state_dir.join("place.rbxl"),
rojo_log: state_dir.join("rojo.log"),
},
config,
mcp,
}
}
pub fn identity(&self) -> String {
worktree_identity(&self.config.root)
}
pub fn project_name(&self) -> String {
format!("{}@{}", self.config.project_name, self.identity())
}
pub fn operation_lock(&self) -> Result<OperationLock> {
fs::create_dir_all(&self.config.state_dir)
.with_context(|| format!("Could not create {}", self.config.state_dir.display()))?;
let file = OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(&self.paths.lock)
.with_context(|| format!("Could not open {}", self.paths.lock.display()))?;
file.lock_exclusive()
.with_context(|| format!("Could not lock {}", self.paths.lock.display()))?;
Ok(OperationLock(file))
}
pub fn load_state(&self) -> Result<SessionState> {
let bytes = match fs::read(&self.paths.state) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(SessionState::default());
}
Err(error) => {
return Err(error)
.with_context(|| format!("Could not read {}", self.paths.state.display()));
}
};
serde_json::from_slice(&bytes)
.with_context(|| format!("Invalid session state in {}", self.paths.state.display()))
}
pub fn save_state(&self, state: &mut SessionState) -> Result<()> {
state.schema_version = Some(SCHEMA_VERSION);
state.worktree_id = Some(self.identity());
state.worktree_root = Some(self.config.root.to_string_lossy().into_owned());
state.updated_at = Some(now());
atomic_json(&self.paths.state, state)
}
fn ensure_session_token(state: &mut SessionState) -> String {
match state
.session_token
.clone()
.filter(|value| !value.is_empty())
{
Some(token) => token,
None => {
let token = Uuid::new_v4().simple().to_string();
state.session_token = Some(token.clone());
token
}
}
}
fn contract_attributes(&self, port: u16, session_token: &str) -> BTreeMap<String, String> {
BTreeMap::from([
(
self.config.contract.endpoint_attribute.clone(),
format!("http://127.0.0.1:{port}"),
),
(
self.config.contract.project_attribute.clone(),
self.project_name(),
),
(
self.config.contract.session_attribute.clone(),
session_token.to_owned(),
),
(
self.config.contract.identity_attribute.clone(),
self.identity(),
),
])
}
pub fn generate_projects(
&self,
port: u16,
session_token: &str,
) -> Result<(Value, Value, String)> {
let bytes = fs::read(&self.config.project_path)
.with_context(|| format!("Could not read {}", self.config.project_path.display()))?;
let mut build: Value = serde_json::from_slice(&bytes).with_context(|| {
format!(
"Invalid Rojo project {}",
self.config.project_path.display()
)
})?;
rebase_project_paths(
&mut build,
self.config
.project_path
.parent()
.context("Rojo project path has no parent")?,
&self.config.state_dir,
);
let build_object = build
.as_object_mut()
.context("Rojo project root must be an object")?;
build_object.insert("name".into(), Value::String(self.project_name()));
let tree = build_object
.get_mut("tree")
.and_then(Value::as_object_mut)
.context("Rojo project must define tree")?;
let workspace = tree
.get_mut("Workspace")
.and_then(Value::as_object_mut)
.context("Rojo project must define tree.Workspace")?;
let attributes = workspace
.entry("$attributes")
.or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()
.context("tree.Workspace.$attributes must be an object")?;
for (name, value) in self.contract_attributes(port, session_token) {
attributes.insert(name, Value::String(value));
}
let mut serve = build.clone();
if self.config.serve.mode == ServeMode::SourceOverlay {
let serve_tree = serve
.get_mut("tree")
.and_then(Value::as_object_mut)
.expect("validated tree");
serve_tree.insert("$ignoreUnknownInstances".into(), Value::Bool(true));
for (service_name, children) in &self.config.serve.preserve {
let service = serve_tree
.get_mut(service_name)
.and_then(Value::as_object_mut)
.with_context(|| format!("Rojo project must define tree.{service_name}"))?;
for child in children {
service.remove(child);
}
service.insert("$ignoreUnknownInstances".into(), Value::Bool(true));
}
for service in serve_tree.values_mut() {
if let Some(service) = service.as_object_mut() {
if service.contains_key("$className") {
service
.entry("$ignoreUnknownInstances")
.or_insert(Value::Bool(true));
}
}
}
}
atomic_json(&self.paths.build_project, &build)?;
atomic_json(&self.paths.serve_project, &serve)?;
Ok((build, serve, self.project_name()))
}
pub fn expand_command(
&self,
template: &[String],
instance_id: Option<&str>,
extra_args: &[String],
) -> Result<Vec<String>> {
let values = BTreeMap::from([
("root", self.config.root.to_string_lossy().into_owned()),
(
"project",
self.config.project_path.to_string_lossy().into_owned(),
),
(
"state_dir",
self.config.state_dir.to_string_lossy().into_owned(),
),
(
"artifact",
self.paths.artifact.to_string_lossy().into_owned(),
),
("instance_id", instance_id.unwrap_or_default().to_owned()),
("mcp_url", self.mcp.base_url().to_owned()),
("worktree_id", self.identity()),
]);
let mut command = Vec::new();
let mut used_args = false;
for token in template {
if token == "{args}" {
command.extend(extra_args.iter().cloned());
used_args = true;
continue;
}
let mut expanded = token.clone();
for (name, value) in &values {
expanded = expanded.replace(&format!("{{{name}}}"), value);
}
if let Some(start) = expanded.find('{') {
if expanded[start..].contains('}') {
bail!("Unknown command placeholder in {token:?}");
}
}
command.push(expanded);
}
if !used_args {
command.extend(extra_args.iter().cloned());
}
Ok(command)
}
fn run_checked(&self, command: &[String]) -> Result<()> {
let (program, args) = command.split_first().context("Command must not be empty")?;
let status = Command::new(program)
.args(args)
.current_dir(&self.config.root)
.status()
.with_context(|| format!("Required command is not installed: {program}"))?;
if !status.success() {
bail!(
"Command failed with exit code {}: {}",
status.code().unwrap_or(-1),
command.join(" ")
);
}
Ok(())
}
pub fn build_artifact(&self, state: &mut SessionState, port: u16) -> Result<()> {
let token = Self::ensure_session_token(state);
self.generate_projects(port, &token)?;
let temporary = self.paths.artifact.with_extension("next.rbxl");
if temporary.exists() {
fs::remove_file(&temporary)
.with_context(|| format!("Could not remove {}", temporary.display()))?;
}
self.run_checked(&[
"rojo".into(),
"build".into(),
self.paths.build_project.to_string_lossy().into_owned(),
"-o".into(),
temporary.to_string_lossy().into_owned(),
])?;
replace_file(&temporary, &self.paths.artifact)?;
state.port = Some(port);
state.project_name = Some(self.project_name());
state.project_source_digest = Some(sha256(&self.config.project_path)?);
state.artifact_digest = Some(sha256(&self.paths.artifact)?);
state.artifact_built_at = Some(now());
self.save_state(state)
}
}
fn process_birth(pid: u32) -> Option<String> {
if let Ok(stat) = fs::read_to_string(format!("/proc/{pid}/stat")) {
let fields: Vec<_> = stat.split_whitespace().collect();
if let Some(start) = fields.get(21) {
return Some(format!("proc:{start}"));
}
}
#[cfg(windows)]
{
let script = format!(
"$p = Get-CimInstance Win32_Process -Filter \"ProcessId = {pid}\" -ErrorAction SilentlyContinue; \
if ($p) {{ $p.CreationDate.ToUniversalTime().ToFileTimeUtc() }}"
);
let output = Command::new("powershell.exe")
.args(["-NoProfile", "-Command", &script])
.output()
.ok()?;
let value = String::from_utf8_lossy(&output.stdout).trim().to_owned();
return (!value.is_empty()).then(|| format!("win:{value}"));
}
#[cfg(not(windows))]
{
let output = Command::new("ps")
.args(["-o", "lstart=", "-p", &pid.to_string()])
.output()
.ok()?;
let value = String::from_utf8_lossy(&output.stdout).trim().to_owned();
(!value.is_empty()).then(|| format!("ps:{value}"))
}
}
fn process_command(pid: u32) -> String {
if let Ok(bytes) = fs::read(format!("/proc/{pid}/cmdline")) {
return String::from_utf8_lossy(&bytes).replace('\0', " ");
}
#[cfg(windows)]
{
let script = format!(
"$p = Get-CimInstance Win32_Process -Filter \"ProcessId = {pid}\" -ErrorAction SilentlyContinue; \
if ($p) {{ $p.CommandLine }}"
);
return Command::new("powershell.exe")
.args(["-NoProfile", "-Command", &script])
.output()
.ok()
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
.unwrap_or_default();
}
#[cfg(not(windows))]
{
Command::new("ps")
.args(["-o", "command=", "-p", &pid.to_string()])
.output()
.ok()
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
.unwrap_or_default()
}
}
impl StudioSession {
fn owns_rojo_process(&self, state: &SessionState) -> bool {
let Some(pid) = state.rojo_pid else {
return false;
};
let birth = state
.rojo_birth
.clone()
.or_else(|| state.rojo_start_ticks.map(|ticks| format!("proc:{ticks}")));
let Some(birth) = birth else {
return false;
};
if process_birth(pid).as_deref() != Some(&birth) {
return false;
}
let command = process_command(pid);
command.contains("rojo")
&& command.contains("serve")
&& command.contains(&self.paths.serve_project.to_string_lossy().to_string())
}
fn wait_for_port(&self, port: u16, child: &mut std::process::Child) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(15);
while Instant::now() < deadline {
if let Some(status) = child.try_wait().context("Could not poll Rojo process")? {
bail!(
"Rojo server exited with {}; see {}",
status.code().unwrap_or(-1),
self.paths.rojo_log.display()
);
}
if TcpStream::connect_timeout(
&(std::net::Ipv4Addr::LOCALHOST, port).into(),
Duration::from_millis(200),
)
.is_ok()
{
return Ok(());
}
thread::sleep(Duration::from_millis(100));
}
bail!(
"Rojo server did not listen on port {port}; see {}",
self.paths.rojo_log.display()
)
}
fn start_rojo(&self, state: &mut SessionState) -> Result<()> {
if self.owns_rojo_process(state) {
return Ok(());
}
let port = match state.port {
Some(port) if is_port_free(port) => {
let token = Self::ensure_session_token(state);
self.generate_projects(port, &token)?;
state.project_name = Some(self.project_name());
port
}
_ => {
let port = choose_port(&self.identity(), &BTreeSet::new())?;
self.build_artifact(state, port)?;
port
}
};
fs::create_dir_all(&self.config.state_dir)
.with_context(|| format!("Could not create {}", self.config.state_dir.display()))?;
let log = OpenOptions::new()
.create(true)
.append(true)
.open(&self.paths.rojo_log)
.with_context(|| format!("Could not open {}", self.paths.rojo_log.display()))?;
let error_log = log.try_clone().context("Could not clone Rojo log handle")?;
let mut command = Command::new("rojo");
command
.args([
"serve",
&self.paths.serve_project.to_string_lossy(),
"--port",
&port.to_string(),
"--color",
"never",
])
.current_dir(&self.config.root)
.stdin(Stdio::null())
.stdout(Stdio::from(log))
.stderr(Stdio::from(error_log));
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0000_0200);
}
let mut child = command
.spawn()
.context("Required command is not installed: rojo")?;
self.wait_for_port(port, &mut child)?;
state.rojo_pid = Some(child.id());
state.rojo_birth = process_birth(child.id());
state.rojo_start_ticks = None;
state.rojo_started_at = Some(now());
self.save_state(state)
}
fn stop_rojo(&self, state: &mut SessionState) {
if !self.owns_rojo_process(state) {
state.rojo_pid = None;
state.rojo_birth = None;
state.rojo_start_ticks = None;
return;
}
let pid = state.rojo_pid.expect("owned process has pid");
#[cfg(unix)]
{
unsafe {
libc::kill(-(pid as i32), libc::SIGTERM);
}
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline && process_birth(pid).is_some() {
thread::sleep(Duration::from_millis(100));
}
if process_birth(pid).is_some() && self.owns_rojo_process(state) {
unsafe {
libc::kill(-(pid as i32), libc::SIGKILL);
}
}
}
#[cfg(windows)]
{
let _ = Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/T", "/F"])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
state.rojo_pid = None;
state.rojo_birth = None;
state.rojo_start_ticks = None;
state.rojo_started_at = None;
}
}
#[derive(Clone, Debug, Deserialize)]
struct WindowsStudioProcess {
pid: u32,
started: u64,
title: String,
}
impl StudioSession {
fn studio_status(&self, instance_id: &str) -> Option<Value> {
self.mcp.manage_status(instance_id).ok()
}
fn rojo_marker(&self, instance_id: &str) -> Option<String> {
let marker = serde_json::to_string(&self.config.contract.connection_marker).ok()?;
let code = format!(
"local marker = game:GetService(\"ServerStorage\"):FindFirstChild({marker})\n\
return if marker and marker:IsA(\"StringValue\") then marker.Value else \"\""
);
self.mcp
.tool(
"execute_luau",
json!({"instance_id": instance_id, "target": "edit", "code": code}),
Duration::from_secs(30),
)
.ok()?
.get("returnValue")?
.as_str()
.filter(|value| !value.is_empty())
.map(str::to_owned)
}
fn nudge_rojo_autoconnect(&self, instance_id: &str, state: &mut SessionState) -> Result<()> {
let port = state.port.context("Session is missing Rojo port")?;
let token = Self::ensure_session_token(state);
let endpoint_name = serde_json::to_string(&self.config.contract.endpoint_attribute)?;
self.mcp.tool(
"execute_luau",
json!({
"instance_id": instance_id,
"target": "edit",
"code": format!("workspace:SetAttribute({endpoint_name}, nil)"),
}),
Duration::from_secs(60),
)?;
let mut lines = Vec::new();
for (name, value) in self.contract_attributes(port, &token) {
lines.push(format!(
"workspace:SetAttribute({}, {})",
serde_json::to_string(&name)?,
serde_json::to_string(&value)?
));
}
self.mcp.tool(
"execute_luau",
json!({
"instance_id": instance_id,
"target": "edit",
"code": lines.join("\n"),
}),
Duration::from_secs(60),
)?;
Ok(())
}
fn studio_contract(&self, instance_id: &str) -> Option<Value> {
let names = &self.config.contract;
let code = format!(
"local HttpService = game:GetService(\"HttpService\")\n\
return HttpService:JSONEncode({{\n\
endpoint = workspace:GetAttribute({}),\n\
project = workspace:GetAttribute({}),\n\
session = workspace:GetAttribute({}),\n\
worktree = workspace:GetAttribute({}),\n\
}})",
serde_json::to_string(&names.endpoint_attribute).ok()?,
serde_json::to_string(&names.project_attribute).ok()?,
serde_json::to_string(&names.session_attribute).ok()?,
serde_json::to_string(&names.identity_attribute).ok()?,
);
let result = self
.mcp
.tool(
"execute_luau",
json!({"instance_id": instance_id, "target": "edit", "code": code}),
Duration::from_secs(10),
)
.ok()?;
serde_json::from_str(result.get("returnValue")?.as_str()?).ok()
}
fn expected_studio_contract(&self, state: &mut SessionState) -> Result<Value> {
Ok(json!({
"endpoint": format!("http://127.0.0.1:{}", state.port.context("Session is missing Rojo port")?),
"project": self.project_name(),
"session": Self::ensure_session_token(state),
"worktree": self.identity(),
}))
}
fn windows_studio_processes(&self) -> Vec<WindowsStudioProcess> {
let script = "Get-Process RobloxStudioBeta -ErrorAction SilentlyContinue | \
ForEach-Object { [PSCustomObject]@{ pid = $_.Id; started = $_.StartTime.ToFileTimeUtc(); \
title = $_.MainWindowTitle } } | ConvertTo-Json -Compress";
let output = match Command::new("powershell.exe")
.args(["-NoProfile", "-Command", script])
.output()
{
Ok(output) if output.status.success() => output.stdout,
_ => return Vec::new(),
};
let value: Value = match serde_json::from_slice(&output) {
Ok(value) => value,
Err(_) => return Vec::new(),
};
if value.is_array() {
serde_json::from_value(value).unwrap_or_default()
} else if value.is_object() {
serde_json::from_value(value)
.map(|entry| vec![entry])
.unwrap_or_default()
} else {
Vec::new()
}
}
fn windows_artifact_path(&self) -> Option<String> {
if Path::new("/mnt/c").is_dir() {
let output = Command::new("wslpath")
.args(["-w", &self.paths.artifact.to_string_lossy()])
.output()
.ok()?;
let value = String::from_utf8_lossy(&output.stdout).trim().to_owned();
return (!value.is_empty()).then_some(value);
}
#[cfg(windows)]
{
Some(self.paths.artifact.to_string_lossy().into_owned())
}
#[cfg(not(windows))]
{
None
}
}
fn record_owned_studio_process(
&self,
state: &mut SessionState,
before_pids: Option<&BTreeSet<u32>>,
) -> bool {
let Some(artifact) = self.windows_artifact_path() else {
return false;
};
let artifact = artifact.to_lowercase();
let matches: Vec<_> = self
.windows_studio_processes()
.into_iter()
.filter(|entry| {
!before_pids.is_some_and(|pids| pids.contains(&entry.pid))
&& entry.title.to_lowercase().contains(&artifact)
})
.collect();
if matches.len() != 1 {
return false;
}
state.studio_process_pid = Some(matches[0].pid);
state.studio_process_started = Some(matches[0].started);
true
}
fn owns_windows_studio_process(&self, state: &SessionState) -> bool {
let (Some(pid), Some(started)) = (state.studio_process_pid, state.studio_process_started)
else {
return false;
};
self.windows_studio_processes()
.iter()
.any(|entry| entry.pid == pid && entry.started == started)
}
fn stop_owned_windows_studio_process(&self, state: &mut SessionState) -> bool {
if !self.owns_windows_studio_process(state)
&& !self.record_owned_studio_process(state, None)
{
return false;
}
let pid = state
.studio_process_pid
.expect("owned Studio process has pid");
let status = Command::new("powershell.exe")
.args([
"-NoProfile",
"-Command",
&format!("Stop-Process -Id {pid} -ErrorAction Stop"),
])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
if !status.is_ok_and(|status| status.success()) {
return false;
}
state.studio_process_pid = None;
state.studio_process_started = None;
true
}
fn wait_for_launched_studio(&self, state: &mut SessionState) -> Result<String> {
let expected = self.expected_studio_contract(state)?;
let deadline = Instant::now() + Duration::from_secs(120);
while Instant::now() < deadline {
let listing = self.mcp.tool(
"get_connected_instances",
json!({}),
Duration::from_secs(10),
)?;
let mut matches = Vec::new();
if let Some(instances) = listing.get("instances").and_then(Value::as_array) {
for candidate in instances {
if candidate.get("role").and_then(Value::as_str) != Some("edit") {
continue;
}
let project_matches = ["dataModelName", "placeName"].iter().any(|field| {
candidate.get(field).and_then(Value::as_str) == Some(&self.project_name())
});
if !project_matches {
continue;
}
let Some(instance_id) = candidate.get("instanceId").and_then(Value::as_str)
else {
continue;
};
if self.studio_contract(instance_id).as_ref() == Some(&expected) {
matches.push(instance_id.to_owned());
}
}
}
match matches.len() {
1 => return Ok(matches.remove(0)),
2.. => bail!(
"More than one Studio process presented this session's exact worktree token; close the duplicates manually"
),
_ => thread::sleep(Duration::from_millis(500)),
}
}
bail!(
"Studio launched but did not present this worktree's exact source contract before timeout"
)
}
fn wait_for_rojo_connection(
&self,
instance_id: &str,
expected: &str,
timeout: Duration,
) -> Result<()> {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if self.rojo_marker(instance_id).as_deref() == Some(expected) {
return Ok(());
}
thread::sleep(Duration::from_millis(500));
}
bail!(
"Studio did not auto-connect to {expected}. Run robloxstudio-worktree bootstrap, restart Studio, and inspect {}.",
self.paths.rojo_log.display()
)
}
fn run_validation_hook(&self, instance_id: &str) -> Result<()> {
let Some(template) = &self.config.hooks.validate else {
return Ok(());
};
let command = self.expand_command(template, Some(instance_id), &[])?;
let (program, args) = command.split_first().context("Validation hook is empty")?;
let output = Command::new(program)
.args(args)
.current_dir(&self.config.root)
.output()
.with_context(|| format!("Could not run project validation hook: {program}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_owned();
let detail = if !stderr.is_empty() {
stderr
} else if !stdout.is_empty() {
stdout
} else {
format!("exit code {}", output.status.code().unwrap_or(-1))
};
bail!("Project validation hook failed: {detail}");
}
Ok(())
}
}
impl StudioSession {
pub fn ensure_up(&self, fresh: bool) -> Result<SessionState> {
let mut state = self.load_state()?;
if let Some(owner) = &state.worktree_id {
if owner != &self.identity() {
bail!("Session state belongs to a different worktree: {owner}");
}
}
if fresh {
self.down_state(&mut state)?;
state = self.load_state()?;
state.session_token = Some(Uuid::new_v4().simple().to_string());
}
if let Some(instance_id) = state.instance_id.clone() {
let status = self.studio_status(&instance_id);
let is_edit = status
.as_ref()
.and_then(|value| value.get("roles"))
.and_then(Value::as_array)
.is_some_and(|roles| roles.iter().any(|role| role.as_str() == Some("edit")));
if is_edit {
let port = match state.port {
Some(port) => port,
None => choose_port(&self.identity(), &BTreeSet::new())?,
};
let token = Self::ensure_session_token(&mut state);
self.generate_projects(port, &token)?;
state.port = Some(port);
state.project_name = Some(self.project_name());
self.start_rojo(&mut state)?;
if self.rojo_marker(&instance_id).as_deref() != Some(&self.project_name()) {
self.nudge_rojo_autoconnect(&instance_id, &mut state)?;
self.wait_for_rojo_connection(
&instance_id,
&self.project_name(),
Duration::from_secs(30),
)?;
}
self.run_validation_hook(&instance_id)?;
if !self.owns_windows_studio_process(&state) {
self.record_owned_studio_process(&mut state, None);
}
state.validated_at = Some(now());
self.save_state(&mut state)?;
return Ok(state);
}
state.instance_id = None;
}
let port = match state.port {
Some(port) if self.owns_rojo_process(&state) || is_port_free(port) => port,
_ => choose_port(&self.identity(), &BTreeSet::new())?,
};
self.build_artifact(&mut state, port)?;
self.start_rojo(&mut state)?;
let before_pids: BTreeSet<u32> = self
.windows_studio_processes()
.into_iter()
.map(|entry| entry.pid)
.collect();
self.mcp.tool(
"manage_instance",
json!({
"action": "launch",
"source": "local_file",
"local_place_file": self.paths.artifact.to_string_lossy(),
"wait_for_connection": false,
"timeout_ms": 120000,
}),
Duration::from_secs(30),
)?;
let instance_id = self.wait_for_launched_studio(&mut state)?;
self.record_owned_studio_process(&mut state, Some(&before_pids));
state.instance_id = Some(instance_id.clone());
state.studio_started_at = Some(now());
self.save_state(&mut state)?;
self.wait_for_rojo_connection(&instance_id, &self.project_name(), Duration::from_secs(45))?;
self.run_validation_hook(&instance_id)?;
state.validated_at = Some(now());
self.save_state(&mut state)?;
Ok(state)
}
fn down_state(&self, state: &mut SessionState) -> Result<()> {
if let Some(instance_id) = state.instance_id.clone() {
let _ = self.mcp.tool(
"solo_playtest",
json!({"action": "stop", "instance_id": instance_id, "timeout": 30}),
Duration::from_secs(60),
);
let mut closed = false;
if self.owns_windows_studio_process(state) {
let expected = self.expected_studio_contract(state)?;
if self.studio_contract(&instance_id).as_ref() != Some(&expected) {
bail!(
"Refusing native Studio teardown: Studio no longer presents this session contract"
);
}
if !self.stop_owned_windows_studio_process(state) {
bail!("Could not stop this session's exact recorded Studio process");
}
closed = true;
}
if !closed {
let close = self.mcp.tool(
"manage_instance",
json!({"action": "close", "instance_id": instance_id}),
Duration::from_secs(45),
);
if let Err(close_error) = close {
if self.studio_status(&instance_id).is_some() {
let expected = self.expected_studio_contract(state)?;
if self.studio_contract(&instance_id).as_ref() != Some(&expected) {
bail!(
"Refusing process fallback: Studio no longer presents this session contract"
);
}
if !self.stop_owned_windows_studio_process(state) {
return Err(close_error);
}
}
}
}
state.instance_id = None;
state.studio_started_at = None;
state.studio_process_pid = None;
state.studio_process_started = None;
}
self.stop_rojo(state);
self.save_state(state)
}
pub fn down(&self) -> Result<SessionState> {
let mut state = self.load_state()?;
self.down_state(&mut state)?;
Ok(state)
}
pub fn status(&self) -> Result<Value> {
let state = self.load_state()?;
let studio = state
.instance_id
.as_deref()
.and_then(|instance_id| self.studio_status(instance_id));
Ok(json!({
"worktree_id": self.identity(),
"worktree_root": self.config.root.to_string_lossy(),
"project_name": state.project_name,
"rojo_port": state.port,
"rojo_running": self.owns_rojo_process(&state),
"studio_instance_id": state.instance_id,
"studio_connected": studio.is_some(),
"studio_roles": studio.as_ref().and_then(|value| value.get("roles")).cloned().unwrap_or_else(|| json!([])),
"rojo_connected_project": match (studio.is_some(), state.instance_id.as_deref()) {
(true, Some(instance_id)) => self.rojo_marker(instance_id),
_ => None,
},
"artifact": self.paths.artifact.exists().then(|| self.paths.artifact.to_string_lossy().into_owned()),
"artifact_digest": state.artifact_digest,
}))
}
pub fn build(&self) -> Result<SessionState> {
let mut state = self.load_state()?;
if state.instance_id.is_some() {
bail!("Studio is active; use robloxstudio-worktree up --fresh to rebuild safely");
}
let port = match state.port {
Some(port) if self.owns_rojo_process(&state) || is_port_free(port) => port,
_ => choose_port(&self.identity(), &BTreeSet::new())?,
};
self.build_artifact(&mut state, port)?;
Ok(state)
}
pub fn run_test_hook(&self, state: &SessionState, extra_args: &[String]) -> Result<i32> {
let template = self
.config
.hooks
.test
.as_ref()
.context("This project does not define hooks.test in robloxstudio-worktree.json")?;
let instance_id = state
.instance_id
.as_deref()
.context("Session is missing Studio instance ID")?;
let command = self.expand_command(template, Some(instance_id), extra_args)?;
let (program, args) = command.split_first().context("Test hook is empty")?;
let status = Command::new(program)
.args(args)
.current_dir(&self.config.root)
.status()
.with_context(|| format!("Could not run project test hook: {program}"))?;
Ok(status.code().unwrap_or(1))
}
pub fn remove_generated_state(&self) -> Result<()> {
match fs::remove_dir_all(&self.config.state_dir) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error)
.with_context(|| format!("Could not remove {}", self.config.state_dir.display())),
}
}
pub fn bootstrap(&self) -> Result<()> {
for template in &self.config.bootstrap.commands {
let command = self.expand_command(template, None, &[])?;
println!("+ {}", command.join(" "));
self.run_checked(&command)?;
}
let mut missing = Vec::new();
for pattern in &self.config.bootstrap.required_globs {
let absolute = self
.config
.root
.join(pattern)
.to_string_lossy()
.into_owned();
let found = glob::glob(&absolute)
.with_context(|| format!("Invalid bootstrap glob: {pattern}"))?
.any(|entry| entry.is_ok());
if !found {
missing.push(pattern.clone());
}
}
if !missing.is_empty() {
bail!(
"Bootstrap did not produce required paths: {}",
missing.join(", ")
);
}
if let Some(plugin) = &self.config.bootstrap.plugin {
let bytes = if plugin == "bundled" {
self.config.bundled_plugin_bytes().to_vec()
} else {
let path = self.config.root.join(plugin);
fs::read(&path).with_context(|| {
format!("Managed Rojo plugin is missing: {}", path.display())
})?
};
self.install_rojo_plugin(&bytes)?;
}
Ok(())
}
fn studio_plugin_dir(&self) -> Result<PathBuf> {
#[cfg(windows)]
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
return Ok(PathBuf::from(local).join("Roblox/Plugins"));
}
let is_wsl = fs::read_to_string("/proc/sys/kernel/osrelease")
.is_ok_and(|release| release.to_lowercase().contains("microsoft"));
if is_wsl {
let windows = Command::new("cmd.exe")
.args(["/d", "/c", "echo", "%LOCALAPPDATA%"])
.output()
.context("Could not locate Windows LOCALAPPDATA from WSL")?;
let windows = String::from_utf8_lossy(&windows.stdout).trim().to_owned();
let wsl = Command::new("wslpath")
.args(["-u", &windows])
.output()
.context("Could not convert Windows LOCALAPPDATA for WSL")?;
let wsl = String::from_utf8_lossy(&wsl.stdout).trim().to_owned();
return Ok(PathBuf::from(wsl).join("Roblox/Plugins"));
}
#[cfg(target_os = "macos")]
if let Some(home) = std::env::var_os("HOME") {
return Ok(PathBuf::from(home).join("Documents/Roblox/Plugins"));
}
bail!("Managed Rojo plugin installation supports Windows, WSL, and macOS")
}
fn install_rojo_plugin(&self, bytes: &[u8]) -> Result<()> {
let plugin_dir = self.studio_plugin_dir()?;
fs::create_dir_all(&plugin_dir)
.with_context(|| format!("Could not create {}", plugin_dir.display()))?;
let target = plugin_dir.join("Rojo.rbxm");
let backup = plugin_dir.join("Rojo.upstream.rbxm.disabled");
let source_hash = format!("{:x}", Sha256::digest(bytes));
if target.is_file() && sha256(&target).ok().as_deref() == Some(&source_hash) {
println!(
"Managed Rojo plugin already installed: {}",
target.display()
);
return Ok(());
}
if target.is_file() && !backup.exists() {
fs::copy(&target, &backup).with_context(|| {
format!(
"Could not back up {} to {}",
target.display(),
backup.display()
)
})?;
println!("Backed up the previous Rojo plugin to {}", backup.display());
}
let temporary = plugin_dir.join("Rojo.rbxm.next");
let mut file = File::create(&temporary)
.with_context(|| format!("Could not create {}", temporary.display()))?;
file.write_all(bytes)
.with_context(|| format!("Could not write {}", temporary.display()))?;
file.sync_all().ok();
replace_file(&temporary, &target)?;
println!(
"Installed managed Rojo plugin: {} ({})",
target.display(),
&source_hash[..12]
);
Ok(())
}
}