feat(state): atomic session in XDG_STATE_HOME; old UI saves theme via SetKey (2C.3)

state.Save writes session.toml atomically (0600, state dir 0700), drops
cursor-memory entries under cache/temp mounts and caps each pane at 200
entries; Load migrates the old ~/.config/vcom/session.toml once. The old
UI's session functions are aliases over state, and theme selection uses
config.SetKey, so the user's comments and keys survive. config.Save is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-31 23:37:23 +03:00
parent 28fd86b8d5
commit 4ed81ef635
7 changed files with 388 additions and 87 deletions

View file

@ -1,86 +1,19 @@
package config
import (
"fmt"
"os"
"path/filepath"
import "vcom/internal/state"
toml "github.com/pelletier/go-toml/v2"
"vcom/internal/homedir"
// Session types and functions are thin aliases over internal/state, kept so
// the old UI compiles unchanged until stage 7.
type (
SessionState = state.Session
PaneSession = state.PaneSession
)
// SessionState stores the UI state that should be restored on next launch.
type SessionState struct {
ActivePane string `toml:"active_pane"`
Left PaneSession `toml:"left"`
Right PaneSession `toml:"right"`
}
// DefaultSessionPath returns the session file ($XDG_STATE_HOME/vcom/session.toml).
func DefaultSessionPath() (string, error) { return state.File() }
// PaneSession stores per-pane session state (path and selected entry name).
type PaneSession struct {
Path string `toml:"path"`
EntryName string `toml:"entry_name"`
CursorMemory map[string]string `toml:"cursor_memory"`
}
// LoadSession reads the session (migrating it from the old location once).
func LoadSession() (SessionState, error) { return state.Load() }
// DefaultSessionPath returns the path to the session file.
func DefaultSessionPath() (string, error) {
homeDir := homedir.Dir()
if homeDir == "" {
return "", fmt.Errorf("cannot determine home directory")
}
xdgDir := os.Getenv("XDG_CONFIG_HOME")
if xdgDir == "" {
xdgDir = filepath.Join(homeDir, ".config")
}
return filepath.Join(xdgDir, "vcom", "session.toml"), nil
}
// LoadSession reads the session state from disk.
// Returns (SessionState, nil) on success, (empty, error) if file doesn't exist.
func LoadSession() (SessionState, error) {
path, err := DefaultSessionPath()
if err != nil {
return SessionState{}, err
}
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return SessionState{}, nil
}
return SessionState{}, fmt.Errorf("read %s: %w", path, err)
}
var s SessionState
if err := toml.Unmarshal(data, &s); err != nil {
return SessionState{}, fmt.Errorf("parse %s: %w", path, err)
}
return s, nil
}
// SaveSession writes the session state to disk.
func SaveSession(s SessionState) error {
path, err := DefaultSessionPath()
if err != nil {
return err
}
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("resolve %s: %w", path, err)
}
if err := os.MkdirAll(filepath.Dir(absPath), 0o755); err != nil {
return fmt.Errorf("mkdir %s: %w", filepath.Dir(absPath), err)
}
data, err := toml.Marshal(s)
if err != nil {
return fmt.Errorf("marshal session: %w", err)
}
if err := os.WriteFile(absPath, data, 0o644); err != nil {
return fmt.Errorf("write %s: %w", path, err)
}
return nil
}
// SaveSession writes the session atomically.
func SaveSession(s SessionState) error { return state.Save(s) }

View file

@ -254,9 +254,3 @@ func verify(out []byte, section, key string, value any) error {
}
return nil
}
// Save persists the theme of cfg with SetKey. Deprecated: it exists only
// for the old UI and is removed in 2C.3; it no longer rewrites the file.
func Save(cfg Config, path string) (string, error) {
return SetKey(path, "ui", "theme", cfg.UI.Theme)
}

184
internal/state/session.go Normal file
View file

@ -0,0 +1,184 @@
// Package state persists the UI session (design §9.1, §9.2):
// $XDG_STATE_HOME/vcom/session.toml, written atomically, migrated once from
// the pre-0.3 location next to the config.
package state
import (
"bytes"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
toml "github.com/pelletier/go-toml/v2"
"vcom/internal/atomicfile"
"vcom/internal/paths"
)
// MaxCursorMemory bounds the remembered "cursor per directory" entries per pane.
const MaxCursorMemory = 200
// Session is the UI state restored on the next launch.
type Session struct {
ActivePane string `toml:"active_pane"`
Left PaneSession `toml:"left"`
Right PaneSession `toml:"right"`
}
// PaneSession is one pane's state: its directory, the selected entry and the
// last selected entry per visited directory.
type PaneSession struct {
Path string `toml:"path"`
EntryName string `toml:"entry_name"`
CursorMemory map[string]string `toml:"cursor_memory"`
}
// File is the session path: StateDir/session.toml.
func File() (string, error) {
d, err := paths.StateDir()
if err != nil {
return "", err
}
return filepath.Join(d, "session.toml"), nil
}
// Load reads the session. A missing file is not an error (zero Session). If
// only the old file (~/.config/vcom/session.toml) exists, it is read, saved
// to the new location and removed — except under sudo, where the old file
// belongs to the invoking user and is left alone.
func Load() (Session, error) {
p, err := File()
if err != nil {
return Session{}, err
}
s, err := read(p)
if err == nil || !errors.Is(err, fs.ErrNotExist) {
return s, err
}
old, oerr := paths.OldSessionFile()
if oerr != nil {
return Session{}, nil
}
s, err = read(old)
if errors.Is(err, fs.ErrNotExist) {
return Session{}, nil
}
if err != nil {
return Session{}, err
}
if err := Save(s); err != nil {
return s, fmt.Errorf("migrate session from %s: %w", old, err)
}
if _, sudo := paths.SudoUser(); !sudo {
_ = os.Remove(old)
}
return s, nil
}
func read(p string) (Session, error) {
data, err := os.ReadFile(p)
if err != nil {
return Session{}, err
}
var s Session
if err := toml.Unmarshal(data, &s); err != nil {
return Session{}, fmt.Errorf("parse %s: %w", p, err)
}
return s, nil
}
// Save normalises s (see Normalize) and writes it atomically (0600) into a
// 0700 state directory.
func Save(s Session) error {
p, err := File()
if err != nil {
return err
}
if err := paths.EnsureDir(filepath.Dir(p)); err != nil {
return err
}
s.Normalize(transientPrefixes())
var buf bytes.Buffer
if err := toml.NewEncoder(&buf).Encode(s); err != nil {
return fmt.Errorf("encode session: %w", err)
}
return atomicfile.WriteFile(p, buf.Bytes(), 0o600)
}
// transientPrefixes are directories whose paths are not worth remembering:
// vcom's cache/run dirs and the old UI's temp mounts.
func transientPrefixes() []string {
var out []string
if c, err := paths.CacheDir(); err == nil {
out = append(out, c)
}
tmp := os.TempDir()
out = append(out, filepath.Join(tmp, "vcom-archive-"), filepath.Join(tmp, "vcom-remote-"))
return out
}
// Normalize drops cursor-memory entries under any of the transient prefixes
// and caps each pane at MaxCursorMemory entries.
func (s *Session) Normalize(transient []string) {
s.Left.CursorMemory = capMemory(s.Left.CursorMemory, s.Left.Path, transient)
s.Right.CursorMemory = capMemory(s.Right.CursorMemory, s.Right.Path, transient)
}
// capMemory keeps at most MaxCursorMemory entries. The map carries no
// recency, so it keeps first the entries on the pane's current path (its
// ancestors and descendants: where the user is most likely to go back), then
// the rest in path order. Deterministic, which keeps the file diff-friendly.
func capMemory(m map[string]string, current string, transient []string) map[string]string {
if len(m) == 0 {
return m
}
keys := make([]string, 0, len(m))
for k, v := range m {
if k == "" || v == "" || hasAnyPrefix(k, transient) {
continue
}
keys = append(keys, k)
}
related := func(k string) bool {
return current != "" && (isWithin(k, current) || isWithin(current, k))
}
sort.Slice(keys, func(i, j int) bool {
ri, rj := related(keys[i]), related(keys[j])
if ri != rj {
return ri
}
return keys[i] < keys[j]
})
if len(keys) > MaxCursorMemory {
keys = keys[:MaxCursorMemory]
}
out := make(map[string]string, len(keys))
for _, k := range keys {
out[k] = m[k]
}
return out
}
func hasAnyPrefix(p string, prefixes []string) bool {
for _, pre := range prefixes {
if pre != "" && (p == pre || strings.HasPrefix(p, pre)) {
return true
}
}
return false
}
func isWithin(child, parent string) bool {
child, parent = filepath.Clean(child), filepath.Clean(parent)
if child == parent {
return true
}
if !strings.HasSuffix(parent, string(filepath.Separator)) {
parent += string(filepath.Separator)
}
return strings.HasPrefix(child, parent)
}

View file

@ -0,0 +1,121 @@
package state
import (
"fmt"
"os"
"path/filepath"
"testing"
)
// isolate points HOME and the XDG dirs at a temp dir.
func isolate(t *testing.T) (home string) {
home = t.TempDir()
t.Setenv("HOME", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_STATE_HOME", filepath.Join(home, ".local", "state"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Setenv("SUDO_USER", "")
return home
}
func TestSessionAtomic(t *testing.T) {
home := isolate(t)
s := Session{ActivePane: "right", Left: PaneSession{Path: "/a", EntryName: "x"}}
if err := Save(s); err != nil {
t.Fatal(err)
}
dir := filepath.Join(home, ".local", "state", "vcom")
p := filepath.Join(dir, "session.toml")
if fi, err := os.Stat(p); err != nil || fi.Mode().Perm() != 0o600 {
t.Fatalf("session file: %v %v", fi, err)
}
if fi, _ := os.Stat(dir); fi.Mode().Perm() != 0o700 {
t.Fatalf("state dir mode %v", fi.Mode().Perm())
}
got, err := Load()
if err != nil || got.ActivePane != "right" || got.Left.EntryName != "x" {
t.Fatalf("round trip: %+v %v", got, err)
}
// A failing write leaves the previous session intact and no temp files.
if os.Geteuid() != 0 {
before, _ := os.ReadFile(p)
if err := os.Chmod(dir, 0o500); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(dir, 0o700) })
if err := Save(Session{ActivePane: "left"}); err == nil {
t.Fatal("save into a read-only dir succeeded")
}
_ = os.Chmod(dir, 0o700)
after, _ := os.ReadFile(p)
if string(before) != string(after) {
t.Fatal("old session damaged by a failed save")
}
if ents, _ := os.ReadDir(dir); len(ents) != 1 {
t.Fatalf("leftovers in state dir: %v", ents)
}
}
}
func TestSessionMigratesFromOldPath(t *testing.T) {
home := isolate(t)
old := filepath.Join(home, ".config", "vcom", "session.toml")
if err := os.MkdirAll(filepath.Dir(old), 0o755); err != nil {
t.Fatal(err)
}
content := "active_pane = 'right'\n[left]\npath = '/srv'\nentry_name = 'data'\n[left.cursor_memory]\n'/srv' = 'data'\n"
if err := os.WriteFile(old, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
s, err := Load()
if err != nil {
t.Fatal(err)
}
if s.ActivePane != "right" || s.Left.Path != "/srv" || s.Left.CursorMemory["/srv"] != "data" {
t.Fatalf("migrated %+v", s)
}
if _, err := os.Stat(filepath.Join(home, ".local", "state", "vcom", "session.toml")); err != nil {
t.Fatalf("not written to the new location: %v", err)
}
if _, err := os.Stat(old); !os.IsNotExist(err) {
t.Fatal("old session file not removed after migration")
}
// Nothing anywhere: empty session, no error.
isolate(t)
if s, err := Load(); err != nil || s.ActivePane != "" {
t.Fatalf("empty: %+v %v", s, err)
}
}
func TestCursorMemoryCapped(t *testing.T) {
home := isolate(t)
mem := map[string]string{}
for i := range 500 {
mem[fmt.Sprintf("/data/d%03d", i)] = "f"
}
mem["/work/project/src"] = "main.go"
mem["/work"] = "project"
cache := filepath.Join(home, ".cache", "vcom", "run-1", "preview")
mem[cache] = "img.png"
mem[filepath.Join(os.TempDir(), "vcom-archive-123", "x")] = "y"
if err := Save(Session{Left: PaneSession{Path: "/work/project", CursorMemory: mem}}); err != nil {
t.Fatal(err)
}
s, err := Load()
if err != nil {
t.Fatal(err)
}
got := s.Left.CursorMemory
if len(got) != MaxCursorMemory {
t.Fatalf("%d entries, want %d", len(got), MaxCursorMemory)
}
if got["/work/project/src"] != "main.go" || got["/work"] != "project" {
t.Fatal("entries on the current path must survive the cap")
}
for k := range got {
if k == cache || filepath.Dir(k) == filepath.Join(os.TempDir(), "vcom-archive-123") {
t.Fatalf("transient path kept: %s", k)
}
}
}

View file

@ -0,0 +1,66 @@
package ui
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"vcom/internal/config"
"vcom/internal/testutil/teadriver"
)
// Choosing a theme rewrites only the theme line of the user's config (2C.3):
// comments, unknown keys and order survive.
func TestSmokeThemeSelectKeepsConfigComments(t *testing.T) {
isolateEnv(t)
dir := t.TempDir()
cfgPath := filepath.Join(dir, "vcom.toml")
before := "# my settings\n[ui]\n# the look\ntheme = 'catppuccin-mocha' # favourite\nicon_mode = 'ascii'\n\n[behavior]\nauto_refresh = true # unknown, keep\n"
writeFile(t, cfgPath, before)
cfg, info, err := config.Load(cfgPath)
if err != nil || !info.Found {
t.Fatalf("load: %v %+v", err, info)
}
cfg.Startup.LeftPath, cfg.Startup.RightPath = dir, dir
m, err := NewModel(cfg, info.Path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { m.cleanupArchiveMounts(); m.cleanupRemoteImageTemp() })
d := teadriver.New(t, m, 160, 40, teadriver.WithLongCmd(300*time.Millisecond))
d.Settle(settle)
d.Press("t", "j", "enter")
d.Settle(settle)
chosen := cur(t, d).cfg.UI.Theme
if chosen == "catppuccin-mocha" {
t.Fatal("theme did not change")
}
b, err := os.ReadFile(cfgPath)
if err != nil {
t.Fatal(err)
}
want := strings.Replace(before, "theme = 'catppuccin-mocha'", "theme = '"+chosen+"'", 1)
if string(b) != want {
t.Fatalf("config rewritten:\n%s\nwant:\n%s", b, want)
}
}
// The session goes to $XDG_STATE_HOME/vcom/session.toml.
func TestSmokeSessionInStateDir(t *testing.T) {
dir := t.TempDir()
d := newDriver(t, dir, dir)
m := cur(t, d)
m.saveSession()
p := filepath.Join(os.Getenv("XDG_STATE_HOME"), "vcom", "session.toml")
if _, err := os.Stat(p); err != nil {
t.Fatalf("session not in state dir: %v", err)
}
if _, err := os.Stat(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "vcom", "session.toml")); !os.IsNotExist(err) {
t.Fatal("session written to the old config location")
}
}

View file

@ -31,6 +31,9 @@ func isolateEnv(t *testing.T) string {
t.Setenv("HOME", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
t.Setenv("XDG_STATE_HOME", filepath.Join(home, ".local", "state"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Setenv("VCOM_CONFIG", "")
t.Setenv("SSH_AUTH_SOCK", "")
t.Setenv("VISUAL", "")
t.Setenv("EDITOR", "")

View file

@ -3045,7 +3045,7 @@ func (m *Model) cycleTheme() (tea.Model, tea.Cmd) {
log.Printf("[TOGGLE] CycleTheme: %s -> %s", m.cfg.UI.Theme, next)
m.cfg.UI.Theme = next
m.palette = palette
savedPath, saveErr := config.Save(m.cfg, m.configPath)
savedPath, saveErr := config.SetKey(m.configPath, "ui", "theme", m.cfg.UI.Theme)
if saveErr != nil {
m.status = fmt.Sprintf("Theme: %s (save failed: %v)", next, saveErr)
return m, nil
@ -3093,7 +3093,7 @@ func (m *Model) finalizeTheme(name string) {
}
m.cfg.UI.Theme = name
m.palette = palette
savedPath, saveErr := config.Save(m.cfg, m.configPath)
savedPath, saveErr := config.SetKey(m.configPath, "ui", "theme", m.cfg.UI.Theme)
if saveErr != nil {
m.status = fmt.Sprintf("Theme: %s (save failed: %v)", name, saveErr)
return