Play your Steam library's Windows games on a jailbroken PS5.
C++
Delete leftover PS5 titles from Storage
Leonardo Lobatocb4d357e6f24
diff --git a/README.md b/README.mdindex 68821ea..3db9ae8 100644--- a/README.md+++ b/README.md@@ -311,6 +311,9 @@ build/homebrew-host/playden-homebrew --simulation --scenario signed-out## Known issues+- Uninstall games from Playden. Title folders belong to Playden; FTP and file managers can't delete them.+ Leftover titles appear in Settings › Storage. Deleting a leftover removes its title folder and Home tile;+ its game files and saves stay on disk because Playden no longer has a record linking them to the title.- New games can stay at *Waiting for the PS5* after you quit Playden when ShadowMountPlus stops registering titles.Reload ShadowMountPlus.Until the game is registered, its Cloud saves are not synced before its first launch.diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 443b0c0..c0a8326 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -847,6 +847,15 @@ void Controller::TickRuntime() {if (model_.TakeRuntimeCleanupRequest()) runtime_->CleanUpRequests();for (const auto& id : model_.TakeKeptDeleteRequests())WithApp(id, [this](std::uint32_t app) { runtime_->DeleteKeptBottle(app); });+ for (const auto& id : model_.TakeLeftoverDeleteRequests()) {+ std::string error;+ if (!runtime_->DeleteLeftoverTitle(id, &error)) {+ auto deletions = leftover_deletions_projected_;+ std::erase_if(deletions, [&](const LiveLeftoverDelete& deletion) { return deletion.title_id == id; });+ deletions.push_back({id, leftover_names_[id], "", error.empty() ? "The title could not be queued for deletion." : error});+ model_.UpdateLeftoverDeletions(std::move(deletions));+ }+ }for (const auto& id : model_.TakeActivityRequests())WithApp(id, [this](std::uint32_t app) { runtime_->CheckActivity(app); });for (const auto id : model_.TakeProgramScanRequests())@@ -889,6 +898,28 @@ void Controller::TickRuntime() {std::vector<LiveKeptBottle> kept;for (const auto& bottle : current.kept_bottles) kept.push_back({bottle.game, bottle.name, bottle.kept_at, bottle.bytes});if (kept != kept_projected_) { kept_projected_ = kept; model_.UpdateKeptBottles(std::move(kept)); }+ std::vector<LiveLeftoverTitle> leftovers;+ for (const auto& title : current.leftover_titles) {+ leftovers.push_back({title.title_id, title.name, title.bytes});+ leftover_names_[title.title_id] = title.name;+ }+ if (leftovers != leftovers_projected_) {+ leftovers_projected_ = leftovers;+ model_.UpdateLeftoverTitles(std::move(leftovers));+ }+ std::vector<LiveLeftoverDelete> deletions;+ if (current.deleting_leftover_title) {+ const auto& id = *current.deleting_leftover_title;+ deletions.push_back({id, leftover_names_[id], current.deleting_leftover_step, ""});+ }+ for (const auto& id : current.queued_leftover_deletes)+ if (current.deleting_leftover_title != id) deletions.push_back({id, leftover_names_[id], "", ""});+ for (const auto& [id, error] : current.leftover_delete_failures)+ deletions.push_back({id, leftover_names_[id], "", error});+ if (deletions != leftover_deletions_projected_) {+ leftover_deletions_projected_ = deletions;+ model_.UpdateLeftoverDeletions(std::move(deletions));+ }}}auto plays = model_.TakeRuntimePlayRequests();diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hppindex 0277a7c..985bfbc 100644--- a/src/homebrew/controller.hpp+++ b/src/homebrew/controller.hpp@@ -291,6 +291,9 @@ class Controller {std::vector<std::pair<GameId, std::string>> uninstall_statuses_;std::uint64_t kept_revision_ = 0;std::vector<LiveKeptBottle> kept_projected_;+ std::vector<LiveLeftoverTitle> leftovers_projected_;+ std::vector<LiveLeftoverDelete> leftover_deletions_projected_;+ std::map<std::string, std::string> leftover_names_;std::map<GameId, std::string> play_notes_;std::uint64_t play_notes_revision_ = 0;std::uint64_t runtime_notes_revision_ = 0;diff --git a/src/homebrew/queue_layout.cpp b/src/homebrew/queue_layout.cppindex ef364d8..1516ac8 100644--- a/src/homebrew/queue_layout.cpp+++ b/src/homebrew/queue_layout.cpp@@ -131,6 +131,30 @@ QueueSection preparations(const State& state) {else uninstalls_running.push_back(std::move(item));}section.rows = std::move(uninstalls_running);+ for (const auto& deletion : state.leftover_deletions) {+ QueueEntry item;+ item.key = "prep-leftover-" + deletion.title_id;+ item.title = deletion.name.empty() ? deletion.title_id : deletion.name;+ item.leftover = true;+ item.note = deletion.failure.empty() ? deletion.step : deletion.failure;+ if (!deletion.failure.empty()) {+ item.status = "Deletion stopped";+ item.tone = "attention";+ ++section.attention;+ } else if (deletion.step.empty()) {+ item.status = "Waiting to delete";+ item.note = deletion.title_id;+ item.tone = "quiet";+ ++section.waiting;+ } else {+ item.status = "Deleting title";+ item.tone = "busy";+ ++section.running;+ ++section.deleting;+ if (!section.active) { section.active = std::move(item); continue; }+ }+ section.rows.push_back(std::move(item));+ }int position = 0;for (const auto id : queue.waiting) {if (queue.active && id == *queue.active) continue;@@ -241,7 +265,7 @@ void summarize(QueueSection& section, const std::string& expanded_words, const s// Games after the card waiting their turn; what needs the player is counted apart.const std::size_t more = static_cast<std::size_t>(std::count_if(section.rows.begin(), section.rows.end(), [](const QueueEntry& row) {if (row.job) return row.job->state == JobState::Queued || running(*row.job);- return row.position > 0 || (row.uninstall && !row.completed && row.tone != "attention");+ return row.position > 0 || ((row.uninstall || row.leftover) && !row.completed && row.tone != "attention");}));if (section.expanded) {text = expanded_words;@@ -265,6 +289,8 @@ std::size_t QueuePending(const State& state) {return job.state != JobState::Cancelled && job.state != JobState::Downloaded && job.stage != JobStage::Uninstall;}));const auto& preparation = state.preparation_queue;+ pending += std::count_if(state.leftover_deletions.begin(), state.leftover_deletions.end(),+ [](const LiveLeftoverDelete& deletion) { return deletion.failure.empty(); });return pending + preparation.waiting.size() + (preparation.active ? 1U : 0U) + preparation.uninstalls.size();}@@ -307,7 +333,8 @@ QueueLayout BuildQueueLayout(const State& state) {if (failed) join(download_attention, std::to_string(failed) + " failed");summarize(download, downloads_words(download, paused, failed), download_attention, "No downloads");std::string prepare_words, prepare_attention;- if (prepare.running > prepare.uninstalling) join(prepare_words, "1 preparing");+ if (prepare.running > prepare.uninstalling + prepare.deleting) join(prepare_words, "1 preparing");+ if (prepare.deleting) join(prepare_words, std::to_string(prepare.deleting) + " deleting titles");if (prepare.uninstalling) join(prepare_words, std::to_string(prepare.uninstalling) + " uninstalling");if (prepare.waiting) join(prepare_words, std::to_string(prepare.waiting) + " waiting");if (prepare.attention) join(prepare_attention, need_attention(prepare.attention));@@ -317,7 +344,8 @@ QueueLayout BuildQueueLayout(const State& state) {std::string summary;if (download.running > download.copying) join(summary, std::to_string(download.running - download.copying) + " downloading");if (download.copying) join(summary, std::to_string(download.copying) + " copying");- if (prepare.running > prepare.uninstalling) join(summary, "1 preparing");+ if (prepare.running > prepare.uninstalling + prepare.deleting) join(summary, "1 preparing");+ if (prepare.deleting) join(summary, std::to_string(prepare.deleting) + " deleting titles");if (prepare.uninstalling) join(summary, std::to_string(prepare.uninstalling) + " uninstalling");if (download.waiting + prepare.waiting) join(summary, std::to_string(download.waiting + prepare.waiting) + " waiting");if (download.attention + prepare.attention)diff --git a/src/homebrew/queue_layout.hpp b/src/homebrew/queue_layout.hppindex 4d1784e..4853ff6 100644--- a/src/homebrew/queue_layout.hpp+++ b/src/homebrew/queue_layout.hpp@@ -28,6 +28,7 @@ struct QueueEntry {std::string tone; // good, busy, attention, problem, quietint position = 0; // waiting preparations, from 1bool uninstall = false;+ bool leftover = false;bool completed = false;std::int64_t finished_at = 0; // completed entries (Unix seconds), 0 unknown};@@ -43,6 +44,7 @@ struct QueueSection {std::vector<QueueEntry> rows;std::size_t running = 0; // downloading, preparing or uninstalling nowstd::size_t copying = 0; // of those running, imported games copied into Playden+ std::size_t deleting = 0; // leftover PS5 titlesstd::size_t uninstalling = 0; // of those running, uninstallsstd::size_t waiting = 0; // queued to run, card included when it only waitsstd::size_t attention = 0; // paused, failed or blocked: not ordinary waiting workdiff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex 9cae1af..1ec9a37 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -308,6 +308,9 @@ struct RuntimeHost::Composition {// PS5 titles removed while Playden runs: the console keeps their registration until Playden// quits, so a new game reusing one fails publication ("ownership is unavailable or incoherent").std::set<std::string> retired_titles;+ std::map<std::string, LeftoverDelete> leftover_deletes;+ std::set<std::string> blocked_leftover_titles;+ bool leftover_journals_known = true;rt::RuntimeInstallRepository repository;rt::RepositoryInstallRecordStore records;std::optional<RuntimeKit> kit;@@ -428,6 +431,7 @@ void RuntimeHost::Prepare(RuntimePrepareRequest request) {if (queued != prepare_requests_.end()) {*queued = std::move(request);} else {+ prepare_order_[request.runtime_number] = ++next_work_order_;snapshot_.queued_prepares.push_back(request.runtime_number);prepare_requests_.push_back(std::move(request));}@@ -444,7 +448,11 @@ bool RuntimeHost::PrepareNext(std::uint32_t app_id) {[&](const auto& waiting) { return waiting.runtime_number == app_id; });if (queued == prepare_requests_.end()) return false;// The others keep their order behind it.+ std::vector<std::uint64_t> orders;+ for (const auto& request : prepare_requests_) orders.push_back(prepare_order_.at(request.runtime_number));std::rotate(prepare_requests_.begin(), queued, queued + 1);+ for (std::size_t i = 0; i < prepare_requests_.size(); ++i)+ prepare_order_[prepare_requests_[i].runtime_number] = orders[i];snapshot_.queued_prepares.clear();for (const auto& waiting : prepare_requests_) snapshot_.queued_prepares.push_back(waiting.runtime_number);++snapshot_.revision;@@ -460,6 +468,7 @@ bool RuntimeHost::WithdrawPrepare(std::uint32_t app_id) {[&](const auto& waiting) { return waiting.runtime_number == app_id; });if (queued == prepare_requests_.end()) return false;prepare_requests_.erase(queued);+ prepare_order_.erase(app_id);std::erase(snapshot_.queued_prepares, app_id);++snapshot_.revision;}@@ -588,7 +597,7 @@ void RuntimeHost::Remove(std::uint32_t app_id, bool delete_saves) {{std::lock_guard<std::mutex> lock(mutex_);if (stopping_) return;- remove_requests_.emplace_back(app_id, delete_saves);+ remove_requests_.push_back({app_id, delete_saves, std::nullopt, ++next_work_order_});}wake_.notify_all();}@@ -602,6 +611,29 @@ void RuntimeHost::DeleteKeptBottle(std::uint32_t app_id) {wake_.notify_all();}+bool RuntimeHost::DeleteLeftoverTitle(const std::string& title_id, std::string* error) {+ {+ std::lock_guard<std::mutex> lock(mutex_);+ if (stopping_) return false;+ const auto found = std::find_if(snapshot_.leftover_titles.begin(), snapshot_.leftover_titles.end(),+ [&](const auto& title) { return title.title_id == title_id; });+ if (found == snapshot_.leftover_titles.end()) {+ if (error) *error = "This leftover PS5 title is no longer available.";+ return false;+ }+ if (snapshot_.deleting_leftover_title == title_id ||+ std::find(snapshot_.queued_leftover_deletes.begin(), snapshot_.queued_leftover_deletes.end(), title_id) !=+ snapshot_.queued_leftover_deletes.end()) return true;+ remove_requests_.push_back({0, false, LeftoverDelete{*found, {}, "retire"}, ++next_work_order_});+ snapshot_.queued_leftover_deletes.push_back(title_id);+ snapshot_.leftover_delete_failures.erase(title_id);+ ++snapshot_.revision;+ }+ published_.notify_all();+ wake_.notify_all();+ return true;+}+void RuntimeHost::ScanPrograms(std::uint32_t app_id, std::string install_path) {{std::lock_guard<std::mutex> lock(mutex_);@@ -2617,6 +2649,7 @@ void RuntimeHost::PublishRecipes(const Composition& c) {}std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest& request, bool* awaiting) {+ if (!c.leftover_journals_known) return "The PS5 title removal records cannot be read; restart Playden before preparing games.";if (!c.kit) return Snapshot().kit_reason;if (const auto replaced = KitReplaced(c); !replaced.empty()) return replaced;// Where the time before the first step goes: the recipe, the reservation and the title's metadata.@@ -2966,8 +2999,10 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&reserve.volume_id = request.volume_id;// Titles removed during this run go last: a kit with fixed titles still gets one back.std::vector<std::string> retired;- for (auto& title : rt::KitTitleCandidates(c.kit->view))+ for (auto& title : rt::KitTitleCandidates(c.kit->view)) {+ if (c.blocked_leftover_titles.count(title)) continue;(c.retired_titles.count(title) ? retired : reserve.kit_title_variants).push_back(std::move(title));+ }reserve.kit_title_variants.insert(reserve.kit_title_variants.end(), retired.begin(), retired.end());auto reserved = c.repository.Reserve(reserve);if (!reserved.ok()) {@@ -3456,6 +3491,296 @@ void RuntimeHost::PublishKeptBottles(Composition& c) {Publish([&](RuntimeSnapshot& s) { s.kept_bottles = std::move(kept); });}+std::optional<RuntimeHost::RemovalFailure> RuntimeHost::RetireTitle(+ Composition& c, const std::string& title_id, const std::string& operation_id,+ const rt::LeftoverTitle* expected) {+ const auto source = config_.homebrew_root / title_id;+ // ShadowMount must no longer discover the source before the native title goes.+ const auto manual = c.registry.RemoveManualSource(title_id);+ Log("remove manual source title=" + title_id + " ok=" + std::to_string(manual.ok) + " stage=" + manual.stage);+ struct stat info{};+ if (lstat(source.c_str(), &info) != 0) {+ if (errno == ENOENT) return std::nullopt;+ return RemovalFailure{"source-unavailable", "The PS5 title's folder cannot be checked."};+ }+ if (!S_ISDIR(info.st_mode) || info.st_uid != geteuid())+ return RemovalFailure{"source-foreign", "The PS5 title's folder is not Playden's; it was left as it is."};+ if (expected && (expected->device != static_cast<std::uint64_t>(info.st_dev) ||+ expected->inode != static_cast<std::uint64_t>(info.st_ino)))+ return RemovalFailure{"source-changed", "The PS5 title's folder changed since it was found; it was left as it is."};+ std::string reason;+ const auto trash = config_.state_root / "trash";+ if (!rt::EnsurePrivateDirectories(config_.boundary, config_.state_root, trash, &reason))+ return RemovalFailure{"trash-unavailable", "Playden could not prepare its private trash: " + reason};+ auto homebrew = platform::ManagedDirectory::Open(config_.homebrew_root, platform::DirectoryPolicy::kApprovedTree);+ auto destination = platform::ManagedDirectory::Open(trash, platform::DirectoryPolicy::kApprovedTree);+ struct stat checked{};+ if (!homebrew || !destination || !homebrew->InspectChild(title_id, &checked) ||+ checked.st_dev != info.st_dev || checked.st_ino != info.st_ino || checked.st_uid != info.st_uid ||+ !homebrew->RenameChild(title_id, *destination, title_id + "-" + operation_id, false) ||+ !homebrew->Sync() || !destination->Sync())+ return RemovalFailure{"retire-failed", "The PS5 title's folder could not be moved away (error " ++ std::to_string(errno) + ")."};+ Log("remove retired title=" + title_id);+ return std::nullopt;+}++std::optional<RuntimeHost::RemovalFailure> RuntimeHost::UnregisterTitle(+ Composition& c, const std::string& title_id, const std::string& operation_id) {+ bool listed = TitleListed(c, title_id);+ TitleRemoverResult result;+ if (listed) {+ if (!config_.unregister_title)+ return RemovalFailure{"remover-unavailable", "Removing PS5 titles is not available in this build."};+ result = config_.unregister_title(title_id, operation_id);+ Log("remove unregister title=" + title_id + " sent=" + std::to_string(result.sent) + " code=" ++ (result.code ? std::to_string(*result.code) : std::string("none")) + " detail=" + result.detail);+ for (int poll = 0; listed && poll < config_.removal_confirm_polls && !Stopping(); ++poll) {+ listed = TitleListed(c, title_id);+ if (!listed) break;+ std::unique_lock<std::mutex> lock(mutex_);+ wake_.wait_for(lock, config_.removal_poll_interval, [this] { return stopping_; });+ }+ if (listed) listed = TitleListed(c, title_id);+ }+ if (!listed) return std::nullopt;+ if (!result.sent)+ return RemovalFailure{"remover-unavailable", "Playden could not start its title remover. Retry to try again."};+ if (result.code && *result.code != 0) {+ char code[16]; std::snprintf(code, sizeof(code), "0x%08x", static_cast<unsigned>(*result.code));+ return RemovalFailure{"unregister-refused", std::string("The console refused to remove the PS5 title (") + code + ")."};+ }+ return RemovalFailure{"unregister-unconfirmed",+ "The console has not confirmed that the PS5 title is gone. Retry checks again."};+}++std::string RuntimeHost::DeleteRetiredTitle(const std::string& title_id, const std::string& operation_id) {+ const auto trash = config_.state_root / "trash" / (title_id + "-" + operation_id);+ struct stat info{};+ if (lstat(trash.c_str(), &info) != 0 && errno == ENOENT) return {};+ auto parent = platform::ManagedDirectory::Open(trash.parent_path(), platform::DirectoryPolicy::kPrivate);+ if (!parent || !parent->InspectChild(trash.filename().string(), &info) ||+ !S_ISDIR(info.st_mode) || info.st_uid != geteuid())+ return "The retired PS5 title's folder is not Playden's; it was left as it is.";+ const auto total = CountTreeNoFollow(trash.string());+ std::uint64_t done = 0;+ const std::function<void()> removed = [&] { ReportWork(++done, total); };+ std::error_code error;+ RemoveTreeNoFollow(trash, error, &removed);+ ClearWork();+ return error ? "The PS5 title's folder could not be deleted: " + error.message() : std::string{};+}++namespace {+std::string LeftoverDeleteFile(const std::string& title) { return "leftover-" + title + ".json"; }++bool LeftoverOperationId(const std::string& operation) {+ if (operation.size() != 36) return false;+ for (std::size_t i = 0; i < operation.size(); ++i) {+ if (i == 8 || i == 13 || i == 18 || i == 23) { if (operation[i] != '-') return false; }+ else if (!((operation[i] >= '0' && operation[i] <= '9') ||+ (operation[i] >= 'a' && operation[i] <= 'f'))) return false;+ }+ return true;+}+} // namespace++std::string RuntimeHost::SaveLeftoverDelete(Composition& c, const LeftoverDelete& request) {+ const auto& title = request.title;+ const auto text = "{\"schema\":1,\"title\":\"" + title.title_id + "\",\"operation_id\":\"" + request.operation_id ++ "\",\"step\":\"" + request.step + "\",\"device\":" + std::to_string(title.device) ++ ",\"inode\":" + std::to_string(title.inode) + ",\"name\":\"" + JsonEscaped(title.name) ++ "\",\"bytes\":" + std::to_string(title.bytes) + "}\n";+ // Storage's durable writer uses ManagedDirectory and creates the journal 0600 before writing.+ c.blocked_leftover_titles.insert(title.title_id);+ const auto saved = c.storage.WriteDurable(LeftoverDeleteFile(title.title_id), Bytes(text.begin(), text.end()));+ if (!saved.ok()) {+ // A failed sync may follow a successful rename: only a fresh journal read after restart may+ // decide which step is durable. Never continue using the previous in-memory step.+ c.leftover_deletes.erase(title.title_id);+ return "The removal could not be recorded; restart Playden before retrying: " + saved.message();+ }+ c.leftover_deletes[title.title_id] = request;+ return {};+}++void RuntimeHost::PublishLeftoverTitles(Composition& c) {+ auto titles = rt::FindLeftoverTitles(config_.homebrew_root, c.repository.Loaded() && c.leftover_journals_known, c.repository.Snapshot(),+ [&c](const std::string& title) { return c.coordinator->Activity(title); }, geteuid());+ // A retired title still waiting for the remover remains available to retry, even though its+ // source has left the scan root. Its private journal reserves the ID until completion.+ if (c.repository.Loaded())+ for (const auto& [id, request] : c.leftover_deletes) {+ const auto records = c.repository.Snapshot();+ if (std::any_of(records.begin(), records.end(), [&](const auto& record) { return record.title_id == id; }) ||+ c.coordinator->Activity(id) != rt::NativeActivity::kStopped) continue;+ if (std::none_of(titles.begin(), titles.end(), [&](const auto& title) { return title.title_id == id; }))+ titles.push_back(request.title);+ }+ std::sort(titles.begin(), titles.end(), [](const auto& a, const auto& b) { return a.title_id < b.title_id; });+ std::string ids;+ for (const auto& title : titles) ids += " " + title.title_id;+ Log("leftover titles found=" + std::to_string(titles.size()) + ids);+ Publish([&](RuntimeSnapshot& s) { s.leftover_titles = std::move(titles); });+}++std::string RuntimeHost::RunDeleteLeftover(Composition& c, LeftoverDelete request) {+ const auto id = request.title.title_id;+ const auto fail = [&](const std::string& message) {+ Log("leftover delete failed title=" + id + " step=" + request.step + " " + message);+ return message;+ };+ if (!c.leftover_journals_known) return fail("The PS5 title removal records cannot be read; restart Playden before retrying.");+ if (!c.repository.Loaded()) {+ const auto loaded = c.repository.Load();+ PublishInstalls(c);+ if (!loaded.ok()) return fail("Playden's records of PS5 titles cannot be read: " + loaded.message() + ".");+ }+ for (const auto& record : c.repository.Snapshot())+ if (record.title_id == id) return fail("This PS5 title now belongs to an installed game; it was left as it is.");+ if (const auto pending = c.leftover_deletes.find(id); pending != c.leftover_deletes.end()) request = pending->second;+ else if (c.blocked_leftover_titles.count(id))+ return fail("The removal record cannot be read; restart Playden before retrying.");+ auto homebrew = platform::ManagedDirectory::Open(config_.homebrew_root, platform::DirectoryPolicy::kApprovedTree);+ if (!homebrew) return fail("The PS5 title's folder cannot be checked.");+ const auto activity = c.coordinator->Activity(id);+ if (activity == rt::NativeActivity::kActive) return fail("Close the game before uninstalling it.");+ if (activity != rt::NativeActivity::kStopped) return fail(kActivityUnknown);+ const auto source = config_.homebrew_root / id;+ struct stat info{};+ if (lstat(source.c_str(), &info) == 0) {+ if (!S_ISDIR(info.st_mode) || info.st_uid != geteuid())+ return fail("The PS5 title's folder is not Playden's; it was left as it is.");+ if (request.step != "retire" || request.title.device != static_cast<std::uint64_t>(info.st_dev) ||+ request.title.inode != static_cast<std::uint64_t>(info.st_ino))+ return fail("The PS5 title's folder changed since it was found; it was left as it is.");+ } else if (errno != ENOENT) return fail("The PS5 title's folder cannot be checked.");+ else if (request.operation_id.empty()) return fail("This leftover PS5 title is no longer available.");+ if (!request.operation_id.empty()) {+ const auto trash = config_.state_root / "trash";+ const auto retired = trash / (id + "-" + request.operation_id);+ if (lstat(retired.c_str(), &info) == 0) {+ const auto parent = platform::ManagedDirectory::Open(trash, platform::DirectoryPolicy::kPrivate);+ if (!parent || !S_ISDIR(info.st_mode) || info.st_uid != geteuid() ||+ request.title.device != static_cast<std::uint64_t>(info.st_dev) ||+ request.title.inode != static_cast<std::uint64_t>(info.st_ino))+ return fail("The retired PS5 title's folder changed; it was left as it is.");+ } else if (errno != ENOENT) return fail("The retired PS5 title's folder cannot be checked.");+ }+ // Check the inventory before retiring: an unavailable remover must leave a listed title's source intact.+ if (TitleListed(c, id) && !config_.unregister_title)+ return fail("Removing PS5 titles is not available in this build.");+ if (request.operation_id.empty()) {+ const auto operation = config_.uuid();+ if (!operation || !LeftoverOperationId(*operation)) return fail("No secure random source for the removal.");+ request.operation_id = *operation;+ if (const auto error = SaveLeftoverDelete(c, request); !error.empty()) return fail(error);+ }+ if (request.step == "retire") {+ Publish([](RuntimeSnapshot& s) { s.deleting_leftover_step = "Removing PS5 title…"; });+ if (const auto error = RetireTitle(c, id, request.operation_id, &request.title)) return fail(error->message);+ request.step = "unregister";+ if (const auto error = SaveLeftoverDelete(c, request); !error.empty()) return fail(error);+ }+ if (request.step == "unregister") {+ Publish([](RuntimeSnapshot& s) { s.deleting_leftover_step = "Removing PS5 title…"; });+ if (Stopping()) return fail("The removal will continue when Playden starts again.");+ if (const auto error = UnregisterTitle(c, id, request.operation_id)) return fail(error->message);+ request.step = "trash";+ if (const auto error = SaveLeftoverDelete(c, request); !error.empty()) return fail(error);+ }+ // A restart or a retry still checks the native inventory before clearing the durable journal.+ if (TitleListed(c, id)) return fail("The console has not confirmed that the PS5 title is gone. Retry checks again.");+ Publish([](RuntimeSnapshot& s) { s.deleting_leftover_step = "Deleting title files…"; });+ if (const auto error = DeleteRetiredTitle(id, request.operation_id); !error.empty()) return fail(error);+ const auto cleared = c.storage.RemoveDurable(LeftoverDeleteFile(id));+ if (!cleared.ok()) {+ c.leftover_deletes.erase(id);+ return fail("The removal could not be completed; restart Playden before retrying: " + cleared.message());+ }+ c.leftover_deletes.erase(id);+ c.blocked_leftover_titles.erase(id);+ c.retired_titles.insert(id);+ Log("leftover delete complete title=" + id);+ return {};+}++void RuntimeHost::ResumeLeftoverDeletes(Composition& c) {+ // Every entry named like a journal counts, whatever it is: one that cannot be inspected still+ // reserves its title. A listing that stops early leaves the journals unknown.+ std::vector<std::string> names;+ DIR* directory = opendir(config_.state_root.c_str());+ if (!directory && errno != ENOENT) {+ c.leftover_journals_known = false;+ Log("leftover removal journals unavailable: errno " + std::to_string(errno));+ return;+ }+ if (directory) {+ for (;;) {+ errno = 0;+ const dirent* entry = readdir(directory);+ if (!entry) break;+ const std::string name = entry->d_name;+ if (name.rfind("leftover-", 0) == 0) names.push_back(name);+ }+ const int listing_error = errno;+ closedir(directory);+ if (listing_error != 0) {+ c.leftover_journals_known = false;+ Log("leftover removal journals unavailable: errno " + std::to_string(listing_error));+ return;+ }+ }+ for (const auto& entry_name : names) {+ // A journal is written before the removal changes anything, so a half-written one alone (.tmp) holds nothing.+ if (entry_name.size() > 4 && entry_name.compare(entry_name.size() - 4, 4, ".tmp") == 0) continue;+ const auto id = entry_name.size() == 23 && entry_name.substr(18) == ".json" ? entry_name.substr(9, 9) : std::string();+ if (!rt::IsManagedTitle(id)) {+ Log("leftover removal journal name not understood: " + entry_name);+ continue;+ }+ c.blocked_leftover_titles.insert(id);+ const auto directory = platform::ManagedDirectory::Open(config_.state_root, platform::DirectoryPolicy::kPrivate);+ struct stat journal_info{};+ if (!directory || !directory->InspectChild(entry_name, &journal_info) || !S_ISREG(journal_info.st_mode) ||+ journal_info.st_uid != geteuid() || (journal_info.st_mode & 07777) != 0600) {+ Log("leftover removal journal permissions invalid title=" + id); continue;+ }+ const auto bytes = c.storage.ReadDurable(entry_name, 8192);+ const auto json = bytes.ok() ? steam::json::Parse(std::string(bytes.value().begin(), bytes.value().end())) : std::nullopt;+ if (!json || !json->is_object()) { Log("leftover removal journal invalid title=" + id); continue; }+ const auto schema = json->Find("schema"), title = json->Find("title"), operation = json->Find("operation_id"),+ step = json->Find("step"), device = json->Find("device"), inode = json->Find("inode"),+ name = json->Find("name"), size = json->Find("bytes");+ if (json->object().size() != 8 || !schema || schema->AsUint64() != 1 || !title || !title->is_string() ||+ title->text() != id || !operation || !operation->is_string() || !LeftoverOperationId(operation->text()) ||+ !step || !step->is_string() || (step->text() != "retire" && step->text() != "unregister" && step->text() != "trash") ||+ !device || !device->AsUint64() || !inode || !inode->AsUint64() || !name || !name->is_string() ||+ name->text().size() > 4096 || !size || !size->AsUint64()) {+ Log("leftover removal journal invalid title=" + id); continue;+ }+ LeftoverDelete request;+ request.title = {id, config_.homebrew_root / id, name->text(), *size->AsUint64(), *device->AsUint64(), *inode->AsUint64()};+ request.operation_id = operation->text();+ request.step = step->text();+ c.leftover_deletes[id] = request;+ }+ // Each journal is reconciled before startup's trash housekeeping; failed ones retain their folder.+ const auto pending = c.leftover_deletes;+ for (const auto& [id, request] : pending) {+ Publish([&](RuntimeSnapshot& s) { s.deleting_leftover_title = id; });+ const auto error = RunDeleteLeftover(c, request);+ ClearWork();+ Publish([&](RuntimeSnapshot& s) {+ s.deleting_leftover_title.reset();+ s.deleting_leftover_step.clear();+ if (!error.empty()) s.leftover_delete_failures[id] = error;+ else s.leftover_delete_failures.erase(id);+ ++s.leftover_deletes_handled;+ });+ }+}+// Removal of a game's PS5 title, journaled in its install record so an interrupted// removal continues where it stopped: retire the title folder out of ShadowMount's// scan root, unregister the title through the one-shot remover, keep or delete the@@ -3536,53 +3861,13 @@ std::string RuntimeHost::RunRemove(Composition& c, std::uint32_t app, bool delet" delete_saves=" + std::to_string(delete_saves));const auto source = config_.homebrew_root / record.title_id;if (record.journal->step == "retire") {- // ShadowMount registers any folder under its scan root, so the folder leaves- // it in one move before the title is unregistered.- const auto manual = c.registry.RemoveManualSource(record.title_id);- Log("remove manual source title=" + record.title_id + " ok=" + std::to_string(manual.ok) + " stage=" + manual.stage);- struct stat info{};- if (lstat(source.c_str(), &info) == 0) {- if (!S_ISDIR(info.st_mode) || info.st_uid != geteuid())- return fail("source-foreign", "The PS5 title's folder is not Playden's; it was left as it is.");- std::string reason;- const auto trash = config_.state_root / "trash";- if (!rt::EnsurePrivateDirectories(config_.boundary, config_.state_root, trash, &reason))- return fail("trash-unavailable", "Playden could not prepare its private trash: " + reason);- const auto retired = trash / (record.title_id + "-" + record.journal->operation_id);- if (rename(source.c_str(), retired.c_str()) != 0)- return fail("retire-failed", "The PS5 title's folder could not be moved away (error " +- std::to_string(errno) + ").");- } else if (errno != ENOENT) {- return fail("source-unavailable", "The PS5 title's folder cannot be checked.");- }+ if (const auto failed = RetireTitle(c, record.title_id, record.journal->operation_id))+ return fail(failed->code, failed->message);if (auto failed = advance("unregister"); !failed.empty()) return failed;}if (record.journal->step == "unregister") {- // Inventory first: a title the console no longer lists is never sent again.- bool listed = TitleListed(c, record.title_id);- TitleRemoverResult result;- if (listed) {- result = config_.unregister_title(record.title_id, record.journal->operation_id);- Log("remove unregister title=" + record.title_id + " sent=" + std::to_string(result.sent) + " code=" +- (result.code ? std::to_string(*result.code) : std::string("none")) + " detail=" + result.detail);- for (int poll = 0; listed && poll < config_.removal_confirm_polls && !Stopping(); ++poll) {- listed = TitleListed(c, record.title_id);- if (!listed) break;- std::unique_lock<std::mutex> lock(mutex_);- wake_.wait_for(lock, config_.removal_poll_interval, [this] { return stopping_; });- }- if (listed) listed = TitleListed(c, record.title_id);- }- if (listed) {- if (!result.sent)- return fail("remover-unavailable", "Playden could not start its title remover. Retry to try again.");- if (result.code && *result.code != 0) {- char code[16]; std::snprintf(code, sizeof(code), "0x%08x", static_cast<unsigned>(*result.code));- return fail("unregister-refused", std::string("The console refused to remove the PS5 title (") + code + ").");- }- // No answer is not a failure of the console: the next attempt checks again.- return fail("unregister-unconfirmed", "The console has not confirmed that the PS5 title is gone. Retry checks again.");- }+ if (const auto failed = UnregisterTitle(c, record.title_id, record.journal->operation_id))+ return fail(failed->code, failed->message);if (auto failed = advance("bottle"); !failed.empty()) return failed;}if (record.journal->step == "bottle") {@@ -3666,16 +3951,8 @@ std::string RuntimeHost::RunRemove(Composition& c, std::uint32_t app, bool deletPublishRecipes(c);}c.admission.erase(record.install_id);- {- // The retired title folder: its progress is the entries removed of those counted.- const auto trash = config_.state_root / "trash" / (record.title_id + "-" + record.journal->operation_id);- const std::uint64_t total = CountTreeNoFollow(trash.string());- std::uint64_t done = 0;- const std::function<void()> removed = [&] { ReportWork(++done, total); };- std::error_code ignored;- RemoveTreeNoFollow(trash, ignored, &removed);- ClearWork();- }+ // A normal uninstall's record is already erased; leftover failures keep their private journal.+ DeleteRetiredTitle(record.title_id, record.journal->operation_id);PublishInstalls(c);Log("remove complete install=" + record.install_id + " title=" + record.title_id);c.retired_titles.insert(record.title_id);@@ -3819,19 +4096,25 @@ bool RuntimeHost::RunServices() {PublishKeptBottles(c);Log("startup kept bottles published");ShareNumbers(&c.repository);- // Startup only reads durable state. Records with a journal wait for an- // explicit recovery action; nothing resumes, registers or rebuilds here.+ // Install records with a journal wait for an explicit recovery action. Leftover-title+ // deletion journals are resumed separately before their retired folders can be swept.Log("startup records loaded installs=" + std::to_string(c.repository.Snapshot().size()));LoadGeneratedRecipes(c);Log("startup generated recipes loaded");PublishInstalls(c);Log("startup installs published");+ ResumeLeftoverDeletes(c);+ PublishLeftoverTitles(c);// Retired title folders left by an earlier removal are outside the scan// root already; deleting them is only housekeeping.- {+ if (c.leftover_journals_known) {std::error_code error;for (std::filesystem::directory_iterator it(config_.state_root / "trash", error), end; !error && it != end;it.increment(error)) {+ const auto entry = it->path().filename().string();+ const bool pending = std::any_of(c.blocked_leftover_titles.begin(), c.blocked_leftover_titles.end(),+ [&](const auto& title) { return entry.rfind(title + "-", 0) == 0; });+ if (pending) continue;std::error_code ignored;RemoveTreeNoFollow(it->path(), ignored); // never follows links}@@ -3973,7 +4256,7 @@ bool RuntimeHost::RunServices() {bool reload = false;for (;;) {std::vector<std::uint32_t> plays;- std::vector<std::pair<std::uint32_t, bool>> removals;+ std::vector<RemovalRequest> removals;std::vector<std::uint32_t> kept_deletes;std::vector<std::pair<std::uint32_t, RuntimeMaintenance>> maintenance;std::vector<std::pair<std::uint32_t, std::string>> scans;@@ -4012,7 +4295,12 @@ bool RuntimeHost::RunServices() {}plays.swap(play_requests_);// Removal changes install records that Handoff reads, like preparation.- if (!snapshot_.handoff_ready) removals.swap(remove_requests_);+ if (!snapshot_.handoff_ready && !remove_requests_.empty() &&+ (prepare_requests_.empty() || prepares_held_ ||+ remove_requests_.front().order < prepare_order_.at(prepare_requests_.front().runtime_number))) {+ removals.push_back(std::move(remove_requests_.front()));+ remove_requests_.erase(remove_requests_.begin());+ }if (!snapshot_.handoff_ready) kept_deletes.swap(kept_delete_requests_);scans.swap(scan_requests_);// Maintenance changes the bottle and install record, like removal.@@ -4102,7 +4390,28 @@ bool RuntimeHost::RunServices() {relocations.clear();}}- for (const auto& [app, delete_saves] : removals) {+ for (const auto& request : removals) {+ const auto app = request.app;+ const auto delete_saves = request.delete_saves;+ if (request.leftover) {+ const auto& title = request.leftover->title.title_id;+ Publish([&](RuntimeSnapshot& s) {+ std::erase(s.queued_leftover_deletes, title);+ s.deleting_leftover_title = title;+ s.leftover_delete_failures.erase(title);+ });+ const auto refusal = composition ? RunDeleteLeftover(*composition, *request.leftover)+ : "The runtime services are unavailable.";+ if (composition) PublishLeftoverTitles(*composition);+ ClearWork();+ Publish([&](RuntimeSnapshot& s) {+ s.deleting_leftover_title.reset();+ s.deleting_leftover_step.clear();+ if (!refusal.empty()) s.leftover_delete_failures[title] = refusal;+ ++s.leftover_deletes_handled;+ });+ continue;+ }std::string refusal;if (!composition) {const auto current = Snapshot();@@ -4111,6 +4420,7 @@ bool RuntimeHost::RunServices() {Publish([&](RuntimeSnapshot& s) { s.removing_app = app; s.removal_failures.erase(app); });refusal = RunRemove(*composition, app, delete_saves);PublishKeptBottles(*composition);+ PublishLeftoverTitles(*composition);}Log("remove result app=" + std::to_string(app) + " " + (refusal.empty() ? "removed" : refusal));if (refusal.empty() && std::erase_if(prepared_history_, [app](const PreparedGame& entry) { return entry.runtime_number == app; })) {@@ -4181,9 +4491,12 @@ bool RuntimeHost::RunServices() {std::optional<RuntimePrepareRequest> next;{std::lock_guard<std::mutex> lock(mutex_);- if (!prepare_requests_.empty() && !snapshot_.handoff_ready && !prepares_held_ && !stopping_) {+ if (!prepare_requests_.empty() && !snapshot_.handoff_ready && !prepares_held_ && !stopping_ &&+ (remove_requests_.empty() ||+ prepare_order_.at(prepare_requests_.front().runtime_number) < remove_requests_.front().order)) {next = std::move(prepare_requests_.front());prepare_requests_.erase(prepare_requests_.begin());+ prepare_order_.erase(next->runtime_number);auto& queued = snapshot_.queued_prepares;queued.erase(std::remove(queued.begin(), queued.end(), next->runtime_number), queued.end());if (composition) {diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex 3b0d3be..b8912c5 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -9,6 +9,7 @@#include "runtime/game_settings.h"#include "runtime/install_service.h"#include "runtime/launch_service.h"+#include "runtime/leftover_titles.h"#include "runtime/package_installer.h"#include "runtime/redist_install.h"@@ -305,7 +306,7 @@ struct RuntimeSnapshot {// Games whose preparation is asked for but not started yet, in the order they will start: each// waits behind another game's preparation, or for the runtime to finish starting.std::vector<std::uint32_t> queued_prepares;- // How far the current copy (preparing_app) or deletion (removing_app) is, when+ // How far the current copy or deletion (including a leftover title) is, when// that is measurable; absent for steps whose progress is unknown.std::optional<float> work_progress;std::optional<RuntimeLaunchView> launch;@@ -333,6 +334,13 @@ struct RuntimeSnapshot {std::uint64_t removals_handled = 0;// Game data kept when a game was uninstalled (bottles with no install record).std::vector<KeptBottleView> kept_bottles;+ // Unrecorded PS5 titles, and their queued/running deletion or latest failure (keyed by title ID).+ std::vector<runtime::LeftoverTitle> leftover_titles;+ std::vector<std::string> queued_leftover_deletes;+ std::optional<std::string> deleting_leftover_title;+ std::string deleting_leftover_step;+ std::map<std::string, std::string> leftover_delete_failures;+ std::uint64_t leftover_deletes_handled = 0;// Maintenance per runtime number, and how many requests the worker has finished.std::map<std::uint32_t, RuntimeMaintenanceView> maintenance;std::uint64_t maintenance_handled = 0;@@ -462,6 +470,8 @@ class RuntimeHost {void Remove(std::uint32_t runtime_number, bool delete_saves);// Queues deletion of a game's kept bottle.void DeleteKeptBottle(std::uint32_t runtime_number);+ // Deletes only a scanned leftover's PS5 title and registration; its game files and saves stay.+ bool DeleteLeftoverTitle(const std::string& title_id, std::string* error = nullptr);// Queues a scan of a game folder for the Program picker (RuntimeSnapshot::game_setups).void ScanPrograms(std::uint32_t runtime_number, std::string install_path);// Measures each game's Windows user folders (where saves of games without Steam Cloud live).@@ -624,6 +634,22 @@ class RuntimeHost {// moving: the title goes because its game was installed again elsewhere (journal "remove-move"),// so Prepare, not Uninstall, finishes a removal that stopped part way.std::string RunRemove(Composition& composition, std::uint32_t runtime_number, bool delete_saves, bool moving = false);+ struct RemovalFailure { std::string code, message; };+ std::optional<RemovalFailure> RetireTitle(Composition& composition, const std::string& title_id,+ const std::string& operation_id,+ const runtime::LeftoverTitle* expected = nullptr);+ std::optional<RemovalFailure> UnregisterTitle(Composition& composition, const std::string& title_id,+ const std::string& operation_id);+ std::string DeleteRetiredTitle(const std::string& title_id, const std::string& operation_id);+ struct LeftoverDelete {+ runtime::LeftoverTitle title;+ std::string operation_id;+ std::string step = "retire";+ };+ std::string RunDeleteLeftover(Composition& composition, LeftoverDelete request);+ std::string SaveLeftoverDelete(Composition& composition, const LeftoverDelete& request);+ void ResumeLeftoverDeletes(Composition& composition);+ void PublishLeftoverTitles(Composition& composition);// Whether the console still lists the title (app.db or /user/app); unknown counts as listed.bool TitleListed(Composition& composition, const std::string& title_id);// Moves the saves of a kept bottle into the game's new bottle and drops the kept copy.@@ -686,7 +712,15 @@ class RuntimeHost {mutable std::uint64_t shared_revision_ = 0;std::vector<RuntimePrepareRequest> prepare_requests_;std::vector<std::uint32_t> play_requests_;- std::vector<std::pair<std::uint32_t, bool>> remove_requests_;+ struct RemovalRequest {+ std::uint32_t app = 0;+ bool delete_saves = false;+ std::optional<LeftoverDelete> leftover;+ std::uint64_t order = 0;+ };+ std::vector<RemovalRequest> remove_requests_;+ std::uint64_t next_work_order_ = 0;+ std::map<std::uint32_t, std::uint64_t> prepare_order_;std::vector<std::uint32_t> kept_delete_requests_;std::vector<std::pair<std::uint32_t, std::string>> scan_requests_;std::vector<std::pair<std::uint32_t, RuntimeMaintenance>> maintenance_requests_;diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex 36bc207..713efb9 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -903,6 +903,46 @@ std::vector<GameId> Simulation::TakeRuntimePrepareRequests() {return requests;}+void Simulation::UpdateLeftoverTitles(std::vector<LiveLeftoverTitle> titles) {+ state_.leftover_titles = std::move(titles);+ std::erase_if(leftover_selected_, [this](const std::string& id) {+ return std::none_of(state_.leftover_titles.begin(), state_.leftover_titles.end(),+ [&](const LiveLeftoverTitle& item) { return item.title_id == id; });+ });+ // An open manager lists what is left now; with nothing left it closes.+ auto& modals = state_.navigation.modals;+ for (std::size_t index = 0; index < modals.size(); ++index) {+ auto& modal = modals[index];+ if (modal.id != "leftover-titles") continue;+ if (state_.leftover_titles.empty()) {+ // Nothing left to choose: the manager closes with anything over it (its confirmation).+ if (pending_destructive_action_ == "leftover-selection-delete") pending_destructive_action_.clear();+ state_.navigation.focus_key = modal.opener_focus_key;+ modals.erase(modals.begin() + static_cast<std::ptrdiff_t>(index), modals.end());+ break;+ }+ const auto focused = modal.action_keys[static_cast<std::size_t>(modal.focused_action)];+ modal.action_keys = leftover_manager_actions();+ const auto found = std::find(modal.action_keys.begin(), modal.action_keys.end(), focused);+ modal.focused_action = found == modal.action_keys.end()+ ? std::min(modal.focused_action, static_cast<int>(modal.action_keys.size()) - 1)+ : static_cast<int>(found - modal.action_keys.begin());+ if (index + 1 == modals.size()) state_.navigation.focus_key = modal.action_keys[static_cast<std::size_t>(modal.focused_action)];+ }+ rebuild_view();+}++void Simulation::UpdateLeftoverDeletions(std::vector<LiveLeftoverDelete> deletions) {+ state_.leftover_deletions = std::move(deletions);+ rebuild_view();+}++std::vector<std::string> Simulation::TakeLeftoverDeleteRequests() {+ auto requests = std::move(pending_leftover_delete_requests_);+ pending_leftover_delete_requests_.clear();+ return requests;+}+void Simulation::UpdateKeptBottles(std::vector<LiveKeptBottle> kept) {state_.kept_bottles = std::move(kept);std::erase_if(kept_selected_, [this](GameId id) {@@ -1334,6 +1374,20 @@ std::vector<std::string> Simulation::kept_manager_actions() const {return actions;}+std::vector<std::string> Simulation::leftover_manager_actions() const {+ std::vector<std::string> actions{"leftover-select-all"};+ for (const auto& title : state_.leftover_titles) actions.push_back("leftover-toggle-" + title.title_id);+ actions.push_back("leftover-selection-delete");+ actions.push_back("cancel");+ return actions;+}++// A title whose deletion is queued or running; one that stopped with a failure can be chosen again.+bool Simulation::leftover_queued(const std::string& title_id) const {+ return std::any_of(state_.leftover_deletions.begin(), state_.leftover_deletions.end(),+ [&](const LiveLeftoverDelete& deletion) { return deletion.title_id == title_id && deletion.failure.empty(); });+}+std::vector<GameId> Simulation::installed_list() const {struct Entry { GameId id; std::uint64_t bytes; std::optional<std::int64_t> played; std::string title; };std::vector<Entry> entries;@@ -3468,7 +3522,15 @@ bool Simulation::save_profile() {bool Simulation::scenario(const std::string& name) {if (live()) return false;- if (name == "download-servers") {+ if (name == "leftover-titles") {+ state_.account().authentication = AuthState::SignedIn;+ state_.navigation.modals.clear();+ state_.navigation.route = Route::Settings;+ state_.navigation.focus_key = "settings-leftovers";+ state_.leftover_titles = {{"FAKE78001", "A Short Hike", 12'000'000}, {"FAKE78002", "Portal", 8'000'000}};+ state_.leftover_deletions.clear();+ state_.jobs.clear();+ } else if (name == "download-servers") {download_server_fixture_ = true;download_servers_ = {};download_servers_.phase = "listed";@@ -4051,6 +4113,9 @@ void Simulation::rebuild_view() {if (modal.id == "kept-data")view_.subtitle = "Saves and settings kept when a game was uninstalled. Installing a game again brings its saves ""back. Saves in Steam Cloud stay in Steam Cloud.";+ if (modal.id == "leftover-titles")+ view_.subtitle = "PS5 titles Playden made but no longer has a record of. Deleting one removes its title and Home "+ "tile; its saves and game files stay.";if (modal.id == "download-server")view_.subtitle = "Applies to downloads that start or resume from now.";for (const auto& action_key : modal.action_keys) {@@ -4576,6 +4641,38 @@ void Simulation::rebuild_view() {item.enabled = !kept_selected_.empty();if (!kept_selected_.empty()) item.value = kept_count(kept_selected_.size()) + " · " + format_bytes(bytes);}+ else if (action_key == "leftover-select-all") {+ std::size_t choosable = 0;+ for (const auto& title : state_.leftover_titles) if (!leftover_queued(title.title_id)) ++choosable;+ item.title = choosable > 0 && leftover_selected_.size() == choosable ? "Clear selection" : "Select all";+ item.enabled = choosable > 0;+ }+ else if (action_key.rfind("leftover-toggle-", 0) == 0) {+ const auto id = action_key.substr(std::strlen("leftover-toggle-"));+ for (const auto& title : state_.leftover_titles) {+ if (title.title_id != id) continue;+ item.kind = RowKind::Toggle;+ item.title = title.name.empty() ? id : title.name;+ item.value = format_bytes(title.bytes);+ item.subtitle = id;+ for (const auto& deletion : state_.leftover_deletions)+ if (deletion.title_id == id)+ item.subtitle += " · " + (!deletion.failure.empty() ? deletion.failure+ : !deletion.step.empty() ? deletion.step : std::string("Queued"));+ item.enabled = !leftover_queued(id);+ item.selected = leftover_selected_.contains(id);+ }+ }+ else if (action_key == "leftover-selection-delete") {+ std::uint64_t bytes = 0;+ for (const auto& title : state_.leftover_titles) if (leftover_selected_.contains(title.title_id)) bytes += title.bytes;+ item.title = "Delete selected";+ item.dangerous = true;+ item.enabled = !leftover_selected_.empty();+ if (!leftover_selected_.empty())+ item.value = std::to_string(leftover_selected_.size()) + (leftover_selected_.size() == 1 ? " title · " : " titles · ") ++ format_bytes(bytes);+ }else if (action_key == "uninstall-delete-saves") {item.kind = RowKind::Toggle;item.dangerous = false;@@ -5380,6 +5477,15 @@ void Simulation::rebuild_view() {kept.value = kept_count(state_.kept_bottles.size()) + " · " + format_bytes(bytes);}}+ if (!state_.leftover_titles.empty()) {+ // PS5 titles Playden made but has no record of: one row that opens their manager, like kept game data.+ std::uint64_t bytes = 0;+ for (const auto& title : state_.leftover_titles) bytes += title.bytes;+ const auto count = state_.leftover_titles.size();+ auto& item = add("settings-leftovers", RowKind::Action, "Leftover PS5 titles", "leftover-manage");+ item.subtitle = "Game titles Playden no longer has a record of";+ item.value = std::to_string(count) + (count == 1 ? " title · " : " titles · ") + format_bytes(bytes);+ }if (live() && state_.runtime_leftover_requests > 0) {// Explicit recovery: settings requests no game is using any more.auto& leftovers = add("settings-runtime-cleanup", RowKind::Action, "Unused game settings data", "runtime-cleanup");@@ -6753,6 +6859,13 @@ void Simulation::activate() {static_cast<std::size_t>(std::count_if(state_.ended_uninstalls.begin(), state_.ended_uninstalls.end(),[](const EndedUninstall& ended) { return ended.stopped.empty(); }));};+ if (key.rfind("prep-leftover-", 0) == 0) {+ ModalEntry progress{"prep-actions", "Title deletion", selected.key, {"cancel"}, 0, false};+ progress.body = selected.title + " · " + selected.value ++ (selected.subtitle.empty() ? std::string() : "\n" + selected.subtitle);+ open_modal(std::move(progress));+ return;+ }if (key.rfind("prep-unin-", 0) == 0) {// An uninstall: its game's page while the library has it; one that ended leaves the list.if (find_game(state_, selected.game_id)) actions.push_back("prep-open-" + id);@@ -7338,6 +7451,49 @@ void Simulation::activate() {confirmation.body = "The game's folder and files stay where they are, and Import games can add it again. Its PS5 ""title is removed; its saves and settings on this console are kept.";open_modal(std::move(confirmation));+ } else if (action_name == "leftover-manage") {+ if (state_.leftover_titles.empty()) return;+ leftover_selected_.clear();+ open_modal({"leftover-titles", "Leftover PS5 titles", state_.navigation.focus_key, leftover_manager_actions(), 0, false});+ } else if (action_name == "leftover-select-all") {+ std::set<std::string> choosable;+ for (const auto& title : state_.leftover_titles) if (!leftover_queued(title.title_id)) choosable.insert(title.title_id);+ if (leftover_selected_ == choosable) leftover_selected_.clear();+ else leftover_selected_ = std::move(choosable);+ } else if (action_name.rfind("leftover-toggle-", 0) == 0) {+ const auto id = action_name.substr(std::strlen("leftover-toggle-"));+ if (leftover_queued(id)) return;+ if (!leftover_selected_.erase(id)) leftover_selected_.insert(id);+ } else if (action_name == "leftover-selection-delete") {+ if (leftover_selected_.empty()) return;+ std::uint64_t bytes = 0;+ std::string only;+ for (const auto& title : state_.leftover_titles)+ if (leftover_selected_.contains(title.title_id)) {+ bytes += title.bytes;+ only = (title.name.empty() ? title.title_id : title.name) + " (" + title.title_id + ")";+ }+ pending_destructive_action_ = action_name;+ const bool one = leftover_selected_.size() == 1;+ ModalEntry confirmation{"confirmation", one ? "Delete leftover PS5 title?" : "Delete leftover PS5 titles?",+ state_.navigation.focus_key, {"cancel", "confirm-destructive"}, 0, true};+ confirmation.body = (one ? only + " and its PS5 Home tile are" : std::to_string(leftover_selected_.size()) ++ " leftover PS5 titles and their Home tiles are") + " deleted (" + format_bytes(bytes) + "). " ++ (one ? "Its" : "Their") + " saves and game files are kept.";+ open_modal(std::move(confirmation));+ } else if (action_name == "confirm-destructive" && pending_destructive_action_ == "leftover-selection-delete") {+ pending_destructive_action_.clear();+ for (const auto& title : state_.leftover_titles) {+ if (!leftover_selected_.contains(title.title_id) || leftover_queued(title.title_id)) continue;+ const auto id = title.title_id;+ std::erase_if(state_.leftover_deletions, [&](const LiveLeftoverDelete& deletion) { return deletion.title_id == id; });+ state_.leftover_deletions.push_back({id, title.name, "", ""});+ if (live()) pending_leftover_delete_requests_.push_back(id);+ else if (state_.leftover_deletions.size() == 1) leftover_delete_ticks_ = 0;+ }+ leftover_selected_.clear();+ state_.navigation.focus_key = state_.navigation.modals.front().opener_focus_key;+ state_.navigation.modals.clear();} else if (live() && action_name == "kept-manage") {if (state_.kept_bottles.empty()) return;kept_selected_.clear();@@ -7824,7 +7980,7 @@ void Simulation::activate() {}else if (kOfferGoBack && live() && action_name == "self-update-back-confirm") { close_modal(); request_self_update_restart("rollback"); }else if (action_name == "scenario-picker") open_modal({"scenarios", "Fixture scenarios", state_.navigation.focus_key,- {"scenario-default", "scenario-download-servers", "scenario-first-run", "scenario-signed-out", "scenario-qr-waiting", "scenario-offline", "scenario-empty", "scenario-no-results", "scenario-delayed-art", "scenario-failed-art", "scenario-install-ready", "scenario-unknown-size", "scenario-insufficient-space", "scenario-storage-disconnect", "scenario-paused", "scenario-download-failed", "scenario-verification-failed", "scenario-restart-recovery", "scenario-save-failure", "scenario-runtime-unavailable", "scenario-launch-failure", "scenario-crash", "scenario-stop-failure", "scenario-controller-disconnected", "scenario-reduced-motion", "scenario-stress", "scenario-import-empty", "scenario-import-candidates", "scenario-import-programs", "scenario-import-choice", "scenario-import-storage", "scenario-import-drop-choice", "scenario-import-drop-storage", "scenario-import-details", "scenario-import-copying", "scenario-import-library", "cancel"}, 0, false});+ {"scenario-default", "scenario-leftover-titles", "scenario-download-servers", "scenario-first-run", "scenario-signed-out", "scenario-qr-waiting", "scenario-offline", "scenario-empty", "scenario-no-results", "scenario-delayed-art", "scenario-failed-art", "scenario-install-ready", "scenario-unknown-size", "scenario-insufficient-space", "scenario-storage-disconnect", "scenario-paused", "scenario-download-failed", "scenario-verification-failed", "scenario-restart-recovery", "scenario-save-failure", "scenario-runtime-unavailable", "scenario-launch-failure", "scenario-crash", "scenario-stop-failure", "scenario-controller-disconnected", "scenario-reduced-motion", "scenario-stress", "scenario-import-empty", "scenario-import-candidates", "scenario-import-programs", "scenario-import-choice", "scenario-import-storage", "scenario-import-drop-choice", "scenario-import-drop-storage", "scenario-import-details", "scenario-import-copying", "scenario-import-library", "cancel"}, 0, false});else if (action_name.rfind("scenario-", 0) == 0) { state_.navigation.modals.clear(); scenario(action_name.substr(9)); }else if (action_name == "session-fixture-controls") open_modal({"session-controls", "Session fixture controls", state_.navigation.focus_key,{"advance-clock", "inject-stop-failure", "inject-crash", "cancel"}, 0, false});@@ -8407,6 +8563,17 @@ void Simulation::tick(int ticks) {}ApplyLiveDownloadServers(progress);}+ if (!state_.leftover_deletions.empty()) {+ auto& deletion = state_.leftover_deletions.front();+ ++leftover_delete_ticks_;+ deletion.step = leftover_delete_ticks_ < 3 ? "Removing PS5 title…" : "Deleting title files…";+ if (leftover_delete_ticks_ >= 6) {+ const auto id = deletion.title_id;+ std::erase_if(state_.leftover_titles, [&](const LiveLeftoverTitle& title) { return title.title_id == id; });+ state_.leftover_deletions.erase(state_.leftover_deletions.begin());+ leftover_delete_ticks_ = 0;+ }+ }advance_jobs();// A finished copy of an imported game: it plays from Playden's storage, not its folder.for (const auto& job : state_.jobs)diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex 68d9444..c711db4 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -258,6 +258,20 @@ struct LiveKeptBottle {std::uint64_t bytes = 0;bool operator==(const LiveKeptBottle&) const = default;};+// A PS5 title folder no install record owns; only its title is removed.+struct LiveLeftoverTitle {+ std::string title_id;+ std::string name;+ std::uint64_t bytes = 0;+ bool operator==(const LiveLeftoverTitle&) const = default;+};+struct LiveLeftoverDelete {+ std::string title_id;+ std::string name;+ std::string step; // empty while queued+ std::string failure;+ bool operator==(const LiveLeftoverDelete&) const = default;+};// A game that plays in place from a folder Playden doesn't manage (an imported game on a drive):// never in Installed games, its files never deleted.struct LiveExternalGame {@@ -619,6 +633,8 @@ struct State {std::size_t runtime_leftover_requests = 0; // live: unused settings requests to clean upLiveKitInfo kit; // live: the runtime kit in useLiveSelfUpdate self_update; // live: Playden's own update+ std::vector<LiveLeftoverTitle> leftover_titles;+ std::vector<LiveLeftoverDelete> leftover_deletions;std::vector<LiveKeptBottle> kept_bottles; // live: saves kept from uninstalled gamesstd::vector<LiveExternalGame> external_games; // live: games playing in place (imported)std::vector<LiveImportCandidate> import_candidates; // live: folders on the drives that could be imported@@ -779,6 +795,9 @@ public:[[nodiscard]] bool TakeRuntimeCleanupRequest();// Live mode: kept game data, deletions the player confirmed, and why an uninstall stopped.void UpdateKeptBottles(std::vector<LiveKeptBottle> kept);+ void UpdateLeftoverTitles(std::vector<LiveLeftoverTitle> titles);+ void UpdateLeftoverDeletions(std::vector<LiveLeftoverDelete> deletions);+ [[nodiscard]] std::vector<std::string> TakeLeftoverDeleteRequests();// Live mode: games playing in place, and what the drives offer to import.void UpdateExternalGames(std::vector<LiveExternalGame> games);void UpdateImportCandidates(std::vector<LiveImportCandidate> candidates, bool scanning);@@ -993,10 +1012,13 @@ private:std::set<GameId> live_installed_ids_;std::set<GameId> pending_uninstalls_;std::vector<GameId> pending_kept_delete_requests_;+ std::vector<std::string> pending_leftover_delete_requests_;+ int leftover_delete_ticks_ = 0;std::vector<std::pair<GameId, MaintenanceKind>> pending_maintenance_requests_;std::vector<GameId> pending_activity_requests_;bool uninstall_delete_saves_ = false; // the uninstall dialog's choicestd::set<GameId> kept_selected_; // the kept game data manager's checked games+ std::set<std::string> leftover_selected_; // the leftover titles manager's checked title IDs// Installed games (Settings > Storage): the checked games and the list's order.std::set<GameId> installed_selected_;bool installed_by_played_ = false; // false: largest first; true: never played, then the oldest@@ -1111,6 +1133,8 @@ private:void advance_jobs();[[nodiscard]] std::vector<std::string> game_settings_actions() const;[[nodiscard]] std::vector<std::string> kept_manager_actions() const;+ [[nodiscard]] std::vector<std::string> leftover_manager_actions() const;+ [[nodiscard]] bool leftover_queued(const std::string& title_id) const;// The Import sheet: Look for games, then the candidates grouped by drive (headings never take// the focus), then Close. Opened from Startup, Home's empty state and Settings › Library.[[nodiscard]] std::vector<std::string> import_sheet_actions() const;diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex cf82cde..064e921 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -2048,13 +2048,13 @@ class Render::Implelse{// Preparing or uninstalling: the actual step, with a spinner; no percentage or time is made up.- const char *label = entry->uninstall ? "Uninstalling" : "Preparing";+ const char *label = entry->leftover ? "Deleting title" : entry->uninstall ? "Uninstalling" : "Preparing";const float status_width = fonts_.semibold.measure(label, 24.0F);spinner(right - status_width - 22.0F, top + 36.0F, 9.0F, kBlue);ui::text(scene_, fonts_.semibold, label, right, top + 44.0F, 24.0F, kBlue, gfx::Align::right);ui::text(scene_, fonts_.regular, fit(fonts_.regular, entry->note.empty() ? "Starting…" : entry->note, 24.0F, 1100.0F),text_x, top + 88.0F, 24.0F, kText);- ui::text(scene_, fonts_.regular, entry->uninstall ? "Removing from this PS5" : "Setting up for this PS5", right,+ ui::text(scene_, fonts_.regular, entry->leftover || entry->uninstall ? "Removing from this PS5" : "Setting up for this PS5", right,top + 88.0F, 21.0F, kSecondary, gfx::Align::right);}focus_ring(scene_, box, amount, true);@@ -2400,8 +2400,9 @@ class Render::Implconst std::string& label = row.value;const float pill = fonts_.display.measure(label, 26.0F) + 64.0F;const gfx::Rect button{right - pill, head.cy() - 28.0F, pill, 56.0F};- scene_.bordered_rect(button, 8.0F, kBackground.with_alpha(0.0F), 2.0F, kText.with_alpha(0.2F));- ui::text(scene_, fonts_.display, label, button.x + 22.0F, button.cy() + 9.0F, 26.0F, kText);+ const gfx::Color ink = row.dangerous ? kRed : kText;+ scene_.bordered_rect(button, 8.0F, kBackground.with_alpha(0.0F), 2.0F, ink.with_alpha(0.2F));+ ui::text(scene_, fonts_.display, label, button.x + 22.0F, button.cy() + 9.0F, 26.0F, ink);const float chevron = button.x + button.w - 26.0F;scene_.line(chevron - 3.0F, button.cy() - 6.0F, chevron + 2.5F, button.cy(), 2.2F, kText);scene_.line(chevron + 2.5F, button.cy(), chevron - 3.0F, button.cy() + 6.0F, 2.2F, kText);@@ -3447,7 +3448,7 @@ class Render::Impl{static const std::map<std::string, std::string> names = {{"choice-picker", "Game settings"}, {"preset-picker", "Game settings"}, {"button-mapping", "Game settings"}, {"controller-tuning", "Game settings"},- {"game-settings", "Playden"}, {"game-maintenance", "Playden"}, {"kept-data", "Settings"}, {"installed-games", "Settings"},+ {"game-settings", "Playden"}, {"game-maintenance", "Playden"}, {"kept-data", "Settings"}, {"leftover-titles", "Settings"}, {"installed-games", "Settings"},{"download-server", "Settings"},{"import-games", "Library"}, {"import-programs", "Import games"}, {"steam-programs", "Setup"}, {"import-choice", "Import games"},{"import-storage", "Import games"},@@ -3496,7 +3497,7 @@ class Render::Implview.surface == "button-mapping" || view.surface == "controller-tuning" ||view.surface == "game-maintenance" ||view.surface == "controller" || view.surface == "logs" ||- view.surface == "storage" || view.surface == "install" || view.surface == "kept-data" ||+ view.surface == "storage" || view.surface == "install" || view.surface == "kept-data" || view.surface == "leftover-titles" ||view.surface == "download-server" ||view.surface == "installed-games" || view.surface == "import-games" ||view.surface == "import-programs" || view.surface == "steam-programs";@@ -3989,7 +3990,7 @@ class Render::Implreturn 54.0F + 12.0F;if (row.kind == RowKind::Heading || row.kind == RowKind::Separator)return 54.0F;- const bool checkbox = (view.surface == "kept-data" || view.surface == "installed-games" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&+ const bool checkbox = (view.surface == "kept-data" || view.surface == "leftover-titles" || view.surface == "installed-games" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&row.kind == RowKind::Toggle;const bool described = (settings_sheet || checkbox || view.surface == "installed-games" || import_sheet) && !row.subtitle.empty();return (described ? 96.0F + hint_extra(row) : 72.0F) + 12.0F;@@ -4062,7 +4063,7 @@ class Render::Impl// Game settings rows carry an effect line under the name (or the reason a row is// disabled), an accent dot when the player changed the value, and a tag.// Kept game data: each game is a checkbox row with its kept date under the name.- const bool checkbox = (view.surface == "kept-data" || view.surface == "installed-games" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&+ const bool checkbox = (view.surface == "kept-data" || view.surface == "leftover-titles" || view.surface == "installed-games" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&row.kind == RowKind::Toggle;const bool described = (settings_sheet || checkbox || view.surface == "installed-games" || import_sheet) && !row.subtitle.empty() && row.kind != RowKind::Heading;const gfx::Rect rect{bounds.x, y, bounds.w, described ? 96.0F + hint_extra(row) : 72.0F};diff --git a/tests/homebrew_library_graphical_test.cpp b/tests/homebrew_library_graphical_test.cppindex 74b374b..d0f3da1 100644--- a/tests/homebrew_library_graphical_test.cpp+++ b/tests/homebrew_library_graphical_test.cpp@@ -266,6 +266,30 @@ int main(int argc,char** argv) {assert(live.action("cross"));assert(live.action("focus:kept-toggle-43") && live.action("cross"));capture_live("kept-manager.png");+ // Leftover title folders: the title ID and size stay beside Delete, which always asks first.+ while(!live.state().navigation.modals.empty()) assert(live.action("circle"));+ live.UpdateLeftoverTitles({{"FAKE78001", "A Short Hike", 12'000'000}, {"FAKE78002", "Portal", 8'000'000}});+ assert(live.action("focus:settings-leftovers"));+ capture_live("settings-leftover-titles.png");+ assert(live.action("cross"));+ assert(live.action("focus:leftover-toggle-FAKE78002"));+ assert(live.action("cross"));+ capture_live("leftover-titles-manager.png");+ assert(live.action("focus:leftover-selection-delete"));+ assert(live.action("cross"));+ assert(live.state().navigation.focus_key == "cancel");+ capture_live("leftover-title-confirm.png");+ assert(live.action("circle"));+ assert(live.action("circle"));+ live.UpdateLeftoverDeletions({{"FAKE78001", "A Short Hike", "Deleting title files…", ""},+ {"FAKE78002", "Portal", "", ""}});+ live.action("l1"); live.action("l1");+ assert(live.state().navigation.route == Route::Downloads);+ capture_live("queue-leftover-titles.png");+ live.action("r1"); live.action("r1");+ assert(live.state().navigation.route == Route::Settings);+ live.UpdateLeftoverTitles({});+ live.UpdateLeftoverDeletions({});// Settings > Storage: the default drive's usage above the rows, then the installed games list.while(!live.state().navigation.modals.empty()) assert(live.action("circle"));live.UpdateVolumes({{"internal","Console storage",true,825'000'000'000ull,512'000'000'000ull}}, "internal");diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cppindex 3c94274..fdcc091 100644--- a/tests/homebrew_library_model_test.cpp+++ b/tests/homebrew_library_model_test.cpp@@ -3224,7 +3224,83 @@ void live_download_server_picker() {"Automatic clears the stored choice");}+void leftover_titles_require_confirmation_and_follow_the_queue() {+ auto model = make_live();+ model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});+ model.action("l1");+ check(!has_row(model, "settings-leftovers"), "no leftover row without titles");+ model.UpdateLeftoverTitles({{"FAKE78001", "Lost game (Steam)", 12'000'000}, {"FAKE78002", "", 3'000'000}});+ const auto* row = find_row(model, "settings-leftovers");+ check(row && row->title == "Leftover PS5 titles" && row->value == "2 titles · 15 MB" && row->section == "Storage" &&+ !has_row(model, "settings-leftover-FAKE78001"),+ "Storage has one Leftover PS5 titles row with their count and size, like Kept game data");+ activate(model, "settings-leftovers");+ check(model.state().navigation.modals.back().id == "leftover-titles" && model.view().surface == "leftover-titles",+ "the row opens the leftover titles manager");+ const auto* named = find_row(model, "leftover-toggle-FAKE78001");+ check(named && named->title == "Lost game (Steam)" && named->subtitle == "FAKE78001" && named->value == "12 MB" &&+ named->kind == RowKind::Toggle && !named->selected,+ "each title is a checkbox with its ID and size");+ check(find_row(model, "leftover-toggle-FAKE78002")->title == "FAKE78002", "an unnamed title uses its ID");+ check(!find_row(model, "leftover-selection-delete")->enabled, "nothing to delete before choosing");+ activate(model, "leftover-toggle-FAKE78001");+ check(find_row(model, "leftover-selection-delete")->value == "1 title · 12 MB", "Delete selected counts the choice");+ activate(model, "leftover-selection-delete");+ check(model.TakeLeftoverDeleteRequests().empty(), "opening the confirmation deletes nothing");+ check(model.state().navigation.focus_key == "cancel" &&+ model.state().navigation.modals.back().body.find("Lost game (Steam) (FAKE78001)") != std::string::npos &&+ model.state().navigation.modals.back().body.find("saves and game files are kept") != std::string::npos,+ "confirmation starts on Cancel and describes the deletion scope");+ activate(model, "cancel");+ check(model.TakeLeftoverDeleteRequests().empty() && model.state().navigation.modals.back().id == "leftover-titles",+ "Cancel deletes nothing and returns to the manager");+ activate(model, "leftover-select-all");+ activate(model, "leftover-selection-delete");+ check(model.state().navigation.modals.back().body.find("2 leftover PS5 titles") != std::string::npos,+ "several titles are named by count");+ activate(model, "confirm-destructive");+ check(model.TakeLeftoverDeleteRequests() == std::vector<std::string>{"FAKE78001", "FAKE78002"},+ "every confirmed title is requested, in list order");+ check(model.TakeLeftoverDeleteRequests().empty(), "requests are consumed once");+ check(model.state().navigation.modals.empty() && model.state().navigation.focus_key == "settings-leftovers",+ "confirming closes the manager and returns to the Storage row");+ model.UpdateLeftoverDeletions({{"FAKE78001", "Lost game (Steam)", "Removing PS5 title…", ""},+ {"FAKE78002", "", "", ""}});+ const auto layout = playden::homebrew::BuildQueueLayout(model.state());+ check(layout.preparation.active && layout.preparation.active->key == "prep-leftover-FAKE78001" &&+ layout.preparation.active->note == "Removing PS5 title…" && layout.preparation.waiting == 1 &&+ playden::homebrew::QueuePending(model.state()) == 2,+ "Queue keeps active and waiting titles distinct with the actual step");+ activate(model, "settings-leftovers");+ const auto* queued = find_row(model, "leftover-toggle-FAKE78002");+ check(queued && !queued->enabled && queued->subtitle == "FAKE78002 · Queued" &&+ find_row(model, "leftover-toggle-FAKE78001")->subtitle == "FAKE78001 · Removing PS5 title…",+ "a queued title shows its step and cannot be chosen again");+ check(!find_row(model, "leftover-select-all")->enabled, "Select all has nothing to choose while both are queued");+ model.UpdateLeftoverDeletions({{"FAKE78001", "Lost game (Steam)", "", "The PS5 refused removal."}});+ const auto stopped = playden::homebrew::BuildQueueLayout(model.state());+ check(stopped.preparation.attention == 1 && stopped.preparation.rows.front().note == "The PS5 refused removal.",+ "a failed leftover deletion remains visible in Queue");+ const auto* failed = find_row(model, "leftover-toggle-FAKE78001");+ check(failed && failed->enabled && failed->subtitle == "FAKE78001 · The PS5 refused removal.",+ "a failed title shows why and can be chosen again");+ activate(model, "leftover-toggle-FAKE78002");+ activate(model, "leftover-selection-delete");+ model.UpdateLeftoverTitles({{"FAKE78001", "Lost game (Steam)", 12'000'000}});+ activate(model, "confirm-destructive");+ check(model.TakeLeftoverDeleteRequests().empty(), "a title that disappeared while confirming is not requested");+ model.UpdateLeftoverDeletions({});+ activate(model, "settings-leftovers");+ activate(model, "leftover-toggle-FAKE78001");+ activate(model, "leftover-selection-delete");+ model.UpdateLeftoverTitles({});+ check(model.state().navigation.modals.empty() && !has_row(model, "settings-leftovers"),+ "the manager and its confirmation close and the row disappears when no leftovers remain");+ check(model.TakeLeftoverDeleteRequests().empty(), "closing the confirmation requested nothing");+}+int main() {+ leftover_titles_require_confirmation_and_follow_the_queue();live_download_server_picker();live_import_sheet_sends_requests();live_import_choice_and_details();diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex 3b44aa4..1c488af 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -5243,9 +5243,307 @@ void RelocationStopsWaitingWhenPlaydenCloses() {host.Shutdown();}+namespace {+constexpr const char* kLeftoverOperation = "00000000-0000-4000-8000-000000000001";++RuntimeHostConfig LeftoverConfig(Fixture& fixture) {+ auto config = fixture.Config();+ config.uuid = [] { return std::optional<std::string>(kLeftoverOperation); };+ config.removal_confirm_polls = 1;+ config.removal_poll_interval = std::chrono::milliseconds(1);+ // Removing a manual source does not itself register the title.+ config.registry_transport = [&fixture](const std::string& route, const std::string&) -> std::optional<std::string> {+ if (route != "/api/v1/games") { ++fixture.registry_mutations; return R"({"status":0})"; }+ if (!fixture.registered) return R"({"status":0,"games":[]})";+ return R"({"status":0,"games":[{"title_id":"FAKE78001","installed":true,"managed":true,)"+ R"("source_available":true,"source_type":"folder","path":"/data/homebrew/FAKE78001"}]})";+ };+ return config;+}++fs::path MakeLeftover(Fixture& fixture) {+ const auto title = fixture.root / "data/homebrew/FAKE78001";+ Write(title / "sce_sys/param.json", R"({"localizedParameters":{"en-US":{"titleName":"Left Behind"}}})", 0644);+ Write(title / "eboot.bin", "title-files", 0755);+ CHECK(chmod(title.c_str(), 0755) == 0);+ return title;+}+} // namespace++void DeletesLeftoverTitleAndResumesFailures() {+ // Listed, already absent, unavailable build, unavailable remover, refused and silent remover.+ for (int scenario = 0; scenario < 6; ++scenario) {+ Fixture fixture;+ auto config = LeftoverConfig(fixture);+ const auto title = MakeLeftover(fixture);+ fixture.registered = scenario != 1;+ unsigned calls = 0;+ if (scenario != 1 && scenario != 2)+ config.unregister_title = [&fixture, &calls, scenario](const std::string& id, const std::string& nonce) {+ CHECK(id == "FAKE78001" && nonce == kLeftoverOperation);+ ++calls;+ if (scenario == 3) return TitleRemoverResult{false, std::nullopt, "unavailable"};+ if (scenario == 4) return TitleRemoverResult{true, -1, "refused"};+ if (scenario == 5) return TitleRemoverResult{true, std::nullopt, "silent"};+ fixture.registered = false;+ return TitleRemoverResult{true, 0, "removed"};+ };+ const auto bottle = fixture.root / "data/playden/games/steam-220/save.dat";+ const auto files = fixture.root / "data/playden-games/steam-220/game.exe";+ Write(bottle, "saved-game", 0600);+ Write(files, "downloaded-game", 0644);+ {+ RuntimeHost host(config);+ CHECK(host.Start());+ const auto started = WaitFor(host, Started);+ CHECK(started.leftover_titles.size() == 1);+ CHECK(started.leftover_titles[0].title_id == "FAKE78001" && started.leftover_titles[0].name == "Left Behind");+ CHECK(started.leftover_titles[0].bytes > 11 && started.installs.empty());+ CHECK(host.DeleteLeftoverTitle("FAKE78001"));+ const auto done = WaitFor(host, [](const RuntimeSnapshot& s) { return s.leftover_deletes_handled == 1; });+ CHECK(!done.deleting_leftover_title && done.queued_leftover_deletes.empty());+ if (scenario <= 1) {+ CHECK(done.leftover_titles.empty() && done.leftover_delete_failures.empty());+ CHECK(!fs::exists(title));+ CHECK(!fs::exists(config.state_root / "leftover-FAKE78001.json"));+ CHECK(calls == (scenario == 0 ? 1 : 0));+ } else {+ CHECK(done.leftover_delete_failures.count("FAKE78001") == 1);+ CHECK(done.leftover_titles.size() == 1); // retry remains available after retire+ if (scenario == 2) {+ CHECK(fs::is_directory(title));+ CHECK(!fs::exists(config.state_root / "leftover-FAKE78001.json"));+ } else {+ CHECK(!fs::exists(title));+ const auto journal = config.state_root / "leftover-FAKE78001.json";+ struct stat info{};+ CHECK(lstat(journal.c_str(), &info) == 0 && (info.st_mode & 07777) == 0600);+ CHECK(Read(journal).find("\"step\":\"unregister\"") != std::string::npos);+ CHECK(fs::is_directory(config.state_root / "trash" / (std::string("FAKE78001-") + kLeftoverOperation)));+ if (scenario == 3) CHECK(done.leftover_delete_failures.at("FAKE78001").find("could not start") != std::string::npos);+ if (scenario == 4) CHECK(done.leftover_delete_failures.at("FAKE78001").find("0xffffffff") != std::string::npos);+ if (scenario == 5) CHECK(done.leftover_delete_failures.at("FAKE78001").find("has not confirmed") != std::string::npos);+ }+ }+ CHECK(Read(bottle) == "saved-game" && Read(files) == "downloaded-game");+ host.Shutdown();+ }+ if (scenario < 3) continue;+ config.unregister_title = [&fixture, &calls](const std::string&, const std::string&) {+ ++calls;+ fixture.registered = false;+ return TitleRemoverResult{true, 0, "removed"};+ };+ RuntimeHost restarted(config);+ CHECK(restarted.Start());+ const auto done = WaitFor(restarted, Started);+ CHECK(done.leftover_deletes_handled == 1 && done.leftover_titles.empty() && done.leftover_delete_failures.empty());+ CHECK(calls == 2 && !fixture.registered);+ CHECK(!fs::exists(config.state_root / "leftover-FAKE78001.json"));+ CHECK(fs::is_empty(config.state_root / "trash"));+ CHECK(Read(bottle) == "saved-game" && Read(files) == "downloaded-game");+ restarted.Shutdown();+ }+}++void LeftoverRemovalRevalidatesBeforeEffects() {+ for (int scenario = 0; scenario < 4; ++scenario) {+ Fixture fixture;+ auto config = LeftoverConfig(fixture);+ const auto title = MakeLeftover(fixture);+ unsigned calls = 0;+ config.unregister_title = [&calls](const std::string&, const std::string&) { ++calls; return TitleRemoverResult{}; };+ RuntimeHost host(config);+ CHECK(host.Start());+ CHECK(WaitFor(host, Started).leftover_titles.size() == 1);+ const auto original = title.parent_path() / "original";+ if (scenario == 0) {+ // Preserve the old inode so the new directory cannot accidentally reuse it.+ fs::rename(title, original);+ Write(title / "replacement", "another-title", 0644);+ } else if (scenario == 1) {+ fs::rename(title, original);+ CHECK(symlink(original.c_str(), title.c_str()) == 0);+ } else {+ fixture.activity->store(static_cast<int>(scenario == 2 ? NativeActivity::kActive : NativeActivity::kUnknown));+ }+ CHECK(host.DeleteLeftoverTitle("FAKE78001"));+ const auto done = WaitFor(host, [](const RuntimeSnapshot& s) { return s.leftover_deletes_handled == 1; });+ CHECK(done.leftover_delete_failures.count("FAKE78001") == 1 && calls == 0 && fixture.registry_mutations == 0);+ CHECK(fs::exists(title));+ CHECK(!fs::exists(config.state_root / "leftover-FAKE78001.json"));+ host.Shutdown();+ }+}++void LeftoverRemovalRecoversRetireWriteGap(int scenario) {+ Fixture fixture;+ auto config = LeftoverConfig(fixture);+ const auto title = MakeLeftover(fixture);+ fixture.registered = true;+ {+ RuntimeHost first(config);+ CHECK(first.Start());+ CHECK(WaitFor(first, Started).leftover_titles.size() == 1);+ first.Shutdown();+ }+ struct stat info{};+ CHECK(lstat(title.c_str(), &info) == 0);+ const auto text = std::string("{\"schema\":1,\"title\":\"FAKE78001\",\"operation_id\":\"") + kLeftoverOperation ++ "\",\"step\":\"retire\",\"device\":" + std::to_string(info.st_dev) + ",\"inode\":" ++ std::to_string(info.st_ino) + ",\"name\":\"Left Behind\",\"bytes\":11}\n";+ playden::Storage storage(config.state_root.string());+ CHECK(storage.WriteDurable("leftover-FAKE78001.json", playden::Bytes(text.begin(), text.end())).ok());+ const auto trash = config.state_root / "trash";+ fs::create_directory(trash);+ CHECK(chmod(trash.c_str(), 0700) == 0);+ const auto retired = trash / (std::string("FAKE78001-") + kLeftoverOperation);+ fs::rename(title, retired);+ if (scenario == 1) {+ fs::rename(retired, config.state_root / "protected-original");+ Write(retired / "replacement", "another-title", 0644);+ } else if (scenario == 2) {+ CHECK(chmod((config.state_root / "leftover-FAKE78001.json").c_str(), 0644) == 0);+ }+ unsigned calls = 0;+ config.unregister_title = [&fixture, &calls](const std::string&, const std::string&) {+ ++calls;+ fixture.registered = false;+ return TitleRemoverResult{true, 0, "removed"};+ };+ RuntimeHost restarted(config);+ CHECK(restarted.Start());+ const auto done = WaitFor(restarted, Started);+ if (scenario == 0) {+ CHECK(done.leftover_deletes_handled == 1 && done.leftover_titles.empty() && calls == 1);+ CHECK(!fs::exists(config.state_root / "leftover-FAKE78001.json") && fs::is_empty(trash));+ } else {+ CHECK(calls == 0 && fixture.registered && fixture.registry_mutations == 0);+ CHECK(fs::exists(config.state_root / "leftover-FAKE78001.json") && fs::is_directory(retired));+ if (scenario == 1) {+ CHECK(done.leftover_deletes_handled == 1);+ CHECK(done.leftover_delete_failures.at("FAKE78001").find("folder changed") != std::string::npos);+ CHECK(Read(retired / "replacement") == "another-title");+ CHECK(Read(config.state_root / "protected-original/eboot.bin") == "title-files");+ } else {+ CHECK(done.leftover_deletes_handled == 0);+ CHECK(Read(retired / "eboot.bin") == "title-files");+ }+ }+ restarted.Shutdown();+}++void LeftoverScanRequiresLoadedRecordsAndRepeatsAfterUninstall() {+ for (bool readable : {false, true}) {+ Fixture fixture;+ auto config = LeftoverConfig(fixture);+ if (!readable) {+ Write(config.state_root / "installs.json", "broken", 0600);+ CHECK(chmod(config.state_root.c_str(), 0700) == 0);+ MakeLeftover(fixture);+ }+ RuntimeHost host(config);+ CHECK(host.Start());+ const auto started = WaitFor(host, Started);+ if (!readable) {+ CHECK(started.status == RuntimeHostStatus::kUnavailable && started.leftover_titles.empty());+ CHECK(started.reason.find("Runtime install records are unavailable") != std::string::npos);+ } else {+ CHECK(started.leftover_titles.empty());+ MakeLeftover(fixture);+ host.Remove(999, false); // every completed uninstall refreshes the scan, including an absent title+ const auto refreshed = WaitFor(host, [](const RuntimeSnapshot& s) { return s.removals_handled == 1; });+ CHECK(refreshed.leftover_titles.size() == 1 && refreshed.leftover_titles[0].title_id == "FAKE78001");+ }+ host.Shutdown();+ }+}++void LeftoverDeletionSharesThePreparationAndUninstallQueue() {+ for (int scenario = 0; scenario < 3; ++scenario) {+ Fixture fixture;+ auto config = LeftoverConfig(fixture);+ MakeLeftover(fixture);+ std::promise<void> scanned, released;+ auto release = released.get_future().share();+ std::mutex order_mutex;+ std::vector<std::string> order;+ config.log = [&](const std::string& line) {+ if (line == "startup trash emptied") { scanned.set_value(); release.wait(); }+ std::lock_guard<std::mutex> lock(order_mutex);+ if (line.rfind("prepare result app=220", 0) == 0) order.push_back("prepare");+ if (line.rfind("remove result app=999", 0) == 0) order.push_back("uninstall");+ if (line == "leftover delete complete title=FAKE78001") order.push_back("leftover");+ };+ RuntimeHost host(config);+ CHECK(host.Start());+ CHECK(scanned.get_future().wait_for(std::chrono::seconds(5)) == std::future_status::ready);+ CHECK(host.Snapshot().leftover_titles.size() == 1);+ const auto prepare = [&] { host.Prepare(Hl2()); };+ const auto remove = [&] { host.Remove(999, false); };+ const auto leftover = [&] { CHECK(host.DeleteLeftoverTitle("FAKE78001")); };+ std::vector<std::string> expected;+ if (scenario == 0) { prepare(); leftover(); remove(); expected = {"prepare", "leftover", "uninstall"}; }+ if (scenario == 1) { leftover(); remove(); prepare(); expected = {"leftover", "uninstall", "prepare"}; }+ if (scenario == 2) { remove(); prepare(); leftover(); expected = {"uninstall", "prepare", "leftover"}; }+ CHECK(host.Snapshot().queued_leftover_deletes == std::vector<std::string>{"FAKE78001"});+ released.set_value();+ const auto done = WaitFor(host, [](const RuntimeSnapshot& s) {+ return s.prepares_handled == 1 && s.removals_handled == 1 && s.leftover_deletes_handled == 1;+ });+ CHECK(done.leftover_delete_failures.empty() && done.leftover_titles.empty());+ host.Shutdown();+ CHECK(order == expected);+ }+}++void LeftoverDeletionRefusesANewInstallUsingTheId() {+ Fixture fixture;+ auto config = LeftoverConfig(fixture);+ const auto title = MakeLeftover(fixture);+ config.host_namespace_prefix = fixture.root;+ config.package_paths.console_data_root = "/data";+ config.package_paths.host_data_root = fixture.root / "data";+ config.package_operations.hash_file = HashArtifactFile;+ config.package_operations.hash_bytes = HashArtifactBytes;+ config.package_operations.free_space_unverifiable = true;+ config.package_operations.validate_bottle = [](const fs::path& bottle) {+ return fs::is_regular_file(bottle / "system.reg") && fs::is_regular_file(bottle / "user.reg");+ };+ const auto kit = SyntheticKit(fixture.root / "kit");+ config.admit_kit = [&kit](std::string*) { return std::optional<RuntimeKit>(kit); };+ unsigned calls = 0;+ config.unregister_title = [&calls](const std::string&, const std::string&) { ++calls; return TitleRemoverResult{}; };+ // Preparation needs the fixture's registration hook; its source-removal mutation must never run.+ config.registry_transport = fixture.Config().registry_transport;+ Write(fixture.root / "data/homebrew/FAKE77031/games/220/hl2.exe", "existing-game", 0644);+ RuntimeHost host(config);+ CHECK(host.Start());+ CHECK(WaitFor(host, Started).leftover_titles.size() == 1);+ fs::rename(title, title.parent_path() / "original");+ host.Prepare(Hl2());+ const auto prepared = WaitFor(host, [](const RuntimeSnapshot& s) { return s.prepares_handled == 1; });+ CHECK(prepared.refusals.empty() && prepared.installs.size() == 1 && prepared.installs[0].title_id == "FAKE78001");+ const auto mutations = fixture.registry_mutations;+ // The scan is deliberately stale: the worker must recheck its authoritative records.+ CHECK(host.DeleteLeftoverTitle("FAKE78001"));+ const auto done = WaitFor(host, [](const RuntimeSnapshot& s) { return s.leftover_deletes_handled == 1; });+ CHECK(done.leftover_delete_failures.at("FAKE78001").find("now belongs to an installed game") != std::string::npos);+ CHECK(done.installs.size() == 1 && fs::is_regular_file(title / "eboot.bin"));+ CHECK(fixture.registry_mutations == mutations && calls == 0);+ CHECK(!fs::exists(config.state_root / "leftover-FAKE78001.json"));+ host.Shutdown();+}+int main(int argc, char** argv) {CHECK(argc == 2);g_runtime_dir = argv[1];+ LeftoverDeletionSharesThePreparationAndUninstallQueue();+ LeftoverDeletionRefusesANewInstallUsingTheId();+ DeletesLeftoverTitleAndResumesFailures();+ LeftoverRemovalRevalidatesBeforeEffects();+ for (int scenario = 0; scenario < 3; ++scenario) LeftoverRemovalRecoversRetireWriteGap(scenario);+ LeftoverScanRequiresLoadedRecordsAndRepeatsAfterUninstall();WorkerMovesGamesUnderPublicationLease();NoKitRefusesPreparationWithoutDurableEffects();ReloadKitAdmitsAKitInstalledWhileRunning();diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cppindex fed7387..43beb1b 100644--- a/tests/homebrew_simulation_test.cpp+++ b/tests/homebrew_simulation_test.cpp@@ -1414,6 +1414,39 @@ void synthetic_download_servers(const std::filesystem::path& fixtures, const std"the simulation profile keeps the choice across restarts");}+void leftover_titles_simulation_uses_controller_navigation(const std::filesystem::path& fixtures,+ const std::filesystem::path& profile) {+ using namespace playden::homebrew;+ Simulation simulation(fixtures, profile);+ check(simulation.scenario("leftover-titles"), "leftover title scenario exists");+ check(simulation.state().leftover_titles.size() == 2 &&+ simulation.state().navigation.focus_key == "settings-leftovers", "the Leftover PS5 titles row starts focused");+ simulation.action("cross");+ check(simulation.state().navigation.focus_key == "leftover-select-all", "the manager opens on Select all");+ simulation.action("down");+ simulation.action("down");+ check(simulation.state().navigation.focus_key == "leftover-toggle-FAKE78002", "Down reaches the second title");+ simulation.action("cross");+ simulation.action("focus:leftover-selection-delete");+ simulation.action("cross");+ check(simulation.state().navigation.focus_key == "cancel", "deletion starts on Cancel");+ simulation.action("circle");+ check(simulation.state().navigation.modals.back().id == "leftover-titles" &&+ simulation.state().leftover_deletions.empty(), "Circle returns to the manager without deleting");+ simulation.action("focus:leftover-selection-delete");+ simulation.action("cross");+ simulation.action("focus:confirm-destructive");+ simulation.action("cross");+ simulation.action("l1");+ simulation.action("l1");+ check(simulation.state().navigation.route == Route::Downloads, "L1 reaches Queue");+ simulation.tick(1);+ check(simulation.state().leftover_deletions.front().step == "Removing PS5 title…", "Queue starts title removal");+ simulation.tick(5);+ check(simulation.state().leftover_titles.size() == 1 && simulation.state().leftover_titles.front().title_id == "FAKE78001" &&+ simulation.state().leftover_deletions.empty(), "only the confirmed title is removed");+}+int main(int argc, char** argv) {check(argc == 2, "fixture directory argument is required");const std::filesystem::path fixtures(argv[1]);@@ -1422,6 +1455,7 @@ int main(int argc, char** argv) {clean();synthetic_download_servers(fixtures, profile);clean();+ leftover_titles_simulation_uses_controller_navigation(fixtures, profile);t01_authentication_ignores_late_approval(fixtures, profile);clean();t02_focus_and_nested_modal_restoration(fixtures, profile);