Skip to content
Closed
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
3 changes: 3 additions & 0 deletions src/cli/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1034,6 +1034,9 @@ pub(crate) enum RestartCommand {
/// Restore this reboot snapshot automatically the next time plain `jcode` starts
#[arg(long)]
auto_restore: bool,
/// Replace an existing auto-restore snapshot that is already armed
#[arg(long)]
replace_armed: bool,
},
/// Restore the most recently saved reboot snapshot
Restore,
Expand Down
29 changes: 25 additions & 4 deletions src/cli/args/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -930,9 +930,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 +945,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
111 changes: 95 additions & 16 deletions src/cli/commands/restart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,130 @@ use anyhow::Result;
use chrono::Utc;
use serde::Deserialize;
use std::io::IsTerminal;
use std::path::PathBuf;
use std::path::{Path, PathBuf};

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 existing
.as_ref()
.is_some_and(|snapshot| snapshot.auto_restore_on_next_start)
&& !replace_armed
{
// The restore-side claim that serializes competing restores belongs to #389.
let snapshot = existing.as_ref().expect("armed snapshot present");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Redundant expect after is_some_and guard.

existing.as_ref().expect("armed snapshot present") is unreachable-as-None because the enclosing if already proved existing is Some and armed. It is safe, but the double-handling is easy to misread. Consider if let Some(snapshot) = existing.as_ref().filter(|s| s.auto_restore_on_next_start) { ... } to make the invariant structural.

@Kilo fix this

Fix these issues in Kilo Cloud

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();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: --auto-restore is silently ignored when no sessions are captured.

auto_restore && !snapshot.sessions.is_empty() forces the flag off for empty captures. The user does get a message (lines 43-48), but the requested --auto-restore intent is dropped with no way to override. This is intentional per the PR description, but consider whether an explicit warning/exit code would be clearer for scripted callers who pass --auto-restore expecting it to be honored.

@Kilo fix this

Fix these issues in Kilo Cloud

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(());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: The replaced-snapshot report is skipped on the empty-capture early return.

When --replace-armed is used but zero sessions are captured, this early return fires before the "replaced ... snapshot" message (lines 53-67). The PR description says --replace-armed "reports the replaced snapshot's creation time and session count in the output", but that report is silently omitted in the empty case. Consider emitting the replaced-snapshot detail here too when existing is Some.

@Kilo fix this

Fix these issues in Kilo Cloud

}

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))",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Misleading message: the replaced snapshot is always described as "unarmed".

This branch is reached when an unarmed snapshot was replaced without --replace-armed, but also when an armed snapshot was replaced with --replace-armed. In the latter case the message still says "replaced unarmed snapshot", which contradicts the PR's stated behavior of reporting the replaced snapshot's details accurately. Branch on existing.auto_restore_on_next_start to say "armed" vs "unarmed".

Suggested change
" (replaced unarmed snapshot created {} with {} session(s))",
" (replaced {} snapshot created {} with {} session(s))",
if existing.auto_restore_on_next_start { "armed" } else { "unarmed" },
existing.created_at,
existing.sessions.len()

@Kilo fix this

Fix these issues in Kilo Cloud

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));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Corrupt/unreadable existing snapshot is silently treated as "missing".

existing_snapshot_for_save returns Ok(None) when the file does not exist OR when load_snapshot failed with a NotFound io error. But read_json (jcode-storage) wraps parse failures and backup-recovery failures in anyhow without a NotFound io cause, so a corrupt snapshot yields Err here and aborts the save — which is the safe choice. However, a file that disappears between load_snapshot and try_exists is also treated as missing, which is fine. The subtle risk: if read_json ever changes to wrap io errors differently, the NotFound detection via nested_io_error could misfire and either (a) abort on a genuinely missing file or (b) treat a real read error as missing and overwrite. Consider matching on the snapshot path's existence first and only then loading, to make the missing-vs-corrupt decision explicit and robust to error-type changes.

@Kilo fix this

Fix these issues in Kilo Cloud

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