Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/panic_budget.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"crates/jcode-provider-anthropic/src/wedge_fixture_check.rs": 3,
"crates/jcode-provider-core/src/model_names.rs": 1,
"crates/jcode-provider-cursor-runtime/src/wire.rs": 1,
"crates/jcode-provider-doctor/src/lifecycle_driver.rs": 2,
"crates/jcode-provider-doctor/src/lifecycle_contracts.rs": 2,
"crates/jcode-provider-openai/src/stream.rs": 3,
"crates/jcode-render-core/src/math.rs": 4,
"crates/jcode-render-core/src/preprocess.rs": 2,
Expand Down
24 changes: 5 additions & 19 deletions src/cli/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ use clap::{Parser, Subcommand, ValueEnum};

use super::provider_init::ProviderChoice;

mod cloud_view;
mod google;
mod provider_auth;
mod session;
#[allow(unused_imports)]
pub(crate) use google::{GoogleAccessTierArg, GoogleLoginArgs};
pub(crate) use cloud_view::CloudSessionViewFormat;
pub(crate) use google::GoogleLoginArgs;
pub(crate) use provider_auth::ProviderAuthArg;
pub(crate) use session::SessionCommand;

Expand Down Expand Up @@ -1010,30 +1011,15 @@ pub(crate) struct JadeCloudOptions {
pub(crate) helper: Option<String>,
}

#[derive(ValueEnum, Debug, Clone, Copy)]
pub(crate) enum CloudSessionViewFormat {
Summary,
Json,
Html,
}

impl CloudSessionViewFormat {
pub(crate) fn as_arg(self) -> &'static str {
match self {
Self::Summary => "summary",
Self::Json => "json",
Self::Html => "html",
}
}
}

#[derive(Subcommand, Debug)]
pub(crate) enum RestartCommand {
/// Save a reboot snapshot of currently active jcode windows
Save {
/// Restore this reboot snapshot automatically the next time plain `jcode` starts
#[arg(long)]
auto_restore: bool,
#[arg(long, help = "Replace an armed auto-restore snapshot")]
replace_armed: bool,
},
/// Restore the most recently saved reboot snapshot
Restore,
Expand Down
20 changes: 20 additions & 0 deletions src/cli/args/cloud_view.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//! Cloud session view format shared by `jcode cloud sessions view`.

use clap::ValueEnum;

#[derive(ValueEnum, Debug, Clone, Copy)]
pub(crate) enum CloudSessionViewFormat {
Summary,
Json,
Html,
}

impl CloudSessionViewFormat {
pub(crate) fn as_arg(self) -> &'static str {
match self {
Self::Summary => "summary",
Self::Json => "json",
Self::Html => "html",
}
}
}
30 changes: 26 additions & 4 deletions src/cli/args/tests.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::google::GoogleAccessTierArg;
use super::*;
use crate::cli::provider_init::ProviderChoice;

Expand Down Expand Up @@ -930,9 +931,11 @@ fn restart_save_subcommand_parses() {
let args = Args::try_parse_from(["jcode", "restart", "save"]).unwrap();
match args.command {
Some(Command::Restart {
action: RestartCommand::Save {
auto_restore: false,
},
action:
RestartCommand::Save {
auto_restore: false,
replace_armed: false,
},
}) => {}
other => panic!("unexpected command: {:?}", other),
}
Expand All @@ -943,7 +946,26 @@ fn restart_save_auto_restore_flag_parses() {
let args = Args::try_parse_from(["jcode", "restart", "save", "--auto-restore"]).unwrap();
match args.command {
Some(Command::Restart {
action: RestartCommand::Save { auto_restore: true },
action:
RestartCommand::Save {
auto_restore: true,
replace_armed: false,
},
}) => {}
other => panic!("unexpected command: {:?}", other),
}
}

#[test]
fn restart_save_replace_armed_flag_parses() {
let args = Args::try_parse_from(["jcode", "restart", "save", "--replace-armed"]).unwrap();
match args.command {
Some(Command::Restart {
action:
RestartCommand::Save {
auto_restore: false,
replace_armed: true,
},
}) => {}
other => panic!("unexpected command: {:?}", other),
}
Expand Down
2 changes: 1 addition & 1 deletion src/cli/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use super::{output::terminal_title, terminal::init_tui_runtime};
mod menubar;
mod provider_setup;
mod report_info;
mod restart;
pub(crate) mod restart;

pub(crate) use super::auth_test::run_post_login_validation;
#[cfg(test)]
Expand Down
128 changes: 112 additions & 16 deletions src/cli/commands/restart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,147 @@ use anyhow::Result;
use chrono::Utc;
use serde::Deserialize;
use std::io::IsTerminal;
use std::path::PathBuf;
use std::path::{Path, PathBuf};

use crate::cli::args::RestartCommand;

/// Dispatch a `jcode restart` subcommand. Kept next to the commands it selects so
/// the CLI entry point stays a single line per top-level command.
pub(crate) async fn run_restart_command(action: RestartCommand) -> Result<()> {
match action {
RestartCommand::Save {
auto_restore,
replace_armed,
} => run_restart_save_command(auto_restore, replace_armed).await?,
RestartCommand::Restore => run_restart_restore_command()?,
RestartCommand::Status => run_restart_status_command()?,
RestartCommand::Clear => run_restart_clear_command()?,
}
Ok(())
}

pub async fn run_restart_save_command(auto_restore: bool, replace_armed: bool) -> Result<()> {
run_restart_save_command_with_writer(auto_restore, replace_armed, &mut std::io::stdout()).await
}

async fn run_restart_save_command_with_writer<W: std::io::Write>(
auto_restore: bool,
replace_armed: bool,
output: &mut W,
) -> Result<()> {
let path = crate::restart_snapshot::snapshot_path()?;
let existing = existing_snapshot_for_save(&path)?;
if !replace_armed {
// The restore-side claim that serializes competing restores belongs to #389.
if let Some(snapshot) = existing
.as_ref()
.filter(|snapshot| snapshot.auto_restore_on_next_start)
{
anyhow::bail!(
"Refusing to overwrite armed reboot snapshot at {}: created {}, {} session(s), auto-restore armed. Run `jcode restart restore` to consume it, or use `jcode restart save --replace-armed` to replace it.",
path.display(),
snapshot.created_at,
snapshot.sessions.len()
);
}
}

pub async fn run_restart_save_command(auto_restore: bool) -> Result<()> {
let mut snapshot = if let Some(snapshot) = capture_connected_restart_snapshot().await? {
snapshot
} else {
crate::restart_snapshot::save_current_snapshot()?
crate::restart_snapshot::capture_current_snapshot()?
};
snapshot.auto_restore_on_next_start = auto_restore;
snapshot.auto_restore_on_next_start = auto_restore && !snapshot.sessions.is_empty();
crate::restart_snapshot::write_snapshot(&snapshot)?;
let path = crate::restart_snapshot::snapshot_path()?;

if snapshot.sessions.is_empty() {
println!("Saved empty reboot snapshot to {}", path.display());
writeln!(output, "Saved empty reboot snapshot to {}", path.display())?;
if auto_restore {
println!("Automatic restore is armed for the next plain `jcode` launch.");
writeln!(
output,
"Automatic restore was not armed because no sessions were captured."
)?;
}
println!("\nNo active jcode windows were detected.");
writeln!(output, "\nNo active jcode windows were detected.")?;
return Ok(());
}

println!(
"Saved reboot snapshot with {} session(s) to {}\n",
writeln!(
output,
"Saved reboot snapshot with {} session(s) to {}{}\n",
snapshot.sessions.len(),
path.display()
);
path.display(),
if let Some(existing) = &existing {
format!(
" (replaced unarmed snapshot created {} with {} session(s))",
existing.created_at,
existing.sessions.len()
)
} else {
String::new()
}
)?;
for session in &snapshot.sessions {
let suffix = if session.is_selfdev {
" [self-dev]"
} else {
""
};
println!(
writeln!(
output,
"- {} ({}){}",
session.display_name, session.session_id, suffix
);
)?;
}
if auto_restore {
println!("\nAutomatic restore is armed for the next plain `jcode` launch.");
writeln!(
output,
"\nAutomatic restore is armed for the next plain `jcode` launch."
)?;
}
println!("\nAfter reboot, restore them with:\n jcode restart restore");
writeln!(
output,
"\nAfter reboot, restore them with:\n jcode restart restore"
)?;

Ok(())
}

fn existing_snapshot_for_save(
path: &Path,
) -> Result<Option<crate::restart_snapshot::RestartSnapshot>> {
match crate::restart_snapshot::load_snapshot() {
Ok(snapshot) => Ok(Some(snapshot)),
Err(error) => {
let missing =
path.try_exists().map_err(|error| {
anyhow::anyhow!(
"Failed to inspect reboot snapshot at {}: {}",
path.display(),
error
)
})? || matches!(nested_io_error(&error), Some(std::io::ErrorKind::NotFound));
if missing {
Ok(None)
} else {
Err(anyhow::anyhow!(
"Failed to read existing reboot snapshot at {}: {}",
path.display(),
error
))
}
}
}
}

fn nested_io_error(error: &anyhow::Error) -> Option<std::io::ErrorKind> {
error.chain().find_map(|cause| {
cause
.downcast_ref::<std::io::Error>()
.map(|error| error.kind())
})
}

pub fn run_restart_status_command() -> Result<()> {
let path = crate::restart_snapshot::snapshot_path()?;
let snapshot = match crate::restart_snapshot::load_snapshot() {
Expand Down
Loading
Loading