Compare commits
4
Commits
02f43b2ee9
...
ccccd485ce
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ccccd485ce
|
||
|
|
5fc31a0495
|
||
|
|
fd3b782889
|
||
|
|
9663b74488
|
No files matched your search
@@ -222,6 +222,13 @@ Detailed list of changes
|
|||||||
0.50.1 [unreleased]
|
0.50.1 [unreleased]
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
- 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
|
- :kbd:`Ctrl+Shift+E` now opens the :doc:`file manager kitten
|
||||||
<kittens/file-manager>` in a left dock by default, instead of requiring a
|
<kittens/file-manager>` in a left dock by default, instead of requiring a
|
||||||
manual mapping. This takes the key over from :ac:`open_url`; remap
|
manual mapping. This takes the key over from :ac:`open_url`; remap
|
||||||
|
|||||||
@@ -34,6 +34,26 @@ you want to work on the project, simply run:
|
|||||||
|
|
||||||
You can also set the session in :file:`kitty.conf` via :opt:`startup_session`.
|
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
|
||||||
|
|
||||||
|
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
|
Thus, it is very easy to create sessions and work on projects. To learn how to
|
||||||
create more complex sessions, see :ref:`complex_sessions`.
|
create more complex sessions, see :ref:`complex_sessions`.
|
||||||
|
|
||||||
|
|||||||
@@ -68,6 +68,7 @@ from .options.types import Options
|
|||||||
from .options.utils import DELETE_ENV_VAR
|
from .options.utils import DELETE_ENV_VAR
|
||||||
from .os_window_size import edge_spacing, initial_window_size_func
|
from .os_window_size import edge_spacing, initial_window_size_func
|
||||||
from .session import create_sessions, get_os_window_sizing_data
|
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 .shaders.slang import load_shader_programs
|
||||||
from .types import LayerShellConfig
|
from .types import LayerShellConfig
|
||||||
from .utils import (
|
from .utils import (
|
||||||
@@ -394,6 +395,8 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (),
|
|||||||
try:
|
try:
|
||||||
boss.child_monitor.main_loop()
|
boss.child_monitor.main_loop()
|
||||||
finally:
|
finally:
|
||||||
|
if not _is_panel_kitten:
|
||||||
|
save_session_of(boss)
|
||||||
boss.destroy()
|
boss.destroy()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+9
-1
@@ -327,7 +327,15 @@ def create_sessions(
|
|||||||
env_when_no_session: dict[str, str] | None = None,
|
env_when_no_session: dict[str, str] | None = None,
|
||||||
) -> Iterator[Session]:
|
) -> Iterator[Session]:
|
||||||
if args and args.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'
|
default_session = 'none'
|
||||||
else:
|
else:
|
||||||
session_arg = args.session
|
session_arg = args.session
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||||
|
|
||||||
|
# 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}')
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||||
|
|
||||||
|
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))
|
||||||
Reference in new issue
Block a user