webui

package
v1.7.20 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 43 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 webui serves ccl conversations over HTTP and Server-Sent Events.

A conversation is a series of ccl-launched Claude Code processes that share one Claude session id and are resumed with --resume. Everything about the conversation (its provider, model, effort, history) lives under ~/.ccl/serve/sessions; the user's ~/.ccl/config.yaml is only read.

Index

Constants

View Source
const (
	// MaxReadBytes is the largest file returned as text for viewing or editing.
	MaxReadBytes = 2 << 20
	// MaxWriteBytes bounds a file saved from the editor.
	MaxWriteBytes = 5 << 20
)
View Source
const (
	EventPermission         = "permission"
	EventPermissionResolved = "permission_resolved"
)
View Source
const (
	TokenHeader = "Authorization"
	// PageTokenHeader is what the page sends: it leaves Authorization to a
	// proxy's Basic auth in front of ccl serve. A request that carries it is
	// judged by it alone.
	PageTokenHeader = "X-CCL-Token"
	// TokenQuery is accepted only by the read-only stream and events endpoints:
	// EventSource cannot set a header.
	TokenQuery = "token"
)

TokenHeader, PageTokenHeader and TokenQuery are the ways a client presents its token.

View Source
const (
	EventInit       = "init"
	EventToken      = "token"
	EventThinking   = "thinking"
	EventContext    = "context"
	EventToolUse    = "tool_use"
	EventToolResult = "tool_result"
	EventResult     = "result"
	EventError      = "error"
	EventQueued     = "queued"
	EventUser       = "user"
	EventStatus     = "status"
	EventTask       = "task"
)

Event types pushed to the browser and persisted in events.jsonl.

View Source
const (
	// MaxImageBytes is the largest image sent inline; the Messages API refuses
	// bigger ones. A larger image is still attached, by path.
	MaxImageBytes = 5 << 20
	// MaxUploadBytes bounds one attached file.
	MaxUploadBytes = 30 << 20
)
View Source
const SummaryLimit = 200

SummaryLimit is the rune count of a tool call's one-line summary.

View Source
const (
	// TitleLimit is the rune count of the title derived from the first message.
	TitleLimit = 40
)
View Source
const (
	// ToolInputStringLimit bounds each string in a forwarded tool input, such
	// as the content of a written file.
	ToolInputStringLimit = 20000
)
View Source
const ToolOutputLineLimit = 2000

ToolOutputLineLimit bounds how many lines of a tool result reach the browser.

Variables

View Source
var EffortLevels = []string{"low", "medium", "high", "xhigh", "max"}

EffortLevels are the values Claude Code's --effort accepts.

View Source
var ErrBusy = errors.New("a turn is already running")

ErrBusy reports a turn already running for the session.

View Source
var ErrClosing = errors.New("ccl serve is shutting down")

ErrClosing refuses a turn while the server shuts down.

View Source
var ErrNotFound = errors.New("session not found")

ErrNotFound reports a conversation that does not exist on disk.

View Source
var ErrWorkspaceNotServed = errors.New("this workspace is not served by ccl serve; add its folder again or start ccl serve with --workspace covering it")

ErrWorkspaceNotServed reports a conversation or request for a directory this server does not offer (any more).

View Source
var ErrWorkspacesLocked = errors.New("ccl serve was started with --lock-workspaces; folders cannot be added from the page")

ErrWorkspacesLocked refuses adding a folder under --lock-workspaces.

View Source
var (
	// ErrWorktreeMissing refuses a turn of a conversation whose worktree was
	// removed outside ccl serve.
	ErrWorktreeMissing = errors.New("this conversation's git worktree no longer exists")
)
View Source
var OAuthProviders = []string{"gpt", "gemini", "grok", "qoder", "kimi", "kiro", "workbuddy", "workbuddycn", "autoclaw", "zed", "cursor"}

OAuthProviders are the names `ccl oauth` accepts.

View Source
var PermissionModes = []string{"default", "acceptEdits", "plan", "bypassPermissions"}

PermissionModes are the --permission-mode values a conversation can use.

Functions

func DefaultLauncher

func DefaultLauncher(ctx context.Context, spec LaunchSpec) (*exec.Cmd, func(), error)

DefaultLauncher prepares Claude Code exactly as a ccl terminal session would, but with the provider taken from the conversation rather than the active selection. It never writes ~/.ccl/config.yaml.

func DefaultRoot

func DefaultRoot() (string, error)

DefaultRoot is where ccl serve keeps conversations.

func DefaultSocketPath added in v1.7.1

func DefaultSocketPath() (string, error)

DefaultSocketPath is where `ccl serve --socket` listens when it is given no path: next to the conversations, in a directory only this user can open.

func ListenUnix added in v1.7.1

func ListenUnix(path string) (net.Listener, error)

ListenUnix listens on a Unix socket at path that only this user can connect to. A socket left behind by a server that died is replaced; one another server still answers on is refused, as is any other file.

func NormalizeBasePath added in v1.7.2

func NormalizeBasePath(value string) (string, error)

NormalizeBasePath returns the URL prefix ccl serve is mounted under: "" for the root, otherwise the path without a trailing slash ("/chat/" is "/chat"). Only plain, unencoded segments are accepted, so a proxy, ServeMux and the browser cannot read the same prefix differently.

func TitleFrom

func TitleFrom(text string) string

TitleFrom derives a conversation title from its first user message.

Types

type ActiveView

type ActiveView struct {
	Normal string `json:"normal"`
	ACP    string `json:"acp"`
}

ActiveView is the persisted selection pair.

type Attachment

type Attachment struct {
	// ID is the stored file name: a random prefix and the sanitized original
	// name, so the name needs no separate record.
	ID   string `json:"id"`
	Name string `json:"name"`
	Type string `json:"type"`
	Size int64  `json:"size"`
	// Image marks a file sent to the model as an image block. Other files are
	// handed to Claude Code by path.
	Image bool `json:"image"`
}

Attachment is a file the user added to a message. It lives in the conversation's uploads directory, so deleting the conversation deletes it.

type ClaudeSession

type ClaudeSession struct {
	ID      string    `json:"id"`
	Title   string    `json:"title"`
	Updated time.Time `json:"updated"`
	Size    int64     `json:"size"`
	Prompts int       `json:"prompts"`
	// WebSession is the conversation that already resumes it, if any.
	WebSession string `json:"webSession,omitempty"`
}

ClaudeSession is one native transcript.

type CloudRemote

type CloudRemote struct {
	Alias       string `json:"alias"`
	Provider    string `json:"provider"`
	Primary     bool   `json:"primary"`
	Mirror      bool   `json:"mirror"`
	SignedIn    bool   `json:"signedIn"`
	AccountHint string `json:"accountHint,omitempty"`
	// State is cloudsync's: up to date, local changes pending, …
	State          string    `json:"state,omitempty"`
	LocalHash      string    `json:"localHash,omitempty"`
	RemoteTag      string    `json:"remoteTag,omitempty"`
	RemoteDeviceID string    `json:"remoteDevice,omitempty"`
	RemoteCreated  time.Time `json:"remoteCreated,omitempty"`
	DeviceID       string    `json:"device,omitempty"`
	LastOperation  string    `json:"lastOperation,omitempty"`
	LastSyncAt     time.Time `json:"lastSyncAt,omitempty"`
	Error          string    `json:"error,omitempty"`
}

CloudRemote is one configured remote with its status, as the page sees it.

type Config

type Config struct {
	// Token authenticates /api requests. It may be empty only when the server
	// listens on a loopback address and RequireToken is false.
	Token string
	// RequireToken makes an empty Token a startup error. ccl serve sets it when
	// the bind address is reachable from outside the machine.
	RequireToken bool
	// Workspace, Workspaces and WorkspaceRoots are the directories
	// conversations may run in: each named directory, and each directory
	// directly inside a root. The page may add folders unless LockWorkspaces.
	// With none, the current directory is the workspace.
	Workspace      string
	Workspaces     []string
	WorkspaceRoots []string
	// MaxConcurrency bounds simultaneous Claude Code processes. <=0 uses 3.
	MaxConcurrency int
	// DefaultProvider/DefaultModel/DefaultEffort seed new conversations.
	DefaultProvider string
	DefaultModel    string
	DefaultEffort   string
	// StoreRoot overrides the on-disk conversation directory (tests).
	StoreRoot string
	// Version is reported by /health.
	Version string
	// Launch overrides the process launcher (tests).
	Launch LaunchFunc
	// SelfBinary is the ccl executable; subscription logins run `ccl oauth`.
	SelfBinary string
	// LatestVersion names the newest ccl release, for the update notice.
	LatestVersion func() (string, error)
	// Shell turns on the web terminal (ccl serve --shell).
	Shell bool
	// LockWorkspaces keeps the page from adding folders (--lock-workspaces).
	LockWorkspaces bool
	// BasePath mounts the page and the API under a URL prefix such as /chat
	// (--base-path); empty serves them at the root.
	BasePath string
}

Config configures a web UI server.

type ConfigView

type ConfigView struct {
	Active    ActiveView              `json:"active"`
	Lang      string                  `json:"lang"`
	Bypass    bool                    `json:"bypassMode"`
	SignOn    bool                    `json:"signOn"`
	LogLevel  string                  `json:"logLevel"`
	Default   DefaultView             `json:"default"`
	Providers map[string]ProviderView `json:"providers"`
	Order     []string                `json:"order"`
}

ConfigView is the JSON shape of ccl's own configuration.

type ContextPayload

type ContextPayload struct {
	Tokens int64 `json:"tokens"`
}

ContextPayload is how many tokens the latest model call read: the size of the conversation's context at that point.

type DefaultView

type DefaultView struct {
	Name      string `json:"name"`
	IsDefault bool   `json:"isDefault"`
	Active    bool   `json:"active"`
	Provider  string `json:"provider,omitempty"`
}

DefaultView describes the reserved `default` selector. It is never a key of the providers map, cannot be edited, and always exists.

type DirEntry

type DirEntry struct {
	Name string `json:"name"`
	Path string `json:"path"`
	// Repo marks a git work tree.
	Repo bool `json:"repo,omitempty"`
}

DirEntry is one folder in the folder picker.

type ErrorPayload

type ErrorPayload struct {
	Message string `json:"message"`
}

ErrorPayload reports a failure that ended the turn early.

type Event

type Event struct {
	Seq     int64           `json:"seq"`
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload,omitempty"`
	TS      int64           `json:"ts"`
}

Event is one persisted entry of a conversation's history. Seq is strictly increasing within a conversation, so a client reconnecting with ?since= can ask for exactly what it missed.

type FileContent

type FileContent struct {
	Path     string    `json:"path"`
	Size     int64     `json:"size"`
	Modified time.Time `json:"modified"`
	// Hash is the content's sha256; a save names the hash it started from.
	Hash   string `json:"hash"`
	Type   string `json:"type"`
	Binary bool   `json:"binary"`
	// Image marks a file the page can show through the raw endpoint.
	Image   bool   `json:"image"`
	TooBig  bool   `json:"tooBig,omitempty"`
	Content string `json:"content,omitempty"`
}

FileContent is a file as the editor sees it.

type FileEntry

type FileEntry struct {
	Name     string    `json:"name"`
	Path     string    `json:"path"`
	Type     string    `json:"type"` // file, dir or symlink
	Size     int64     `json:"size"`
	Modified time.Time `json:"modified"`
}

FileEntry is one directory entry.

type GitCommit

type GitCommit struct {
	Hash    string `json:"hash"`
	Short   string `json:"short"`
	Author  string `json:"author"`
	Date    string `json:"date"`
	Subject string `json:"subject"`
}

GitCommit is one history entry.

type GitFile

type GitFile struct {
	Path       string `json:"path"`
	OrigPath   string `json:"origPath,omitempty"`
	Index      string `json:"index"`
	Worktree   string `json:"worktree"`
	Untracked  bool   `json:"untracked,omitempty"`
	Conflicted bool   `json:"conflicted,omitempty"`
	Added      int    `json:"added"`
	Deleted    int    `json:"deleted"`
}

GitFile is one changed path. Index and Worktree are porcelain status letters ('.' for unchanged).

type GitStatus

type GitStatus struct {
	Repo     bool      `json:"repo"`
	Branch   string    `json:"branch,omitempty"`
	Detached bool      `json:"detached,omitempty"`
	Upstream string    `json:"upstream,omitempty"`
	Ahead    int       `json:"ahead"`
	Behind   int       `json:"behind"`
	Files    []GitFile `json:"files"`
	Added    int       `json:"added"`
	Deleted  int       `json:"deleted"`
	Error    string    `json:"error,omitempty"`
}

GitStatus is the working tree as the changes panel shows it.

type InitPayload

type InitPayload struct {
	SessionID string `json:"sessionId"`
	Model     string `json:"model,omitempty"`
	Cwd       string `json:"cwd,omitempty"`
	// SlashCommands are the commands a prompt can start with.
	SlashCommands []string `json:"slashCommands,omitempty"`
	// MCPServers are the connectors Claude Code loaded, with their state.
	MCPServers []MCPServer `json:"mcpServers,omitempty"`
}

InitPayload reports the Claude session a turn runs in and what it offers.

type LaunchAttachment

type LaunchAttachment struct {
	Path      string
	Name      string
	MediaType string
	// Image sends the file as an image block; otherwise Claude Code gets its path.
	Image bool
}

LaunchAttachment is one attached file as the process sees it.

type LaunchFunc

type LaunchFunc func(ctx context.Context, spec LaunchSpec) (*exec.Cmd, func(), error)

LaunchFunc prepares and starts the Claude Code process for one turn. Stdout and stderr are wired by the caller through cmd. It must not touch the caller's stdio. The returned cleanup runs when the process has exited.

type LaunchSpec

type LaunchSpec struct {
	Provider string
	// Subscription is set for an OAuth provider; its result says so.
	Subscription bool
	// Model is a slot alias (opus, sonnet, …) or a full model id.
	Model     string
	Effort    string
	Workspace string
	// Resume is the Claude session to continue; empty starts a new one.
	Resume string
	Prompt string
	// PermissionMode is Claude Code's --permission-mode. Every mode but
	// bypassPermissions asks the page before tools that need approval.
	PermissionMode string
	// Attachments are files sent with the prompt. A turn with attachments
	// writes its message to stdin as stream-json, which can carry images.
	Attachments []LaunchAttachment
	// contains filtered or unexported fields
}

LaunchSpec is everything one conversation turn needs.

type MCPEntry

type MCPEntry struct {
	Name   string   `json:"name"`
	Scope  string   `json:"scope"` // user, project or local
	Type   string   `json:"type"`
	Target string   `json:"target"`
	Env    []string `json:"env,omitempty"` // names only
}

MCPEntry is one configured MCP server. Environment and header values are never shown: they usually carry keys.

type MCPServer

type MCPServer struct {
	Name   string `json:"name"`
	Status string `json:"status"`
}

MCPServer is one MCP server as Claude Code reported it.

type Meta

type Meta struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	Provider string `json:"provider"`
	Model    string `json:"model"`
	Effort   string `json:"effort"`
	// PermissionMode is the --permission-mode of the next turn; empty uses
	// the server default (bypassPermissions when ccl's bypass mode is on).
	PermissionMode string `json:"permissionMode,omitempty"`
	// ClaudeSessionID is the id Claude Code reported in its first init event.
	// A turn resumes it instead of starting a new conversation.
	ClaudeSessionID string `json:"claudeSessionId,omitempty"`
	Workspace       string `json:"workspace"`
	// Worktree is set when the conversation runs on a branch of its own in
	// a git worktree of Workspace (worktree.go).
	Worktree *SessionWorktree `json:"worktree,omitempty"`
	// Pinned and Archived only change where the page lists the conversation.
	Pinned   bool `json:"pinned,omitempty"`
	Archived bool `json:"archived,omitempty"`
	// ShareToken opens the conversation read-only at /share/<token>.
	ShareToken string    `json:"shareToken,omitempty"`
	CreatedAt  time.Time `json:"createdAt"`
	UpdatedAt  time.Time `json:"updatedAt"`
	// Turns counts the messages sent, so a conversation list needs no history.
	Turns int `json:"turns"`
	// Usage is the conversation total: the sum of every turn's TurnUsage.
	Usage Usage `json:"usage"`
	// ClaudeCostUSD is the running cost Claude Code last reported for the
	// session. The next turn's cost is the difference from it.
	ClaudeCostUSD float64 `json:"claudeCostUsd,omitempty"`
}

Meta is the persisted description of one conversation.

type ModelChoice

type ModelChoice struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

ModelChoice is one entry of a conversation's model picker. Value is passed to claude --model as is; Label is what the browser shows.

type PermissionDecision

type PermissionDecision struct {
	RequestID string `json:"requestId"`
	Behavior  string `json:"behavior"`
	// Message tells Claude why a call was refused.
	Message string `json:"message"`
	// Answers holds AskUserQuestion answers, question text → chosen label(s).
	Answers map[string]string `json:"answers"`
	// Remember applies Claude Code's suggested rules for the rest of the session.
	Remember bool `json:"remember"`
	// Mode switches the permission mode, as approving a plan does.
	Mode string `json:"mode"`
}

PermissionDecision is the user's answer.

type PermissionPayload

type PermissionPayload struct {
	RequestID string `json:"requestId"`
	ToolName  string `json:"toolName"`
	ToolUseID string `json:"toolUseId,omitempty"`
	// Title and Description are Claude Code's own wording, when it gives one.
	Title       string          `json:"title,omitempty"`
	Description string          `json:"description,omitempty"`
	Summary     string          `json:"summary,omitempty"`
	Reason      string          `json:"reason,omitempty"`
	BlockedPath string          `json:"blockedPath,omitempty"`
	Input       json.RawMessage `json:"input,omitempty"`
	// CanRemember says Claude Code offered rules that would stop asking.
	CanRemember bool `json:"canRemember,omitempty"`
	// contains filtered or unexported fields
}

PermissionPayload is one approval Claude Code asks for.

type PermissionResolvedPayload

type PermissionResolvedPayload struct {
	RequestID string `json:"requestId"`
	// Behavior is allow, deny or cancelled (Claude Code withdrew the request).
	Behavior string `json:"behavior"`
	Message  string `json:"message,omitempty"`
	Mode     string `json:"mode,omitempty"`
}

PermissionResolvedPayload closes a permission request.

type ProbeResult

type ProbeResult struct {
	OK      bool     `json:"ok"`
	Status  int      `json:"status,omitempty"`
	Models  []string `json:"models,omitempty"`
	Message string   `json:"message,omitempty"`
	Elapsed int64    `json:"elapsedMs"`
}

ProbeResult reports one connectivity check.

type ProjectDefaults

type ProjectDefaults struct {
	Provider       string `json:"provider,omitempty"`
	Model          string `json:"model,omitempty"`
	Effort         string `json:"effort,omitempty"`
	PermissionMode string `json:"permissionMode,omitempty"`
}

ProjectDefaults are what a new conversation in a project starts with when the request names none: provider, model, effort and permission mode.

type ProviderInfo

type ProviderInfo struct {
	Name        string            `json:"name"`
	IsDefault   bool              `json:"isDefault"`
	Slots       map[string]string `json:"slots"`
	EffortLevel string            `json:"effortLevel,omitempty"`
	Active      bool              `json:"active,omitempty"`
}

ProviderInfo is one selectable provider, as the browser sees it.

type ProviderInput

type ProviderInput struct {
	Name           *string            `json:"name"`
	Type           *string            `json:"type"`
	Endpoint       *string            `json:"endpoint"`
	APIKey         *string            `json:"apiKey"`
	OAuthProvider  *string            `json:"oauthProvider"`
	OpusModel      *string            `json:"opusModel"`
	SonnetModel    *string            `json:"sonnetModel"`
	HaikuModel     *string            `json:"haikuModel"`
	FableModel     *string            `json:"fableModel"`
	CustomModelID  *string            `json:"customModelId"`
	SubagentModel  *string            `json:"subagentModel"`
	EffortLevel    *string            `json:"effortLevel"`
	AnthropicAuth  *string            `json:"anthropicAuth"`
	Models         *string            `json:"models"`
	ModelOverrides *map[string]string `json:"modelOverrides"`
	FastMode       *bool              `json:"fastMode"`
	ContextPreset  *string            `json:"contextPreset"`
}

ProviderInput is the writable subset of a provider. Its fields are pointers so PATCH can distinguish "leave alone" (nil) from "clear" ("").

type ProviderView

type ProviderView struct {
	Name           string            `json:"name"`
	Type           string            `json:"type"`
	Endpoint       string            `json:"endpoint"`
	APIKey         string            `json:"apiKey"`
	HasKey         bool              `json:"hasKey"`
	OAuthProvider  string            `json:"oauthProvider,omitempty"`
	OpusModel      string            `json:"opusModel,omitempty"`
	SonnetModel    string            `json:"sonnetModel,omitempty"`
	HaikuModel     string            `json:"haikuModel,omitempty"`
	FableModel     string            `json:"fableModel,omitempty"`
	CustomModelID  string            `json:"customModelId,omitempty"`
	SubagentModel  string            `json:"subagentModel,omitempty"`
	EffortLevel    string            `json:"effortLevel,omitempty"`
	AnthropicAuth  string            `json:"anthropicAuth,omitempty"`
	Models         string            `json:"models,omitempty"`
	ModelOverrides map[string]string `json:"modelOverrides,omitempty"`
	FastMode       bool              `json:"fastMode,omitempty"`
	ContextPreset  string            `json:"contextPreset,omitempty"`
	// ContextWindow is the window a Balanced preset caps every slot to; zero
	// for Default, where a slot's [1m] marker decides.
	ContextWindow int  `json:"contextWindow,omitempty"`
	Active        bool `json:"active"`
	ACPActive     bool `json:"acpActive"`
	// ModelChoices is what a conversation on this provider can pick.
	ModelChoices []ModelChoice `json:"modelChoices"`
}

ProviderView is one provider with its credential masked.

type ResultPayload

type ResultPayload struct {
	// Usage is Claude Code's report as it stands. Its cost is the running total
	// of the Claude session, which a resumed turn continues, so it must not be
	// summed across turns; its token counts and duration are this turn's.
	Usage Usage `json:"usage"`
	// TurnUsage is what this turn alone spent. It is absent when Claude Code
	// reported nothing, such as a turn stopped before it finished.
	TurnUsage *Usage `json:"turnUsage,omitempty"`
	IsError   bool   `json:"isError"`
	// Cancelled marks a turn the user stopped; it is not a failure.
	Cancelled bool   `json:"cancelled,omitempty"`
	Message   string `json:"message,omitempty"`
	// Subscription marks a turn on a subscription (OAuth) provider: Claude
	// Code prices it from its own table, which is not what the user pays.
	Subscription bool `json:"subscription,omitempty"`
}

ResultPayload closes one turn.

type Runner

type Runner struct {
	// Prepare launches Claude Code. It is a field so tests can inject a fake.
	Prepare LaunchFunc
	// MaxConcurrency bounds how many runs execute at once across sessions.
	MaxConcurrency int
	// contains filtered or unexported fields
}

Runner executes turns for a session and serializes them.

func NewRunner

func NewRunner(maxConcurrency int) *Runner

NewRunner returns a runner using the real ccl launcher.

func (*Runner) Capabilities

func (r *Runner) Capabilities() InitPayload

Capabilities is the most recent init event any turn reported.

type Schedule

type Schedule struct {
	ID      string    `json:"id"`
	Session string    `json:"session"`
	At      time.Time `json:"at"`
	Text    string    `json:"text"`
}

Schedule is one message waiting for its time.

type Server

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

Server is the HTTP surface of ccl serve.

func New

func New(cfg Config) (*Server, error)

New creates a server. An empty token is an error: ccl serve never listens without authentication.

func (*Server) Close

func (s *Server) Close(ctx context.Context) error

Close stops what the server started: scheduled messages, subscription logins, terminals and turns in flight. A cancelled turn is still stored with its result, so Close waits for that until ctx ends.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the HTTP handler.

func (*Server) Publish

func (s *Server) Publish(id string)

Publish wakes the streams watching a session. Callers use it after appending events themselves; the turn runner publishes per event.

func (*Server) Store

func (s *Server) Store() *Store

Store exposes the conversation store (tests, tooling).

func (*Server) WorkspaceCount

func (s *Server) WorkspaceCount() int

WorkspaceCount is how many workspaces the server offers right now.

type Session

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

Session is one open conversation: its metadata and append-only history.

func (*Session) Append

func (s *Session) Append(kind string, payload any) (Event, error)

Append stores one event and returns it with its assigned seq.

func (*Session) AppendAt

func (s *Session) AppendAt(kind string, payload any, ts time.Time) (Event, error)

AppendAt stores an event that happened at ts (zero means now), such as one replayed from an imported transcript.

func (*Session) Attachment

func (s *Session) Attachment(id string) (Attachment, error)

Attachment describes a stored upload.

func (*Session) AttachmentPath

func (s *Session) AttachmentPath(id string) string

AttachmentPath is where Claude Code reads an attachment.

func (*Session) Events

func (s *Session) Events(since int64) ([]Event, error)

Events returns every stored event with Seq greater than since.

func (*Session) ID

func (s *Session) ID() string

ID is the conversation id.

func (*Session) LastSeq

func (s *Session) LastSeq() int64

LastSeq is the newest event seq, 0 for an empty conversation.

func (*Session) Meta

func (s *Session) Meta() Meta

Meta returns a copy of the conversation metadata.

func (*Session) RelabelMeta

func (s *Session) RelabelMeta(fn func(*Meta)) (Meta, error)

RelabelMeta changes how a conversation is listed (pinned, archived) without making it the most recently updated.

func (*Session) SaveUpload

func (s *Session) SaveUpload(name string, content io.Reader) (Attachment, error)

SaveUpload stores one uploaded file.

func (*Session) Touch

func (s *Session) Touch() error

Touch persists the metadata as it stands, refreshing UpdatedAt. It is called once per turn rather than per event.

func (*Session) UpdateMeta

func (s *Session) UpdateMeta(fn func(*Meta)) (Meta, error)

UpdateMeta applies fn to the metadata and persists it.

type SessionView

type SessionView struct {
	Meta
	Running bool `json:"running"`
}

SessionView is a conversation as the browser sees it. Running is known only to this process, so it is never stored in meta.json.

type SessionWorktree

type SessionWorktree struct {
	Name   string `json:"name"`
	Branch string `json:"branch"`
	// Base is the branch the project had checked out when the worktree was
	// made; empty when its HEAD was detached. BaseCommit is where it started.
	Base       string `json:"base,omitempty"`
	BaseCommit string `json:"baseCommit"`
}

SessionWorktree is the worktree a conversation runs in.

type SharedSession

type SharedSession struct {
	Title     string           `json:"title"`
	Provider  string           `json:"provider"`
	Model     string           `json:"model"`
	Workspace string           `json:"workspace"`
	CreatedAt time.Time        `json:"createdAt"`
	UpdatedAt time.Time        `json:"updatedAt"`
	Worktree  *SessionWorktree `json:"worktree,omitempty"`
	Events    []Event          `json:"events"`
	Diff      *WorktreeDiff    `json:"diff,omitempty"`
}

SharedSession is what a share link reveals.

type StatusPayload

type StatusPayload struct {
	State  string `json:"state"`
	Detail string `json:"detail,omitempty"`
}

StatusPayload reports a non-fatal state change (queued, still running).

type Store

type Store struct {

	// OnAppend is called after a session stores an event. The server uses it to
	// wake open SSE streams.
	OnAppend func(sessionID string)
	// contains filtered or unexported fields
}

Store is the on-disk conversation repository:

<root>/<id>/meta.json
<root>/<id>/events.jsonl

func NewStore

func NewStore(root string) (*Store, error)

NewStore creates root when needed and returns a store over it.

func (*Store) Create

func (s *Store) Create(meta Meta) (*Session, error)

Create writes a new conversation and returns it.

func (*Store) Delete

func (s *Store) Delete(id string) error

Delete removes a conversation and its history.

func (*Store) List

func (s *Store) List() ([]Meta, error)

List returns every conversation, most recently updated first.

func (*Store) Open

func (s *Store) Open(id string) (*Session, error)

Open returns the conversation with that id.

func (*Store) Root

func (s *Store) Root() string

Root is the directory holding every conversation.

type TaskPayload added in v1.7.4

type TaskPayload struct {
	// ID is the tool call that started the task.
	ID string `json:"id"`
	// Status is running, completed, failed or stopped.
	Status      string `json:"status"`
	Description string `json:"description,omitempty"`
	// Agent is the sub-agent type of an agent task.
	Agent string `json:"agent,omitempty"`
	// Summary is the task's latest progress line, or how it ended.
	Summary  string     `json:"summary,omitempty"`
	LastTool string     `json:"lastTool,omitempty"`
	Usage    *TaskUsage `json:"usage,omitempty"`
}

TaskPayload reports the state of a task a tool call started: a sub-agent (Agent / Task), which Claude Code always runs in the background, or a background shell. The call's tool_result only says it was launched; these events say when the work itself is running and how it ended.

type TaskUsage added in v1.7.4

type TaskUsage struct {
	Tokens     int64 `json:"tokens"`
	ToolUses   int64 `json:"toolUses"`
	DurationMs int64 `json:"durationMs"`
}

TaskUsage is what a task has spent so far.

type Timeline

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

Timeline is the per-session turn gate.

func NewTimeline

func NewTimeline() *Timeline

NewTimeline returns an empty turn gate.

func (*Timeline) CancelAll

func (t *Timeline) CancelAll() []<-chan struct{}

CancelAll stops every turn in flight and returns channels that close once each one is stored.

func (*Timeline) RequestCancel

func (t *Timeline) RequestCancel(id string) bool

RequestCancel stops the turn in flight for a session, if any.

func (*Timeline) Respond

func (t *Timeline) Respond(session *Session, decision PermissionDecision) error

Respond answers a permission request of the session's running turn.

func (*Timeline) Running

func (t *Timeline) Running(id string) bool

func (*Timeline) Settle

func (t *Timeline) Settle(id string, timeout time.Duration)

Running reports whether the session has a turn in flight. Settle waits up to timeout for a turn that already stored its result to exit, so a message sent right after the result is not refused as busy. A turn still working is not waited for.

func (*Timeline) Start

func (t *Timeline) Start(r *Runner, session *Session, spec LaunchSpec) (*TurnHandle, error)

Start runs one turn: it stores the user message, launches Claude Code, and stores every translated event. It returns ErrBusy when a turn already runs.

A turn that has to wait for a global slot returns at once and launches in the background; a launch failure is then reported in the history only.

func (*Timeline) Steer added in v1.7.9

func (t *Timeline) Steer(id string, spec LaunchSpec) error

Steer sends a message into the session's running turn. Claude Code reads it between the steps of the turn, or answers it in another turn of the same process whose result then ends this one. The message is stored when Claude Code echoes it, so the history shows it where the model read it. It returns errTurnEnded when no running turn can take it, and ErrBusy while the turn still waits for its slot.

type TokenPayload

type TokenPayload struct {
	Text string `json:"text"`
	// Subagent marks text produced by a sub-agent, which the UI indents.
	Subagent bool `json:"subagent,omitempty"`
	// Parent is the Task call a sub-agent's event belongs to.
	Parent string `json:"parent,omitempty"`
}

TokenPayload is one streamed fragment of assistant text (or, as a thinking event, of its reasoning).

type ToolResultPayload

type ToolResultPayload struct {
	ID       string `json:"id"`
	Name     string `json:"name,omitempty"`
	OK       bool   `json:"ok"`
	Output   string `json:"output"`
	Subagent bool   `json:"subagent,omitempty"`
	Parent   string `json:"parent,omitempty"`
}

ToolResultPayload reports the outcome of a tool call.

type ToolUsePayload

type ToolUsePayload struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Summary string `json:"summary"`
	// Description is the call's own one-line explanation (Bash and Task take
	// one), which the page shows in place of the raw command.
	Description string `json:"description,omitempty"`
	// Input is the call's arguments with credentials masked and long strings
	// cut (see toolInput): what the page needs for diffs, todo lists and plans.
	Input    json.RawMessage `json:"input,omitempty"`
	Subagent bool            `json:"subagent,omitempty"`
	Parent   string          `json:"parent,omitempty"`
}

ToolUsePayload reports a tool call the assistant started.

type TurnHandle

type TurnHandle struct {
	// Done closes when the process has exited and its events are stored.
	Done <-chan struct{}
	// Session is the session the turn appends to.
	Session *Session
	// Cancel asks the process to stop: SIGINT, then SIGKILL after 2s.
	Cancel func()
}

TurnHandle is what a started turn exposes.

type Usage

type Usage struct {
	InputTokens  int64   `json:"inputTokens"`
	OutputTokens int64   `json:"outputTokens"`
	CostUSD      float64 `json:"costUsd"`
	DurationMs   int64   `json:"durationMs"`
}

Usage is token, cost and time accounting, for one turn or a whole conversation.

type UserMemory

type UserMemory struct {
	Path string `json:"path"`
	// Hash is empty when the file does not exist yet.
	Hash    string `json:"hash"`
	Content string `json:"content"`
	TooBig  bool   `json:"tooBig,omitempty"`
}

UserMemory is the user's own CLAUDE.md, which Claude Code reads in every project.

type UserPayload

type UserPayload struct {
	Text        string       `json:"text"`
	Attachments []Attachment `json:"attachments,omitempty"`
	// Mirrored marks a prompt read from the transcript (mirror.go): typed in
	// a terminal or imported, not a turn the page runs.
	Mirrored bool `json:"mirrored,omitempty"`
	// Steered marks a message sent into a running turn (Timeline.Steer): it
	// continues that turn instead of starting one.
	Steered bool `json:"steered,omitempty"`
}

UserPayload is a message the user sent.

type Workspace

type Workspace struct {
	// ID is derived from the real path, so it is stable across restarts.
	ID   string `json:"id"`
	Name string `json:"name"`
	Path string `json:"path"`
	// Added marks a directory the page added; only those can be removed.
	Added bool `json:"added,omitempty"`
	// contains filtered or unexported fields
}

Workspace is one directory the server offers.

type WorktreeDiff

type WorktreeDiff struct {
	Base      string `json:"base"`
	Diff      string `json:"diff"`
	Truncated bool   `json:"truncated,omitempty"`
}

WorktreeDiff is a worktree's change against its base, uncommitted tracked changes included.

type WorktreeFile

type WorktreeFile struct {
	Path   string `json:"path"`
	Status string `json:"status"`
}

type WorktreeStatus

type WorktreeStatus struct {
	SessionWorktree
	Path   string `json:"path"`
	Exists bool   `json:"exists"`
	// Ahead and Behind count commits against the base (branch, else commit).
	Ahead  int `json:"ahead"`
	Behind int `json:"behind"`
	// Dirty counts uncommitted changes in the worktree.
	Dirty int `json:"dirty"`
	// Files are the paths the branch changed since the base.
	Files []WorktreeFile `json:"files"`
	// Current is the branch the project itself has checked out: a merge
	// goes there, so it must be Base.
	Current  string `json:"current,omitempty"`
	Remote   string `json:"remote,omitempty"`
	Upstream string `json:"upstream,omitempty"`
}

WorktreeStatus is a session worktree as the page shows it.

Jump to

Keyboard shortcuts

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