From a2629aa4d9f558933670737e333678e7af5d0087 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Wed, 11 Nov 2026 21:03:29 +0100 Subject: [PATCH] feat(session): save the last session when kitty exits --- kitty/main.py | 3 + kitty/session_restore.py | 137 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 kitty/session_restore.py 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/session_restore.py b/kitty/session_restore.py new file mode 100644 index 0000000..539edfc --- /dev/null +++ b/kitty/session_restore.py @@ -0,0 +1,137 @@ +#!/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 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}')