iterm2

package
v0.0.132 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildSessionsRestoreScript added in v0.0.127

func BuildSessionsRestoreScript(doc *SaveDocument) string

BuildSessionsRestoreScript returns AppleScript that creates one new iTerm2 window per saved window and one tab per saved tab, then sends:

cd <cwd>
<resume_cmd>

as two separate write text lines (empty cwd skips the cd line).

Window title setting is best-effort: each set name is wrapped in try/on error so a refused title does not abort remaining windows. Failures are returned as one line per title on stdout (empty stdout means all titles OK).

func DefaultSessionsSavePath added in v0.0.127

func DefaultSessionsSavePath() string

DefaultSessionsSavePath is ~/.config/iterm2/sessions-save.json.

func Handle

func Handle(args []string) error

Handle runs the kool iterm2 subcommand.

func InstallPhasedFixtureCollectorForTest added in v0.0.127

func InstallPhasedFixtureCollectorForTest(t testing.TB, opts PhasedFixtureOpts)

InstallPhasedFixtureCollectorForTest installs an injectable SnapshotCollector that implements ListWindows / ListTabsAndSessions from opts.Windows and process enrich from IdleTTYs / BusyTTYs. Restored via t.Cleanup. Holds an exclusive inject lock so parallel doctest leaves cannot race.

func RenderSessionStatus added in v0.0.127

func RenderSessionStatus(w io.Writer, snap *Snapshot, s *SnapshotSession, opt RenderOptions) error

RenderSessionStatus writes a single-session status report.

func RenderSnapshot added in v0.0.127

func RenderSnapshot(w io.Writer, snap *Snapshot, opt RenderOptions) error

RenderSnapshot writes the snapshot in the requested format to w.

func RunForTest

func RunForTest(args []string, stdout, stderr io.Writer, workingDir string) int

RunForTest runs the handler in-process for doctest handler phase.

func SetGOOSForTest

func SetGOOSForTest(goos string)

SetGOOSForTest overrides platform detection for handler tests.

func SetSessionsRunRestoreASForTest added in v0.0.132

func SetSessionsRunRestoreASForTest(fn func(script string) (string, error))

SetSessionsRunRestoreASForTest installs the restore AppleScript runner for L2/unit tests. Pass nil to restore the production default. Prefer t.Cleanup to restore.

func SetSnapshotCollectorForTest added in v0.0.127

func SetSnapshotCollectorForTest(c *SnapshotCollector)

SetSnapshotCollectorForTest overrides the collector used by CaptureSnapshot. Pass nil to restore production defaults. Tests should t.Cleanup restore. Prefer InstallPhasedFixtureCollectorForTest for parallel-safe inject.

func SetSpaceBackendForTest added in v0.0.132

func SetSpaceBackendForTest(b SpaceBackend)

SetSpaceBackendForTest installs a Space Backend for restore placement. Pass nil to restore live path. Tests should t.Cleanup restore.

func SetSpaceIndexForWindowForTest added in v0.0.132

func SetSpaceIndexForWindowForTest(fn SpaceIndexResolver)

SetSpaceIndexForWindowForTest installs a Space index resolver. Pass nil to restore. Tests should t.Cleanup restore.

func WriteError added in v0.0.127

func WriteError(stderr io.Writer, msg string)

WriteError prints a red Error line when appropriate.

func WriteSaveDocument added in v0.0.127

func WriteSaveDocument(path string, doc *SaveDocument) error

WriteSaveDocument writes the checkpoint atomically (temp + rename).

func WriteWarning added in v0.0.127

func WriteWarning(stderr io.Writer, msg string)

WriteWarning prints a yellow warning line to stderr when color is appropriate.

Types

type AgentResolveFixture added in v0.0.127

type AgentResolveFixture struct {
	Kind      string // grok | codex | none
	SessionID string
	Title     string // optional GrokTitle
	Tree      []AgentTreeNode
}

AgentResolveFixture is an injectable procresolve result keyed by tty (tests).

type AgentTreeNode added in v0.0.127

type AgentTreeNode struct {
	PID  int    `json:"pid"`
	PPID int    `json:"ppid"`
	Role string `json:"role,omitempty"` // input | agent-run | … | grok | codex | other
	Cmd  string `json:"cmd"`
}

AgentTreeNode is one process in the agent process tree (JSON + FormatTree).

type CaptureOpts added in v0.0.127

type CaptureOpts struct {
	// NoEnrich skips procresolve agent attach (CLI --no-enrich).
	NoEnrich bool
}

CaptureOpts controls optional phases of snapshot capture.

type FormatFlags added in v0.0.127

type FormatFlags struct {
	JSON     bool
	Markdown bool
	HTML     bool
}

FormatFlags are mutually exclusive explicit format options.

type OutputFormat added in v0.0.127

type OutputFormat string

OutputFormat is how a snapshot is rendered.

const (
	FormatCLI      OutputFormat = "cli"
	FormatJSON     OutputFormat = "json"
	FormatMarkdown OutputFormat = "markdown"
	FormatHTML     OutputFormat = "html"
)

func ResolveFormat added in v0.0.127

func ResolveFormat(flags FormatFlags, outputPath string) (OutputFormat, error)

ResolveFormat picks the output format from explicit flags and optional -o path. Explicit format flags win over file suffix. Multiple format flags → error. Unknown suffix with no flag → FormatCLI (plain text when writing to a file).

type PhasedFixtureOpts added in v0.0.127

type PhasedFixtureOpts struct {
	Windows       []SnapshotWindow
	ITermRunning  bool
	OnListWindows func()
	OnListTabs    func(windowIndex int)
	// IdleTTYs are short tty names (e.g. "ttys001") classified idle (shell only).
	IdleTTYs []string
	// BusyTTYs are short tty names classified busy (non-shell foreground work).
	BusyTTYs []string
	// BusyLeafByTTY overrides the default busy leaf command (python train.py)
	// for that short tty. Use e.g. "mark still waiting" for mark fixtures.
	BusyLeafByTTY map[string]string
	// CwdByTTY sets the cwd returned for processes on that short tty (default /tmp).
	CwdByTTY map[string]string
	Now      time.Time
	Hostname string
	// AgentResolveByTTY injects procresolve results keyed by short tty (e.g. "ttys002").
	// Applied after process enrich for busy sessions when enrich is on.
	AgentResolveByTTY map[string]AgentResolveFixture
}

PhasedFixtureOpts configures InstallPhasedFixtureCollectorForTest.

type RenderOptions added in v0.0.127

type RenderOptions struct {
	Format  OutputFormat
	NoColor bool
	// NoTree omits FormatTree process-tree lines while keeping agent session id.
	NoTree bool
	// ForceColor forces ANSI even when stdout is not a TTY (tests).
	ForceColor bool
	// ColorWriter is checked for TTY (defaults to os.Stdout).
	ColorWriter *os.File
}

RenderOptions control snapshot rendering.

type SaveDocument added in v0.0.127

type SaveDocument struct {
	Version    int          `json:"version"`
	SavedAt    string       `json:"saved_at"`
	RestoredAt *string      `json:"restored_at"` // null until restore succeeds
	Host       string       `json:"host"`
	Source     string       `json:"source"`
	Summary    SaveSummary  `json:"summary"`
	Windows    []SaveWindow `json:"windows"`
}

SaveDocument is the checkpoint written by sessions save / read by restore.

func BuildSaveDocument added in v0.0.127

func BuildSaveDocument(snap *Snapshot, now time.Time, host string) (*SaveDocument, []string)

BuildSaveDocument filters a live snapshot to critical grok/codex/mark tabs. Skips panes with empty cwd (warning). Prefers agent over mark on the same pane.

func ReadSaveDocument added in v0.0.127

func ReadSaveDocument(path string) (*SaveDocument, error)

ReadSaveDocument loads and validates a checkpoint file.

func (*SaveDocument) IsConsumed added in v0.0.127

func (d *SaveDocument) IsConsumed() bool

IsConsumed returns true when restored_at is set to a non-empty string.

type SaveSummary added in v0.0.127

type SaveSummary struct {
	Windows  int            `json:"windows"`
	Tabs     int            `json:"tabs"`
	Sessions int            `json:"sessions"`
	ByKind   map[string]int `json:"by_kind"`
}

SaveSummary counts critical tabs in the checkpoint.

type SaveTab added in v0.0.127

type SaveTab struct {
	SourceTabIndex  int    `json:"source_tab_index,omitempty"`
	SourcePaneIndex int    `json:"source_pane_index,omitempty"`
	Name            string `json:"name,omitempty"`
	Cwd             string `json:"cwd"`
	Kind            string `json:"kind"` // grok | codex | mark
	SessionID       string `json:"session_id,omitempty"`
	Message         string `json:"message,omitempty"` // mark only
	Title           string `json:"title,omitempty"`
	ResumeCmd       string `json:"resume_cmd"`
	ItermSessionID  string `json:"iterm_session_id,omitempty"`
	SourceCmdLine   string `json:"source_command_line,omitempty"`
}

SaveTab is one critical pane to restore as a tab (cd + resume_cmd).

type SaveWindow added in v0.0.127

type SaveWindow struct {
	SourceIndex   int       `json:"source_index"`
	Name          string    `json:"name,omitempty"`
	Space         int       `json:"space"`                     // 0-based Desktop; always emitted when not ignore
	ItermWindowID int64     `json:"iterm_window_id,omitempty"` // info only at save; restore never uses it
	Tabs          []SaveTab `json:"tabs"`
	// contains filtered or unexported fields
}

SaveWindow is one original iTerm window that had critical tabs.

func (SaveWindow) MarshalJSON added in v0.0.132

func (w SaveWindow) MarshalJSON() ([]byte, error)

MarshalJSON always emits "space" (including 0) unless noSpaceRecord.

type SessionAgent added in v0.0.127

type SessionAgent struct {
	Kind      string          `json:"kind"`
	SessionID string          `json:"session_id"`
	Title     string          `json:"title,omitempty"`
	Tree      []AgentTreeNode `json:"tree,omitempty"`
}

SessionAgent is the procresolve result attached to a busy SnapshotSession.

type Snapshot added in v0.0.127

type Snapshot struct {
	CapturedAt string           `json:"captured_at"`
	Host       string           `json:"host"`
	Source     string           `json:"source"`
	Summary    SnapshotSummary  `json:"summary"`
	Windows    []SnapshotWindow `json:"windows"`
}

Snapshot is a full inventory of iTerm2 windows, tabs, and sessions (panes).

func CaptureSnapshot added in v0.0.127

func CaptureSnapshot() (*Snapshot, []string, error)

CaptureSnapshot builds a full live snapshot of iTerm2 sessions.

func CaptureSnapshotWith added in v0.0.127

func CaptureSnapshotWith(opts CaptureOpts) (*Snapshot, []string, error)

CaptureSnapshotWith builds a snapshot with capture options (e.g. NoEnrich).

type SnapshotCollector added in v0.0.127

type SnapshotCollector struct {
	// RunAppleScript runs an AppleScript body and returns stdout.
	RunAppleScript func(script string) (string, error)
	// ListProcs returns processes on a short tty name (e.g. "ttys003").
	ListProcs func(ttyShort string) ([]rawProc, error)
	// ListCwds returns cwd paths keyed by pid for the given pids.
	ListCwds func(pids []int) (map[int]string, error)
	// ITermRunning reports whether iTerm2 appears to be running.
	ITermRunning func() bool
	// Now is the clock (defaults to time.Now).
	Now func() time.Time
	// Hostname defaults to os.Hostname.
	Hostname func() (string, error)

	// OnListWindows is an optional test hook invoked at the start of ListWindows.
	OnListWindows func()
	// OnListTabs is an optional test hook invoked at the start of ListTabsAndSessions.
	OnListTabs func(windowIndex int)

	// ResolveFromPID optionally overrides live procresolve (production default).
	ResolveFromPID func(pid int) (*procresolve.Result, error)
	// contains filtered or unexported fields
}

SnapshotCollector gathers hierarchy + process enrichment. Fields may be overridden in tests.

func ActiveSnapshotCollectorForTest added in v0.0.127

func ActiveSnapshotCollectorForTest() *SnapshotCollector

ActiveSnapshotCollectorForTest returns the collector CaptureSnapshot will use.

func (*SnapshotCollector) Capture added in v0.0.127

func (c *SnapshotCollector) Capture() (*Snapshot, []string, error)

Capture runs phased hierarchy collection + process enrichment.

func (*SnapshotCollector) CaptureWith added in v0.0.127

func (c *SnapshotCollector) CaptureWith(opts CaptureOpts) (*Snapshot, []string, error)

CaptureWith runs Capture with options (e.g. skip agent enrich).

func (*SnapshotCollector) ListTabsAndSessions added in v0.0.127

func (c *SnapshotCollector) ListTabsAndSessions(windowIndex int) (tabs []SnapshotTab, warnings []string, err error)

ListTabsAndSessions returns tabs and sessions for one window (by 1-based index).

func (*SnapshotCollector) ListWindows added in v0.0.127

func (c *SnapshotCollector) ListWindows() (windows []SnapshotWindow, warnings []string, err error)

ListWindows returns window index + name headers (tabs may be empty).

type SnapshotProc added in v0.0.127

type SnapshotProc struct {
	PID             int     `json:"pid"`
	PPID            int     `json:"ppid"`
	Stat            string  `json:"stat"`
	Etime           string  `json:"etime"`
	DurationSeconds int64   `json:"duration_seconds"`
	Duration        string  `json:"duration"`
	StartTime       *string `json:"start_time"`
	StartTimeUnix   *int64  `json:"start_time_unix"`
	RSSKB           int64   `json:"rss_kb"`
	Command         string  `json:"command"`
}

SnapshotProc is one process observed on a session tty.

type SnapshotSession added in v0.0.127

type SnapshotSession struct {
	Index             int            `json:"index"`
	ID                string         `json:"id"`
	Name              string         `json:"name"`
	TTY               string         `json:"tty"`
	Profile           string         `json:"profile"`
	ItermIsProcessing bool           `json:"iterm_is_processing"`
	Idle              *bool          `json:"idle"` // nil = unknown
	Cwd               *string        `json:"cwd"`
	ShellPID          *int           `json:"shell_pid"`
	PID               *int           `json:"pid"`
	PPID              *int           `json:"ppid"`
	Stat              *string        `json:"stat"`
	Command           *string        `json:"command"`
	CommandLine       *string        `json:"command_line"`
	StartTime         *string        `json:"start_time"`
	StartTimeUnix     *int64         `json:"start_time_unix"`
	DurationSeconds   *int64         `json:"duration_seconds"`
	Duration          *string        `json:"duration"`
	Etime             *string        `json:"etime"`
	RSSKB             *int64         `json:"rss_kb"`
	Processes         []SnapshotProc `json:"processes"`
	// Agent is set when procresolve finds a grok/codex session on a busy pane.
	Agent *SessionAgent `json:"agent,omitempty"`
	// Layout hints (not required for id resolution).
	WindowIndex int `json:"window_index,omitempty"`
	TabIndex    int `json:"tab_index,omitempty"`
}

SnapshotSession is one pane/session. Id is the iTerm2 session unique ID (UUID).

func FindSessionsByRef added in v0.0.127

func FindSessionsByRef(snap *Snapshot, ref string) []*SnapshotSession

FindSessionInSnapshot returns sessions matching a user-supplied id token.

type SnapshotSummary added in v0.0.127

type SnapshotSummary struct {
	Windows  int `json:"windows"`
	Tabs     int `json:"tabs"`
	Sessions int `json:"sessions"`
	Idle     int `json:"idle"`
	Busy     int `json:"busy"`
	Unknown  int `json:"unknown"`
}

SnapshotSummary counts windows/tabs/sessions and idle/busy.

type SnapshotTab added in v0.0.127

type SnapshotTab struct {
	Index    int               `json:"index"`
	Name     string            `json:"name"`
	Sessions []SnapshotSession `json:"sessions"`
}

SnapshotTab is one tab; sessions are panes within the tab.

type SnapshotWindow added in v0.0.127

type SnapshotWindow struct {
	Index int    `json:"index"`
	Name  string `json:"name"`
	// WindowID is the iTerm/AppleScript window id (CG window number when available).
	// Used to resolve macOS Space on sessions save; zero means unknown.
	WindowID uint64        `json:"window_id,omitempty"`
	Tabs     []SnapshotTab `json:"tabs"`
}

SnapshotWindow is one iTerm2 window.

type SpaceBackend added in v0.0.132

type SpaceBackend = space.Backend

SpaceBackend is Create / Switch / Highest for restore placement. Matches space.Backend (Create/Switch/List/Highest); tests typically inject space.MockBackend.

type SpaceIndexResolver added in v0.0.132

type SpaceIndexResolver func(windowID uint64) (int, error)

SpaceIndexResolver maps an iTerm/CG window id to a 0-based Desktop index.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL