Documentation
¶
Overview ¶
Package session owns the core domain: a running AI coding agent represented by the Instance type.
An Instance moves through a small lifecycle — Ready → Loading → Running → Paused (and optionally Killed) — coordinating with neighbouring packages at each stage: session/git for worktree creation and cleanup, session/tmux for the PTY that drives the agent, and session/agent for program-specific behaviour such as trust-prompt handling and recovery flags.
Persistence lives in storage.go and is versioned via CurrentSchemaVersion; when the on-disk InstanceData schema changes, bump the constant and add an upgrade step in storage_migrate.go. State transitions are validated through Instance.TransitionTo; disallowed edges return an error rather than silently mutating.
Index ¶
- Constants
- Variables
- func BuildEffortCommand(program, effort string) string
- func BuildModelCommand(program, model string) string
- func BuildPermissionModeCommand(program, mode string) string
- func BuildRecoveryCommand(program string) string
- func BuildRemoteControlCommand(program, sessionName string) string
- func CacheTTL1hEnv(enabled bool, program string) []string
- func CheckTmuxAlive(sessionTitle string, cmdExec internalexec.Executor) bool
- func CheckWorktreeExists(worktreePath string) bool
- func CleanupOrphanedSessions(claimedTitles map[string]bool, cmdExec internalexec.Executor) error
- func HeadroomProxyEnv(enabled bool, program string) []string
- func HumanizeBranchLeaf(branch string) string
- func InstanceEnv(program string, headroomProxy, cacheTTL1h bool) []string
- func IsAllowedTransition(from, to Status) bool
- func IsClaudeProgram(program string) bool
- func KillTmuxSessionByTitle(title string, cmdExec internalexec.Executor) error
- func RemoveOrphanWorktree(repoPath, worktreePath string) error
- func SanitizedToTmuxName(title string) string
- type DiffStatsData
- type GitWorktreeData
- type Instance
- func (i *Instance) CaptureAndProcessStatus() (updated bool, hasPrompt bool, err error)
- func (i *Instance) CaptureHistory() (string, bool)
- func (i *Instance) CheckAndHandleTrustPrompt() bool
- func (i *Instance) CrashRestart() error
- func (i *Instance) EnsureRunning() error
- func (i *Instance) ForwardMouse(cb, col, row int, press bool) error
- func (i *Instance) ForwardWheel(up bool, n int) error
- func (i *Instance) GetBranch() string
- func (i *Instance) GetContentHash() []byte
- func (i *Instance) GetDiffStats() *git.DiffStats
- func (i *Instance) GetGitWorktree() (*git.GitWorktree, error)
- func (i *Instance) GetStatus() Status
- func (i *Instance) GetWorktreePath() string
- func (i *Instance) HasUpdated() (updated bool, hasPrompt bool)
- func (i *Instance) IsAlternateScreen() bool
- func (i *Instance) Kill() (err error)
- func (i *Instance) Paste(text string) error
- func (i *Instance) Pause(saveState func() error) (err error)
- func (i *Instance) Paused() bool
- func (i *Instance) Preview() (string, error)
- func (i *Instance) RepoName() (string, error)
- func (i *Instance) Restart() error
- func (i *Instance) Resume(saveState func() error) (err error)
- func (i *Instance) SendKeys(keys string) error
- func (i *Instance) SendKeysRaw(b []byte) error
- func (i *Instance) SendPrompt(prompt string) error
- func (i *Instance) SetPreviewSize(width, height int) error
- func (i *Instance) SetSelectedBranch(branch string)
- func (i *Instance) SetTitle(title string) error
- func (i *Instance) SetTmuxSession(session *tmux.TmuxSession)
- func (i *Instance) ShouldRefreshDiff(tmuxUpdated, wantFull bool) bool
- func (i *Instance) Snapshot() InstanceData
- func (i *Instance) Start(firstTimeSetup bool) (err error)
- func (i *Instance) Started() bool
- func (i *Instance) TapEnter()
- func (i *Instance) TmuxAlive() bool
- func (i *Instance) TmuxSession() *tmux.TmuxSession
- func (i *Instance) ToInstanceData() InstanceData
- func (i *Instance) TransitionTo(to Status) error
- func (i *Instance) UpdateDiffStats() error
- func (i *Instance) UpdateDiffStatsShort() error
- type InstanceData
- type InstanceOptions
- type OrphanCandidate
- type OrphanDisposition
- type RecoveryAction
- type RemoteControlAuth
- type RemoteControlAuthState
- type SessionBackend
- type Status
- type Storage
- func (s *Storage) DeleteAllInstances() error
- func (s *Storage) DeleteInstance(title string) error
- func (s *Storage) LoadAndReconcile(cmdExec internalexec.Executor) ([]*Instance, error)
- func (s *Storage) LoadInstanceData() ([]InstanceData, error)
- func (s *Storage) LoadInstances() ([]*Instance, error)
- func (s *Storage) SaveInstances(instances []*Instance) error
- func (s *Storage) UnrecoveredWorktreePaths() map[string]bool
- func (s *Storage) UpdateInstance(instance *Instance) error
Constants ¶
const CurrentSchemaVersion = 5
CurrentSchemaVersion is the schema version written by the current binary. Any on-disk InstanceData with a lower SchemaVersion is routed through storage_migrate.go's Migrate before use.
const HeadroomProxyURL = "http://127.0.0.1:8787"
HeadroomProxyURL is the base URL Loom points ANTHROPIC_BASE_URL at when the Headroom Proxy launch option is enabled — Headroom's own default proxy address (`headroom proxy`, port 8787). Loom does not start or manage the proxy process itself; the user is expected to have it running already (e.g. via `headroom install`'s persistent deployment).
Variables ¶
var ErrInstanceNotFound = errors.New("instance not found")
ErrInstanceNotFound signals that a storage mutation (delete, update) referenced a title that is no longer persisted. Callers performing idempotent cleanup — e.g. the kill path, where Kill() has already destroyed tmux + worktree before DeleteInstance runs — can match it with errors.Is to distinguish "already gone" from a real write error.
Functions ¶
func BuildEffortCommand ¶ added in v0.6.0
BuildEffortCommand modifies a program command string to launch with the given --effort value. The adapter registry decides whether and how the string is modified. Idempotent, and a no-op for agents without an effort-level concept or when effort is "" / "default".
func BuildModelCommand ¶ added in v0.5.0
BuildModelCommand modifies a program command string to launch with the given --model value. The adapter registry decides whether and how the string is modified. Idempotent, and a no-op for agents without a model-selection concept or when model is "" / "default".
func BuildPermissionModeCommand ¶ added in v0.4.0
BuildPermissionModeCommand modifies a program command string to launch with the given --permission-mode value. The adapter registry decides whether and how the string is modified. Idempotent, and a no-op for agents without a permission-mode concept or when mode is "" / "default".
func BuildRecoveryCommand ¶
BuildRecoveryCommand modifies a program command string for crash recovery. The adapter registry decides whether and how the string is modified (e.g. "claude" → "claude --continue"). Unsupported agents are returned unchanged.
func BuildRemoteControlCommand ¶ added in v0.3.0
BuildRemoteControlCommand modifies a program command string to launch the agent with its remote-control mode enabled, naming the remote session after sessionName. The adapter registry decides whether and how the string is modified (e.g. "claude" → "claude --remote-control <name>"). Idempotent, and a no-op for agents without a remote-control mode.
func CacheTTL1hEnv ¶ added in v0.6.0
CacheTTL1hEnv returns the tmux session environment variable that extends Claude's prompt cache from the default 5-minute TTL to 1 hour. A no-op (nil) unless enabled and program resolves to Claude — ENABLE_PROMPT_CACHING_1H is a Claude-CLI-specific toggle, so setting it for any other agent wouldn't do anything useful.
func CheckTmuxAlive ¶
func CheckTmuxAlive(sessionTitle string, cmdExec internalexec.Executor) bool
CheckTmuxAlive checks if a tmux session exists by its sanitized name.
func CheckWorktreeExists ¶
CheckWorktreeExists checks if the worktree directory exists on disk.
func CleanupOrphanedSessions ¶
func CleanupOrphanedSessions(claimedTitles map[string]bool, cmdExec internalexec.Executor) error
CleanupOrphanedSessions kills any tmux sessions with the loom or legacy claude-squad prefix that are not claimed by a loaded instance. Legacy-prefixed sessions are swept too so upgrades from claude-squad don't leave zombie panes behind.
func HeadroomProxyEnv ¶ added in v0.6.0
HeadroomProxyEnv returns the tmux session environment variables needed to route program's API calls through Headroom's proxy. A no-op (nil) unless enabled and program resolves to Claude — ANTHROPIC_BASE_URL is Anthropic-API-specific, so setting it for any other agent wouldn't do anything useful.
func HumanizeBranchLeaf ¶ added in v0.1.3
HumanizeBranchLeaf turns a branch name into a plausible display title by taking the last `/`-segment and replacing dashes with spaces. e.g. "aidanb/example-jupyter-notebook" → "example jupyter notebook". This is the lossy fallback used when the original title is unrecoverable; users can rename via the existing rename flow if the auto-derived title is wrong.
func InstanceEnv ¶ added in v0.6.0
InstanceEnv combines every per-session environment variable derived from an instance's launch options (Headroom Proxy, Cache TTL) into the single slice tmux.NewTmuxSession's variadic env parameter needs. Centralized here so the four Instance call sites that construct a TmuxSession don't each repeat the same combination.
func IsAllowedTransition ¶
IsAllowedTransition reports whether from → to is permitted by the Status state machine. Self-transitions are always allowed.
func IsClaudeProgram ¶ added in v0.3.0
IsClaudeProgram reports whether program launches the Claude Code agent (matching by binary basename, so absolute paths and trailing flags still resolve). Used to scope remote-control behavior to Claude sessions.
func KillTmuxSessionByTitle ¶
func KillTmuxSessionByTitle(title string, cmdExec internalexec.Executor) error
KillTmuxSessionByTitle kills the tmux session matching title's sanitized name. Best-effort: returns the command error if any (commonly a benign "session not found"), which most callers can ignore. Used to clear orphan sessions left over from a prior crash before reusing the title.
func RemoveOrphanWorktree ¶ added in v0.3.0
RemoveOrphanWorktree removes an orphaned worktree directory while preserving its branch (git worktree remove -f deletes the working tree but never the branch). Used to auto-clean stale leftovers during reconciliation. -f is required because the worktree may hold tracked edits we have already decided to discard, or git may consider it dirty.
func SanitizedToTmuxName ¶ added in v0.1.3
SanitizedToTmuxName mirrors tmux.ToLoomTmuxName. Re-exporting the computation here keeps orphan discovery self-contained — callers don't have to reach into the tmux package directly.
Types ¶
type DiffStatsData ¶
type DiffStatsData struct {
Added int `json:"added"`
Removed int `json:"removed"`
Content string `json:"content"`
}
DiffStatsData represents the serializable data of a DiffStats
type GitWorktreeData ¶
type GitWorktreeData struct {
RepoPath string `json:"repo_path"`
WorktreePath string `json:"worktree_path"`
SessionName string `json:"session_name"`
BranchName string `json:"branch_name"`
BaseCommitSHA string `json:"base_commit_sha"`
IsExistingBranch bool `json:"is_existing_branch"`
// StashRef is the commit SHA of a pending git stash created by
// Instance.Pause for this worktree's uncommitted changes, or ""
// if none is pending (nothing was dirty at pause time, or Resume
// already applied and cleared it). Added in schema v3.
StashRef string `json:"stash_ref,omitempty"`
}
GitWorktreeData represents the serializable data of a GitWorktree
type Instance ¶
type Instance struct {
// Title is the title of the instance.
Title string
// Path is the path to the workspace.
Path string
// Branch is the branch of the instance.
Branch string
// Status is the status of the instance.
Status Status
// Program is the program to run in the instance.
Program string
// HeadroomProxy controls whether this instance's tmux session gets
// ANTHROPIC_BASE_URL pointed at Headroom's proxy (see
// session.HeadroomProxyEnv). A no-op unless Program resolves to
// Claude. Set once before Start() (same convention as Program) and
// persisted so pause/resume and crash recovery — which construct a
// brand new TmuxSession for the same instance — still apply it.
HeadroomProxy bool
// CacheTTL1h controls whether this instance's tmux session gets
// ENABLE_PROMPT_CACHING_1H=1, extending Claude's prompt cache from
// the default 5-minute TTL to 1 hour (see session.CacheTTL1hEnv). A
// no-op unless Program resolves to Claude. Same set-once/persisted
// convention as HeadroomProxy.
CacheTTL1h bool
// Height is the height of the instance.
Height int
// Width is the width of the instance.
Width int
// CreatedAt is the time the instance was created.
CreatedAt time.Time
// UpdatedAt is the time the instance was last updated.
UpdatedAt time.Time
// Prompt is the initial prompt to pass to the instance on startup
Prompt string
// ConfigDir is the workspace config directory for worktree resolution.
ConfigDir string
// IsWorkspaceTerminal is true if this instance operates in the root repo without a worktree.
IsWorkspaceTerminal bool
// CrashRecovered is a runtime-only flag set when this instance was restored
// after a crash. Used to trigger agent-aware restart (e.g. --continue).
CrashRecovered bool
// contains filtered or unexported fields
}
Instance is a single agent session managed by Loom. Each Instance owns a git worktree (or, for workspace terminals, targets the root repo) and a tmux session where the agent command runs. Instances move through the Status state machine — Ready → Loading → Running → Paused → Deleting — governed by allowedTransitions; use TransitionTo for every status write.
Field access rules: mu guards Status, diffStats, Branch, tmuxSession, gitWorktree, and the started/starting flags. External callers must go through the exported accessors (GetStatus, GetBranch, GetDiffStats, Snapshot, TmuxSession) or the unexported get*/set* helpers — never read or write those fields directly. Holding mu across I/O is forbidden.
Lifecycle entry points: NewInstance creates a blank instance (call Start(true) to materialize worktree + tmux). FromInstanceData rehydrates persisted state and does not spawn a PTY — callers must invoke EnsureRunning to bring a non-paused instance back online.
func FromInstanceData ¶
func FromInstanceData(data InstanceData, configDir string) (*Instance, error)
FromInstanceData creates a new Instance from serialized data without spawning a tmux PTY attachment. Paused instances are constructed fully (started=true, TmuxSession object present, no PTY — matches their on-disk shape). Non-paused instances are returned with started=false; the caller must invoke EnsureRunning to attach the PTY. configDir is injected for workspace-scoped worktree resolution.
func NewInstance ¶
func NewInstance(opts InstanceOptions) (*Instance, error)
NewInstance constructs a blank Instance in the Ready state. No git worktree or tmux session is allocated until Start(true) runs — this constructor only captures the caller's intent. The workspace path is resolved to an absolute path so worktree setup is not affected by later chdir calls.
func ReconcileAndRestore ¶
func ReconcileAndRestore(data InstanceData, configDir string, cmdExec internalexec.Executor) (*Instance, error)
ReconcileAndRestore loads an instance from serialized data, checks the health of its tmux session and worktree, and takes the appropriate recovery action.
func (*Instance) CaptureAndProcessStatus ¶
CaptureAndProcessStatus captures tmux pane content once and checks for trust prompts and content updates. Avoids duplicate CapturePaneContent calls. Returns a non-nil err when the underlying capture failed — previously the error was swallowed inside tmux.CaptureAndProcess and surfaced only in the log file, so callers saw "no updates" instead of a genuine capture failure.
func (*Instance) CaptureHistory ¶ added in v0.3.0
CaptureHistory returns the agent pane's full tmux buffer (scrollback + visible screen) for windowed scroll-back, or ("",false) if unavailable.
func (*Instance) CheckAndHandleTrustPrompt ¶
CheckAndHandleTrustPrompt detects and dismisses an agent-specific trust prompt (e.g., Claude's folder-trust dialog) when the agent adapter declares a TrustPromptResponse. Returns true when a prompt was detected and dismissed. No-op for unknown programs.
func (*Instance) CrashRestart ¶
CrashRestart starts a new tmux session for a crash-recovered instance. The worktree already exists (for regular instances) or is unnecessary (for workspace terminals). The program is modified with --continue for supported agents.
func (*Instance) EnsureRunning ¶
EnsureRunning attaches a PTY to the instance's tmux session, restoring any previously-persisted session state. A no-op for paused instances (they deliberately have no PTY) and for already-started instances. Idempotent: the underlying Start guards against double-attaches.
func (*Instance) ForwardMouse ¶ added in v0.3.0
ForwardMouse forwards one SGR mouse event (click/drag/release) to the agent's pane at (col,row). No-op for non-started/paused instances.
func (*Instance) ForwardWheel ¶ added in v0.3.0
ForwardWheel forwards n mouse-wheel events (up or down) to the agent's pane so a TUI agent scrolls its own view. No-op for non-started/paused instances.
func (*Instance) GetBranch ¶
GetBranch returns the branch name under a read lock. Safe to call concurrently with UpdateDiffStats* for workspace terminals, which refresh Branch on every tick.
func (*Instance) GetContentHash ¶
GetContentHash returns the content hash of the last captured tmux pane.
func (*Instance) GetDiffStats ¶
GetDiffStats returns the current git diff statistics
func (*Instance) GetGitWorktree ¶
func (i *Instance) GetGitWorktree() (*git.GitWorktree, error)
GetGitWorktree returns the git worktree for the instance
func (*Instance) GetWorktreePath ¶
GetWorktreePath returns the worktree path for the instance, or empty string if unavailable. For workspace terminals, returns the root repo path.
func (*Instance) HasUpdated ¶
HasUpdated reports whether the tmux pane content has changed since the last call and whether an auto-yes-eligible prompt is currently visible. Returns (false, false) for non-started instances.
func (*Instance) IsAlternateScreen ¶ added in v0.3.0
IsAlternateScreen reports whether the agent is a full-screen TUI on the alternate screen (no tmux scrollback). Scroll-back for such agents must be forwarded into the app via ForwardWheel rather than windowed from history.
func (*Instance) Paste ¶ added in v0.3.0
Paste sends text to the agent's pane as a bracketed paste. No-op for non-started/paused instances.
func (*Instance) Pause ¶
Pause stops the tmux session and removes the worktree, preserving the branch. If saveState is non-nil, it is called after committing changes and marking the instance as Paused, providing a checkpoint that reduces the crash inconsistency window.
func (*Instance) Paused ¶
Paused reports whether the instance is currently in the Paused state (worktree removed, branch preserved; can be resumed with Resume).
func (*Instance) Preview ¶
Preview returns the current visible tmux pane content. Returns empty string (not an error) when the instance is not started or paused — the live tail is only meaningful for running sessions.
func (*Instance) RepoName ¶
RepoName returns the human-visible repo/workspace name, delegating to the instance's backend. Errors if called before the instance has been started.
func (*Instance) Restart ¶ added in v0.1.3
Restart brings an instance back online after its tmux session died out-of-band (e.g. a workspace terminal whose shell the user exited, or the tmux server was killed). Start(true) alone is a silent no-op on an already-started instance because reserveStart sees started=true and bails — that is the correct INST-04 behavior for a concurrent Start race, but the wrong behavior when the caller knows the tmux session is gone and wants to recreate it. Restart clears the flags first so Start can run its real path.
func (*Instance) Resume ¶
Resume recreates the worktree and restarts the tmux session. If saveState is non-nil, it is called after the instance is Running, providing a checkpoint that reduces the crash inconsistency window.
func (*Instance) SendKeysRaw ¶
SendKeysRaw writes raw bytes to the tmux PTY. Used by inline attach mode.
func (*Instance) SendPrompt ¶
SendPrompt sends a prompt to the tmux session
func (*Instance) SetPreviewSize ¶
SetPreviewSize resizes the detached tmux pane so capture output matches the preview viewport. Returns an error if the instance is not running; paused instances have no live pane to resize.
func (*Instance) SetSelectedBranch ¶
SetSelectedBranch sets the branch to use when starting the instance.
func (*Instance) SetTitle ¶
SetTitle sets the title of the instance. Returns an error if the instance has started. We cant change the title once it's been used for a tmux session etc.
func (*Instance) SetTmuxSession ¶
func (i *Instance) SetTmuxSession(session *tmux.TmuxSession)
SetTmuxSession sets the tmux session for testing purposes
func (*Instance) ShouldRefreshDiff ¶
ShouldRefreshDiff reports whether a metadata tick needs to re-run the diff backend for this instance. It returns true when:
- the instance has no cached diff stats yet (first-time fetch),
- the tmux pane content changed since the last tick (agent wrote files),
- the caller needs full diff content but only short-stats are cached (selection-change upgrade path).
When false, the tick can skip the git subprocess entirely. The paused branch is also short-circuited so a paused instance's tick stays cheap.
func (*Instance) Snapshot ¶
func (i *Instance) Snapshot() InstanceData
Snapshot returns a serialization-safe copy of every Instance field under a single RLock. This is the only safe way to read every field at once from outside the main goroutine. Callers that previously invoked ToInstanceData from background Cmd goroutines (e.g. storage.DeleteInstance) must use this to avoid racing with the main loop's writes (INST-11, STORE-16).
GitWorktree's Get* accessors are pure field reads, so it is safe to call them while holding i.mu — no I/O happens under the lock.
func (*Instance) Start ¶
Start brings the instance online: sets up the worktree, spawns the tmux session, and transitions Ready → Loading → Running. Pass firstTimeSetup=true when the instance is newly created (initial commit, copy user-supplied prompt) and false when loaded from storage. Returns an error if setup fails, leaving the instance in its prior status.
func (*Instance) Started ¶
Started reports whether Start or Resume has completed setup, so the instance has a live tmux session and worktree (or root-repo terminal).
func (*Instance) TapEnter ¶
func (i *Instance) TapEnter()
TapEnter sends a single Enter keystroke to the tmux session when the instance is running. No-op otherwise. Exposed to Lua scripts as inst:tap_enter().
func (*Instance) TmuxAlive ¶
TmuxAlive returns true if the tmux session is alive. This is a sanity check before attaching.
func (*Instance) TmuxSession ¶
func (i *Instance) TmuxSession() *tmux.TmuxSession
TmuxSession returns the backing tmux session, or nil if the instance has not been started yet. Exposed so the app layer can drive a full-screen attach via tea.ExecProcess.
func (*Instance) ToInstanceData ¶
func (i *Instance) ToInstanceData() InstanceData
ToInstanceData converts an Instance to its serializable form. Kept as a thin wrapper around Snapshot for backwards compatibility with existing callers; new code should prefer Snapshot.
func (*Instance) TransitionTo ¶
TransitionTo validates from→to against the state-machine allow-list and updates Status atomically. Disallowed transitions return an error and leave Status unchanged. Self-transitions are no-ops (success).
func (*Instance) UpdateDiffStats ¶
UpdateDiffStats updates the git diff statistics for this instance
func (*Instance) UpdateDiffStatsShort ¶
UpdateDiffStatsShort updates only the line counts (Added/Removed) without fetching full diff content. Cheaper for non-selected instances that only display counts in the list view.
type InstanceData ¶
type InstanceData struct {
SchemaVersion int `json:"schema_version,omitempty"`
Title string `json:"title"`
Path string `json:"path"`
Branch string `json:"branch"`
Status Status `json:"status"`
Height int `json:"height"`
Width int `json:"width"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Program string `json:"program"`
HeadroomProxy bool `json:"headroom_proxy,omitempty"`
CacheTTL1h bool `json:"cache_ttl_1h,omitempty"`
Worktree GitWorktreeData `json:"worktree"`
DiffStats DiffStatsData `json:"diff_stats"`
IsWorkspaceTerminal bool `json:"is_workspace_terminal"`
}
InstanceData represents the serializable data of an Instance.
SchemaVersion is tracked for forward-compatible migrations. A missing field (zero) is interpreted as v0 (pre-versioning); migrations.go upgrades it to CurrentSchemaVersion at decode time.
func InstanceDataFromOrphan ¶ added in v0.3.0
func InstanceDataFromOrphan(cand OrphanCandidate, program string) InstanceData
InstanceDataFromOrphan reconstructs InstanceData for an orphan candidate. IsExistingBranch is always true so a later Kill (discard) removes only the worktree, never the branch. Status is left zero (Running); callers override it (Recoverable for the inline placeholder, Running for recovery).
func Migrate ¶
func Migrate(raw []byte) (InstanceData, error)
Migrate decodes a single raw JSON object representing a stored instance and upgrades it to CurrentSchemaVersion. The function is idempotent: a record already at CurrentSchemaVersion round-trips unchanged.
v0 records (missing SchemaVersion field → decodes to 0) are treated as pre-versioning. The v0→v1 step is a pure field-default upgrade and exists to establish the migration plumbing. v1→v2 drops the AutoYes field (encoding/json already ignores the now-unknown "auto_yes" key on unmarshal, so this step too is just a version stamp). v2→v3 adds GitWorktreeData.StashRef; v3→v4 adds HeadroomProxy; v4→v5 adds CacheTTL1h — all default correctly on their own (empty string, false), so every step is a pure version stamp.
Contributor protocol: when adding/renaming/removing an InstanceData field, bump CurrentSchemaVersion and append a new case to the switch that upgrades from the previous version. The JSON fixture in cmd/workspace_migrate_shape_test.go is a drift guard for the `workspace migrate` CLI's typed mirror struct and must be updated in the same commit.
func MigrateAll ¶
func MigrateAll(rawArray []byte) ([]InstanceData, error)
MigrateAll applies Migrate to every element of a JSON array of raw instance records. Callers that already have []json.RawMessage should prefer this over decoding twice.
type InstanceOptions ¶
type InstanceOptions struct {
// Title is the title of the instance.
Title string
// Path is the path to the workspace.
Path string
// Program is the program to run in the instance (e.g. "claude", "aider --model ollama_chat/gemma3:1b")
Program string
// HeadroomProxy controls whether this instance's tmux session gets
// ANTHROPIC_BASE_URL pointed at Headroom's proxy. See Instance.HeadroomProxy.
HeadroomProxy bool
// CacheTTL1h controls whether this instance's tmux session gets
// ENABLE_PROMPT_CACHING_1H=1. See Instance.CacheTTL1h.
CacheTTL1h bool
// Branch is an existing branch name to start the session on (empty = new branch from HEAD)
Branch string
// ConfigDir is the workspace config directory for worktree resolution.
ConfigDir string
// IsWorkspaceTerminal creates a workspace terminal instance (no worktree).
IsWorkspaceTerminal bool
}
InstanceOptions collects the arguments for NewInstance. All fields except IsWorkspaceTerminal, WsCtx, and ExecutorOverride are required.
type OrphanCandidate ¶ added in v0.1.3
type OrphanCandidate struct {
// WorktreePath is the absolute path of the orphaned worktree.
WorktreePath string
// BranchName is the sanitized branch this worktree was created on,
// recovered by stripping the trailing `_<hex>` timestamp suffix
// from the worktree directory name.
BranchName string
// RepoPath is the main repository's working tree (resolved via
// `git -C <worktreePath> rev-parse --git-common-dir`). Discovery
// drops candidates where this lookup fails — there's no way to
// reconstruct a usable Instance without it.
RepoPath string
// BaseCommitSHA is the worktree's current HEAD, captured as the
// recovered instance's diff-stats baseline. Without it, the diff
// pipeline emits "base commit SHA not set" warnings on every
// metadata tick until the user pause+resumes the instance.
BaseCommitSHA string
// Title is the humanized branch leaf (e.g. branch
// "aidanb/example-jupyter-notebook" → title "example jupyter
// notebook"). Used as the recovered instance's display title.
Title string
// HasLiveTmux reports whether a tmux session named
// loom_<sanitized-title> is currently running. When true, recovery
// can adopt the live PTY rather than spawning a new one.
HasLiveTmux bool
// HasUncommittedChanges reports whether the worktree has uncommitted
// edits (git status --porcelain). True (conservatively, on probe
// error) keeps an orphan in the needs-review bucket so auto-clean
// never discards unsaved work.
HasUncommittedChanges bool
}
OrphanCandidate describes a worktree directory found on disk that no loaded Instance refers to — typically the consequence of state.json being overwritten without removing the underlying worktree, or a crash mid-cleanup. Each field is populated to the extent possible from the filesystem and a quick git probe; downstream code uses this to reconstruct an InstanceData entry without losing the user's work.
func DiscoverOrphans ¶ added in v0.1.3
func DiscoverOrphans(configDir string, claimedPaths map[string]bool, cmdExec internalexec.Executor) ([]OrphanCandidate, error)
DiscoverOrphans scans configDir's worktrees directory and returns every entry that is not referenced by claimedPaths. Each returned candidate is enriched with the branch name, repo path (best-effort), humanized title, and a tmux liveness probe.
claimedPaths is the set of WorktreePaths already accounted for in state.json — typically built by the caller from instance.GetGitWorktree().GetWorktreePath() across the loaded list.
Returns an empty slice (not nil) when configDir has no worktree dir or no orphans exist. Errors from individual worktree probes are logged but do not abort discovery; the function only returns an error when the worktrees directory itself is unreadable for a non-NotExist reason.
func (OrphanCandidate) Disposition ¶ added in v0.3.0
func (c OrphanCandidate) Disposition() OrphanDisposition
Disposition buckets a candidate. Any signal of life (a running agent or unsaved edits) routes to review; everything else is safe to auto-clean.
type OrphanDisposition ¶ added in v0.3.0
type OrphanDisposition int
OrphanDisposition tells reconcileOrphans how to handle a candidate.
const ( // DisposeClean means dead tmux and no uncommitted changes — a stale // leftover. Auto-remove the worktree (branch preserved). DisposeClean OrphanDisposition = iota // DisposeReview means live tmux or uncommitted changes — surface // inline as a Recoverable entry for the user to recover or discard. DisposeReview )
type RecoveryAction ¶
type RecoveryAction int
RecoveryAction describes what to do with an instance during startup reconciliation.
const ( // ActionNoChange means the instance is already in a consistent state (e.g. Paused). ActionNoChange RecoveryAction = iota // ActionRestore means tmux + worktree are healthy; do a normal restore. ActionRestore // ActionRestart means tmux is dead but worktree exists; restart with scrollback + agent context. ActionRestart // ActionMarkPaused means both tmux and worktree are gone; mark as Paused (branch is preserved). ActionMarkPaused // ActionKillAndPause means tmux is alive but worktree is gone; kill tmux, mark Paused. ActionKillAndPause // ActionRestartWsTerminal means workspace terminal's tmux is dead; recreate it. ActionRestartWsTerminal )
func DetermineRecoveryAction ¶
func DetermineRecoveryAction(status Status, tmuxAlive, worktreeExists, isWorkspaceTerminal bool) RecoveryAction
DetermineRecoveryAction decides what to do with a loaded instance based on its persisted status and current filesystem/tmux state.
type RemoteControlAuth ¶ added in v0.3.0
type RemoteControlAuth struct {
State RemoteControlAuthState
Reason string
}
RemoteControlAuth carries the detection state plus a human-readable reason shown to the user when Blocked.
func DetectClaudeRemoteControlAuth ¶ added in v0.3.0
func DetectClaudeRemoteControlAuth(program string, runner internalexec.Executor) RemoteControlAuth
DetectClaudeRemoteControlAuth determines whether the given program's Claude authentication can establish a --remote-control session. It is a no-op (Unknown) for non-Claude programs. Remote control requires a claude.ai OAuth login; API keys, Console accounts, and inference-scoped tokens are rejected by Claude, so this reports Blocked for them.
func (RemoteControlAuth) Blocked ¶ added in v0.3.0
func (a RemoteControlAuth) Blocked() bool
Blocked reports whether auth was clearly determined to be incompatible with remote control.
func (RemoteControlAuth) OK ¶ added in v0.3.0
func (a RemoteControlAuth) OK() bool
OK reports whether remote control is confirmed usable.
type RemoteControlAuthState ¶ added in v0.3.0
type RemoteControlAuthState int
RemoteControlAuthState is the tri-state result of checking whether the active Claude authentication can establish a --remote-control session.
Detection is deliberately conservative: only a clear positive is OK and only a clear negative is Blocked. Anything ambiguous is Unknown so callers can fail closed (skip the flag) without interrupting the user.
const ( // RemoteControlAuthUnknown means auth could not be determined — the // program isn't Claude, the `auth status` subcommand is missing, or its // output didn't parse. Callers add no flag and show no prompt. RemoteControlAuthUnknown RemoteControlAuthState = iota // RemoteControlAuthOK means the session is logged in with a claude.ai // account and no API-key override — remote control will work. RemoteControlAuthOK // RemoteControlAuthBlocked means auth was clearly determined to be // incompatible with remote control (API-key/console/token auth, an // override env var, or simply not logged in). RemoteControlAuthBlocked )
type SessionBackend ¶
type SessionBackend interface {
// RepoName returns the human-visible repo/workspace name used in
// UI labels.
RepoName() (string, error)
// WorkTreePath returns the filesystem directory where the tmux
// session should operate.
WorkTreePath() string
// Diff returns the current diff stats (line counts + content).
Diff() *git.DiffStats
// DiffShort returns diff line counts only, without content body —
// cheaper for non-focused instances that only render counts.
DiffShort() *git.DiffStats
// RefreshBranch returns the current branch name, or empty string
// if the backend doesn't need to refresh (worktrees have a fixed
// branch for their lifetime; workspace terminals track HEAD).
RefreshBranch() string
}
SessionBackend is the polymorphic surface for operations that differ between regular (worktree-backed) instances and workspace terminals. It consolidates scattered IsWorkspaceTerminal branching into a single indirection so new backend types (e.g., remote sessions) can be added by implementing this interface rather than extending a switch.
Scope note: lifecycle operations (Setup/Kill/Pause/Resume) still branch inline in Instance because they interact with shared state (tmux session, lock bookkeeping) in ways that don't fit cleanly behind this interface. Migrating those is a follow-up.
type Status ¶
type Status int
Status is the Instance lifecycle state. Transitions are gated by allowedTransitions in instance.go; use Instance.TransitionTo for every write so invariants hold across the app and tests.
const ( // Running is the status when the instance is running and claude is working. Running Status = iota // Ready is if the claude instance is ready to be interacted with (waiting for user input). Ready // Loading is if the instance is loading (if we are starting it up or something). Loading // Paused is if the instance is paused (worktree removed but branch preserved). Paused // Prompting is when the agent is asking for user permission. Prompting // Deleting is a transient status set immediately when the user confirms // deletion. Cleanup runs asynchronously; on failure the status reverts. Deleting // Recoverable is an orphaned worktree found on disk and surfaced inline // for the user to recover or discard. It has a worktree but no live tmux // and is never persisted to state.json (re-derived from disk each load). // Appended last so existing serialized Status ints are unchanged. Recoverable )
type Storage ¶
type Storage struct {
// contains filtered or unexported fields
}
Storage handles saving and loading instances using the state interface
func NewStorage ¶
func NewStorage(state config.InstanceStorage, configDir string) (*Storage, error)
NewStorage creates a new storage instance. configDir is the workspace config directory injected into loaded instances.
func (*Storage) DeleteAllInstances ¶
DeleteAllInstances removes all stored instances
func (*Storage) DeleteInstance ¶
DeleteInstance removes an instance from storage. Operates on raw InstanceData so it does not construct live Instance objects (which would open tmux attach PTYs for every remaining running instance).
func (*Storage) LoadAndReconcile ¶
func (s *Storage) LoadAndReconcile(cmdExec internalexec.Executor) ([]*Instance, error)
LoadAndReconcile loads instance data from disk and reconciles each instance against the live tmux/worktree state. Unlike LoadInstances, a single failing instance is logged and skipped rather than aborting the whole load. This is the correct entry point for any caller that can tolerate reconciliation side effects (killing orphan tmux sessions, marking instances paused).
Records that fail ReconcileAndRestore are stashed in s.unrecovered so the next SaveInstances preserves them on disk. Previously such failures led to permanent data loss: the failed record was silently omitted from the live list, and the next save overwrote state.json with only the survivors.
func (*Storage) LoadInstanceData ¶
func (s *Storage) LoadInstanceData() ([]InstanceData, error)
LoadInstanceData loads raw serialized instance data without constructing Instance objects. Used by reconciliation to inspect state before deciding how to restore. All records pass through Migrate so callers receive CurrentSchemaVersion data.
func (*Storage) LoadInstances ¶
LoadInstances loads the list of instances from disk
func (*Storage) SaveInstances ¶
SaveInstances saves the list of instances to disk. Callers are responsible for filtering out instances that should not be persisted (e.g. Ready-but-not-yet-configured, Deleting) via persistableInstances at the call site. Filtering here on Instance.Started() is unsafe because Kill() flips started=false early (before tmux/worktree teardown), so a save during the kill window would silently drop the instance from disk and cause DeleteInstance to fail with ErrInstanceNotFound.
Unrecovered records from the most recent LoadAndReconcile pass are appended to the payload (deduped by title — a live record always wins) so reconcile failures do not silently delete persisted state.
func (*Storage) UnrecoveredWorktreePaths ¶ added in v0.1.3
UnrecoveredWorktreePaths returns the set of worktree paths currently held in the unrecovered cache. Orphan discovery uses this so a preserved-but-failed record's worktree is not also surfaced as an orphan candidate, which would let the user re-recover it under a different title and produce a duplicate state.json entry.
func (*Storage) UpdateInstance ¶
UpdateInstance replaces the persisted record for an existing instance. Uses the in-memory snapshot of the provided instance and the raw-data load path so the other stored entries are never reconstructed.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agent consolidates program-specific knowledge for the supported coding agents (claude, aider, gemini, etc.).
|
Package agent consolidates program-specific knowledge for the supported coding agents (claude, aider, gemini, etc.). |
|
Package files provides filesystem enumeration helpers for the file explorer overlay.
|
Package files provides filesystem enumeration helpers for the file explorer overlay. |
|
Package git encapsulates the per-session git worktree: creation, diff stats, push, and cleanup.
|
Package git encapsulates the per-session git worktree: creation, diff stats, push, and cleanup. |
|
Package tmux manages the tmux sessions that drive each agent.
|
Package tmux manages the tmux sessions that drive each agent. |
|
Package vt defines Loom's pane-display abstraction.
|
Package vt defines Loom's pane-display abstraction. |