diff --git a/docs/changelog.rst b/docs/changelog.rst index 890c22e..bb8a586 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -237,6 +237,13 @@ Detailed list of changes can paste back. Nothing is written to disk and private clipboard writes are never recorded. See :ref:`clipboard_history` for details. +- kitty now remembers the state of the session that was in use when it exited, + in :file:`$XDG_STATE_HOME/kitty/last-session.json`, so that + :code:`kitty --session=last` brings back the tabs, layouts, working + directories and titles of the previous run. Restoring is explicit, never + automatic, and a corrupt or oversized saved state is discarded instead of + blocking startup. See :ref:`sessions` for details. + - :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten ` in a left dock by default, instead of requiring a manual mapping. This takes the key over from :ac:`open_url`; remap diff --git a/docs/sessions.rst b/docs/sessions.rst index 07f1d64..0ff91b1 100644 --- a/docs/sessions.rst +++ b/docs/sessions.rst @@ -34,6 +34,30 @@ you want to work on the project, simply run: You can also set the session in :file:`kitty.conf` via :opt:`startup_session`. +Restoring the last session +---------------------------- + +kitty saves the state of its tabs, windows, layouts, working directories and +titles when it exits, in :file:`$XDG_STATE_HOME/kitty/last-session.json` +(usually :file:`~/.local/state/kitty/last-session.json`). The saved state is +limited to 1 MiB and is overwritten at every exit, so it never accumulates. + +To restore it, start kitty with: + +.. code-block:: sh + + kitty --session=last + +The same saved state can be restored inside a running kitty with the +:ac:`restore_last_session` action, which is mapped to :kbd:`kitty_mod+alt+r` +by default and adds the saved tabs to the current window. + +Restoring is never automatic: without this option the saved state is ignored, +so an unexpected state is never imposed on you. A state file that is corrupt, +unreadable or too large is discarded and kitty starts normally. :code:`cd` +directives whose directory no longer exists are dropped when restoring. Use +:ac:`save_as_session` for sessions that must survive beyond the next exit. + Thus, it is very easy to create sessions and work on projects. To learn how to create more complex sessions, see :ref:`complex_sessions`. diff --git a/kitty/boss.py b/kitty/boss.py index 5a6a589..1231c61 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -2530,6 +2530,7 @@ class Boss: if not self._call_on_quit_watchers({'confirmed': True}): set_application_quit_request(NO_CLOSE_REQUESTED) return + self.save_last_session() self.save_session_if_logging_out() set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED) return @@ -2559,9 +2560,20 @@ class Boss: if not self._call_on_quit_watchers({'confirmed': True}): set_application_quit_request(NO_CLOSE_REQUESTED) return + self.save_last_session() self.save_session_if_logging_out() set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED if confirmed else NO_CLOSE_REQUESTED) + def save_last_session(self) -> None: + # Must run before the quit request is set: the C side then closes the windows and there is + # nothing left to serialize. Saving an empty session is a no-op, so this never clobbers a + # good state with a torn down one. + from .main import is_panel_kitten + from .session_restore import save_session_of + + if not is_panel_kitten(): + save_session_of(self) + def save_session_if_logging_out(self) -> None: from .logout_session import is_logout_in_progress @@ -3991,6 +4003,13 @@ class Boss: def goto_session(self, *cmdline: str) -> None: goto_session(self, cmdline) + @ac('session', 'Restore the tabs and windows of the session saved when kitty last quit. See :ref:`sessions`.') + def restore_last_session(self) -> None: + from .session_restore import restore_last_session_into + + if not restore_last_session_into(self): + self.ring_bell_if_allowed() + @ac('session', 'Save the current kitty state as a session file. See :ref:`save_as_session`.') def save_as_session(self, *cmdline: str) -> None: save_as_session(self, cmdline) diff --git a/kitty/main.py b/kitty/main.py index 3c705c6..1431433 100644 --- a/kitty/main.py +++ b/kitty/main.py @@ -68,6 +68,7 @@ from .options.types import Options from .options.utils import DELETE_ENV_VAR from .os_window_size import edge_spacing, initial_window_size_func from .session import create_sessions, get_os_window_sizing_data +from .session_restore import save_session_of from .shaders.slang import load_shader_programs from .types import LayerShellConfig from .utils import ( @@ -394,6 +395,8 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (), try: boss.child_monitor.main_loop() finally: + if not _is_panel_kitten: + save_session_of(boss) boss.destroy() diff --git a/kitty/options/definition.py b/kitty/options/definition.py index 4be4d29..15c17e7 100644 --- a/kitty/options/definition.py +++ b/kitty/options/definition.py @@ -4661,6 +4661,23 @@ shortcuts. For a full description see :doc:`hints kitten `. """) # }}} +# shortcuts.session {{{ +agr('shortcuts.session', 'Sessions') + +map( + 'Restore the last session', + 'restore_last_session --allow-fallback=shifted,ascii kitty_mod+alt+r restore_last_session', + long_text=""" +Restores the tabs, windows, layouts and working directories of the session that +was saved when kitty last quit, without restarting kitty. The state is written +by :code:`quit`; see :ref:`sessions`. If there is nothing to restore, a bell is +rung instead. +""", +) + +egr() # }}} + + # shortcuts.misc {{{ agr('shortcuts.misc', 'Miscellaneous') diff --git a/kitty/options/types.py b/kitty/options/types.py index 8ba2c6e..d6d6ff2 100644 --- a/kitty/options/types.py +++ b/kitty/options/types.py @@ -1028,6 +1028,8 @@ defaults.map = [ KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=110),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type linenum'), # open_selected_hyperlink KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=121),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type hyperlink'), + # restore_last_session + KeyDefinition(trigger=SingleKey(mods=258, key=114), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='restore_last_session'), # show_kitty_doc KeyDefinition(trigger=SingleKey(mods=256, key=57364), definition='show_kitty_doc overview'), # command_palette diff --git a/kitty/session.py b/kitty/session.py index 7a8ba86..8d054a9 100644 --- a/kitty/session.py +++ b/kitty/session.py @@ -327,7 +327,15 @@ def create_sessions( env_when_no_session: dict[str, str] | None = None, ) -> Iterator[Session]: if args and args.session: - if args.session == 'none': + if args.session == 'last': + from .session_restore import load_last_session, state_path + + raw = load_last_session() + if raw: + yield from parse_session(raw, opts, session_arg='last', session_path=state_path()) + return + log_error('There is no saved session to restore, starting a new session instead') + elif args.session == 'none': default_session = 'none' else: session_arg = args.session diff --git a/kitty/session_restore.py b/kitty/session_restore.py new file mode 100644 index 0000000..f50dd0b --- /dev/null +++ b/kitty/session_restore.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +# License: GPL v3 Copyright: 2026, Kovid Goyal + +# Keep the state of the session that was last in use so that `kitty --session=last` can restore it. +# +# The state is stored in the XDG state directory, is bounded in size and is only ever read when the +# user explicitly asks for it, since restoring an unexpected state is worse than not restoring +# anything. Anything that cannot be read back is discarded instead of preventing startup. + +import json +import os +import time +from contextlib import suppress +from typing import TYPE_CHECKING, Any + +from .config import atomic_save +from .utils import log_error + +if TYPE_CHECKING: + from .typing_compat import BossType + +STATE_VERSION = 1 +MAX_STATE_SIZE = 1024 * 1024 +STATE_FILE_NAME = 'last-session.json' + + +def state_dir() -> str: + base = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state') + return os.path.join(base, 'kitty') + + +def state_path() -> str: + return os.path.join(state_dir(), STATE_FILE_NAME) + + +def serialize_state(session: str, saved_at: float | None = None) -> bytes: + state = {'version': STATE_VERSION, 'saved_at': time.time() if saved_at is None else saved_at, 'session': session} + return json.dumps(state, ensure_ascii=False).encode('utf-8') + + +def save_last_session(session: str) -> bool: + """Store the session text, returning False when it cannot be stored.""" + if not session.strip(): + return False + if len(session) > MAX_STATE_SIZE: + log_error(f'Not saving the last session as it is larger than {MAX_STATE_SIZE} characters, use save_as_session for large sessions') + return False + path = state_path() + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + atomic_save(serialize_state(session), path) + except OSError as e: + log_error(f'Failed to save the last session to {path}: {e}') + return False + return True + + +def prune_missing_directories(session: str) -> tuple[str, int]: + """Drop cd directives whose directory is gone, so that a stale state does not fail to restore.""" + lines: list[str] = [] + pruned = 0 + for line in session.splitlines(): + stripped = line.strip() + if stripped.startswith('cd ') and stripped[3:].strip(): + raw = stripped[3:].strip().strip('"\'') + path = os.path.expanduser(raw) + if os.path.isabs(path) and not os.path.isdir(path): + pruned += 1 + continue + lines.append(line) + return '\n'.join(lines), pruned + + +def discard_last_session() -> None: + try: + os.remove(state_path()) + except FileNotFoundError: + pass + except OSError as e: + log_error(f'Failed to delete the unreadable last session: {e}') + + +def parse_state(raw: bytes) -> str: + try: + parsed: Any = json.loads(raw) + except (ValueError, UnicodeDecodeError) as e: + raise ValueError(f'not valid JSON: {e}') from e + if not isinstance(parsed, dict): + raise ValueError('not a JSON object') + version = parsed.get('version') + if not isinstance(version, int): + raise ValueError('missing state version') + if version > STATE_VERSION: + raise ValueError(f'state version {version} is newer than the supported version {STATE_VERSION}') + session = parsed.get('session') + if not isinstance(session, str): + raise ValueError('missing session text') + return session + + +def load_last_session() -> str: + """Return the stored session text, or an empty string when there is nothing usable.""" + path = state_path() + try: + with open(path, 'rb') as f: + raw = f.read(MAX_STATE_SIZE + 1) + except FileNotFoundError: + return '' + except OSError as e: + log_error(f'Failed to read the last session from {path}: {e}') + return '' + if len(raw) > MAX_STATE_SIZE: + log_error(f'Discarding the last session in {path} as it is larger than {MAX_STATE_SIZE} bytes') + discard_last_session() + return '' + try: + session = parse_state(raw) + except ValueError as e: + log_error(f'Discarding the last session in {path} as it cannot be read: {e}') + discard_last_session() + return '' + session, pruned = prune_missing_directories(session) + if pruned: + log_error(f'Dropped {pruned} working directory directive(s) from the last session as the directories no longer exist') + return session + + +def save_session_of(boss: 'BossType') -> None: + """Save the state of a running kitty instance, never raising so that it cannot break quitting.""" + from .session import default_save_as_session_opts + + try: + opts = default_save_as_session_opts() + opts.os_window_geometry = True + session = '\n'.join(boss.serialize_state_as_session('', opts)) + save_last_session(session) + except Exception as e: + log_error(f'Failed to save the last session: {e}') + + +def restore_last_session_into(boss: 'BossType') -> bool: + """Add the tabs and windows of the last saved session to a running kitty. + + Returns False when there is nothing to restore. The saved state is a JSON document, so it is + handed to the session parser through a short lived file rather than duplicating the parsing. + """ + raw = load_last_session() + if not raw: + return False + import tempfile + + from .session import create_session + + fd, path = tempfile.mkstemp(prefix='last-session-', suffix='.kitty-session') + try: + with open(fd, 'w', encoding='utf-8') as f: + f.write(raw) + create_session(boss, path) + finally: + with suppress(OSError): + os.unlink(path) + return True diff --git a/kitty_tests/session_restore.py b/kitty_tests/session_restore.py new file mode 100644 index 0000000..6428ef9 --- /dev/null +++ b/kitty_tests/session_restore.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python +# License: GPL v3 Copyright: 2026, Kovid Goyal + +import json +import os +import shutil +import tempfile +from unittest.mock import patch + +from kitty.config import load_config +from kitty.session import create_sessions, parse_session +from kitty.session_restore import ( + MAX_STATE_SIZE, + discard_last_session, + load_last_session, + prune_missing_directories, + save_last_session, + state_path, +) +from kitty.utils import log_error + +from .base import BaseTest + + +class TestSessionRestore(BaseTest): + def setUp(self) -> None: + super().setUp() + self.tdir = tempfile.mkdtemp() + self.env_patch = patch.dict(os.environ, {'XDG_STATE_HOME': self.tdir}) + self.env_patch.start() + self.error_messages: list[str] = [] + log_error.redirect = self.error_messages.append + + def tearDown(self) -> None: + del log_error.redirect + self.env_patch.stop() + shutil.rmtree(self.tdir) + super().tearDown() + + def write_state(self, data: bytes) -> None: + os.makedirs(os.path.dirname(state_path()), exist_ok=True) + with open(state_path(), 'wb') as f: + f.write(data) + + def test_state_lives_in_the_xdg_state_directory(self) -> None: + self.ae(state_path(), os.path.join(self.tdir, 'kitty', 'last-session.json')) + + def test_roundtrip(self) -> None: + session = 'new_tab work\nlayout tall\ncd /tmp\nlaunch --title editor\nlaunch' + self.assertTrue(save_last_session(session)) + self.assertTrue(os.path.exists(state_path())) + self.ae(load_last_session(), session) + + def test_nothing_is_saved_for_an_empty_session(self) -> None: + self.assertFalse(save_last_session(' \n')) + self.ae(load_last_session(), '') + + def test_missing_state_is_not_an_error(self) -> None: + self.ae(load_last_session(), '') + self.ae(self.error_messages, []) + + def test_too_large_state_is_neither_saved_nor_restored(self) -> None: + self.assertFalse(save_last_session('x' * (MAX_STATE_SIZE + 1))) + self.assertFalse(os.path.exists(state_path())) + self.write_state(json.dumps({'version': 1, 'session': 'x' * (MAX_STATE_SIZE + 1)}).encode()) + self.ae(load_last_session(), '') + self.assertFalse(os.path.exists(state_path())) + self.assertTrue(self.error_messages) + + def test_corrupt_state_is_discarded(self) -> None: + self.write_state(b'{"version": 1, "session": ') + self.ae(load_last_session(), '') + self.assertFalse(os.path.exists(state_path())) + self.assertTrue(any('cannot be read' in msg for msg in self.error_messages)) + + def test_newer_state_version_is_discarded(self) -> None: + self.write_state(json.dumps({'version': 99, 'session': 'launch'}).encode()) + self.ae(load_last_session(), '') + self.assertFalse(os.path.exists(state_path())) + + def test_missing_or_invalid_fields_are_discarded(self) -> None: + for data in ({}, {'version': 1}, {'session': 'launch'}, {'version': '1', 'session': 'launch'}, []): + self.write_state(json.dumps(data).encode()) + self.ae(load_last_session(), '', data) + self.assertFalse(os.path.exists(state_path()), data) + self.assertFalse(os.path.exists(state_path())) + + def test_discard_is_idempotent(self) -> None: + discard_last_session() + self.ae(self.error_messages, []) + + def test_stale_directories_are_pruned(self) -> None: + missing = os.path.join(self.tdir, 'gone') + session = f'new_tab a\ncd {missing}\nlaunch\nnew_tab b\ncd {self.tdir}\nlaunch' + session, pruned = prune_missing_directories(session) + self.ae(pruned, 1) + self.assertNotIn(missing, session) + self.assertIn(f'cd {self.tdir}', session) + self.assertIn('new_tab b', session) + self.assertTrue(self.error_messages == []) # pruning itself does not log + + def test_pruning_is_applied_when_loading(self) -> None: + missing = os.path.join(self.tdir, 'gone') + self.assertTrue(save_last_session(f'cd {missing}\nlaunch')) + self.ae(load_last_session(), 'launch') + self.assertTrue(any('no longer exist' in msg for msg in self.error_messages)) + + def test_saved_state_is_a_valid_session(self) -> None: + session = 'new_tab one\nlayout tall\nlaunch\nnew_tab two\nlaunch' + self.assertTrue(save_last_session(session)) + opts = load_config() + sessions = tuple(parse_session(load_last_session(), opts, session_arg='last', session_path=state_path())) + self.ae(len(sessions), 1) + self.ae(sessions[0].session_name, 'last') + self.ae([t.name for t in sessions[0].tabs], ['one', 'two']) + + def test_restore_is_explicit_on_the_command_line(self) -> None: + from kitty.cli import parse_args + + self.assertTrue(save_last_session('launch')) + opts = load_config() + args, rest = parse_args(['--session', 'last']) + args.args = [] # type: ignore + self.ae(args.session, 'last') + self.ae(rest, []) + sessions = tuple(create_sessions(opts, args)) + self.ae(len(sessions), 1) + self.ae(sessions[0].session_name, 'last') + self.ae(len(sessions[0].tabs[0].windows), 1) + + def test_missing_state_falls_back_to_a_fresh_session(self) -> None: + from kitty.cli import parse_args + + opts = load_config() + args, rest = parse_args(['--session', 'last']) + args.args = [] # type: ignore + sessions = tuple(create_sessions(opts, args)) + self.ae(len(sessions), 1) + self.ae(sessions[0].session_name, '') + self.assertTrue(any('no saved session' in msg for msg in self.error_messages)) + + def test_restore_action_without_state_returns_false(self) -> None: + from kitty.session_restore import restore_last_session_into + + self.assertFalse(restore_last_session_into(None)) # type: ignore