sessions

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 28 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 sessions follows the coding-agent sessions the app launches, from the item each was launched on, while they run in the user's own terminal.

Every launch is recorded in a ledger, the agent_sessions table this package owns, under an ID the app mints before the launch. A Watcher then reconciles what each agent reports through its own supported interface into the ledger, as a controller does: an Observer per agent (the observe/claude and observe/codex packages) turns the agent's own shapes into one State, and the Watcher stores each change, tells the window, and hands the moments that need the user to an AttentionSink. It observes only while some session has not ended, and it reconciles every session that has not ended when the app starts again, so it survives restarts.

Following is read-only. The app never sends a session input, never answers its approvals, and never writes into an agent's config or conversation, apart from the session ID a Claude Code launch passes. Everything stays on this Mac: nothing here talks to GitHub or to any network.

Index

Constants

View Source
const (
	// KeepEnded is how long an ended session is kept.
	KeepEnded = 30 * 24 * time.Hour

	// KeepPerItem is how many sessions of each item are kept, the newest; one still
	// running is always kept.
	KeepPerItem = 20

	// RecentWindow is how far back the window's list reaches for sessions that ended.
	RecentWindow = 7 * 24 * time.Hour
)

Retention: the sessions the ledger keeps.

View Source
const (
	// DefaultTick is how often the Watcher asks the observers while a session runs. Each
	// observer decides itself how often it asks its agent; most ticks cost a few file
	// stats.
	DefaultTick = time.Second

	// DefaultDebounce is how long a session must wait for the user before the
	// AttentionSink hears of it, so a prompt answered at once never shows a banner.
	DefaultDebounce = 5 * time.Second

	// ReviveWindow is how long after it ended a session is watched for being resumed
	// outside the app, as `claude --resume <id>` in a terminal resumes it.
	ReviveWindow = 24 * time.Hour

	// ReviveTick is how often the Watcher looks for a resumed session while none runs.
	ReviveTick = 20 * time.Second
)

The Watcher's pace.

View Source
const MaxMessageRunes = 500

MaxMessageRunes caps the last message a session keeps.

View Source
const MaxWordsRunes = 20000

MaxWordsRunes caps a session's last message as LastWords reads it in full.

Variables

View Source
var (
	// ErrEnded is returned by Focus for a session that has ended.
	ErrEnded = errors.New("the session has ended")

	// ErrNoTerminal is returned by Focus for a session whose terminal cannot be found.
	ErrNoTerminal = errors.New("the session's terminal is not known")

	// ErrNoFolder is returned by ShowFolder for a session whose folder is gone.
	ErrNoFolder = errors.New("the session's folder is gone")

	// ErrNoFinder is returned by ShowFolder where there is no Finder to show it in.
	ErrNoFinder = errors.New("no file manager to show the folder in")
)
View Source
var (
	// ErrNotFound is returned for a session the ledger does not hold.
	ErrNotFound = errors.New("the session is no longer recorded")

	// ErrInvalidRecord is returned for a session record missing what storing it needs.
	ErrInvalidRecord = errors.New("invalid session record")

	// ErrLive is returned by Forget for a session that has not ended.
	ErrLive = errors.New("the session is still running")
)
View Source
var ErrNoWords = errors.New("the session's last message can't be read")

ErrNoWords is returned by a WordsReader that finds nothing the session said.

Functions

func TTY

func TTY(ctx context.Context, run execpath.Runner, pid int) (string, error)

TTY returns the terminal device the process pid runs on, such as /dev/ttys004, asking ps through run. A process with no terminal, or none at all, is ErrNoTerminal.

Types

type AttentionSink

type AttentionSink interface {
	// NeedsYou says a session has waited for the user for the debounce.
	NeedsYou(ctx context.Context, s Session)

	// Finished says a session finished a turn it was working on.
	Finished(ctx context.Context, s Session)
}

AttentionSink hears the moments a session needs the user: it has waited for them a while, or it finished a turn. The notify package's banners implement it.

type Change

type Change struct {
	Before Record
	After  Record
}

Change is a session whose record an observation changed: as it was, and as it is.

func (Change) StateChanged

func (c Change) StateChanged() bool

StateChanged reports a change of state.

type Config

type Config struct {
	Store *Store

	// Watcher is woken when a launch records a session. Optional.
	Watcher *Watcher

	// Switch is the user's master switch; without it, sessions are always followed.
	Switch Switch

	// Focuser shows a session's terminal; without it, Focus fails.
	Focuser Focuser

	// PS runs ps, which names the terminal a session's process runs in.
	PS execpath.Runner

	// Reveal shows a session's folder in Finder; without it, ShowFolder fails.
	Reveal Revealer

	// Home shows home as ~.
	Home string

	// Events hears an event.SessionsUpdated when a launch records a session, and when the
	// user forgets one.
	Events event.Sink

	// Words reads each agent's sessions' last messages in full, for LastWords; an agent
	// with none falls back to the start the ledger keeps.
	Words map[agent.ID]WordsReader

	Clock  clock.Clock
	Logger *slog.Logger
}

Config holds a Service's and a Ledger's dependencies. Store is required.

type Focuser

type Focuser interface {
	// Focus selects the tab, in the terminal named by its settings ID, whose tty is
	// tty, such as /dev/ttys004, and brings its window forward.
	Focus(ctx context.Context, terminal, tty string) error
}

Focuser brings a terminal's tab that runs on a tty forward. The app adapts the launcher's terminal drivers to it.

type Ledger

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

Ledger records the sessions launches start, and reads them for the launcher and the menu bar. It is not bound to the window.

func NewLedger

func NewLedger(cfg Config) *Ledger

NewLedger returns the Ledger over cfg.

func (*Ledger) AgentProcesses

func (l *Ledger) AgentProcesses(ctx context.Context) (map[int]agent.ID, error)

AgentProcesses returns the coding agent of each running session's process, by PID, or none while the app does not follow sessions, when the processes it knows may be stale.

func (*Ledger) ConversationLive

func (l *Ledger) ConversationLive(ctx context.Context, agentSessionID string) (bool, error)

ConversationLive reports whether a session that has not ended carries on the agent's conversation agentSessionID, as one resumed does; false while the app does not follow sessions, when what it knows may be stale.

func (*Ledger) Get

func (l *Ledger) Get(ctx context.Context, id string) (Record, error)

Get returns one recorded session, or ErrNotFound.

func (*Ledger) Running

func (l *Ledger) Running(ctx context.Context, dir string) ([]Session, error)

Running returns the sessions that have not ended running in the folder dir, whichever item each was started on, newest first, or none while the app does not follow sessions. Folders are compared with their symbolic links resolved.

func (*Ledger) Start

func (l *Ledger) Start(ctx context.Context, r Record) error

Start records a session a launch just started, tells the window, and wakes the Watcher, so it follows the session at once.

func (*Ledger) Waiting

func (l *Ledger) Waiting(ctx context.Context) ([]Session, error)

Waiting returns the running sessions waiting for the user, the longest waiting first, or none while the app does not follow sessions.

type Observation

type Observation struct {
	// ID is the app's ID of the session observed.
	ID string

	// AgentSessionID is the agent's own ID, once found.
	AgentSessionID string

	// State is what the session is doing, and Detail says more, or is "".
	State  State
	Detail string

	// PID is the agent's process, once found.
	PID int

	// LastMessage is what the agent last said.
	LastMessage string

	// Seen reports that the agent itself listed the session as running, rather than its
	// process or its folder suggesting so.
	Seen bool

	// Relinked reports that the session's own process moved on to the conversation
	// AgentSessionID, as Claude Code's /clear starts a new one, so the session follows it
	// in place of the one it was linked to.
	Relinked bool
}

Observation is what an Observer saw of one session. A zero field keeps what is stored.

type Observer

type Observer interface {
	// Observe reports what each of live, the agent's sessions that have not ended, is
	// doing as of now, with an observation for every one it has news of. The Watcher
	// calls it about once a Tick while any runs; the observer decides how often it asks
	// the agent, and answers from what it learned last in between. It never fails: an
	// agent it cannot ask makes the sessions StateUnknown, or StateEnded once their
	// process is gone.
	Observe(ctx context.Context, now time.Time, live []Record) []Observation

	// Close releases what the observer keeps between calls, such as a connection. The
	// next Observe starts again.
	Close()
}

Observer reports what one agent's sessions are doing, through the agent's own supported interface.

type Record

type Record struct {
	// ID is the app's own ID, AgentSessionID the agent's, or "", and ResumedFrom the ID
	// of the session this one resumed, or "".
	ID             string
	AgentSessionID string
	ResumedFrom    string

	// Agent, Profile, and ConfigDir are what it runs with: ConfigDir is the profile's
	// config directory, or "" for the agent's default.
	Agent     agent.ID
	Profile   string
	ConfigDir string

	// Prompt is the nickname of the prompt it was started with, and PromptHead the start
	// of the prompt.
	Prompt     string
	PromptHead string

	// Terminal is the terminal it runs in.
	Terminal string

	// ItemID, Owner, Name, Kind, Number, Title, and URL are the item.
	ItemID int64
	Owner  string
	Name   string
	Kind   item.Kind
	Number int
	Title  string
	URL    string

	// Dir is the absolute folder it runs in; ClonePath and Worktree say whose worktree
	// that is, when it is one.
	Dir       string
	ClonePath string
	Worktree  string

	// WorktreeAction is what the launch did to that worktree, Permission summarizes the
	// permissions it started with, and Notice says what the launch worked around; each is
	// "" when there is nothing to say or it was recorded before they were kept.
	WorktreeAction WorktreeAction
	Permission     string
	Notice         string

	// PID is the agent's process, or 0 while unknown.
	PID int

	// State, Detail, and LastMessage are what it last reported.
	State       State
	Detail      string
	LastMessage string

	// LaunchedAt is when it was launched; LinkedAt when its agent's ID was found, StateAt
	// when it came to its state, and EndedAt when it ended, each zero when not yet.
	LaunchedAt time.Time
	LinkedAt   time.Time
	StateAt    time.Time
	EndedAt    time.Time
}

Record is one session as the ledger stores it.

func (Record) Repo

func (r Record) Repo() string

Repo is the item's repository as "owner/name".

func (Record) Session

func (r Record) Session(home string) Session

Session is the record as the window shows it, with home shown as ~.

type Rereader

type Rereader interface{ Reread(itemID int64) }

Rereader hears the item a session worked on once the session stops working, so the item is read again from GitHub: the agent may have reviewed, commented, or pushed. Reread must not block. The inbox implements it, through core.

type Revealer

type Revealer interface {
	Reveal(ctx context.Context, path string) error
}

Revealer shows a file or a folder in Finder. Core adapts open -R, on macOS only.

type Service

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

Service is the sessions as the window binds them.

func NewService

func NewService(cfg Config) *Service

NewService returns the Service over cfg.

func (*Service) Focus

func (s *Service) Focus(ctx context.Context, id string) error

Focus brings forward the terminal tab a running session is in.

func (*Service) Forget

func (s *Service) Forget(ctx context.Context, id string) error

Forget forgets a session that has ended, on the user's click, so it leaves the card and the panel, and tells the window. A session already forgotten counts as done, and one still running is refused and kept.

func (*Service) LastWords

func (s *Service) LastWords(ctx context.Context, id string) (Words, error)

LastWords returns what the session with id last said, in full, read from the agent's own files, so the review sheet can show a whole verdict where a card shows its start. When the agent's files can't be read, it returns the start the ledger keeps, marked Partial; a session that said nothing has empty Words.

func (*Service) List

func (s *Service) List(ctx context.Context) (Snapshot, error)

List returns every session still running and the others launched in the last week, newest first, and whether the app follows sessions.

func (*Service) ShowFolder

func (s *Service) ShowFolder(ctx context.Context, id string) error

ShowFolder shows the folder a session runs in, its worktree or the clone, in Finder, whether or not the session still runs.

type Session

type Session struct {
	// ID is the app's own ID of the session.
	ID string `json:"id"`

	// AgentSessionID is the agent's own ID of it, or "" until the agent reports it.
	AgentSessionID string `json:"agentSessionId"`

	// ResumedFrom is the ID of the session this one resumed, or "".
	ResumedFrom string `json:"resumedFrom"`

	// Agent is the agent, with the profile it ran with, and the nickname of the prompt
	// it was started with, or "" for a session resumed.
	Agent   agent.ID `json:"agent"`
	Profile string   `json:"profile"`
	Prompt  string   `json:"prompt"`

	// Terminal is the terminal it runs in.
	Terminal string `json:"terminal"`

	// ItemID is the item's local ID, Repo is "owner/name", and Kind, Number, Title, and
	// URL are the item.
	ItemID int64     `json:"itemId"`
	Repo   string    `json:"repo"`
	Kind   item.Kind `json:"kind"`
	Number int       `json:"number"`
	Title  string    `json:"title"`
	URL    string    `json:"url"`

	// Dir is the folder it runs in, with ~ for home, and Worktree the item's worktree
	// there, or "" when it runs in the clone.
	Dir      string `json:"dir"`
	Worktree string `json:"worktree"`

	// WorktreeAction is what its launch did to that worktree, or "" in the clone or when
	// not known.
	WorktreeAction WorktreeAction `json:"worktreeAction"`

	// Permission summarizes the permissions it started with, such as "full access", and
	// Notice says what its launch worked around; each is "" when not known.
	Permission string `json:"permission"`
	Notice     string `json:"notice"`

	// State is what it is doing, Detail says more where the agent did, and StateAt is
	// when it came to that state, as RFC 3339.
	State   State  `json:"state"`
	Detail  string `json:"detail"`
	StateAt string `json:"stateAt"`

	// LastMessage is the start of what the agent last said, or "".
	LastMessage string `json:"lastMessage"`

	// LaunchedAt is when it was launched, and EndedAt when it ended, or "", as RFC 3339.
	LaunchedAt string `json:"launchedAt"`
	EndedAt    string `json:"endedAt"`

	// CanFocus reports a session whose terminal can be shown: it runs, and its process
	// is known. CanResume reports one that can be resumed: it ended, and the agent named
	// its conversation.
	CanFocus  bool `json:"canFocus"`
	CanResume bool `json:"canResume"`
}

Session is one session as the window shows it. Every field is a plain value.

type Snapshot

type Snapshot struct {
	// Following reports whether the app follows sessions; the window shows none while
	// it does not.
	Following bool `json:"following"`

	Sessions []Session `json:"sessions"`
}

Snapshot is the sessions the window shows: every one still running, and the others launched in the last week, newest first.

type State

type State string

State is what a session is doing, as its agent last reported it.

const (
	// StateStarting is a session launched whose agent has not reported it yet.
	StateStarting State = "starting"

	// StateWorking is an agent working on its turn.
	StateWorking State = "working"

	// StateNeedsApproval is an agent waiting for the user to allow an action.
	StateNeedsApproval State = "needs_approval"

	// StateNeedsInput is an agent waiting for the user to answer it.
	StateNeedsInput State = "needs_input"

	// StateIdle is an agent that finished its turn and waits for the next message.
	StateIdle State = "idle"

	// StateEnded is a session whose agent has quit. It is the only state that ends.
	StateEnded State = "ended"

	// StateFailed is an agent that reported an error it could not get past.
	StateFailed State = "failed"

	// StateUnknown is a session still running whose agent could not be asked how it is.
	StateUnknown State = "unknown"
)

The states of a session.

func States

func States() []State

States returns every state.

func (State) Live

func (s State) Live() bool

Live reports a session that has not ended.

func (State) NeedsYou

func (s State) NeedsYou() bool

NeedsYou reports a session waiting for the user.

func (State) Phrase

func (s State) Phrase() string

Phrase says what a session in the state is doing, after the agent's name: "Claude needs approval", "Codex is working".

func (State) Valid

func (s State) Valid() bool

Valid reports whether s is one of States.

type Store

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

Store reads and writes the ledger.

func NewStore

func NewStore(db *sql.DB) *Store

NewStore returns a Store over the pool db.

func (*Store) Apply

func (s *Store) Apply(ctx context.Context, now time.Time, observed []Observation) ([]Change, error)

Apply stores what was observed at now, in one transaction, and returns the sessions it changed. An ended session is left as it ended, and an observation of a session the ledger no longer holds is dropped.

func (*Store) ConversationLive

func (s *Store) ConversationLive(ctx context.Context, agentSessionID string) (bool, error)

ConversationLive reports whether a session that has not ended carries on the agent's conversation agentSessionID. It is false for "".

func (*Store) EndedSince

func (s *Store) EndedSince(ctx context.Context, since time.Time) ([]Record, error)

EndedSince returns the sessions the agent named that ended since a time, the last to end first.

func (*Store) Forget

func (s *Store) Forget(ctx context.Context, id string) error

Forget forgets one session that has ended. A session the ledger does not hold is ErrNotFound, and one that has not ended is ErrLive and kept.

func (*Store) Get

func (s *Store) Get(ctx context.Context, id string) (Record, error)

Get returns one session, or ErrNotFound.

func (*Store) Insert

func (s *Store) Insert(ctx context.Context, r Record) error

Insert records a session just launched. A session the agent already named is linked at once.

func (*Store) InsertUnlessLive

func (s *Store) InsertUnlessLive(ctx context.Context, r Record) (bool, error)

InsertUnlessLive records r, as Insert does, unless a session that has not ended already carries on r's conversation, in one transaction, so two writers never both follow it. It reports whether it recorded r.

func (*Store) Live

func (s *Store) Live(ctx context.Context) ([]Record, error)

Live returns every session that has not ended, oldest first.

func (*Store) Prune

func (s *Store) Prune(ctx context.Context, now time.Time) (int64, error)

Prune forgets, as of now, the sessions that ended more than KeepEnded ago, and each item's ended sessions past its newest KeepPerItem. It returns how many it forgot.

func (*Store) Recent

func (s *Store) Recent(ctx context.Context, since time.Time) ([]Record, error)

Recent returns every session that has not ended, and those launched since, newest first.

type Switch

type Switch interface {
	FollowSessions(ctx context.Context) (bool, error)
}

Switch reads whether the user follows sessions. The settings service implements it.

type Watcher

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

Watcher reconciles what the agents report into the ledger: a desktop.Worker that runs while the app is open. It observes only while some session has not ended, reconciles every one when it starts, and wakes at once when a launch records a new one.

func NewWatcher

func NewWatcher(cfg WatcherConfig) *Watcher

NewWatcher returns a Watcher over cfg that has not started.

func (*Watcher) Reconcile

func (w *Watcher) Reconcile(ctx context.Context) time.Duration

Reconcile asks the observers about every session that has not ended, stores what changed, tells the window, and hands the AttentionSink the sessions that need the user. It returns how long to wait before the next, or 0 to wait to be woken.

func (*Watcher) Run

func (w *Watcher) Run(ctx context.Context)

Run reconciles until ctx ends: at once, then once a Tick while a session runs, or once woken while none does. It closes the observers before it returns.

func (*Watcher) Wake

func (w *Watcher) Wake()

Wake asks the Watcher to reconcile now, as a launch does once it records a session. It never waits.

type WatcherConfig

type WatcherConfig struct {
	Store *Store

	// Observers holds each agent's Observer. An agent without one has its sessions left
	// as they are.
	Observers map[agent.ID]Observer

	// Switch is the user's master switch; without it, sessions are always followed.
	Switch Switch

	// Optional: the moments a session needs the user are handed to Attention.
	Attention AttentionSink

	// Optional: the item of a session that stops working is handed to Rereader.
	Rereader Rereader

	// Events hears an event.SessionsUpdated whenever a session changes.
	Events event.Sink

	// Clock stamps every change; it defaults to the system clock.
	Clock clock.Clock

	// Home shows home as ~ in the sessions the AttentionSink hears of.
	Home string

	Logger *slog.Logger

	// Tick and Debounce default to DefaultTick and DefaultDebounce.
	Tick     time.Duration
	Debounce time.Duration

	// ReviveTick and ReviveWindow default to the ReviveTick and ReviveWindow constants.
	ReviveTick   time.Duration
	ReviveWindow time.Duration

	// NewID mints the ID of a session resumed outside the app; it defaults to a random
	// UUID.
	NewID func() string
}

WatcherConfig holds a Watcher's dependencies. Store is required.

type Words

type Words struct {
	// Text is the message, as the agent wrote it, as markdown.
	Text string `json:"text"`

	// Partial reports that Text is not the whole message: it was cut to MaxWordsRunes, or
	// it is the start the ledger keeps, because the agent's own files could not be read.
	Partial bool `json:"partial"`
}

Words is what an agent session last said, read in full on demand.

type WordsReader

type WordsReader interface {
	LastWords(ctx context.Context, r Record) (string, error)
}

WordsReader reads the whole last message of one agent's session from the agent's own files on this Mac. It never reaches the network. Each agent's observer package provides one.

type WorktreeAction

type WorktreeAction string

WorktreeAction is what a session's launch did to its item's worktree.

const (
	// WorktreeNone is a session in the clone, or one recorded before the action was kept.
	WorktreeNone WorktreeAction = ""

	// WorktreeResume reused the item's worktree.
	WorktreeResume WorktreeAction = "resume"

	// WorktreeAdopt took over a worktree found on the item's branch somewhere else.
	WorktreeAdopt WorktreeAction = "adopt"

	// WorktreeAttach made a worktree again on the item's branch left from an earlier one.
	WorktreeAttach WorktreeAction = "attach"

	// WorktreeCreate made a new worktree.
	WorktreeCreate WorktreeAction = "create"
)

What a launch did to give its item a worktree, as the launcher names it.

func (WorktreeAction) Valid

func (a WorktreeAction) Valid() bool

Valid reports whether a is one of the actions, WorktreeNone included.

Directories

Path Synopsis
internal
observe
claude
Package claude observes Claude Code sessions through `claude agents --json`, which Claude Code documents as the supported way to read session state from outside it, and reads a session's last message from the transcript it keeps.
Package claude observes Claude Code sessions through `claude agents --json`, which Claude Code documents as the supported way to read session state from outside it, and reads a session's last message from the transcript it keeps.
codex
Package codex observes OpenAI Codex sessions through the local app-server daemon's JSON-RPC protocol, the one Codex's own IDE and desktop clients use, reached through `codex app-server proxy`.
Package codex observes OpenAI Codex sessions through the local app-server daemon's JSON-RPC protocol, the one Codex's own IDE and desktop clients use, reached through `codex app-server proxy`.

Jump to

Keyboard shortcuts

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