workspace

package
v0.99.1 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 69 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package workspace manages git worktrees and tmux sessions for parallel development workflows, with AI agent orchestration, PR fetching, and interactive shell access.

Index

Constants

View Source
const (
	PaneTerminal = panelayout.Terminal
	PaneDoc      = panelayout.Document
	PaneIssue    = panelayout.Issue
)
View Source
const (
	SplitCols = panelayout.Columns
	SplitRows = panelayout.Rows
)
View Source
const (
	DiffViewUnified    = workspacediff.ViewUnified
	DiffViewSideBySide = workspacediff.ViewSideBySide
	DiffViewFullFile   = workspacediff.ViewFullFile

	DiffScopeWorkingTree = workspacediff.ScopeWorkingTree
	DiffScopeCommits     = workspacediff.ScopeCommits
	DiffScopeAggregate   = workspacediff.ScopeAggregate

	LoadStateUnknown   = workspacediff.LoadStateUnknown
	LoadStateLoading   = workspacediff.LoadStateLoading
	LoadStateClean     = workspacediff.LoadStateClean
	LoadStateReady     = workspacediff.LoadStateReady
	LoadStateTruncated = workspacediff.LoadStateTruncated
	LoadStateError     = workspacediff.LoadStateError

	DiffTabFocusFileList    = workspacediff.FocusFileList
	DiffTabFocusDiff        = workspacediff.FocusDiff
	DiffTabFocusCommitFiles = workspacediff.FocusCommitFiles
	DiffTabFocusCommitDiff  = workspacediff.FocusCommitDiff
)
View Source
const AckDwell = 2 * time.Second

AckDwell is how long a session's output must stay selected before its completion is treated as read. Short enough to feel immediate when you stop on a card, long enough that scrolling through the list clears nothing.

Variables

View Source
var AgentCommands = map[AgentType]string{
	AgentClaude:      "claude",
	AgentCodex:       "codex",
	AgentCopilot:     "copilot",
	AgentAider:       "aider",
	AgentAntigravity: "agy",
	AgentCursor:      "cursor-agent",
	AgentOpenCode:    "opencode",
	AgentPi:          "pi",
	AgentAmp:         "amp",
	AgentGrok:        "grok",
}

AgentCommands maps agent types to their CLI commands.

View Source
var AgentDisplayNames = map[AgentType]string{
	AgentNone:        "None (attach only)",
	AgentClaude:      "Claude Code",
	AgentCodex:       "Codex CLI",
	AgentCopilot:     "GitHub Copilot CLI",
	AgentAntigravity: "Antigravity",
	AgentCursor:      "Cursor Agent",
	AgentOpenCode:    "OpenCode",
	AgentPi:          "Pi Agent",
	AgentAmp:         "Amp",
	AgentGrok:        "Grok",
	AgentShell:       "Project Shell",
}

AgentDisplayNames provides human-readable names for agent types.

AgentTypeOrder defines the order of agents in selection UI.

View Source
var DefaultEnvOverrides = map[string]string{

	"GOWORK": "off",

	"GOFLAGS": "",

	"NODE_OPTIONS": "",
	"NODE_PATH":    "",

	"PYTHONPATH":  "",
	"VIRTUAL_ENV": "",
}

DefaultEnvOverrides contains environment variables to clear/override for worktree isolation. These prevent common issues when running commands in worktrees.

View Source
var PrintModeArgs = map[AgentType][]string{
	AgentClaude:      {"-p"},
	AgentCodex:       {"exec", "-"},
	AgentAntigravity: {"-p"},
}

PrintModeArgs maps agent types to their non-interactive/print mode CLI arguments. Agents with print mode can generate output to stdout without an interactive session. Only agents that support true non-interactive one-shot output are included. Values are passed as arguments to exec.Command after the agent binary name.

ShellAgentOrder defines agent order for shell creation (None first as default). td-a902fe: shells default to no agent, so "None" is first.

View Source
var SkipPermissionsFlags = map[AgentType]string{
	AgentClaude:      "--dangerously-skip-permissions",
	AgentCodex:       "--dangerously-bypass-approvals-and-sandbox",
	AgentCopilot:     "",
	AgentAider:       "--yes",
	AgentAntigravity: "--dangerously-skip-permissions",
	AgentCursor:      "-f",
	AgentOpenCode:    "",
	AgentPi:          "",
	AgentAmp:         "--dangerously-allow-all",
	AgentGrok:        "--always-approve",
}

SkipPermissionsFlags maps agent types to their skip-permissions CLI flags.

View Source
var SystemPromptAppendFlags = map[AgentType]string{
	AgentClaude: "--append-system-prompt",
	AgentGrok:   "--rules",
}

SystemPromptAppendFlags maps agent types to the flag that appends text to their system prompt for one session. Only harnesses with a documented flag appear here: guidance an agent never sees is worse than none, and a guessed flag would break the launch outright. Harnesses without one rely on the SIDECAR_SHELL_NAME environment cue (and project docs such as AGENTS.md).

Grok: --rules appends session rules (documented alias: --append-system-prompt). Claude: --append-system-prompt.

Functions

func ApplyEnvOverrides

func ApplyEnvOverrides(baseEnv []string, overrides map[string]string) []string

ApplyEnvOverrides applies overrides to an existing environment slice. Returns a new slice with overrides applied.

func BuildEnvOverrides

func BuildEnvOverrides(mainRepoPath string) map[string]string

BuildEnvOverrides returns the combined environment overrides for a worktree. User overrides from .worktree-env take precedence over defaults.

func EnsureDefaultPrompts

func EnsureDefaultPrompts(globalConfigDir string) bool

EnsureDefaultPrompts creates the global config with default prompts if no config exists. Returns true if defaults were created.

func ExpandPromptTemplate

func ExpandPromptTemplate(body, taskID string) string

ExpandPromptTemplate expands template variables in a prompt body. - {{ticket}} expands to taskID (returns empty if taskID is empty) - {{ticket || 'default'}} expands to taskID, or 'default' if taskID is empty

func ExtractFallback

func ExtractFallback(body string) string

ExtractFallback extracts the fallback value from a prompt body. Returns the first fallback found, or empty string if none.

func GenerateExportCommands

func GenerateExportCommands(overrides map[string]string) []string

GenerateExportCommands generates shell commands to apply environment overrides. Empty values generate unset commands, non-empty generate export commands.

func GenerateSingleEnvCommand

func GenerateSingleEnvCommand(overrides map[string]string) string

GenerateSingleEnvCommand returns a single shell command that applies all env overrides. This is less noisy than sending multiple commands individually.

func HasTicketPlaceholder

func HasTicketPlaceholder(body string) bool

HasTicketPlaceholder returns true if the body contains {{ticket}} or {{ticket || '...'}}

func LayoutPanes added in v0.98.0

func LayoutPanes(root *PaneNode, box Box, floors Floors) ([]Placement, []Divider, bool)

func SanitizeBranchName

func SanitizeBranchName(name string) string

SanitizeBranchName converts a string to a valid git branch name. The output should always pass ValidateBranchName.

func SetRatio added in v0.98.0

func SetRatio(root *PaneNode, id, ratio int) bool

func ValidateBranchName

func ValidateBranchName(name string) (bool, []string, string)

ValidateBranchName validates a git branch name and returns validation state. Returns: (valid, errors, sanitized suggestion) Based on git-check-ref-format rules.

func WorktreeActionRefusal added in v0.94.0

func WorktreeActionRefusal(wt *Worktree, action WorktreeAction) string

WorktreeActionRefusal returns a user-facing reason when an action is unsafe.

func WriteDefaultPromptsToConfig

func WriteDefaultPromptsToConfig(globalConfigDir string) bool

WriteDefaultPromptsToConfig merges default prompts into the global config. If config.json exists, it preserves other fields and adds/replaces the prompts key. If config.json does not exist, it creates one with default prompts. Returns true on success.

Types

type Agent

type Agent struct {
	Type               AgentType // claude, codex, aider, gemini
	TmuxSession        string    // tmux session name
	TmuxPane           string    // Pane identifier (e.g., "%12" - globally unique)
	PID                int       // Process ID (if available)
	StartedAt          time.Time
	LastOutput         time.Time         // Last time output was detected
	OutputBuf          *tty.OutputBuffer // Last N lines of output
	WaitingFor         string            // Prompt text if waiting
	Activity           agentactivity.Tracker
	ActivityCapturedAt time.Time

	// Runaway detection fields (td-018f25)
	// Track recent poll times to detect continuous output that would cause CPU spikes.
	RecentPollTimes    []time.Time // Last N poll times for runaway detection
	PollsThrottled     bool        // True if this agent is throttled due to continuous output
	UnchangedPollCount int         // Consecutive unchanged polls (for throttle reset)
}

Agent represents an AI coding agent process.

func (*Agent) CheckRunaway

func (a *Agent) CheckRunaway() bool

CheckRunaway checks if this agent should be throttled (td-018f25). Returns true and sets PollsThrottled if runaway condition is detected.

func (*Agent) RecordPollTime

func (a *Agent) RecordPollTime()

RecordPollTime records a poll time for runaway detection (td-018f25). Should be called when an AgentOutputMsg (content changed) is received.

func (*Agent) RecordUnchangedPoll

func (a *Agent) RecordUnchangedPoll()

RecordUnchangedPoll records an unchanged poll for throttle reset (td-018f25). Should be called when an AgentPollUnchangedMsg is received.

type AgentOutputMsg

type AgentOutputMsg struct {
	WorkspaceName string
	Generation    int
	AgentType     AgentType // Live provider inferred from the captured pane
	Output        string
	Status        WorktreeStatus
	WaitingFor    string
	// Cursor position captured atomically with output (only set in interactive mode)
	CursorRow     int
	CursorCol     int
	CursorVisible bool
	HasCursor     bool // True if cursor position was captured
	PaneHeight    int  // Tmux pane height for cursor offset calculation
	PaneWidth     int  // Tmux pane width for display alignment
	HistorySize   int
	CaptureBase   int
	HasHistory    bool
	// RowsJoined says the capture was taken with -J, so it carries no usable
	// history/pane split.
	RowsJoined bool
	// MouseReporting is tmux's #{mouse_any_flag} for the pane. Only meaningful
	// when HasCursor is set.
	MouseReporting bool
	Activity       agentactivity.Result
	CapturedAt     time.Time
	PaneTitle      string
	CurrentCommand string
}

AgentOutputMsg delivers new agent output.

type AgentPollUnchangedMsg

type AgentPollUnchangedMsg struct {
	WorkspaceName string
	Generation    int
	AgentType     AgentType // Live provider inferred from the captured pane
	Output        string
	CurrentStatus WorktreeStatus // Status including session file re-check
	WaitingFor    string         // Prompt text if waiting
	// Cursor position captured atomically (even when content unchanged)
	CursorRow     int
	CursorCol     int
	CursorVisible bool
	HasCursor     bool
	PaneHeight    int // Tmux pane height for cursor offset calculation
	PaneWidth     int // Tmux pane width for display alignment
	HistorySize   int
	CaptureBase   int
	HasHistory    bool
	// RowsJoined says the capture was taken with -J, so it carries no usable
	// history/pane split.
	RowsJoined bool
	// MouseReporting is tmux's #{mouse_any_flag} for the pane. Only meaningful
	// when HasCursor is set.
	MouseReporting bool
	Activity       agentactivity.Result
	CapturedAt     time.Time
	PaneTitle      string
	CurrentCommand string
}

AgentPollUnchangedMsg signals content unchanged, schedule next poll.

type AgentStartedMsg

type AgentStartedMsg struct {
	Epoch         uint64 // Epoch when request was issued (for stale detection)
	WorktreeKey   string
	WorkspaceName string
	SessionName   string
	PaneID        string // tmux pane ID (e.g., "%12") for interactive mode
	AgentType     AgentType
	Reconnected   bool // True if we reconnected to an existing session
	Err           error
}

AgentStartedMsg signals an agent has been started in a worktree.

func (AgentStartedMsg) GetEpoch

func (m AgentStartedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type AgentStoppedMsg

type AgentStoppedMsg struct {
	WorkspaceName string
	Generation    int
	Err           error
}

AgentStoppedMsg signals an agent has stopped.

type AgentType

type AgentType string

AgentType represents the type of AI coding agent.

const (
	AgentNone        AgentType = ""            // No agent (attach only)
	AgentClaude      AgentType = "claude"      // Claude Code
	AgentCodex       AgentType = "codex"       // Codex CLI
	AgentCopilot     AgentType = "copilot"     // GitHub Copilot CLI
	AgentAider       AgentType = "aider"       // Aider
	AgentAntigravity AgentType = "antigravity" // Antigravity (agy)
	AgentCursor      AgentType = "cursor"      // Cursor Agent
	AgentOpenCode    AgentType = "opencode"    // OpenCode
	AgentPi          AgentType = "pi"          // Pi Agent
	AgentAmp         AgentType = "amp"         // Amp
	AgentGrok        AgentType = "grok"        // Grok Build
	AgentCustom      AgentType = "custom"      // Custom command
	AgentShell       AgentType = "shell"       // Project shell (not an AI agent)
)

type ApproveResultMsg

type ApproveResultMsg struct {
	WorkspaceName string
	Err           error
}

ApproveResultMsg signals the result of an approve action.

type AsyncCaptureResultMsg

type AsyncCaptureResultMsg struct {
	WorkspaceName string // Worktree this capture is for
	SessionName   string // tmux session name
	Output        string // Captured output (empty on error)
	Err           error  // Non-nil if capture failed
}

AsyncCaptureResultMsg delivers async tmux capture results. Used to avoid blocking the UI thread on tmux subprocess calls (td-c2961e).

type AsyncShellCaptureResultMsg

type AsyncShellCaptureResultMsg struct {
	TmuxName string // Shell session tmux name
	Output   string // Captured output (empty on error)
	Err      error  // Non-nil if capture failed
}

AsyncShellCaptureResultMsg delivers async shell capture results.

type BaseUpdateResult added in v0.94.0

type BaseUpdateResult struct {
	Branch        string
	TargetPath    string
	Fetched       bool
	Updated       bool
	LeftUnchanged bool
	Message       string
	Err           error
}

BaseUpdateResult describes a safe post-merge base refresh.

type Box added in v0.98.0

type Box = panelayout.Box

type BranchListMsg

type BranchListMsg struct {
	OperationScope
	Branches []string
	Err      error
}

BranchListMsg delivers available branches.

type CheckPRMergedMsg

type CheckPRMergedMsg struct {
	OperationScope
	WorkspaceName string
	Result        PRPollResult
}

CheckPRMergedMsg signals the result of checking if a PR was merged.

type CleanupDoneMsg

type CleanupDoneMsg struct {
	OperationScope
	WorkspaceName string
	Results       *CleanupResults
}

CleanupDoneMsg signals that cleanup operations completed.

type CleanupPlan added in v0.94.0

type CleanupPlan struct {
	RepoPath          string
	WorktreePath      string
	Branch            string
	ExpectedOID       string
	BranchRemote      string
	ExpectedRemoteOID string
	BaseRemote        string
	BaseBranch        string
	DeleteWorktree    bool
	DeleteBranch      bool
	DeleteRemote      bool
	UpdateBase        bool
	PRIdentity        *PRIdentity
	ReviewedOID       string
	ForceDeleteBranch bool
}

CleanupPlan is captured before cleanup starts and executed in order.

type CleanupResults

type CleanupResults struct {
	LocalWorktreeDeleted bool
	LocalBranchDeleted   bool
	RemoteBranchDeleted  bool
	PullAttempted        bool
	PullSuccess          bool
	PullError            error
	Errors               []string

	// Error detail expansion state (for UX improvements)
	ShowErrorDetails bool   // Toggle for expanded error view
	PullErrorSummary string // Concise 1-line summary
	PullErrorFull    string // Full git output for details view
	PullMessage      string // Explicit update/intentional-no-update result
	BranchDiverged   bool   // Enables rebase/merge resolution actions
	BaseBranch       string // Branch name for resolution commands
}

CleanupResults holds the results of cleanup operations for display in summary.

type CommitDetailLoadedMsg added in v0.81.0

type CommitDetailLoadedMsg struct {
	Epoch         uint64
	WorkspaceName string
	CommitHash    string
	Commit        *gitstatus.Commit
	Err           error
}

CommitDetailLoadedMsg is sent when commit detail (file list) is loaded.

func (CommitDetailLoadedMsg) GetEpoch added in v0.81.0

func (m CommitDetailLoadedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type CommitFileDiffLoadedMsg added in v0.81.0

type CommitFileDiffLoadedMsg struct {
	Epoch         uint64
	WorkspaceName string
	CommitHash    string
	FilePath      string
	Raw           string
	Err           error
}

CommitFileDiffLoadedMsg is sent when a commit file's diff is loaded.

func (CommitFileDiffLoadedMsg) GetEpoch added in v0.81.0

func (m CommitFileDiffLoadedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type CommitStatusInfo

type CommitStatusInfo = workspacediff.CommitInfo

CommitStatusInfo holds commit information with merge/push status.

type CommitStatusLoadedMsg

type CommitStatusLoadedMsg struct {
	Epoch         uint64 // Epoch when request was issued (for stale detection)
	WorkspaceName string
	Commits       []CommitStatusInfo
	Err           error
}

CommitStatusLoadedMsg delivers commit status info for the diff view header.

func (CommitStatusLoadedMsg) GetEpoch

func (m CommitStatusLoadedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type Conflict

type Conflict struct {
	Worktrees []string // Stable keys of worktrees with overlapping dirty files
	Files     []string // List of conflicting files
}

Conflict represents a file conflict between worktrees.

type ConflictsDetectedMsg

type ConflictsDetectedMsg struct {
	OperationScope
	Conflicts []Conflict
	Err       error
}

ConflictsDetectedMsg signals that conflicts have been detected.

type Content added in v0.99.0

type Content interface {
	// Kind is the stable persistence key and registry key for this content.
	Kind() string
	// Title is the content's identity for a header row.
	Title() string
	// SetSize gives the content its box. The command is how a content asserts
	// geometry it owns beyond this process, such as a live tmux pane.
	SetSize(Size) tea.Cmd
	// View draws exactly Size.Height rows of exactly Size.Width columns.
	View(Render) string
}

Content is what one pane-tree leaf shows. The tree places boxes and the frame composes them; neither learns what is inside one. A bottom-relative offset, a freeze, a tmux geometry lease are the content's business alone — the structure layer never sees a *tty.Model.

The contract is four methods on purpose. Capability beyond it — update, focus, keys, pointers, scrolling, persistence — arrives as an optional interface when its first real implementation does, not before: a document leaf has no native cursor and no transport to gate, and a mandatory method invites a wrong stub.

type CreateDoneMsg

type CreateDoneMsg struct {
	OperationScope
	Worktree  *Worktree
	AgentType AgentType // Agent selected at creation
	SkipPerms bool      // Whether to skip permissions
	Prompt    *Prompt   // Selected prompt template (nil if none)
	Err       error
}

CreateDoneMsg signals worktree creation completed.

type CreateOpenAnywayMsg added in v0.94.0

type CreateOpenAnywayMsg struct{ OperationScope }

type CreateOperationPlan added in v0.94.0

type CreateOperationPlan struct {
	RepoKey        string
	OperationID    string
	SourceWorktree string
	MainWorktree   string
	SourceRef      string
	SourceOID      string
	Branch         string
	Path           string
	DisplayName    string
	TaskID         string
	TaskTitle      string
	AgentType      AgentType
	SkipPerms      bool
	Prompt         *Prompt
	RemotePolicy   string
	CopyEnv        bool
	EnvFiles       []string
	RunHook        bool
	HookPath       string
	HookRequired   bool
}

CreateOperationPlan is the immutable contract shown to the user before any repository mutation. It is also retained for retry and identity-checked undo.

type CreateOutcomeKind added in v0.94.0

type CreateOutcomeKind string
const (
	CreateOutcomeIdentity CreateOutcomeKind = "identity"
	CreateOutcomeTDRoot   CreateOutcomeKind = "td-root"
	CreateOutcomeTaskLink CreateOutcomeKind = "task-link"
	CreateOutcomeTDStart  CreateOutcomeKind = "td-start"
	CreateOutcomeAgent    CreateOutcomeKind = "agent-metadata"
	CreateOutcomeEnv      CreateOutcomeKind = "env-copy"
	CreateOutcomeHook     CreateOutcomeKind = "setup-hook"
)

type CreatePlanResolvedMsg added in v0.94.0

type CreatePlanResolvedMsg struct {
	OperationScope
	Plan *CreateOperationPlan
	Err  error
}

CreatePlanResolvedMsg completes the non-mutating Git-plumbing preflight.

type CreateRecoveryDeleteDoneMsg added in v0.94.0

type CreateRecoveryDeleteDoneMsg struct {
	OperationScope
	Result CreateRecoveryDeleteResult
}

type CreateRecoveryDeleteResult added in v0.94.0

type CreateRecoveryDeleteResult struct {
	WorktreeRemoved bool
	BranchDeleted   bool
	BranchRetained  bool
	Err             error
}

type CreateSetupDoneMsg added in v0.94.0

type CreateSetupDoneMsg struct {
	OperationScope
	Plan   *CreateOperationPlan
	Result *CreateSetupResult
}

type CreateSetupOutcome added in v0.94.0

type CreateSetupOutcome struct {
	Kind     CreateOutcomeKind
	Action   string
	Err      error
	Required bool
}

CreateSetupOutcome records one independently recoverable setup action.

type CreateSetupResult added in v0.94.0

type CreateSetupResult struct {
	Worktree *Worktree
	Outcomes []CreateSetupOutcome
}

func (*CreateSetupResult) HasRequiredFailure added in v0.94.0

func (r *CreateSetupResult) HasRequiredFailure() bool

func (*CreateSetupResult) Warnings added in v0.94.0

func (r *CreateSetupResult) Warnings() []CreateSetupOutcome

type CreateWorktreeAddedMsg added in v0.94.0

type CreateWorktreeAddedMsg struct {
	OperationScope
	Plan     *CreateOperationPlan
	Worktree *Worktree
	Err      error
}

CreateWorktreeAddedMsg means Git created the worktree. Setup is a separate, recoverable phase and may still produce warnings or a required failure.

type CreateWorktreeMsg

type CreateWorktreeMsg struct {
	Name       string
	BaseBranch string
	TaskID     string
}

CreateWorktreeMsg requests worktree creation.

type DeleteDoneMsg

type DeleteDoneMsg struct {
	OperationScope
	Name     string
	Err      error
	Warnings []string // Non-fatal warnings (e.g., branch deletion failures)
}

DeleteDoneMsg signals worktree deletion completed.

type DeleteWorktreeMsg

type DeleteWorktreeMsg struct {
	Name  string
	Force bool
}

DeleteWorktreeMsg requests worktree deletion.

type DiffErrorMsg

type DiffErrorMsg struct {
	OperationScope
	WorkspaceName string
	Err           error
	Command       string
	BaseRef       string
}

DiffErrorMsg signals diff loading failed.

func (DiffErrorMsg) GetEpoch added in v0.94.0

func (m DiffErrorMsg) GetEpoch() uint64

type DiffLoadedMsg

type DiffLoadedMsg struct {
	OperationScope
	WorkspaceName string
	Content       string
	Raw           string
	Snapshot      *DiffSnapshot
}

DiffLoadedMsg delivers diff content for a worktree.

func (DiffLoadedMsg) GetEpoch

func (m DiffLoadedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type DiffScope added in v0.94.0

type DiffScope = workspacediff.Scope

Diff view types live in workspacediff so the global preview can use the same model without constructing a Plugin.

type DiffSnapshot added in v0.94.0

type DiffSnapshot = workspacediff.Snapshot

DiffSnapshot contains all three explicit diff views resolved from the same immutable worktree/base identity.

type DiffTabFocus added in v0.81.0

type DiffTabFocus = workspacediff.Focus

Diff view types live in workspacediff so the global preview can use the same model without constructing a Plugin.

type DiffViewMode

type DiffViewMode = workspacediff.ViewMode

Diff view types live in workspacediff so the global preview can use the same model without constructing a Plugin.

type DirectMergeDoneMsg

type DirectMergeDoneMsg struct {
	OperationScope
	WorkspaceName string
	BaseBranch    string
	Operation     *DirectMergeOperation
	Err           error
}

DirectMergeDoneMsg signals that direct merge completed.

type DirectMergeOperation added in v0.94.0

type DirectMergeOperation struct {
	SourcePath   string
	TargetPath   string
	SourceBranch string
	TargetBranch string
	Remote       string
	SourceOID    string
	TargetOID    string // target HEAD captured during visible preflight
	PreMergeOID  string // target HEAD immediately before merge, after ff-only update
	MergeOID     string
	Completed    []string
	Recovery     DirectMergeRecovery
	GitState     string
	Err          error
	Aborted      bool
	// contains filtered or unexported fields
}

DirectMergeOperation is the immutable context and accumulated result of a merge.

type DirectMergePreflightMsg added in v0.94.0

type DirectMergePreflightMsg struct {
	OperationScope
	WorkspaceName string
	BaseBranch    string
	Operation     *DirectMergeOperation
	Err           error
}

type DirectMergeRecovery added in v0.94.0

type DirectMergeRecovery string

DirectMergeRecovery describes the safe actions available after a failed merge.

const (
	DirectMergeRecoveryNone        DirectMergeRecovery = ""
	DirectMergeRecoveryConflict    DirectMergeRecovery = "conflict"
	DirectMergeRecoveryPushFailure DirectMergeRecovery = "push-failure"
)

type Divider added in v0.98.0

type Divider = panelayout.Divider

type FetchPRDoneMsg

type FetchPRDoneMsg struct {
	OperationScope
	Worktree     *Worktree
	AlreadyLocal bool   // branch already existed locally
	Branch       string // for finding existing worktree when Worktree is nil
	Err          error
}

FetchPRDoneMsg signals that a PR branch was fetched and worktree created.

type FetchPRListMsg

type FetchPRListMsg struct {
	OperationScope
	PRs []PRListItem
	Err error
}

FetchPRListMsg delivers the list of open PRs from gh CLI.

type Floors added in v0.98.0

type Floors = panelayout.Floors

type FocusPane

type FocusPane int

FocusPane represents which pane is active in the split view.

const (
	PaneSidebar FocusPane = iota // Worktree list
	PanePreview                  // Preview pane (output/diff/task)
)

type FullFileDiffLoadedMsg added in v0.81.0

type FullFileDiffLoadedMsg struct {
	Epoch         uint64
	WorkspaceName string
	OldContent    string
	NewContent    string
	Parsed        *gitstatus.ParsedDiff
	FilePath      string
	CommitHash    string // Non-empty when loaded for a commit file diff
}

FullFileDiffLoadedMsg is sent when full-file content is loaded for workspace diff view.

func (FullFileDiffLoadedMsg) GetEpoch added in v0.81.0

func (m FullFileDiffLoadedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type GitStats

type GitStats struct {
	Additions    int
	Deletions    int
	FilesChanged int
	Ahead        int // Commits ahead of base branch
	Behind       int // Commits behind base branch
}

GitStats holds file change statistics.

type InteractivePasteResultMsg

type InteractivePasteResultMsg struct {
	Err         error
	Empty       bool
	SessionDead bool
}

InteractivePasteResultMsg reports clipboard paste results for interactive mode.

type InteractiveSessionDeadMsg

type InteractiveSessionDeadMsg struct{}

InteractiveSessionDeadMsg indicates the tmux session has ended. Sent when send-keys or capture fails with a session/pane not found error.

type InteractiveState

type InteractiveState struct {
	// Active indicates whether interactive mode is currently active.
	Active bool

	// TargetPane is the tmux pane ID (e.g., "%12") receiving input.
	TargetPane string

	// TargetSession is the tmux session name for the active pane.
	TargetSession string

	// TermPanel is true when interactive mode targets the terminal panel session
	// (rather than the main agent/shell session).
	TermPanel bool

	// PaneOnEntry is the pane that was active before interactive mode took over,
	// restored on exit. Interactive mode forces the preview pane active so the
	// embedded terminal owns the cursor and mouse mode (td-62b8ab).
	PaneOnEntry FocusPane

	// LastKeyTime tracks when the last key was sent for polling decay.
	LastKeyTime time.Time

	// CursorRow and CursorCol track the cached cursor position for overlay rendering.
	// Updated asynchronously via cursorPositionMsg from poll handler (td-648af4).
	CursorRow int
	CursorCol int

	// CursorVisible indicates if the cursor should be rendered.
	// Updated asynchronously via cursorPositionMsg from poll handler (td-648af4).
	CursorVisible bool

	// PaneHeight tracks the tmux pane height for cursor offset calculation.
	// Used to adjust cursor_y when display height differs from pane height, and
	// to find pane row 0 in the buffer: a capture ends at the bottom of the
	// pane, so its last PaneHeight rows are the pane.
	PaneHeight int

	// PaneWidth tracks the tmux pane width for display width alignment.
	PaneWidth int

	// BracketedPasteEnabled tracks whether the target app has enabled
	// bracketed paste mode (ESC[?2004h). Updated from captured output.
	BracketedPasteEnabled bool

	// MouseReportingEnabled tracks whether the application in the target pane has
	// asked for mouse events. It is mirrored from the terminal component and read
	// only to describe the surface: who owns a click or a notch is that
	// component's PaneMouseReporting, so the two can never disagree.
	MouseReportingEnabled bool

	// LastResizeAt tracks the last time we attempted to resize the tmux pane.
	LastResizeAt time.Time

	// ResizeRetryPending records that a deferred assertion of the pane's
	// geometry is already armed. A layout still moving delivers one size per
	// frame; without this each of them would arm its own retry and the burst
	// would become a chain of resizes spaced a debounce window apart.
	ResizeRetryPending bool
}

InteractiveState tracks state for interactive mode (tmux input passthrough). Feature-gated behind tmux_interactive_input feature flag.

type LoadState added in v0.94.0

type LoadState = workspacediff.LoadState

Diff view types live in workspacediff so the global preview can use the same model without constructing a Plugin.

type LocalBranchesMsg

type LocalBranchesMsg struct {
	OperationScope
	Branches []string
	Err      error
}

LocalBranchesMsg returns available local branches for target selection.

type MergeCommitDoneMsg

type MergeCommitDoneMsg struct {
	OperationScope
	WorkspaceName string
	CommitHash    string
	// NothingToCommit reports that the worktree was already clean by the time
	// the commit ran (the modal's counts came from a cached status snapshot).
	NothingToCommit bool
	Err             error
}

MergeCommitDoneMsg signals that the commit before merge completed.

type MergeCommitState

type MergeCommitState struct {
	Worktree       *Worktree
	StagedCount    int
	ModifiedCount  int
	UntrackedCount int
	CommitMessage  string
	Error          string
}

MergeCommitState holds state for the commit-before-merge modal.

type MergeResolutionMsg

type MergeResolutionMsg struct {
	OperationScope
	WorkspaceName string
	Branch        string
	Success       bool
	Err           error
}

MergeResolutionMsg signals result of merge resolution attempt.

type MergeStepCompleteMsg

type MergeStepCompleteMsg struct {
	OperationScope
	WorkspaceName   string
	Step            MergeWorkflowStep
	Data            string // Step-specific data (e.g., PR URL)
	Err             error
	ExistingPRFound bool // True if PR already existed (vs newly created)
	PR              PRIdentity
	ReviewedOID     string
	BaseRemote      string
}

MergeStepCompleteMsg signals a merge workflow step completed.

type MergeWorkflowState

type MergeWorkflowState struct {
	OperationScope
	Worktree         *Worktree
	Step             MergeWorkflowStep
	DiffSummary      string
	PRTitle          string
	PRBody           string
	PRURL            string
	PR               PRIdentity
	ExistingPR       bool // True if using an existing PR (vs newly created)
	ReviewedOID      string
	PushRemote       string
	BaseRemote       string
	Error            error
	ErrorTitle       string                       // Short title for error display (e.g. "Direct Merge Failed")
	ErrorDetail      string                       // Full error text for display and clipboard copy
	ErrorFromStep    MergeWorkflowStep            // Which step produced the error
	StepStatus       map[MergeWorkflowStep]string // "pending", "running", "done", "error", "skipped"
	DeleteAfterMerge bool                         // true = delete worktree after merge (default)

	// Target branch selection
	TargetBranch       string   // Resolved target branch for merge/PR
	TargetBranchOption int      // Selected index in branch list
	TargetBranches     []string // Available branches for selection

	// Merge method selection
	UseDirectMerge    bool // true = direct merge to base, false = PR workflow
	MergeMethodOption int  // 0 = Create PR (default), 1 = Direct merge

	// Post-merge confirmation options
	DeleteLocalWorktree bool   // Checkbox: delete local worktree (default: true)
	DeleteLocalBranch   bool   // Checkbox: delete local branch (default: true)
	DeleteRemoteBranch  bool   // Checkbox: delete remote branch (default: false)
	PullAfterMerge      bool   // Checkbox: pull changes to current branch after merge
	CurrentBranch       string // Branch user was on before merge (for pull)
	ConfirmationFocus   int    // 0-3=checkboxes, 4=confirm btn, 5=skip btn
	ConfirmationHover   int    // Mouse hover state

	// PR generation state
	PRGenerationDots       int                // Animation counter for progress dots (0-3)
	PRGenerationCancel     context.CancelFunc // Cancel func for in-flight agent process
	PRGenerationActive     bool
	PRTitleInput           textinput.Model
	PRBodyInput            textarea.Model
	PRPollAttempt          int
	PRWatchStopped         bool
	PRPollKind             PRPollKind
	ForceDeleteRequired    bool // squash/rebase means ordinary branch -d cannot prove safety
	ForceDeleteLocalBranch bool // explicit user choice after the explanation is shown

	// Cleanup results for summary display
	CleanupResults    *CleanupResults
	PendingCleanupOps int // Counter for cleanup result messages in flight
	DirectOperation   *DirectMergeOperation
}

MergeWorkflowState holds the state for the merge workflow modal.

type MergeWorkflowStep

type MergeWorkflowStep int

MergeWorkflowStep represents the current step in the merge workflow.

const (
	MergeStepReviewDiff   MergeWorkflowStep = iota
	MergeStepTargetBranch                   // Choose target branch for merge/PR
	MergeStepMergeMethod                    // Choose: PR workflow or direct merge
	MergeStepPush
	MergeStepGeneratePR // User chooses deterministic or disclosed agent assistance
	MergeStepEditPR     // User edits title/body before creation
	MergeStepCreatePR
	MergeStepWaitingMerge
	MergeStepDirectMerge           // Performing direct merge (no PR)
	MergeStepPostMergeConfirmation // User confirms cleanup options after PR merge
	MergeStepCleanup
	MergeStepDone
	MergeStepError // Error display step (strategy-agnostic)
)

func (MergeWorkflowStep) String

func (s MergeWorkflowStep) String() string

String returns a display name for the merge step.

type OpenCreateModalWithTaskMsg

type OpenCreateModalWithTaskMsg struct {
	TaskID    string
	TaskTitle string
}

OpenCreateModalWithTaskMsg opens create modal pre-filled with task data. Sent from td-monitor plugin when user presses send-to-worktree hotkey.

type OperationScope added in v0.94.0

type OperationScope struct {
	Epoch       uint64
	OperationID string
	RepoKey     string
	WorktreeKey string
	Lifecycle   bool
}

OperationScope is copied into every lifecycle command result so Update can reject work completed for a prior repository, worktree, or plugin epoch.

func (OperationScope) GetOperationScope added in v0.94.0

func (s OperationScope) GetOperationScope() OperationScope

type PRGenerationDoneMsg added in v0.78.0

type PRGenerationDoneMsg struct {
	OperationScope
	WorkspaceName string
	Title         string
	Body          string
	Err           error
}

PRGenerationDoneMsg signals that agent-powered PR description generation completed.

type PRIdentity added in v0.94.0

type PRIdentity struct {
	Number     int    `json:"number"`
	URL        string `json:"url"`
	NodeID     string `json:"id"`
	Repository string `json:"repository,omitempty"`
	HeadRef    string `json:"headRefName"`
	HeadOwner  string `json:"headOwner,omitempty"`
	HeadRepo   string `json:"headRepository,omitempty"`
	HeadOID    string `json:"headRefOid,omitempty"`
	BaseRef    string `json:"baseRefName"`
	State      string `json:"state,omitempty"`
	MergedAt   string `json:"mergedAt,omitempty"`
	MergeOID   string `json:"mergeCommitOid,omitempty"`
}

PRIdentity is the stable identity Sidecar uses after a pull request is found or created. Branch names are display/routing data; Number and NodeID identify the pull request across checkout and branch changes.

type PRListItem

type PRListItem struct {
	Number     int          `json:"number"`
	NodeID     string       `json:"id"`
	Title      string       `json:"title"`
	Branch     string       `json:"headRefName"`
	HeadOID    string       `json:"headRefOid"`
	BaseBranch string       `json:"baseRefName"`
	HeadRepo   ghRepository `json:"headRepository"`
	HeadOwner  ghOwner      `json:"headRepositoryOwner"`
	Repository string       `json:"-"`
	Author     prAuthor     `json:"author"`
	URL        string       `json:"url"`
	CreatedAt  string       `json:"createdAt"`
	IsDraft    bool         `json:"isDraft"`
}

PRListItem represents an open pull request for the fetch modal.

type PRPollKind added in v0.94.0

type PRPollKind string
const (
	PRPollOpen        PRPollKind = "open"
	PRPollMerged      PRPollKind = "merged"
	PRPollClosed      PRPollKind = "closed"
	PRPollAuth        PRPollKind = "authentication"
	PRPollRepository  PRPollKind = "repository-mismatch"
	PRPollNetwork     PRPollKind = "network-unavailable"
	PRPollUnavailable PRPollKind = "unavailable"
)

type PRPollResult added in v0.94.0

type PRPollResult struct {
	Kind                PRPollKind
	Identity            PRIdentity
	Err                 error
	ForceDeleteRequired bool
}

type PaneFloor added in v0.98.0

type PaneFloor = panelayout.Floor

type PaneKind added in v0.98.0

type PaneKind = panelayout.Kind

type PaneLayout added in v0.99.0

type PaneLayout = panelayout.Layout

func LayoutPaneTree added in v0.99.0

func LayoutPaneTree(root *PaneNode, box Box, floors Floors, focus int) (PaneLayout, bool)

type PaneNode added in v0.98.0

type PaneNode = panelayout.Node

func ClosePane added in v0.98.0

func ClosePane(root *PaneNode, leafID int) (*PaneNode, int)

func FindPane added in v0.98.0

func FindPane(root *PaneNode, id int) *PaneNode

func SplitLeaf added in v0.98.0

func SplitLeaf(root *PaneNode, leafID int, axis SplitAxis, leaf *PaneNode) (*PaneNode, int)

type PaneSplit added in v0.98.0

type PaneSplit = panelayout.Split

type Placement added in v0.98.0

type Placement = panelayout.Placement

type Plugin

type Plugin struct {
	// contains filtered or unexported fields
}

Plugin implements the worktree manager plugin.

func New

func New() *Plugin

New creates a new worktree manager plugin.

func (*Plugin) Approve

func (p *Plugin) Approve(wt *Worktree) tea.Cmd

Approve sends "y" to approve a pending prompt.

func (*Plugin) ApproveAll

func (p *Plugin) ApproveAll() tea.Cmd

ApproveAll approves all worktrees with pending prompts.

func (*Plugin) AttachToSession

func (p *Plugin) AttachToSession(wt *Worktree) tea.Cmd

AttachToSession attaches to a tmux session using tea.ExecProcess.

func (*Plugin) AttachToWorktreeDir

func (p *Plugin) AttachToWorktreeDir(wt *Worktree) tea.Cmd

AttachToWorktreeDir creates a tmux session in the worktree directory and attaches to it.

func (*Plugin) BlocksGlobalKeys added in v0.96.0

func (p *Plugin) BlocksGlobalKeys() bool

BlocksGlobalKeys reports whether a plugin-owned modal has keyboard focus.

func (*Plugin) Cleanup

func (p *Plugin) Cleanup(removeSessions bool) error

Cleanup cleans up tmux sessions, optionally removing them.

func (*Plugin) CleanupOrphanedSessions

func (p *Plugin) CleanupOrphanedSessions() error

CleanupOrphanedSessions removes sessions that no longer have worktrees.

func (*Plugin) Commands

func (p *Plugin) Commands() []plugin.Command

Commands returns the available commands.

func (*Plugin) ConsumesTextInput

func (p *Plugin) ConsumesTextInput() bool

ConsumesTextInput reports whether the workspace plugin is currently in a mode that expects typed text input.

func (*Plugin) Cursor added in v0.88.0

func (p *Plugin) Cursor() *tea.Cursor

Cursor exposes the active embedded terminal's native cursor in plugin-local coordinates. App-level focus, modal, and bounds checks are applied later.

func (*Plugin) FocusContext

func (p *Plugin) FocusContext() string

FocusContext returns the current focus context for keybinding dispatch.

func (*Plugin) ID

func (p *Plugin) ID() string

ID returns the plugin identifier.

func (*Plugin) Icon

func (p *Plugin) Icon() string

Icon returns the plugin icon.

func (*Plugin) Init

func (p *Plugin) Init(ctx *plugin.Context) error

Init initializes the plugin with context.

func (*Plugin) IsFocused

func (p *Plugin) IsFocused() bool

IsFocused returns whether the plugin is focused.

func (*Plugin) Name

func (p *Plugin) Name() string

Name returns the plugin display name.

func (*Plugin) PreferredMouseMode added in v0.88.0

func (p *Plugin) PreferredMouseMode() tea.MouseMode

PreferredMouseMode keeps hover-rich all-motion reporting for ordinary workspace views and requests cell motion only while a child terminal owns interactive input.

func (*Plugin) Reject

func (p *Plugin) Reject(wt *Worktree) tea.Cmd

Reject sends "n" to reject a pending prompt.

func (*Plugin) SendText

func (p *Plugin) SendText(wt *Worktree, text string) tea.Cmd

SendText sends arbitrary text to an agent.

func (*Plugin) SetFocused

func (p *Plugin) SetFocused(f bool)

SetFocused sets the focus state.

func (*Plugin) SetPendingWorkspaceSelection added in v0.94.0

func (p *Plugin) SetPendingWorkspaceSelection(selection plugin.PendingWorkspaceSelection)

func (*Plugin) Start

func (p *Plugin) Start() tea.Cmd

Start begins async operations.

func (*Plugin) StartAgent

func (p *Plugin) StartAgent(wt *Worktree, agentType AgentType) tea.Cmd

StartAgent creates a tmux session and starts an agent for a worktree. If a session already exists, it reconnects to it instead of failing.

func (*Plugin) StartAgentWithOptions

func (p *Plugin) StartAgentWithOptions(wt *Worktree, agentType AgentType, skipPerms bool, prompt *Prompt) tea.Cmd

StartAgentWithOptions creates a tmux session and starts an agent with options. If a session already exists, it reconnects to it instead of failing.

func (*Plugin) Stop

func (p *Plugin) Stop()

Stop cleans up plugin resources.

func (*Plugin) StopAgent

func (p *Plugin) StopAgent(wt *Worktree) tea.Cmd

StopAgent stops an agent running in a worktree.

func (*Plugin) Update

func (p *Plugin) Update(msg tea.Msg) (plugin.Plugin, tea.Cmd)

Update routes terminal-owned lifecycle messages through the shared component before applying workspace product state. Ordinary keys and mouse events are routed explicitly by interactive mode so a visible preview never captures input intended for workspace navigation.

func (*Plugin) View

func (p *Plugin) View(width, height int) string

View renders the plugin UI.

type PreviewTab

type PreviewTab int

PreviewTab represents the active tab in the preview pane.

const (
	PreviewTabOutput PreviewTab = iota // Agent output
	PreviewTabDiff                     // Git diff
	PreviewTabTask                     // TD task info
)

type Prompt

type Prompt struct {
	Name       string     `json:"name"`
	TicketMode TicketMode `json:"ticketMode"`
	Body       string     `json:"body"`
	Source     string     `json:"-"` // "global" or "project" (set at load time)
}

Prompt represents a configurable prompt template.

func DefaultPrompts

func DefaultPrompts() []Prompt

DefaultPrompts returns the built-in default prompts. These serve as examples users can modify.

func LoadPrompts

func LoadPrompts(globalConfigDir, projectDir string) []Prompt

LoadPrompts loads and merges prompts from global and project config directories. Project prompts override global prompts with the same name. If no config exists, creates global config with default prompts. Returns sorted list by name.

type PromptCancelledMsg

type PromptCancelledMsg struct{}

PromptCancelledMsg is sent when the picker is cancelled.

type PromptInstallDefaultsMsg

type PromptInstallDefaultsMsg struct{}

PromptInstallDefaultsMsg is sent when user requests installing default prompts.

type PromptPicker

type PromptPicker struct {
	// contains filtered or unexported fields
}

PromptPicker is a modal for selecting a prompt template.

func NewPromptPicker

func NewPromptPicker(prompts []Prompt, width, height int) *PromptPicker

NewPromptPicker creates a new prompt picker.

func (*PromptPicker) ClearHover

func (pp *PromptPicker) ClearHover()

ClearHover clears the hover state.

func (*PromptPicker) FocusFilter

func (pp *PromptPicker) FocusFilter()

FocusFilter focuses the filter input field.

func (*PromptPicker) SetHover

func (pp *PromptPicker) SetHover(idx int)

SetHover sets the hover index for visual feedback.

func (*PromptPicker) Update

func (pp *PromptPicker) Update(msg tea.Msg) (*PromptPicker, tea.Cmd)

Update handles input for the prompt picker.

func (*PromptPicker) View

func (pp *PromptPicker) View() string

View renders the prompt picker modal.

type PromptSelectedMsg

type PromptSelectedMsg struct {
	Prompt *Prompt // nil means "none" was selected
}

PromptSelectedMsg is sent when a prompt is selected.

type PullAfterMergeMsg

type PullAfterMergeMsg struct {
	OperationScope
	WorkspaceName string
	Branch        string
	Success       bool
	Err           error
}

PullAfterMergeMsg signals that pull after merge completed.

type PushDoneMsg

type PushDoneMsg struct {
	OperationScope
	WorkspaceName string
	Err           error
}

PushDoneMsg signals push operation completed.

type PushMsg

type PushMsg struct {
	WorkspaceName string
	Force         bool
	SetUpstream   bool
}

PushMsg requests pushing a worktree branch.

type RebaseResolutionMsg

type RebaseResolutionMsg struct {
	OperationScope
	WorkspaceName string
	Branch        string
	Success       bool
	Err           error
}

RebaseResolutionMsg signals result of rebase resolution attempt.

type RefreshDoneMsg

type RefreshDoneMsg struct {
	OperationScope
	Worktrees      []*Worktree
	Snapshot       *RepoSnapshot
	Err            error
	Conflicts      []Conflict
	Duration       time.Duration
	Processes      int
	MaxConcurrency int
}

RefreshDoneMsg signals that refresh has completed.

func (RefreshDoneMsg) GetEpoch

func (m RefreshDoneMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type RefreshMsg

type RefreshMsg struct{}

RefreshMsg triggers a worktree list refresh.

type RejectResultMsg

type RejectResultMsg struct {
	WorkspaceName string
	Err           error
}

RejectResultMsg signals the result of a reject action.

type RemoteBranchDeleteMsg

type RemoteBranchDeleteMsg struct {
	OperationScope
	WorkspaceName string
	BranchName    string
	Err           error
}

RemoteBranchDeleteMsg signals the result of deleting a remote branch.

type RemoteCheckDoneMsg

type RemoteCheckDoneMsg struct {
	OperationScope
	WorkspaceName string
	Branch        string
	Exists        bool
}

RemoteCheckDoneMsg signals remote branch existence check completed.

type RenameShellDoneMsg

type RenameShellDoneMsg struct {
	TmuxName string // Session name (stable identifier)
	NewName  string // New display name
	Err      error  // Non-nil if rename failed
}

RenameShellDoneMsg signals shell rename operation completed

type Render added in v0.99.0

type Render struct {
	// Focused is true when this leaf owns the preview's keyboard focus.
	Focused bool
	// Zoomed is true when the box could not hold the whole tree and this leaf
	// was given all of it.
	Zoomed bool
	// Origin is the leaf's box in plugin-local coordinates, which is what hit
	// math needs; the size handed to SetSize is content-local.
	Origin mouse.Rect
}

Render is what the frame knows about a placed leaf and the content does not. It carries no theme: styles are process-global in internal/styles, so a content reads them there rather than through a copy that can go stale.

type RepoSnapshot added in v0.94.0

type RepoSnapshot struct {
	Key                string
	CanonicalRoot      string
	CanonicalCommonDir string
	Worktrees          []WorktreeSnapshot
	CheckedOut         map[string]string // local branch -> stable worktree key
}

RepoSnapshot is one immutable inventory used to identify and validate all worktree lifecycle operations. Callers replace the whole value after refresh; commands never mutate it.

func BuildRepoSnapshot added in v0.94.0

func BuildRepoSnapshot(ctx context.Context, repoPath string) (*RepoSnapshot, error)

BuildRepoSnapshot reads one porcelain worktree inventory and enriches it with a single branch-ref inventory. This avoids independently rediscovering correctness-critical paths and branch ownership during an operation.

type ResumeConversationMsg

type ResumeConversationMsg struct {
	SessionID string // Adapter session ID for resume command
	AdapterID string // Adapter type (claude-code, codex, etc.)
	ResumeCmd string // Full resume command (e.g., "claude --resume xyz")
	Type      string // "shell" or "worktree"
	// Worktree-specific fields (only used when Type == "worktree")
	WorktreeName string    // Branch name for new worktree
	BaseBranch   string    // Base branch to create from
	AgentType    AgentType // Agent to start (matches adapter or user selection)
	SkipPerms    bool      // Whether to auto-approve agent actions
}

ResumeConversationMsg requests resuming a conversation in a new shell or worktree. Sent from conversations plugin when user presses O key.

type SendTextResultMsg

type SendTextResultMsg struct {
	WorkspaceName string
	Text          string
	Err           error
}

SendTextResultMsg signals the result of sending text to an agent.

type SetupConfig

type SetupConfig struct {
	CopyEnv        bool     // Whether to copy env files (default: true)
	EnvFiles       []string // List of env files to copy
	SymlinkDirs    []string // Directories to symlink (default: empty, opt-in)
	RunSetupScript bool     // Whether to run .worktree-setup.sh (default: true)
}

SetupConfig holds worktree setup configuration.

func DefaultSetupConfig

func DefaultSetupConfig() *SetupConfig

DefaultSetupConfig returns the default setup configuration.

type ShellAgentErrorMsg

type ShellAgentErrorMsg struct {
	TmuxName string // Shell's tmux session name
	Err      error  // Error that occurred
}

ShellAgentErrorMsg signals agent failed to start in a shell session. td-21a2d8: Sent when agent command fails to execute.

type ShellAgentStartedMsg

type ShellAgentStartedMsg struct {
	TmuxName  string    // Shell's tmux session name
	AgentType AgentType // Agent type that was started
	SkipPerms bool      // Whether skip permissions was enabled
}

ShellAgentStartedMsg signals agent was started in a shell session. td-21a2d8: Sent after agent command is sent to tmux.

type ShellCreatedMsg

type ShellCreatedMsg struct {
	SessionName string    // tmux session name
	DisplayName string    // Display name (e.g., "Shell 1")
	PaneID      string    // tmux pane ID (e.g., "%12") for interactive mode
	Err         error     // Non-nil if creation failed
	AgentType   AgentType // td-16b2b5: Agent to start (AgentNone if plain shell)
	SkipPerms   bool      // td-16b2b5: Whether to skip permissions for agent
	// KeepSelection leaves the sidebar selection where it is instead of
	// selecting the new shell. Set for shells created without the user
	// explicitly asking for one (auto-create on first focus).
	KeepSelection bool
}

ShellCreatedMsg signals shell session was created

type ShellDefinition

type ShellDefinition = shellstate.Definition

ShellDefinition is retained as the workspace-facing name for the shared persisted model. New non-interactive surfaces use shellstate.Definition directly rather than defining another manifest shape.

type ShellDetachedMsg

type ShellDetachedMsg struct {
	Err error
}

ShellDetachedMsg signals user detached from shell session

type ShellKilledMsg

type ShellKilledMsg struct {
	SessionName string // tmux session name that was killed
}

ShellKilledMsg signals shell session was terminated

type ShellManifest

type ShellManifest struct {
	Version int               `json:"version"`
	Shells  []ShellDefinition `json:"shells"`
	// contains filtered or unexported fields
}

ShellManifest stores persistent shell definitions for cross-instance sync and reboot survival. Stored in $XDG_STATE_HOME/sidecar/projects/<slug>/shells.json.

func LoadShellManifest

func LoadShellManifest(path string) (*ShellManifest, error)

LoadShellManifest loads the shell manifest from disk. Returns an empty manifest (not error) if file doesn't exist or is corrupted.

func (*ShellManifest) AddShell

func (m *ShellManifest) AddShell(def ShellDefinition) error

AddShell adds a shell definition and saves.

func (*ShellManifest) BackfillWorkDirs added in v0.98.0

func (m *ShellManifest) BackfillWorkDirs(byTmux map[string]string) error

BackfillWorkDirs writes inferred parent worktree paths onto definitions that still lack WorkDir. Existing non-empty values are left untouched.

func (*ShellManifest) EnsureShells added in v0.93.0

func (m *ShellManifest) EnsureShells(defs []ShellDefinition) (bool, error)

EnsureShells adds any definitions the manifest is missing and saves once. Existing entries are left untouched. Returns true when the file changed.

This is the additive counterpart to AddShell: it heals a manifest another instance narrowed (td-8d18de) without ever overwriting what that instance wrote.

func (*ShellManifest) FindShell

func (m *ShellManifest) FindShell(tmuxName string) *ShellDefinition

FindShell returns a shell definition by tmuxName, or nil if not found.

func (*ShellManifest) Path

func (m *ShellManifest) Path() string

Path returns the manifest file path.

func (*ShellManifest) RemoveShell

func (m *ShellManifest) RemoveShell(tmuxName string) error

RemoveShell removes a shell by tmuxName and saves.

func (*ShellManifest) RenameShell added in v0.96.0

func (m *ShellManifest) RenameShell(tmuxName, namespace, name string) (shellstate.RenameResult, error)

RenameShell routes display-name validation and persistence through the same application boundary as the agent-facing CLI.

func (*ShellManifest) Revision added in v0.93.0

func (m *ShellManifest) Revision() uint64

Revision counts the successful writes this process has made through this manifest object. A reconciliation that started before a local delete and lands after it would resurrect the deleted shell, so callers stamp the revision they observed and discard (or re-run) a sync whose base moved underneath them (td-8d18de).

func (*ShellManifest) Save

func (m *ShellManifest) Save() error

Save writes the manifest to disk atomically with file locking.

func (*ShellManifest) UpdateShell

func (m *ShellManifest) UpdateShell(def ShellDefinition) error

UpdateShell updates an existing shell definition and saves.

type ShellManifestChangedMsg

type ShellManifestChangedMsg struct{}

ShellManifestChangedMsg is emitted when the manifest file changes. This can be triggered by another sidecar instance modifying the manifest.

type ShellOutputMsg

type ShellOutputMsg struct {
	TmuxName       string // Session name (stable identifier)
	Generation     int
	AgentType      AgentType // Live provider inferred from the captured pane
	Output         string
	Err            error
	Activity       agentactivity.Result
	CapturedAt     time.Time
	PaneTitle      string
	CurrentCommand string
	// Cursor position captured atomically with output (only set in interactive mode)
	CursorRow     int
	CursorCol     int
	CursorVisible bool
	HasCursor     bool // True if cursor position was captured
	PaneHeight    int  // Tmux pane height for cursor offset calculation
	PaneWidth     int  // Tmux pane width for display alignment
	HistorySize   int
	CaptureBase   int
	HasHistory    bool
	// RowsJoined says the capture was taken with -J, so it carries no usable
	// history/pane split.
	RowsJoined bool
	// MouseReporting is tmux's #{mouse_any_flag} for the pane. Only
	// meaningful when HasCursor is set.
	MouseReporting bool
}

ShellOutputMsg signals shell output was captured (for polling)

type ShellSession

type ShellSession struct {
	Name        string // Display name (e.g., "Shell 1")
	TmuxName    string // tmux session name (e.g., "sidecar-sh-project-1")
	WorkDir     string // Parent worktree path; persisted on the definition
	Agent       *Agent // Reuses Agent struct for tmux state
	CreatedAt   time.Time
	ChosenAgent AgentType // td-317b64: Agent type selected at creation (AgentNone for plain shell)
	SkipPerms   bool      // td-317b64: Whether skip permissions was enabled
	IsOrphaned  bool      // td-f88fdd: True if manifest entry exists but tmux session is gone
}

ShellSession represents a tmux shell session (not tied to a git worktree).

type ShellSessionDeadMsg

type ShellSessionDeadMsg struct {
	TmuxName   string // Session name for cleanup (stable identifier)
	Generation int    // Poll owner; zero for non-poll lifecycle checks
}

ShellSessionDeadMsg signals shell session was externally terminated (e.g., user typed 'exit' in the shell)

type ShellWatcher

type ShellWatcher struct {
	// contains filtered or unexported fields
}

ShellWatcher monitors the shell manifest file for changes. When changes are detected, it emits ShellManifestChangedMsg for cross-instance sync.

func NewShellWatcher

func NewShellWatcher(manifestPath string) (*ShellWatcher, error)

NewShellWatcher creates a watcher for the shell manifest file.

func (*ShellWatcher) Start

func (w *ShellWatcher) Start() <-chan tea.Msg

Start begins watching and returns a channel for receiving messages. The channel emits ShellManifestChangedMsg when the manifest changes.

func (*ShellWatcher) Stop

func (w *ShellWatcher) Stop()

Stop stops the watcher and closes channels.

type Size added in v0.99.0

type Size struct {
	Width, Height int
}

Size is the box a content draws into. It is the leaf's whole box, header row included: the terminal leaf's header is still drawn by the legacy renderer from inside its box, so each content spends its own header row. M1 absorbs the terminal panel into the tree, and this becomes the box below the row the frame draws.

type SplitAxis added in v0.98.0

type SplitAxis = panelayout.Axis

type StatsErrorMsg

type StatsErrorMsg struct {
	OperationScope
	WorkspaceName string
	Err           error
	Command       string
}

StatsErrorMsg signals stats loading failed.

func (StatsErrorMsg) GetEpoch added in v0.94.0

func (m StatsErrorMsg) GetEpoch() uint64

type StatsLoadedMsg

type StatsLoadedMsg struct {
	OperationScope
	WorkspaceName string
	Stats         *GitStats
}

StatsLoadedMsg delivers git stats for a worktree.

func (StatsLoadedMsg) GetEpoch

func (m StatsLoadedMsg) GetEpoch() uint64

GetEpoch implements plugin.EpochMessage.

type Task

type Task struct {
	ID          string
	Title       string
	Status      string
	Description string
	EpicTitle   string // Parent epic title for search
}

Task represents a TD task for linking.

type TaskDetails

type TaskDetails struct {
	ID          string
	Title       string
	Status      string
	Priority    string
	Type        string
	Description string
	Acceptance  string
	CreatedAt   string
	UpdatedAt   string
}

TaskDetails contains full task information for preview pane.

type TaskDetailsLoadedMsg

type TaskDetailsLoadedMsg struct {
	OperationScope
	TaskID  string
	Details *TaskDetails
	Err     error
}

TaskDetailsLoadedMsg delivers task details for the preview pane.

type TaskLinkedMsg

type TaskLinkedMsg struct {
	OperationScope
	WorkspaceName string
	TaskID        string
	Err           error
}

TaskLinkedMsg signals a task was linked to a worktree.

type TaskSearchResultsMsg

type TaskSearchResultsMsg struct {
	OperationScope
	Tasks []Task
	Err   error
}

TaskSearchResultsMsg delivers task search results.

type TermPanelLayout added in v0.83.0

type TermPanelLayout int

TermPanelLayout represents the terminal panel split orientation.

const (
	TermPanelBottom TermPanelLayout = iota // Terminal below output (horizontal divider)
	TermPanelRight                         // Terminal to the right of output (vertical divider)
)

type TermPanelSessionCreatedMsg added in v0.83.0

type TermPanelSessionCreatedMsg struct {
	SessionName string
	PaneID      string
	Err         error
}

TermPanelSessionCreatedMsg is sent when the terminal panel tmux session is created.

type TicketMode

type TicketMode string

TicketMode defines how the task field behaves with a prompt.

const (
	TicketRequired TicketMode = "required" // Task must be selected
	TicketOptional TicketMode = "optional" // Task is optional (may have fallback)
	TicketNone     TicketMode = "none"     // Task field is hidden
)

type TmuxAttachFinishedMsg

type TmuxAttachFinishedMsg struct {
	WorkspaceName string
	Err           error
}

TmuxAttachFinishedMsg signals return from tmux attach.

type UncommittedChangesCheckMsg

type UncommittedChangesCheckMsg struct {
	OperationScope
	WorkspaceName  string
	HasChanges     bool
	StagedCount    int
	ModifiedCount  int
	UntrackedCount int
	Err            error
}

UncommittedChangesCheckMsg signals the result of checking for uncommitted changes.

type ViewMode

type ViewMode int

ViewMode represents the current view state.

const (
	ViewModeList               ViewMode = iota // List view (default)
	ViewModeKanban                             // Kanban board view
	ViewModeCreate                             // New worktree modal
	ViewModeTaskLink                           // Task link modal (for existing worktrees)
	ViewModeMerge                              // Merge workflow modal
	ViewModeAgentChoice                        // Agent action choice modal (attach/restart)
	ViewModeConfirmDelete                      // Delete confirmation modal
	ViewModeConfirmDeleteShell                 // Shell delete confirmation modal
	ViewModeCommitForMerge                     // Commit modal before merge workflow
	ViewModePromptPicker                       // Prompt template picker modal
	ViewModeTypeSelector                       // Type selector modal (shell vs worktree)
	ViewModeRenameShell                        // Rename shell modal
	ViewModeFilePicker                         // Diff file picker modal
	ViewModeInteractive                        // Interactive mode (tmux input passthrough)
	ViewModeFetchPR                            // Fetch remote PR modal
	ViewModeAgentConfig                        // Agent config modal (start/restart with options)
)

type WatchEventMsg

type WatchEventMsg struct {
	Path string
}

WatchEventMsg signals a filesystem change was detected.

type WatcherErrorMsg

type WatcherErrorMsg struct {
	Err error
}

WatcherErrorMsg signals a file watcher error.

type WatcherStartedMsg

type WatcherStartedMsg struct{}

WatcherStartedMsg signals the file watcher is running.

type WorkDirDeletedMsg

type WorkDirDeletedMsg struct {
	MainWorktreePath string
}

WorkDirDeletedMsg signals that the current working directory was deleted. This happens when sidecar is running inside a worktree that gets deleted.

type Worktree

type Worktree struct {
	Key             string           // Stable normalized-path identity; never presentation
	RepoKey         string           // Stable canonical common-dir identity
	Name            string           // e.g., "auth-oauth-flow"
	Path            string           // Absolute path
	Branch          string           // Git branch name
	BaseBranch      string           // Branch worktree was created from
	TaskID          string           // Linked td task (e.g., "td-a1b2")
	TaskTitle       string           // Task title (used as fallback if td show fails)
	PRURL           string           // URL of open PR (if any)
	PRState         string           // open, merged, closed, or unavailable when known
	SetupWarning    string           // Last visible setup warning for this worktree
	ChosenAgentType AgentType        // Agent selected at creation (persists even when agent not running)
	Agent           *Agent           // nil if no agent running
	Status          WorktreeStatus   // Derived from agent state
	Stats           *GitStats        // +/- line counts
	Changes         *WorktreeChanges // One refresh result shared by badges/stats/overlap/gating
	CreatedAt       time.Time
	UpdatedAt       time.Time
	IsOrphaned      bool // True if agent file exists but tmux session is gone
	IsMain          bool // True if this is the primary/main worktree (project root)
	IsMissing       bool // True if worktree directory no longer exists (detected via os.Stat or git prunable)
	IsBare          bool // True if Git reports a bare worktree entry
	IsDetached      bool // True if HEAD is detached
	IsLocked        bool // True if Git reports the worktree as locked
	IsPrunable      bool // True if Git reports the worktree record as prunable
	HEADOID         string
	BaseOID         string
	Remote          string
	Upstream        string
}

Worktree represents a git worktree with optional agent.

func (*Worktree) IdentityKey added in v0.94.0

func (w *Worktree) IdentityKey() string

type WorktreeAction added in v0.94.0

type WorktreeAction string

WorktreeAction identifies a mutating action offered by the workspace UI.

const (
	WorktreeActionDelete WorktreeAction = "delete"
	WorktreeActionPush   WorktreeAction = "push"
	WorktreeActionMerge  WorktreeAction = "merge"
)

type WorktreeChanges added in v0.94.0

type WorktreeChanges struct {
	State          LoadState
	Staged         []string
	Unstaged       []string
	Untracked      []string
	Dirty          []string
	Truncated      bool
	TruncatedFiles int
	TruncatedBytes int64
	Err            error
}

WorktreeChanges is the bounded, immutable status result for one refresh. Paths are repository-relative and originate from a single porcelain status invocation. Stats and dirty overlap are derived from this same value.

type WorktreeSnapshot added in v0.94.0

type WorktreeSnapshot struct {
	Key      string
	RepoKey  string
	Path     string
	Branch   string
	Detached bool
	HEADOID  string
	BaseRef  string
	BaseOID  string
	Remote   string
	Upstream string
	Locked   bool
	Prunable bool
	Bare     bool
	IsMain   bool
}

WorktreeSnapshot contains Git identity and routing facts, separate from the user-facing Worktree.Name.

type WorktreeStatus

type WorktreeStatus int

WorktreeStatus represents the current state of a worktree.

const (
	StatusPaused   WorktreeStatus = iota // No agent, worktree exists
	StatusActive                         // Agent running, recent output
	StatusThinking                       // Agent is processing/thinking
	StatusWaiting                        // Agent waiting for input
	StatusDone                           // Agent completed task
	StatusError                          // Agent crashed or errored
)

func (WorktreeStatus) Icon

func (s WorktreeStatus) Icon() string

Icon returns the status indicator icon for display.

func (WorktreeStatus) String

func (s WorktreeStatus) String() string

String returns the display string for a WorktreeStatus.

Jump to

Keyboard shortcuts

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