iterm2

package
v0.0.154 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CanonicalITermAppSystem = "/Applications/iTerm.app"
	CanonicalITermAppHome   = "~/Applications/iTerm.app"
)

Canonical iTerm2 install paths recorded in SaveWindow.app (D9). Home form is always ~/… never expanded /Users/….

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).

Uses bare tell application "iTerm2". Prefer BuildSessionsRestoreScriptWithTell when a path target is known.

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 BuildSessionsRestoreScriptWithTell added in v0.0.142

func BuildSessionsRestoreScriptWithTell(doc *SaveDocument, appTell string) string

BuildSessionsRestoreScriptWithTell is BuildSessionsRestoreScript with an optional path-tell target. appTell is an absolute .app path (or expanded home path); empty or "iTerm2" uses bare tell application "iTerm2".

func ClearRestoreAppDiskForTest added in v0.0.142

func ClearRestoreAppDiskForTest()

ClearRestoreAppDiskForTest restores live disk checks and releases the exclusive inject hold from SetRestoreAppDiskForTest.

func DefaultSessionsAutoPath added in v0.0.143

func DefaultSessionsAutoPath() string

DefaultSessionsAutoPath is ~/.config/iterm2/sessions-auto.json. Distinct from DefaultSessionsSavePath (manual sessions-save.json).

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 RunFocusForTest added in v0.0.133

func RunFocusForTest(args []string, stdout, stderr io.Writer, fake *FocusFake) int

RunFocusForTest runs the iterm2 focus route against an injected boundary. args are the full arguments after "kool iterm2", mirroring the public handler rather than requiring callers to strip the focus subcommand.

func RunForTest

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

RunForTest runs the handler in-process for doctest handler phase. workingDir is unused; callers pass absolute paths in args.

func RunForTestEnv added in v0.0.150

func RunForTestEnv(args []string, stdout, stderr io.Writer, env TestRun) int

RunForTestEnv is RunForTest with explicit hooks (no process Setenv/Chdir).

func SetGOOSForTest

func SetGOOSForTest(goos string)

SetGOOSForTest overrides platform detection for handler tests.

func SetInstallHTTPForTest added in v0.0.144

func SetInstallHTTPForTest(latestURL string, client *http.Client) (restore func())

SetInstallHTTPForTest injects latest URL + HTTP client for install resolve/download. Returns restore; callers should defer restore (also safe under a process mutex).

func SetMultiAppPreflightForTest added in v0.0.140

func SetMultiAppPreflightForTest(fn MultiAppPreflightFn)

SetMultiAppPreflightForTest installs a preflight resolver for tests. Pass nil to restore live discovery. Prefer t.Cleanup.

func SetRestoreAppDiskForTest added in v0.0.142

func SetRestoreAppDiskForTest(homeExists, systemExists bool)

SetRestoreAppDiskForTest injects which canonical installs exist for restore target resolution (prefer-home / --same-app). Takes an exclusive hold until ClearRestoreAppDiskForTest so parallel leaves cannot clobber each other. Prefer t.Cleanup(ClearRestoreAppDiskForTest).

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
	// SpaceAllow, when non-empty, enables space-first filtering: resolve each
	// window's Space from WindowID/FixedSpace and skip ListTabsAndSessions +
	// enrich when the index is not in the allowlist (go-best-practice: cheap
	// gate before expensive work). Used by sessions save --spaces.
	SpaceAllow []int
	// SpaceSkipped, when non-nil, receives the count of window headers skipped
	// by SpaceAllow (not deep-captured).
	SpaceSkipped *int
}

CaptureOpts controls optional phases of snapshot capture.

type FocusCandidate added in v0.0.133

type FocusCandidate struct {
	WindowID      string
	WindowTitle   string
	TabIndex      int
	SessionID     string
	Path          string
	KoolTargetDir string
}

FocusCandidate identifies one candidate session. Its order is presented to users as the stable zero-based --index order.

type FocusFake added in v0.0.133

type FocusFake struct {
	Candidates    []FocusCandidate
	Focused       []string
	DiscoverCalls int
}

FocusFake is the deterministic injected iTerm boundary used by L2 callers.

func (*FocusFake) Discover added in v0.0.133

func (f *FocusFake) Discover(_ string) ([]FocusCandidate, error)

func (*FocusFake) Focus added in v0.0.133

func (f *FocusFake) Focus(candidate FocusCandidate) error

type FormatFlags added in v0.0.127

type FormatFlags struct {
	JSON     bool
	Markdown bool
	HTML     bool
}

FormatFlags are mutually exclusive explicit format options.

type MultiAppPreflight added in v0.0.140

type MultiAppPreflight struct {
	// AsApp is the canonical app that bare `tell application "iTerm2"` targets.
	AsApp string
	// RunningApps is the set of canonical installs with a live process
	// (home and/or system). Order is not significant.
	RunningApps []string
}

MultiAppPreflight is the resolved bare-AS app and running install list (save-only).

type MultiAppPreflightFn added in v0.0.140

type MultiAppPreflightFn func() (MultiAppPreflight, error)

MultiAppPreflightFn resolves preflight for multi-app save.

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 RestoreAppTarget added in v0.0.142

type RestoreAppTarget struct {
	// Canonical is ~/Applications/iTerm.app or /Applications/iTerm.app, or empty when Bare.
	Canonical string
	// Bare means fall back to tell application "iTerm2" (no path).
	Bare bool
	// Warning is optional user message without the "warning:" prefix.
	Warning string
}

RestoreAppTarget is a resolved create/tell target for restore.

func (RestoreAppTarget) Display added in v0.0.142

func (t RestoreAppTarget) Display() string

Display returns the plan-text form: canonical path or bare "iTerm2".

func (RestoreAppTarget) TellPath added in v0.0.142

func (t RestoreAppTarget) TellPath() string

TellPath returns the absolute .app path for AppleScript path-tell, or "" for bare.

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"`
	Filter     *SaveFilter  `json:"filter,omitempty"` // present when save used --spaces
	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 SaveFilter added in v0.0.140

type SaveFilter struct {
	// Spaces is the sorted, deduped 0-based allowlist from --spaces.
	Spaces []int `json:"spaces,omitempty"`
}

SaveFilter records save-time constraints applied when building the checkpoint. Restore ignores this object for placement; it is audit/metadata only.

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"`
	App           string    `json:"app,omitempty"`             // canonical install; restore prefer-home or --same-app
	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. App is omitempty (canonical strings only when known).

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 CaptureSnapshotForSave added in v0.0.140

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

CaptureSnapshotForSave captures all multi-app sources when live (not fixture). Fixture collectors already carry dual App tags in one snapshot — single pass. opts.SpaceAllow enables space-first deep-capture filter (save --spaces).

func CaptureSnapshotForSaveStream added in v0.0.140

func CaptureSnapshotForSaveStream(opts CaptureOpts, onWindowReady func(win SnapshotWindow) error) (*Snapshot, []string, error)

CaptureSnapshotForSaveStream is CaptureSnapshotForSave with an optional per-window callback after each deep-captured window is ready (streaming dry-run).

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)

	// AppTell is the AppleScript application target for live capture.
	// Empty → "iTerm2". Absolute path → tell that .app (second dual-install instance).
	// Canonical App tags are set separately via AppTag / multi-app merge.
	AppTell string
	// AppTag is stamped on every window from this collector (canonical app path).
	// Empty leaves window.App unset (fixtures may set App per window).
	AppTag string
	// 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"`
	// FixedSpace, when non-nil, is the resolved 0-based Space for tests/fixtures.
	// Prefer this over SpaceIndexForWindow so parallel tests need no global hook.
	FixedSpace *int `json:"-"`
	// App is the canonical iTerm install that owns this window (fixture tag or
	// multi-app save source). Only "~/Applications/iTerm.app" or
	// "/Applications/iTerm.app". Not emitted on sessions snapshot JSON.
	App  string        `json:"-"`
	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.

type TestRun added in v0.0.150

type TestRun struct {
	TabSetDir string
	GOOS      string
	Installed func() bool
	Osascript func(script string) error
	// Contents overrides lib.Contents (tests).
	Contents func(sessionID string, cfg *lib.ContentsConfig) (lib.ContentsResult, error)
}

TestRun injects handler-test overrides. Do not mutate process env or cwd.

Jump to

Keyboard shortcuts

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