Skip to content

Truly independent web browser

LibWebView: Hand frontends a launch plan from leftover windows

sideshowbarkerc44ad4b8c756
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index 7b3c3bbf51b..c49f00db752 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -266,6 +266,11 @@ Application::~Application()
s_the = nullptr;
}
+SessionLaunchPolicy Application::launch_restore_policy() const
+{
+ return SessionLaunchPolicy::None;
+}
+
bool Application::claim_cpu_profiler(ProcessType process_type)
{
if (m_cpu_profiler_claimed || m_browser_options.profile_tool != ProfileTool::CPU || m_browser_options.profile_helper_process != process_type)
@@ -1706,10 +1711,17 @@ ErrorOr<void> Application::launch_services()
// Fall back without modifying the existing Sessions database.
auto session_store = [&]() -> ErrorOr<NonnullOwnPtr<SessionStore>> {
+ // A headless run, a browser that WebDriver drives, and one that logs process statistics never join a browser
+ // already running on their profile. Yet startup recovery would still rewrite the saved session, reset the
+ // unclean-exit count, and demote the open windows of a browser running on this profile. So each gets a
+ // transient store instead, leaving the Sessions database as the last run left it.
+ if (m_browser_options.headless_mode.has_value() || m_browser_options.webdriver_browser_endpoint.has_value() || m_stats_log)
+ return SessionStore::create();
+
auto session_database = TRY(Database::Database::create(database_path, "Sessions"sv, { .foreign_keys = Database::Database::ForeignKeys::Yes }));
if (TRY(SessionStore::migrate_schema(session_database)) != Database::MigrationOutcome::Success)
return Error::from_string_literal("Sessions database was created by a newer Ladybird version");
- return SessionStore::create(session_database);
+ return SessionStore::create(session_database, launch_restore_policy());
}();
if (session_store.is_error()) {
dbgln("Sessions will not be persisted this session: {}", session_store.error());
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.h
index 5c2faa667a2..4dbd1be97fc 100644
--- a/Libraries/LibWebView/Application.h
+++ b/Libraries/LibWebView/Application.h
@@ -127,6 +127,11 @@ public:
virtual bool supports_private_browsing_windows() const { return false; }
virtual bool supports_client_side_window_decorations() const { return false; }
virtual bool supports_picture_in_picture() const;
+
+ // What startup recovery does with the windows the last run left open. Only a frontend that shows the launch plan
+ // asks for more than None.
+ virtual SessionLaunchPolicy launch_restore_policy() const;
+
// Returns true if the platform sends momentum scroll events after a touchpad flick.
// If it does not, the compositor makes the fling.
virtual bool platform_reports_scroll_momentum() const { return true; }
diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.h
index 78b62662a48..3322ab830ed 100644
--- a/Libraries/LibWebView/Forward.h
+++ b/Libraries/LibWebView/Forward.h
@@ -78,6 +78,8 @@ struct SearchEngine;
struct WebContentOptions;
class WebContentPage;
+enum class SessionLaunchPolicy : u8;
+
}
namespace AK {
diff --git a/Libraries/LibWebView/SessionStore.cpp b/Libraries/LibWebView/SessionStore.cpp
index 338b6c4fa6f..6d87d5c6322 100644
--- a/Libraries/LibWebView/SessionStore.cpp
+++ b/Libraries/LibWebView/SessionStore.cpp
@@ -24,6 +24,11 @@ static constexpr u32 SESSIONS_SCHEMA_DIRECTIVE_STATE_VERSION = 3u;
static constexpr u32 SESSIONS_SCHEMA_DOCUMENT_POLICY_VERSION = 4u;
static constexpr u32 SESSIONS_SCHEMA_PINNED_TABS_VERSION = 5u;
static constexpr u32 SESSIONS_SCHEMA_SESSION_LIFECYCLE_VERSION = 6u;
+static constexpr u32 SESSIONS_SCHEMA_LAUNCH_RESTORE_VERSION = 7u;
+
+// After this many unclean exits in a row, launch restore stops, so a session that crashes the browser doesn't restore
+// into the same crash every time.
+static constexpr u32 UNCLEAN_EXITS_THAT_STOP_LAUNCH_RESTORE = 2;
static constexpr u32 MAX_CLOSED_TABS = 25;
static constexpr u32 MAX_CLOSED_WINDOWS = 5;
static constexpr size_t MAX_ACTIVE_URL_BYTES = 8uz * 1024 * 1024;
@@ -233,6 +238,13 @@ ErrorOr<Database::MigrationOutcome> SessionStore::PersistedStorage::migrate_sche
);
)#"sv,
},
+ {
+ .version = SESSIONS_SCHEMA_LAUNCH_RESTORE_VERSION,
+ .sql = R"#(
+ ALTER TABLE Sessions ADD COLUMN activation_sequence INTEGER NOT NULL DEFAULT 0;
+ ALTER TABLE Sessions ADD COLUMN restore_at_launch INTEGER NOT NULL DEFAULT 0;
+ )#"sv,
+ },
});
return database.migrate("Sessions"sv, migrations, mode);
@@ -255,8 +267,8 @@ ErrorOr<SessionStore::PersistedStorage> SessionStore::PersistedStorage::create(D
statements.update_tab_row = TRY(database.prepare_statement("UPDATE SessionTabs SET active_url = :active_url, current_used_step_index = :current_used_step_index, pinned = :pinned WHERE id = :id;"sv));
statements.update_tab_placement = TRY(database.prepare_statement("UPDATE SessionTabs SET session_id = :session_id, tab_ordinal = :tab_ordinal, pinned = :pinned WHERE id = :id;"sv));
statements.update_tab_parent = TRY(database.prepare_statement("UPDATE SessionTabs SET session_id = :session_id, tab_ordinal = :tab_ordinal WHERE id = :id;"sv));
- statements.update_session_closed = TRY(database.prepare_statement("UPDATE Sessions SET kind = :kind, closed_time = :closed_time, close_sequence = :close_sequence, source_window_id = :source_window_id, source_tab_index = :source_tab_index, origin = :origin, active_tab_index = :active_tab_index WHERE id = :id;"sv));
- statements.update_session_active_tab_index = TRY(database.prepare_statement("UPDATE Sessions SET active_tab_index = :active_tab_index WHERE id = :id;"sv));
+ statements.update_session_closed = TRY(database.prepare_statement("UPDATE Sessions SET kind = :kind, closed_time = :closed_time, close_sequence = :close_sequence, source_window_id = :source_window_id, source_tab_index = :source_tab_index, origin = :origin, active_tab_index = :active_tab_index, restore_at_launch = :restore_at_launch WHERE id = :id;"sv));
+ statements.update_session_metadata = TRY(database.prepare_statement("UPDATE Sessions SET active_tab_index = :active_tab_index, activation_sequence = :activation_sequence WHERE id = :id;"sv));
statements.delete_session = TRY(database.prepare_statement("DELETE FROM Sessions WHERE id = :id;"sv));
statements.delete_tab = TRY(database.prepare_statement("DELETE FROM SessionTabs WHERE id = :id;"sv));
statements.prune_closed = TRY(database.prepare_statement(R"#(
@@ -268,7 +280,11 @@ ErrorOr<SessionStore::PersistedStorage> SessionStore::PersistedStorage::create(D
statements.select_max_close_sequence = TRY(database.prepare_statement("SELECT MAX(close_sequence) AS maximum_id FROM Sessions;"sv));
statements.select_closed_sessions = TRY(database.prepare_statement("SELECT id, closed_time, close_sequence, source_window_id, source_tab_index, origin, active_tab_index FROM Sessions WHERE kind = :kind ORDER BY close_sequence DESC, closed_time DESC, id DESC LIMIT :max_units;"sv));
statements.select_session_tabs = TRY(database.prepare_statement("SELECT id, tab_ordinal, active_url, current_used_step_index, pinned FROM SessionTabs WHERE session_id = :session_id ORDER BY tab_ordinal;"sv));
- statements.select_open_sessions = TRY(database.prepare_statement("SELECT id FROM Sessions WHERE kind = :open_window_kind ORDER BY id;"sv));
+ statements.select_max_activation_sequence = TRY(database.prepare_statement("SELECT MAX(activation_sequence) AS maximum_id FROM Sessions;"sv));
+ statements.select_open_sessions = TRY(database.prepare_statement("SELECT id, active_tab_index, activation_sequence FROM Sessions WHERE kind = :open_window_kind ORDER BY activation_sequence, id;"sv));
+ statements.select_restore_at_launch_session = TRY(database.prepare_statement("SELECT id, active_tab_index, activation_sequence FROM Sessions WHERE kind = :closed_window_kind AND restore_at_launch != 0 ORDER BY close_sequence DESC, id DESC LIMIT 1;"sv));
+ statements.clear_restore_at_launch = TRY(database.prepare_statement("UPDATE Sessions SET restore_at_launch = 0 WHERE restore_at_launch != 0;"sv));
+ statements.reopen_closed_session = TRY(database.prepare_statement("UPDATE Sessions SET kind = :open_window_kind, closed_time = 0, close_sequence = 0, source_window_id = NULL, source_tab_index = NULL, origin = :origin WHERE id = :id;"sv));
statements.recover_open_session = TRY(database.prepare_statement("UPDATE Sessions SET kind = :closed_window_kind, closed_time = :closed_time, close_sequence = :close_sequence, source_window_id = NULL, source_tab_index = NULL, origin = :origin WHERE id = :id;"sv));
statements.delete_empty_open_sessions = TRY(database.prepare_statement("DELETE FROM Sessions WHERE kind = :open_window_kind AND NOT EXISTS (SELECT 1 FROM SessionTabs WHERE session_id = Sessions.id);"sv));
statements.select_lifecycle = TRY(database.prepare_statement("SELECT clean_exit, consecutive_unclean_exits FROM SessionLifecycle WHERE id = 1;"sv));
@@ -278,11 +294,11 @@ ErrorOr<SessionStore::PersistedStorage> SessionStore::PersistedStorage::create(D
return PersistedStorage { database, move(statements) };
}
-ErrorOr<NonnullOwnPtr<SessionStore>> SessionStore::create(Database::Database& database)
+ErrorOr<NonnullOwnPtr<SessionStore>> SessionStore::create(Database::Database& database, SessionLaunchPolicy policy)
{
auto persisted_storage = TRY(PersistedStorage::create(database));
auto store = adopt_own(*new SessionStore(move(persisted_storage)));
- TRY(store->run_startup_recovery(UnixDateTime::now()));
+ TRY(store->run_startup_recovery(UnixDateTime::now(), policy));
store->m_flush_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(FLUSH_TIMER_INTERVAL_MILLISECONDS), [store = store.ptr()]() {
store->flush_dirty_state();
@@ -404,6 +420,16 @@ void SessionStore::TransientStorage::set_active_tab(SessionTabId tab_id)
window->value.metadata_dirty = true;
}
+void SessionStore::TransientStorage::set_activation_sequence(SessionWindowId window_id, i64 activation_sequence)
+{
+ auto window = m_windows.find(window_id);
+ if (window == m_windows.end() || window->value.activation_sequence == activation_sequence)
+ return;
+
+ window->value.activation_sequence = activation_sequence;
+ window->value.metadata_dirty = true;
+}
+
void SessionStore::TransientStorage::set_tab_order(SessionWindowId window_id, Vector<SessionTabId> const& ordered_tabs)
{
auto window = m_windows.find(window_id);
@@ -600,12 +626,7 @@ ErrorOr<void> SessionStore::PersistedStorage::apply_window_metadata(WindowMetada
++tab_ordinal;
}
- TRY(database->try_execute_bound_statement(statements.update_session_active_tab_index, [&](auto& bind) -> ErrorOr<void> {
- TRY(bind("active_tab_index"sv, write.active_tab_index));
- TRY(bind("id"sv, write.id));
- return {};
- }));
- return {};
+ return write_session_metadata(write.id, write.active_tab_index, write.activation_sequence);
}
ErrorOr<void> SessionStore::PersistedStorage::insert_closed_unit_row(ClosedUnitWrite const& write)
@@ -724,6 +745,7 @@ ErrorOr<void> SessionStore::PersistedStorage::close_window(ClosedWindowWrite con
TRY(bind("source_tab_index"sv, write.unit.source_tab_index));
TRY(bind("origin"sv, to_underlying(write.unit.origin)));
TRY(bind("active_tab_index"sv, write.unit.active_tab_index));
+ TRY(bind("restore_at_launch"sv, i64 { write.unit.restore_at_launch ? 1 : 0 }));
TRY(bind("id"sv, write.unit.id));
return {};
}));
@@ -763,37 +785,209 @@ ErrorOr<void> SessionStore::PersistedStorage::clear_closed_units(ClearClosedUnit
});
}
-ErrorOr<SessionStore::RecoveryResult> SessionStore::PersistedStorage::recover_open_windows(RecoveryWrite const& write, IdAllocator& close_sequence_allocator)
+ErrorOr<void> SessionStore::PersistedStorage::write_session_metadata(SessionWindowId window_id, i64 active_tab_index, i64 activation_sequence)
+{
+ return database->try_execute_bound_statement(statements.update_session_metadata, [&](auto& bind) -> ErrorOr<void> {
+ TRY(bind("active_tab_index"sv, active_tab_index));
+ TRY(bind("activation_sequence"sv, activation_sequence));
+ TRY(bind("id"sv, window_id));
+ return {};
+ });
+}
+
+ErrorOr<void> SessionStore::PersistedStorage::clear_restore_at_launch()
+{
+ return database->try_execute_bound_statement(statements.clear_restore_at_launch, [](auto&) -> ErrorOr<void> { return {}; });
+}
+
+ErrorOr<void> SessionStore::PersistedStorage::demote_to_startup_recovery_unit(SessionWindowId window_id, UnixDateTime recovered_at, IdAllocator& close_sequence_allocator)
+{
+ auto close_sequence = TRY(close_sequence_allocator.allocate());
+ return database->try_execute_bound_statement(statements.recover_open_session, [&](auto& bind) -> ErrorOr<void> {
+ TRY(bind("closed_window_kind"sv, to_underlying(UnitKind::ClosedWindow)));
+ TRY(bind("closed_time"sv, recovered_at));
+ TRY(bind("close_sequence"sv, close_sequence));
+ TRY(bind("origin"sv, to_underlying(ClosedSessionUnit::Origin::StartupRecovery)));
+ TRY(bind("id"sv, window_id));
+ return {};
+ });
+}
+
+ErrorOr<void> SessionStore::PersistedStorage::reopen_session(SessionWindowId window_id)
+{
+ return database->try_execute_bound_statement(statements.reopen_closed_session, [&](auto& bind) -> ErrorOr<void> {
+ TRY(bind("open_window_kind"sv, to_underlying(UnitKind::OpenWindow)));
+ TRY(bind("origin"sv, to_underlying(ClosedSessionUnit::Origin::CloseAction)));
+ TRY(bind("id"sv, window_id));
+ return {};
+ });
+}
+
+// A row that fails validation is deleted, so the window keeps only tabs it can restore.
+ErrorOr<Vector<SessionStore::RecoveredTab>> SessionStore::PersistedStorage::read_recovered_tabs(SessionWindowId window_id)
+{
+ Vector<RecoveredTab> tabs;
+ Vector<SessionTabId> corrupt_tabs;
+ TRY(database->try_execute_bound_statement(
+ statements.select_session_tabs,
+ [&](auto& bind) -> ErrorOr<void> {
+ return bind("session_id"sv, window_id);
+ },
+ [&](Database::ResultRow& row) -> ErrorOr<void> {
+ auto tab_id = row.read_integer<SessionTabId>("id"sv);
+ if (tab_id.is_error())
+ return {};
+ auto tab = [&]() -> ErrorOr<RecoveredTab> {
+ auto url = URL::Parser::basic_parse(TRY(row.read_text("active_url"sv, MAX_ACTIVE_URL_BYTES)));
+ if (!url.has_value())
+ return Error::from_string_literal("Session tab has an unparseable active url");
+ return RecoveredTab {
+ .id = tab_id.value(),
+ .ordinal = TRY(row.read_integer<i64>("tab_ordinal"sv)),
+ .url = url.release_value(),
+ .current_used_step_index = TRY(row.read_integer<size_t>("current_used_step_index"sv)),
+ .pinned = TRY(row.read_integer<i64>("pinned"sv)) != 0,
+ };
+ }();
+ if (tab.is_error())
+ corrupt_tabs.append(tab_id.value());
+ else
+ tabs.append(tab.release_value());
+ return {};
+ }));
+
+ // Buffered so the deletes never run while the select is still stepping.
+ for (auto tab_id : corrupt_tabs)
+ TRY(delete_tab_rows(tab_id));
+ return tabs;
+}
+
+ErrorOr<void> SessionStore::PersistedStorage::reparent_tabs(SessionWindowId window_id, Vector<RecoveredTab> const& tabs)
+{
+ i64 tab_ordinal = 0;
+ for (auto const& tab : tabs) {
+ TRY(database->try_execute_bound_statement(statements.update_tab_parent, [&](auto& bind) -> ErrorOr<void> {
+ TRY(bind("session_id"sv, window_id));
+ TRY(bind("tab_ordinal"sv, tab_ordinal));
+ TRY(bind("id"sv, tab.id));
+ return {};
+ }));
+ ++tab_ordinal;
+ }
+ return {};
+}
+
+ErrorOr<SessionStore::RecoveryResult> SessionStore::PersistedStorage::recover_open_windows(RecoveryWrite const& write, IdAllocator& session_id_allocator, IdAllocator& close_sequence_allocator)
{
RecoveryResult result;
TRY(database->transaction([&]() -> ErrorOr<void> {
result.consecutive_unclean_exits = TRY(record_run_start());
+ auto policy = result.consecutive_unclean_exits >= UNCLEAN_EXITS_THAT_STOP_LAUNCH_RESTORE ? SessionLaunchPolicy::None : write.policy;
TRY(database->try_execute_bound_statement(statements.delete_empty_open_sessions, [&](auto& bind) -> ErrorOr<void> {
return bind("open_window_kind"sv, to_underlying(UnitKind::OpenWindow));
}));
- Vector<SessionWindowId> open_windows;
+ struct Candidate {
+ SessionWindowId id { 0 };
+ i64 active_tab_index { 0 };
+ i64 activation_sequence { 0 };
+ bool was_open { true };
+ };
+ Vector<Candidate> candidates;
+ auto read_candidate = [&](Database::ResultRow& row, bool was_open) -> ErrorOr<void> {
+ candidates.append({
+ .id = TRY(row.read_integer<SessionWindowId>("id"sv)),
+ .active_tab_index = TRY(row.read_integer<i64>("active_tab_index"sv)),
+ .activation_sequence = TRY(row.read_integer<i64>("activation_sequence"sv)),
+ .was_open = was_open,
+ });
+ return {};
+ };
TRY(database->try_execute_bound_statement(
statements.select_open_sessions,
[&](auto& bind) -> ErrorOr<void> {
return bind("open_window_kind"sv, to_underlying(UnitKind::OpenWindow));
},
- [&](Database::ResultRow& row) -> ErrorOr<void> {
- open_windows.append(TRY(row.read_integer<SessionWindowId>("id"sv)));
- return {};
- }));
- for (auto window_id : open_windows) {
- auto close_sequence = TRY(close_sequence_allocator.allocate());
- TRY(database->try_execute_bound_statement(statements.recover_open_session, [&](auto& bind) -> ErrorOr<void> {
- TRY(bind("closed_window_kind"sv, to_underlying(UnitKind::ClosedWindow)));
- TRY(bind("closed_time"sv, write.recovered_at));
- TRY(bind("close_sequence"sv, close_sequence));
- TRY(bind("origin"sv, to_underlying(ClosedSessionUnit::Origin::StartupRecovery)));
- TRY(bind("id"sv, window_id));
- return {};
- }));
+ [&](Database::ResultRow& row) { return read_candidate(row, true); }));
+
+ // With no window left open, the last window closed counts as left open.
+ if (candidates.is_empty() && policy != SessionLaunchPolicy::None) {
+ TRY(database->try_execute_bound_statement(
+ statements.select_restore_at_launch_session,
+ [&](auto& bind) -> ErrorOr<void> {
+ return bind("closed_window_kind"sv, to_underlying(UnitKind::ClosedWindow));
+ },
+ [&](Database::ResultRow& row) { return read_candidate(row, false); }));
+ }
+ TRY(clear_restore_at_launch());
+
+ for (auto const& candidate : candidates) {
+ if (policy == SessionLaunchPolicy::None) {
+ if (candidate.was_open)
+ TRY(demote_to_startup_recovery_unit(candidate.id, write.recovered_at, close_sequence_allocator));
+ continue;
+ }
+
+ auto tabs = TRY(read_recovered_tabs(candidate.id));
+ auto active_tab = tabs.find_first_index_if([&](auto const& tab) { return tab.ordinal == candidate.active_tab_index; });
+
+ Vector<RecoveredTab> pinned_tabs;
+ Vector<RecoveredTab> unpinned_tabs;
+ Optional<size_t> active_pinned_tab;
+ Optional<size_t> active_unpinned_tab;
+ for (size_t i = 0; i < tabs.size(); ++i) {
+ auto is_active = active_tab == i;
+ if (tabs[i].pinned) {
+ if (is_active)
+ active_pinned_tab = pinned_tabs.size();
+ pinned_tabs.append(move(tabs[i]));
+ } else {
+ if (is_active)
+ active_unpinned_tab = unpinned_tabs.size();
+ unpinned_tabs.append(move(tabs[i]));
+ }
+ }
+
+ if (policy == SessionLaunchPolicy::Everything) {
+ if (pinned_tabs.is_empty() && unpinned_tabs.is_empty()) {
+ TRY(delete_session_rows(candidate.id));
+ continue;
+ }
+ if (!candidate.was_open)
+ TRY(reopen_session(candidate.id));
+
+ // The pinned tabs always lead their window, so a saved order with an unpinned tab ahead of a pinned one
+ // is put right here, with the same tab active.
+ auto active_tab_index = index_as_i64(active_pinned_tab.value_or(active_unpinned_tab.has_value() ? pinned_tabs.size() + *active_unpinned_tab : 0));
+ auto window_tabs = move(pinned_tabs);
+ window_tabs.extend(move(unpinned_tabs));
+ TRY(reparent_tabs(candidate.id, window_tabs));
+ TRY(write_session_metadata(candidate.id, active_tab_index, candidate.activation_sequence));
+ result.windows.append({ .id = candidate.id, .tabs = move(window_tabs), .active_tab_index = active_tab_index, .activation_sequence = candidate.activation_sequence });
+ continue;
+ }
+
+ if (!pinned_tabs.is_empty()) {
+ auto pinned_window_id = TRY(session_id_allocator.allocate());
+ TRY(insert_open_window(pinned_window_id));
+ TRY(reparent_tabs(pinned_window_id, pinned_tabs));
+ auto pinned_active_tab_index = index_as_i64(active_pinned_tab.value_or(0));
+ TRY(write_session_metadata(pinned_window_id, pinned_active_tab_index, candidate.activation_sequence));
+ result.windows.append({ .id = pinned_window_id, .tabs = move(pinned_tabs), .active_tab_index = pinned_active_tab_index, .activation_sequence = candidate.activation_sequence });
+ }
+
+ if (unpinned_tabs.is_empty()) {
+ // Any tab rows that were kept have moved, so deleting the window takes nothing else with it.
+ TRY(delete_session_rows(candidate.id));
+ } else {
+ TRY(reparent_tabs(candidate.id, unpinned_tabs));
+ TRY(write_session_metadata(candidate.id, index_as_i64(active_unpinned_tab.value_or(0)), candidate.activation_sequence));
+ if (candidate.was_open)
+ TRY(demote_to_startup_recovery_unit(candidate.id, write.recovered_at, close_sequence_allocator));
+ }
}
+
TRY(prune_closed_units(UnitKind::ClosedTab, write.closed_tab_limit));
return prune_closed_units(UnitKind::ClosedWindow, write.closed_window_limit);
}));
@@ -884,6 +1078,7 @@ ErrorOr<SessionStore::IdAllocators> SessionStore::PersistedStorage::create_id_al
.session_ids = TRY(IdAllocator::create_from_maximum(database, statements.select_max_session_id)),
.tab_ids = TRY(IdAllocator::create_from_maximum(database, statements.select_max_tab_id)),
.close_sequences = TRY(IdAllocator::create_from_maximum(database, statements.select_max_close_sequence)),
+ .activation_sequences = TRY(IdAllocator::create_from_maximum(database, statements.select_max_activation_sequence)),
};
}
@@ -1218,28 +1413,46 @@ u32 SessionStore::max_closed_units(UnitKind kind)
return kind == UnitKind::ClosedTab ? MAX_CLOSED_TABS : MAX_CLOSED_WINDOWS;
}
-ErrorOr<void> SessionStore::run_startup_recovery(UnixDateTime recovered_at)
+ErrorOr<void> SessionStore::run_startup_recovery(UnixDateTime recovered_at, SessionLaunchPolicy policy)
{
auto allocators = TRY(m_persisted_storage->create_id_allocators());
m_session_id_allocator = allocators.session_ids;
m_tab_id_allocator = allocators.tab_ids;
m_close_sequence_allocator = allocators.close_sequences;
+ m_activation_sequence_allocator = allocators.activation_sequences;
auto recovery = TRY(m_persisted_storage->recover_open_windows({
.recovered_at = canonicalized_to_milliseconds(recovered_at),
.closed_tab_limit = max_closed_units(UnitKind::ClosedTab),
.closed_window_limit = max_closed_units(UnitKind::ClosedWindow),
+ .policy = policy,
},
- m_close_sequence_allocator));
+ m_session_id_allocator, m_close_sequence_allocator));
m_consecutive_unclean_exits = recovery.consecutive_unclean_exits;
+ for (auto& window : recovery.windows) {
+ m_transient_storage.open_window(window.id);
+ RestoredSessionWindow restored { .window_id = window.id, .tabs = {}, .active_tab_index = window.active_tab_index };
+ for (auto& tab : window.tabs) {
+ restored.tabs.append({ .tab_id = tab.id, .url = tab.url, .pinned = tab.pinned });
+ (void)m_transient_storage.open_tab(window.id, tab.id,
+ OpenTab { .window_id = window.id, .url = move(tab.url), .current_used_step_index = tab.current_used_step_index, .history = {}, .dirty = false, .pinned = tab.pinned });
+ }
+ if (auto active_tab_index = index_as_size(window.active_tab_index); active_tab_index.has_value() && *active_tab_index < restored.tabs.size())
+ m_transient_storage.set_active_tab(restored.tabs[*active_tab_index].tab_id);
+ m_transient_storage.set_activation_sequence(window.id, window.activation_sequence);
+ // Recovery already wrote these windows' rows as they stand.
+ m_transient_storage.mark_window_metadata_clean(window.id);
+ m_launch_plan.append(move(restored));
+ }
+
m_transient_storage.set_closed_units(TRY(m_persisted_storage->load_closed_units()));
return {};
}
SessionStore::WindowMetadataWrite SessionStore::window_metadata_write(SessionWindowId window_id, OpenWindow const& window) const
{
- WindowMetadataWrite write { .id = window_id, .tabs_in_order = window.tabs, .pinned_tabs = {}, .active_tab_index = 0 };
+ WindowMetadataWrite write { .id = window_id, .tabs_in_order = window.tabs, .pinned_tabs = {}, .active_tab_index = 0, .activation_sequence = window.activation_sequence };
for (auto tab_id : window.tabs) {
if (auto const* tab = m_transient_storage.find_tab(tab_id); tab && tab->pinned)
write.pinned_tabs.set(tab_id);
@@ -1269,7 +1482,7 @@ Optional<SessionStore::WindowMetadataWrite> SessionStore::remaining_window_write
for (auto const& pending : m_pending_window_closes) {
if (pending.window_id != window_id)
continue;
- WindowMetadataWrite write { .id = window_id, .tabs_in_order = {}, .pinned_tabs = {}, .active_tab_index = 0 };
+ WindowMetadataWrite write { .id = window_id, .tabs_in_order = {}, .pinned_tabs = {}, .active_tab_index = 0, .activation_sequence = pending.activation_sequence };
for (auto const& member : pending.members) {
if (member.tab_id == closing_tab)
continue;
@@ -1354,8 +1567,15 @@ ErrorOr<void> SessionStore::drain_window_metadata()
ErrorOr<SessionWindowId> SessionStore::window_opened()
{
auto window_id = TRY(m_session_id_allocator.allocate());
- if (m_persisted_storage.has_value())
+ if (m_persisted_storage.has_value()) {
TRY(m_persisted_storage->insert_open_window(window_id));
+ // A window that opens after the last one closed means the closed one no longer counts as left open. The window
+ // is already tracked by now, so a failed clear is logged rather than failing the open.
+ if (auto result = m_persisted_storage->clear_restore_at_launch(); result.is_error() && history_debug_enabled())
+ dbgln("[History] Failed to clear the restore-at-launch flag: {}", result.error());
+ }
+ for (auto& pending : m_pending_window_closes)
+ pending.restore_at_launch = false;
m_transient_storage.open_window(window_id);
return window_id;
}
@@ -1400,6 +1620,16 @@ ErrorOr<SessionWindowId> SessionStore::default_window()
return *m_transient_storage.default_window;
}
+void SessionStore::window_activated(SessionWindowId window_id)
+{
+ if (!m_transient_storage.find_window(window_id))
+ return;
+ auto activation_sequence = m_activation_sequence_allocator.allocate();
+ if (activation_sequence.is_error())
+ return;
+ m_transient_storage.set_activation_sequence(window_id, activation_sequence.value());
+}
+
ErrorOr<SessionTabId> SessionStore::tab_opened(TabOpened opened)
{
// A crash before the tab's first flush must not leave an unparseable URL that
@@ -1619,6 +1849,7 @@ ErrorOr<void> SessionStore::finish_window_close(PendingWindowClose const& pendin
.source_tab_index = {},
.origin = ClosedSessionUnit::Origin::CloseAction,
.active_tab_index = min(pending.active_tab_index, index_as_i64(pending.members.size() - 1)),
+ .restore_at_launch = pending.restore_at_launch,
},
.members = {},
.retention_limit = max_closed_units(UnitKind::ClosedWindow),
@@ -1783,6 +2014,9 @@ ErrorOr<void> SessionStore::window_closing(WindowClosing closing)
auto closed_at = canonicalized_to_milliseconds(closing.closed_at);
closing.active_tab_index = max(closing.active_tab_index, 0);
+ // The last window closing counts as left open, until another window opens.
+ auto restore_at_launch = m_transient_storage.window_count() == 1;
+
auto make_pending_close = [&](SessionCloseSequence close_sequence, bool discard) {
PendingWindowClose close {
.window_id = closing.window_id,
@@ -1791,6 +2025,8 @@ ErrorOr<void> SessionStore::window_closing(WindowClosing closing)
.closed_at = closed_at,
.close_sequence = close_sequence,
.discard = discard,
+ .restore_at_launch = restore_at_launch,
+ .activation_sequence = window->activation_sequence,
};
for (auto member_id : window->tabs) {
if (auto const* tab = m_transient_storage.find_tab(member_id))
@@ -1883,6 +2119,28 @@ bool SessionStore::has_closed_units() const
return m_transient_storage.has_closed_units();
}
+Vector<RestoredSessionWindow> SessionStore::take_launch_plan()
+{
+ return move(m_launch_plan);
+}
+
+Optional<SessionHistorySnapshot> SessionStore::load_tab_history(SessionTabId tab_id)
+{
+ auto const* tab = m_transient_storage.find_tab(tab_id);
+ if (!tab)
+ return {};
+ if (tab->dirty || !m_persisted_storage.has_value())
+ return tab->history;
+
+ auto snapshot = m_persisted_storage->load_tab_snapshot(tab_id, tab->current_used_step_index);
+ if (snapshot.is_error()) {
+ if (history_debug_enabled())
+ dbgln("[History] Failed to load tab {} history: {}", tab_id, snapshot.error());
+ return {};
+ }
+ return snapshot.release_value();
+}
+
ErrorOr<Optional<ClosedSessionUnit>> SessionStore::take_most_recently_closed()
{
auto const* unit = m_transient_storage.last_closed_unit();
diff --git a/Libraries/LibWebView/SessionStore.h b/Libraries/LibWebView/SessionStore.h
index 249bc7a8915..a607d21e921 100644
--- a/Libraries/LibWebView/SessionStore.h
+++ b/Libraries/LibWebView/SessionStore.h
@@ -46,8 +46,32 @@ struct ClosedSessionUnit {
Origin origin { Origin::CloseAction };
};
-// Persists live windows and tabs plus a bounded recently-closed stack. State updates coalesce;
-// lifecycle mutations write through. Startup recovers leftover open windows.
+// What startup recovery does with the windows the last run left open.
+enum class SessionLaunchPolicy : u8 {
+ // Every leftover window becomes a closed unit on the Reopen Closed Window stack.
+ None,
+ // Each leftover window's pinned tabs come back in a window of their own, and the rest becomes a closed unit.
+ PinnedOnly,
+ // Every leftover window comes back whole.
+ Everything,
+};
+
+struct RestoredSessionTab {
+ SessionTabId tab_id { 0 };
+ URL::URL url;
+ bool pinned { false };
+};
+
+// A window that startup recovery kept open for the frontend to show, with its tabs in order.
+struct RestoredSessionWindow {
+ SessionWindowId window_id { 0 };
+ Vector<RestoredSessionTab> tabs;
+ i64 active_tab_index { 0 };
+};
+
+// Persists live windows and tabs plus a bounded recently-closed stack. State updates coalesce; lifecycle mutations
+// write through. At startup, recovery hands the windows the last run left open to the frontend, or to the closed stack,
+// as its launch policy says.
class WEBVIEW_API SessionStore {
AK_MAKE_NONCOPYABLE(SessionStore);
AK_MAKE_NONMOVABLE(SessionStore);
@@ -97,7 +121,7 @@ public:
static ErrorOr<Database::MigrationOutcome> migrate_schema(Database::Database&, Database::MigrationMode = Database::MigrationMode::Apply);
- static ErrorOr<NonnullOwnPtr<SessionStore>> create(Database::Database&);
+ static ErrorOr<NonnullOwnPtr<SessionStore>> create(Database::Database&, SessionLaunchPolicy = SessionLaunchPolicy::None);
static NonnullOwnPtr<SessionStore> create();
~SessionStore();
@@ -105,6 +129,7 @@ public:
ErrorOr<SessionWindowId> window_opened();
ErrorOr<void> window_closing(WindowClosing);
void window_detached(SessionWindowId);
+ void window_activated(SessionWindowId);
ErrorOr<SessionTabId> tab_opened(TabOpened);
void update_tab_state(TabStateUpdate);
ErrorOr<void> tab_closed(TabClosed);
@@ -132,6 +157,12 @@ public:
ErrorOr<Optional<ClosedSessionUnit>> take_most_recently_closed();
ErrorOr<void> remove_entries_accessed_since(UnixDateTime);
+ // The windows startup recovery kept open, in activation order with the frontmost last. It's handed over once.
+ Vector<RestoredSessionWindow> take_launch_plan();
+
+ // A tab's history: the store's own copy if it holds a newer one than the tab's rows, and otherwise the rows'.
+ Optional<SessionHistorySnapshot> load_tab_history(SessionTabId);
+
void flush_dirty_state();
Optional<TabStateUpdate> cached_tab_state_for_testing(SessionTabId) const;
@@ -162,6 +193,7 @@ private:
IdAllocator session_ids;
IdAllocator tab_ids;
IdAllocator close_sequences;
+ IdAllocator activation_sequences;
};
struct Statements {
@@ -172,16 +204,20 @@ private:
Database::StatementID update_tab_placement;
Database::StatementID update_tab_parent;
Database::StatementID update_session_closed;
- Database::StatementID update_session_active_tab_index;
+ Database::StatementID update_session_metadata;
Database::StatementID delete_session;
Database::StatementID delete_tab;
Database::StatementID prune_closed;
Database::StatementID select_max_session_id;
Database::StatementID select_max_tab_id;
Database::StatementID select_max_close_sequence;
+ Database::StatementID select_max_activation_sequence;
Database::StatementID select_closed_sessions;
Database::StatementID select_session_tabs;
Database::StatementID select_open_sessions;
+ Database::StatementID select_restore_at_launch_session;
+ Database::StatementID clear_restore_at_launch;
+ Database::StatementID reopen_closed_session;
Database::StatementID recover_open_session;
Database::StatementID delete_empty_open_sessions;
Database::StatementID select_lifecycle;
@@ -210,6 +246,7 @@ private:
Vector<SessionTabId> tabs;
SessionTabId active_tab { 0 };
bool metadata_dirty { false };
+ i64 activation_sequence { 0 };
};
struct ClosedTab {
@@ -257,6 +294,7 @@ private:
Vector<SessionTabId> tabs_in_order;
HashTable<SessionTabId> pinned_tabs;
i64 active_tab_index { 0 };
+ i64 activation_sequence { 0 };
};
struct OpenTabWrite {
@@ -273,6 +311,7 @@ private:
Optional<i64> source_tab_index;
ClosedSessionUnit::Origin origin { ClosedSessionUnit::Origin::CloseAction };
i64 active_tab_index { 0 };
+ bool restore_at_launch { false };
};
struct ClosedTabWrite {
@@ -311,10 +350,27 @@ private:
UnixDateTime recovered_at;
u32 closed_tab_limit { 0 };
u32 closed_window_limit { 0 };
+ SessionLaunchPolicy policy { SessionLaunchPolicy::None };
+ };
+
+ struct RecoveredTab {
+ SessionTabId id { 0 };
+ i64 ordinal { 0 };
+ URL::URL url;
+ size_t current_used_step_index { 0 };
+ bool pinned { false };
+ };
+
+ struct RecoveredWindow {
+ SessionWindowId id { 0 };
+ Vector<RecoveredTab> tabs;
+ i64 active_tab_index { 0 };
+ i64 activation_sequence { 0 };
};
struct RecoveryResult {
u32 consecutive_unclean_exits { 0 };
+ Vector<RecoveredWindow> windows;
};
// Applies mutations atomically while preserving persisted row invariants.
@@ -330,7 +386,8 @@ private:
ErrorOr<void> close_window(ClosedWindowWrite const&);
ErrorOr<void> discard_tab(DiscardTabWrite const&);
ErrorOr<void> clear_closed_units(ClearClosedUnitsWrite const&);
- ErrorOr<RecoveryResult> recover_open_windows(RecoveryWrite const&, IdAllocator& close_sequence_allocator);
+ ErrorOr<RecoveryResult> recover_open_windows(RecoveryWrite const&, IdAllocator& session_id_allocator, IdAllocator& close_sequence_allocator);
+ ErrorOr<void> clear_restore_at_launch();
ErrorOr<void> delete_session_rows(SessionWindowId);
ErrorOr<void> prune_closed_units(UnitKind, u32 max_units);
ErrorOr<void> write_lifecycle(bool clean_exit, u32 consecutive_unclean_exits);
@@ -349,6 +406,11 @@ private:
ErrorOr<void> apply_window_metadata(WindowMetadataWrite const&);
ErrorOr<void> insert_closed_unit_row(ClosedUnitWrite const&);
ErrorOr<void> delete_tab_rows(SessionTabId);
+ ErrorOr<Vector<RecoveredTab>> read_recovered_tabs(SessionWindowId);
+ ErrorOr<void> reparent_tabs(SessionWindowId, Vector<RecoveredTab> const&);
+ ErrorOr<void> write_session_metadata(SessionWindowId, i64 active_tab_index, i64 activation_sequence);
+ ErrorOr<void> demote_to_startup_recovery_unit(SessionWindowId, UnixDateTime recovered_at, IdAllocator& close_sequence_allocator);
+ ErrorOr<void> reopen_session(SessionWindowId);
};
// A close whose database write failed; the frontend tab or window is already gone, so the
@@ -370,6 +432,8 @@ private:
UnixDateTime closed_at;
SessionCloseSequence close_sequence { 0 };
bool discard { false };
+ bool restore_at_launch { false };
+ i64 activation_sequence { 0 };
};
// Owns in-memory membership, ordering, and dirty state.
@@ -380,11 +444,13 @@ private:
OpenTab const* find_tab(SessionTabId) const;
OpenWindow const* find_window(SessionWindowId) const;
Optional<size_t> tab_index(SessionTabId) const;
+ size_t window_count() const { return m_windows.size(); }
void set_tab_state(SessionTabId, Optional<SessionHistorySnapshot>, URL::URL, bool dirty);
bool set_tab_pinned(SessionTabId, bool pinned);
void mark_tab_flushed(SessionTabId, size_t current_used_step_index);
void set_active_tab(SessionTabId);
+ void set_activation_sequence(SessionWindowId, i64);
void set_tab_order(SessionWindowId, Vector<SessionTabId> const&);
Optional<SessionWindowId> move_tab(SessionTabId, SessionWindowId, size_t ordinal);
void remove_tab(SessionTabId);
@@ -425,7 +491,7 @@ private:
explicit SessionStore(Optional<PersistedStorage>);
- ErrorOr<void> run_startup_recovery(UnixDateTime recovered_at);
+ ErrorOr<void> run_startup_recovery(UnixDateTime recovered_at, SessionLaunchPolicy);
ErrorOr<void> flush_tab(SessionTabId, OpenTab const&);
ErrorOr<void> drain_window_metadata();
WindowMetadataWrite window_metadata_write(SessionWindowId, OpenWindow const&) const;
@@ -450,10 +516,12 @@ private:
Vector<WindowMetadataWrite> m_retired_window_metadata;
bool m_quitting { false };
u32 m_consecutive_unclean_exits { 0 };
+ Vector<RestoredSessionWindow> m_launch_plan;
IdAllocator m_session_id_allocator;
IdAllocator m_tab_id_allocator;
IdAllocator m_close_sequence_allocator;
+ IdAllocator m_activation_sequence_allocator;
};
}
diff --git a/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp b/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp
index 1a302b904b1..889f3087dec 100644
--- a/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp
+++ b/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp
@@ -533,6 +533,8 @@ TEST_CASE(snapshot_entries_saved_before_the_user_agent_initiated_column_load_as_
// Take the database back to the baseline schema, keeping the entry's row.
TRY_OR_FAIL(database->execute_raw(R"#(
+ ALTER TABLE Sessions DROP COLUMN restore_at_launch;
+ ALTER TABLE Sessions DROP COLUMN activation_sequence;
DROP TABLE SessionLifecycle;
ALTER TABLE SessionTabs DROP COLUMN pinned;
ALTER TABLE SessionPolicyContainers DROP COLUMN force_load_at_top;
@@ -544,7 +546,7 @@ TEST_CASE(snapshot_entries_saved_before_the_user_agent_initiated_column_load_as_
)#"sv));
auto migrated_statements = prepare_snapshot_tables(*database);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 6u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 7u });
auto loaded = TRY_OR_FAIL(load_session_history_snapshot(*database, migrated_statements, 42, 0));
EXPECT_EQ(loaded.entries.size(), 1uz);
diff --git a/Tests/LibWebView/TestSessionStore.cpp b/Tests/LibWebView/TestSessionStore.cpp
index a5a9579cee9..0701bbd9468 100644
--- a/Tests/LibWebView/TestSessionStore.cpp
+++ b/Tests/LibWebView/TestSessionStore.cpp
@@ -75,11 +75,22 @@ static SessionTabId open_tab(SessionStore& store, SessionWindowId window, String
// Takes the schema back to SESSIONS_SCHEMA_DOCUMENT_POLICY_VERSION, so every migration after it runs again.
static void rewind_sessions_schema_to_version_4(Database::Database& database)
{
+ MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN restore_at_launch;"sv));
+ MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN activation_sequence;"sv));
MUST(database.execute_raw("DROP TABLE SessionLifecycle;"sv));
MUST(database.execute_raw("ALTER TABLE SessionTabs DROP COLUMN pinned;"sv));
MUST(database.execute_raw("UPDATE SchemaVersions SET version = 4 WHERE store = 'Sessions';"sv));
}
+// What the frontend does at Quit: Every window closes in quitting mode, and the run then ends normally.
+static void quit_cleanly(SessionStore& store, Vector<SessionWindowId> const& windows)
+{
+ store.application_quitting();
+ for (auto window : windows)
+ MUST(store.window_closing({ .window_id = window, .active_tab_index = 0, .closed_at = UnixDateTime::now() }));
+ store.mark_clean_exit();
+}
+
TEST_CASE(fresh_database_migrates_to_the_latest_schema)
{
auto database = TRY_OR_FAIL(Database::Database::create_memory_backed({ .foreign_keys = Database::Database::ForeignKeys::Yes }));
@@ -88,7 +99,7 @@ TEST_CASE(fresh_database_migrates_to_the_latest_schema)
for (auto table : { "Sessions"sv, "SessionTabs"sv, "SessionUsedSteps"sv, "SessionHistories"sv, "SessionNestedHistories"sv, "SessionEntries"sv })
EXPECT(TRY_OR_FAIL(database->table_exists(table)));
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 6u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 7u });
}
TEST_CASE(deleting_a_session_cascades_through_its_tabs)
@@ -135,7 +146,7 @@ TEST_CASE(version_4_database_migrates_to_the_latest_schema)
rewind_sessions_schema_to_version_4(*database);
EXPECT_EQ(TRY_OR_FAIL(SessionStore::migrate_schema(*database)), Database::MigrationOutcome::Success);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 6u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 7u });
EXPECT_EQ(select_i64(*database, "SELECT pinned FROM SessionTabs WHERE id = 2;"_string), 0);
}
@@ -1332,6 +1343,478 @@ TEST_CASE(unclean_exits_count_up_until_a_clean_exit)
EXPECT_EQ(TRY_OR_FAIL(SessionStore::create(*database))->consecutive_unclean_exits(), 0u);
}
+TEST_CASE(the_default_policy_keeps_leftover_windows_for_reopening)
+{
+ auto database = create_session_database();
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ quit_cleanly(*store, { window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ EXPECT(store->take_launch_plan().is_empty());
+ EXPECT(store->has_closed_units());
+}
+
+TEST_CASE(everything_re_adopts_leftover_windows_in_place)
+{
+ auto database = create_session_database();
+ SessionWindowId first_window = 0;
+ SessionWindowId second_window = 0;
+ SessionTabId a = 0;
+ SessionTabId b = 0;
+ SessionTabId c = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ first_window = TRY_OR_FAIL(store->window_opened());
+ second_window = TRY_OR_FAIL(store->window_opened());
+ a = open_tab(*store, first_window, "https://a.example/"sv);
+ b = open_tab(*store, first_window, "https://b.example/"sv);
+ c = open_tab(*store, second_window, "https://c.example/"sv);
+ store->active_tab_changed(b);
+ // The first window ends up frontmost.
+ store->window_activated(second_window);
+ store->window_activated(first_window);
+ quit_cleanly(*store, { first_window, second_window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 2uz);
+ EXPECT_EQ(plan[0].window_id, second_window);
+ EXPECT_EQ(plan[0].tabs.size(), 1uz);
+ EXPECT_EQ(plan[0].tabs[0].tab_id, c);
+ EXPECT_EQ(plan[1].window_id, first_window);
+ EXPECT_EQ(plan[1].tabs.size(), 2uz);
+ EXPECT_EQ(plan[1].tabs[0].tab_id, a);
+ EXPECT_EQ(plan[1].tabs[1].tab_id, b);
+ EXPECT_EQ(plan[1].tabs[1].url.serialize(), "https://b.example/"sv);
+ EXPECT_EQ(plan[1].active_tab_index, 1);
+ EXPECT(!store->has_closed_units());
+
+ // The plan is handed over once.
+ EXPECT(store->take_launch_plan().is_empty());
+}
+
+TEST_CASE(a_never_selected_tab_keeps_its_history_across_relaunches)
+{
+ auto database = create_session_database();
+ SessionWindowId window = 0;
+ SessionTabId tab = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ window = TRY_OR_FAIL(store->window_opened());
+ tab = open_tab(*store, window, "about:blank"sv);
+ store->update_tab_state({ .tab_id = tab, .history = make_snapshot({ "https://a.example/"sv, "https://b.example/"sv }), .url = parse_url("https://b.example/"sv) });
+ quit_cleanly(*store, { window });
+ }
+
+ // Relaunches that never select the tab never read or rewrite its rows.
+ for (int relaunch = 0; relaunch < 2; ++relaunch) {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ EXPECT_EQ(store->take_launch_plan().size(), 1uz);
+ quit_cleanly(*store, { window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ EXPECT_EQ(store->take_launch_plan().size(), 1uz);
+ auto history = store->load_tab_history(tab);
+ EXPECT(history.has_value());
+ EXPECT_EQ(history->entries.size(), 2uz);
+ EXPECT_EQ(history->current_used_step_index, 1uz);
+}
+
+TEST_CASE(pinned_only_splits_pinned_tabs_from_the_rest)
+{
+ auto database = create_session_database();
+ SessionWindowId window = 0;
+ SessionTabId first_pinned = 0;
+ SessionTabId second_pinned = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ window = TRY_OR_FAIL(store->window_opened());
+ first_pinned = open_tab(*store, window, "https://a.example/"sv);
+ second_pinned = open_tab(*store, window, "https://b.example/"sv);
+ auto unpinned = open_tab(*store, window, "https://c.example/"sv);
+ TRY_OR_FAIL(store->tab_pinned_changed(first_pinned, true));
+ TRY_OR_FAIL(store->tab_pinned_changed(second_pinned, true));
+ store->active_tab_changed(unpinned);
+ quit_cleanly(*store, { window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT(plan[0].window_id != window);
+ EXPECT_EQ(plan[0].tabs.size(), 2uz);
+ EXPECT_EQ(plan[0].tabs[0].tab_id, first_pinned);
+ EXPECT_EQ(plan[0].tabs[1].tab_id, second_pinned);
+ EXPECT(plan[0].tabs[0].pinned);
+ EXPECT(plan[0].tabs[1].pinned);
+
+ // The unpinned remainder stays on the Reopen Closed Window stack, as the same unit.
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT kind FROM Sessions WHERE id = {};", window))), 2);
+ auto unit = TRY_OR_FAIL(store->take_most_recently_closed());
+ EXPECT(unit.has_value());
+ EXPECT(unit->was_window);
+ EXPECT_EQ(unit->origin, ClosedSessionUnit::Origin::StartupRecovery);
+ EXPECT_EQ(unit->tabs.size(), 1uz);
+ EXPECT_EQ(unit->tabs[0].active_url.serialize(), "https://c.example/"sv);
+}
+
+TEST_CASE(pinned_only_leaves_no_unit_for_a_window_with_only_pinned_tabs)
+{
+ auto database = create_session_database();
+ SessionWindowId window = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ window = TRY_OR_FAIL(store->window_opened());
+ auto first = open_tab(*store, window, "https://a.example/"sv);
+ auto second = open_tab(*store, window, "https://b.example/"sv);
+ TRY_OR_FAIL(store->tab_pinned_changed(first, true));
+ TRY_OR_FAIL(store->tab_pinned_changed(second, true));
+ quit_cleanly(*store, { window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ EXPECT_EQ(store->take_launch_plan().size(), 1uz);
+ EXPECT(!store->has_closed_units());
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT COUNT(*) FROM Sessions WHERE id = {};", window))), 0);
+}
+
+TEST_CASE(pinned_only_keeps_a_window_without_pins_for_reopening)
+{
+ auto database = create_session_database();
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ quit_cleanly(*store, { window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ EXPECT(store->take_launch_plan().is_empty());
+ EXPECT(store->has_closed_units());
+}
+
+TEST_CASE(closing_the_last_window_restores_it_at_launch)
+{
+ auto database = create_session_database();
+ SessionWindowId window = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ (void)open_tab(*store, window, "https://b.example/"sv);
+ TRY_OR_FAIL(store->window_closing({ .window_id = window, .active_tab_index = 1, .closed_at = UnixDateTime::now() }));
+ store->mark_clean_exit();
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT_EQ(plan[0].window_id, window);
+ EXPECT_EQ(plan[0].tabs.size(), 2uz);
+ EXPECT_EQ(plan[0].active_tab_index, 1);
+ EXPECT(!store->has_closed_units());
+}
+
+TEST_CASE(pinned_only_restores_the_last_windows_pins)
+{
+ auto database = create_session_database();
+ SessionWindowId window = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ window = TRY_OR_FAIL(store->window_opened());
+ auto pinned = open_tab(*store, window, "https://a.example/"sv);
+ (void)open_tab(*store, window, "https://b.example/"sv);
+ TRY_OR_FAIL(store->tab_pinned_changed(pinned, true));
+ TRY_OR_FAIL(store->window_closing({ .window_id = window, .active_tab_index = 0, .closed_at = UnixDateTime::now() }));
+ store->mark_clean_exit();
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT_EQ(plan[0].tabs.size(), 1uz);
+ auto unit = TRY_OR_FAIL(store->take_most_recently_closed());
+ EXPECT(unit.has_value());
+ EXPECT_EQ(unit->tabs.size(), 1uz);
+ EXPECT_EQ(unit->tabs[0].active_url.serialize(), "https://b.example/"sv);
+}
+
+TEST_CASE(closing_one_of_two_windows_doesnt_restore_it_at_launch)
+{
+ auto database = create_session_database();
+ SessionWindowId second_window = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto first_window = TRY_OR_FAIL(store->window_opened());
+ second_window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, first_window, "https://a.example/"sv);
+ (void)open_tab(*store, second_window, "https://b.example/"sv);
+ TRY_OR_FAIL(store->window_closing({ .window_id = first_window, .active_tab_index = 0, .closed_at = UnixDateTime::now() }));
+ quit_cleanly(*store, { second_window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT_EQ(plan[0].window_id, second_window);
+ EXPECT(store->has_closed_units());
+}
+
+TEST_CASE(opening_a_window_cancels_the_last_windows_restore)
+{
+ auto database = create_session_database();
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ TRY_OR_FAIL(store->window_closing({ .window_id = window, .active_tab_index = 0, .closed_at = UnixDateTime::now() }));
+ // A window that's still empty at the quit is discarded at the next launch, so only the flag's fate matters.
+ (void)TRY_OR_FAIL(store->window_opened());
+ store->mark_clean_exit();
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ EXPECT(store->take_launch_plan().is_empty());
+ EXPECT(store->has_closed_units());
+}
+
+TEST_CASE(reopening_the_last_window_cancels_its_restore)
+{
+ auto database = create_session_database();
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ TRY_OR_FAIL(store->window_closing({ .window_id = window, .active_tab_index = 0, .closed_at = UnixDateTime::now() }));
+ EXPECT(TRY_OR_FAIL(store->take_most_recently_closed()).has_value());
+ store->mark_clean_exit();
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ EXPECT(store->take_launch_plan().is_empty());
+}
+
+TEST_CASE(clearing_history_cancels_the_last_windows_restore)
+{
+ auto database = create_session_database();
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ TRY_OR_FAIL(store->window_closing({ .window_id = window, .active_tab_index = 0, .closed_at = UnixDateTime::now() }));
+ TRY_OR_FAIL(store->remove_entries_accessed_since(UnixDateTime::epoch()));
+ store->mark_clean_exit();
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ EXPECT(store->take_launch_plan().is_empty());
+ EXPECT(!store->has_closed_units());
+}
+
+TEST_CASE(a_second_unclean_exit_in_a_row_stops_launch_restore)
+{
+ auto database = create_session_database();
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ // Destroyed without mark_clean_exit(): a crash.
+ }
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ EXPECT_EQ(store->take_launch_plan().size(), 1uz);
+ // And a second crash.
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ EXPECT(store->take_launch_plan().is_empty());
+ auto unit = TRY_OR_FAIL(store->take_most_recently_closed());
+ EXPECT(unit.has_value());
+ EXPECT_EQ(unit->origin, ClosedSessionUnit::Origin::StartupRecovery);
+}
+
+TEST_CASE(a_clean_exit_resumes_launch_restore)
+{
+ auto database = create_session_database();
+ // Two crashes in a row.
+ for (int run = 0; run < 2; ++run) {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ }
+ SessionWindowId window = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ EXPECT(store->take_launch_plan().is_empty());
+ window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://b.example/"sv);
+ quit_cleanly(*store, { window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT_EQ(plan[0].window_id, window);
+}
+
+TEST_CASE(everything_moves_pinned_tabs_ahead_of_unpinned_ones)
+{
+ auto database = create_session_database();
+ SessionWindowId window = 0;
+ SessionTabId a = 0;
+ SessionTabId b = 0;
+ SessionTabId c = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ window = TRY_OR_FAIL(store->window_opened());
+ a = open_tab(*store, window, "https://a.example/"sv);
+ b = open_tab(*store, window, "https://b.example/"sv);
+ c = open_tab(*store, window, "https://c.example/"sv);
+ store->active_tab_changed(b);
+ quit_cleanly(*store, { window });
+ }
+
+ // A saved session whose last tab is pinned, with the unpinned tabs still ahead of it.
+ TRY_OR_FAIL(database->execute_raw(ByteString::formatted("UPDATE SessionTabs SET pinned = 1 WHERE id = {};", c)));
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT_EQ(plan[0].tabs.size(), 3uz);
+ EXPECT_EQ(plan[0].tabs[0].tab_id, c);
+ EXPECT(plan[0].tabs[0].pinned);
+ EXPECT_EQ(plan[0].tabs[1].tab_id, a);
+ EXPECT_EQ(plan[0].tabs[2].tab_id, b);
+ EXPECT_EQ(plan[0].active_tab_index, 2);
+
+ // The corrected order is saved too.
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT tab_ordinal FROM SessionTabs WHERE id = {};", c))), 0);
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT tab_ordinal FROM SessionTabs WHERE id = {};", b))), 2);
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT active_tab_index FROM Sessions WHERE id = {};", window))), 2);
+}
+
+TEST_CASE(a_corrupt_tab_row_drops_only_that_tab_from_the_launch_plan)
+{
+ auto database = create_session_database();
+ SessionTabId a = 0;
+ SessionTabId b = 0;
+ SessionTabId c = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ a = open_tab(*store, window, "https://a.example/"sv);
+ b = open_tab(*store, window, "https://b.example/"sv);
+ c = open_tab(*store, window, "https://c.example/"sv);
+ quit_cleanly(*store, { window });
+ }
+ TRY_OR_FAIL(database->execute_raw(MUST(String::formatted("UPDATE SessionTabs SET active_url = 'not a url' WHERE id = {};", b)).to_byte_string()));
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT_EQ(plan[0].tabs.size(), 2uz);
+ EXPECT_EQ(plan[0].tabs[0].tab_id, a);
+ EXPECT_EQ(plan[0].tabs[1].tab_id, c);
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT COUNT(*) FROM SessionTabs WHERE id = {};", b))), 0);
+}
+
+TEST_CASE(a_window_whose_every_tab_row_is_corrupt_leaves_no_launch_plan_entry)
+{
+ auto database = create_session_database();
+ SessionWindowId emptied = 0;
+ SessionTabId kept = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ emptied = TRY_OR_FAIL(store->window_opened());
+ auto lost = open_tab(*store, emptied, "https://lost.example/"sv);
+ auto other = TRY_OR_FAIL(store->window_opened());
+ kept = open_tab(*store, other, "https://kept.example/"sv);
+ quit_cleanly(*store, { emptied, other });
+ TRY_OR_FAIL(database->execute_raw(MUST(String::formatted("UPDATE SessionTabs SET active_url = 'not a url' WHERE id = {};", lost)).to_byte_string()));
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT_EQ(plan[0].tabs.size(), 1uz);
+ EXPECT_EQ(plan[0].tabs[0].tab_id, kept);
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT COUNT(*) FROM Sessions WHERE id = {};", emptied))), 0);
+}
+
+TEST_CASE(pinned_only_with_a_corrupt_row_in_a_window_without_pins_drops_only_that_tab)
+{
+ auto database = create_session_database();
+ SessionTabId a = 0;
+ SessionTabId b = 0;
+ SessionTabId c = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ a = open_tab(*store, window, "https://a.example/"sv);
+ b = open_tab(*store, window, "https://b.example/"sv);
+ c = open_tab(*store, window, "https://c.example/"sv);
+ quit_cleanly(*store, { window });
+ }
+ TRY_OR_FAIL(database->execute_raw(MUST(String::formatted("UPDATE SessionTabs SET active_url = 'not a url' WHERE id = {};", b)).to_byte_string()));
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ EXPECT(store->take_launch_plan().is_empty());
+ EXPECT(store->has_closed_units());
+ auto unit = TRY_OR_FAIL(store->take_most_recently_closed());
+ EXPECT(unit.has_value());
+ EXPECT_EQ(unit->tabs.size(), 2uz);
+ EXPECT_EQ(unit->tabs[0].active_url.serialize(), "https://a.example/"sv);
+ EXPECT_EQ(unit->tabs[1].active_url.serialize(), "https://c.example/"sv);
+ (void)a;
+ (void)c;
+}
+
+TEST_CASE(pinned_only_maps_the_active_tab_into_the_pinned_window_and_the_remainder)
+{
+ auto database = create_session_database();
+ SessionTabId p1 = 0;
+ SessionTabId p2 = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ p1 = open_tab(*store, window, "https://p1.example/"sv);
+ (void)open_tab(*store, window, "https://u1.example/"sv);
+ p2 = open_tab(*store, window, "https://p2.example/"sv);
+ (void)open_tab(*store, window, "https://u2.example/"sv);
+ TRY_OR_FAIL(store->tab_pinned_changed(p1, true));
+ TRY_OR_FAIL(store->tab_pinned_changed(p2, true));
+ store->active_tab_changed(p2);
+ quit_cleanly(*store, { window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT_EQ(plan[0].tabs.size(), 2uz);
+ EXPECT_EQ(plan[0].tabs[0].tab_id, p1);
+ EXPECT_EQ(plan[0].tabs[1].tab_id, p2);
+ EXPECT_EQ(plan[0].active_tab_index, 1);
+
+ auto unit = TRY_OR_FAIL(store->take_most_recently_closed());
+ EXPECT(unit.has_value());
+ EXPECT_EQ(unit->tabs.size(), 2uz);
+ EXPECT_EQ(unit->tabs[0].active_url.serialize(), "https://u1.example/"sv);
+ EXPECT_EQ(unit->tabs[1].active_url.serialize(), "https://u2.example/"sv);
+}
+
+TEST_CASE(a_transient_store_has_no_launch_plan)
+{
+ auto store = SessionStore::create();
+ EXPECT(store->take_launch_plan().is_empty());
+ EXPECT(!store->load_tab_history(1).has_value());
+}
+
TEST_CASE(retention_keeps_the_newest_closed_units)
{
auto database = create_session_database();