workbench

package
v0.186.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 24 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 workbench projects persisted jobs and relay sessions into the conversation-first WEB-11 model. It owns projection and dispatch only; job and sessionrelay remain authoritative for execution and replies.

Index

Constants

View Source
const (
	RefKindPrompt   = "prompt"
	RefKindDecision = "decision"
	// RefKindMessage: a message to a terminal session (ref = its session outbox id).
	RefKindMessage = "message"
)

RefKindPrompt / RefKindDecision are the attachment ref kinds a send records.

View Source
const (
	MaxReviewComments     = 50
	MaxReviewCommentRunes = 4000
)
View Source
const MaxLayoutBodyBytes = 64 * 1024

Variables

View Source
var (
	// ErrAttachmentForbidden: an attachment is unknown or belongs to another caller (the
	// two are indistinguishable to the caller, so ids do not leak).
	ErrAttachmentForbidden = errors.New("workbench: attachment not available to this caller")
	// ErrAttachmentSent: the attachment was already sent with another message, or expired.
	ErrAttachmentSent = errors.New("workbench: attachment already sent or expired")
	// ErrTooManyAttachments: more attachments than server.attachments.max_per_message.
	ErrTooManyAttachments = errors.New("workbench: too many attachments")
	// ErrAttachmentsUnsupported: the receiver takes no images (the reason follows).
	ErrAttachmentsUnsupported = errors.New("workbench: thread does not accept attachments")
	// ErrAttachmentDelivery: placing the images on the executing machine failed; nothing
	// was sent (design decision 6).
	ErrAttachmentDelivery = errors.New("workbench: attachment delivery failed")
)

Attachment errors; the HTTP layer maps them (403 / 409 / 400 / 502).

View Source
var (
	ErrInvalidThreadID = errors.New("workbench: invalid thread id")
	ErrUnknownThread   = errors.New("workbench: unknown thread")
	ErrNotResumable    = errors.New("workbench: thread is not resumable")
	ErrEmptyTurn       = errors.New("workbench: turn text is required")
	ErrUnavailable     = errors.New("workbench: service unavailable")
	ErrInvalidLayout   = errors.New("workbench: invalid layout")
	ErrLayoutTooLarge  = errors.New("workbench: layout body exceeds 64 KiB")
	ErrMissingDiffBase = errors.New("workbench: first turn has no git diff base")
	ErrDiffUnavailable = errors.New("workbench: thread diff unavailable")
	ErrDiffTimeout     = errors.New("workbench: thread diff timed out")
	ErrInvalidReview   = errors.New("workbench: invalid review")
)
View Source
var ErrRelayDelivery = errors.New("workbench: session message not delivered")

ErrRelayDelivery wraps a failed message to a terminal session (the outbox already holds the failed record); the HTTP layer answers it as 409 with a readable reason.

Functions

func JobThreadID

func JobThreadID(jobID, sessionID string) string

JobThreadID is the canonical job-event to workbench-thread mapping. A captured agent session groups every resume turn; a one-shot job stands alone.

func PromptRef added in v0.177.0

func PromptRef(jobID string, n int) string

PromptRef is the attachment ref of the prompt number n (1-based) of job id: the key the ACP history joins on (the n-th prompt event of the job's structured record).

func TerminalNeedsReview

func TerminalNeedsReview(status, agent string, hasChanges, seen bool) bool

TerminalNeedsReview is F16's single review predicate, shared by the workbench projection and Web Push dispatcher.

Types

type AttachMode added in v0.177.0

type AttachMode string

AttachMode is how the images of a message reach the receiver.

const (
	// AttachInline: ACP image content blocks (the session advertised promptCapabilities.image).
	AttachInline AttachMode = "inline"
	// AttachFile: the images are placed on the executing machine and the message names
	// their absolute paths; the agent opens them itself.
	AttachFile AttachMode = "file"
	// AttachArg: the images are placed on the executing machine and each absolute path rides
	// the ARGV of the job that carries the message (the agent's image_args template), so the
	// text stays clean — no `[附图 n]` line.
	AttachArg AttachMode = "arg"
	// AttachNone: the receiver cannot take images; Reason says why.
	AttachNone AttachMode = "none"
)

type AttachmentDeps added in v0.177.0

type AttachmentDeps struct {
	Store         AttachmentStore
	Files         AttachmentFiles
	Xfer          Placer
	Jobs          ImageJobs
	Config        func() *config.Config
	MaxPerMessage func() int
}

AttachmentDeps wires the send path; without Store/Files the service accepts no attachments and reports no capability bit.

type AttachmentFiles added in v0.177.0

type AttachmentFiles interface {
	Read(rec jobstore.Attachment) ([]byte, error)
	AbsPath(rec jobstore.Attachment) (string, error)
}

AttachmentFiles reads the stored originals (attachment.Service).

type AttachmentStore added in v0.177.0

type AttachmentStore interface {
	GetAttachment(id string) (jobstore.Attachment, bool, error)
	BindAttachment(id, threadID, refKind, refID string) error
	UnbindAttachment(id, threadID string) error
	ListAttachmentsByThread(threadID string) ([]jobstore.Attachment, error)
}

AttachmentStore is the slice of jobstore.Store the send path uses.

type AttentionAction

type AttentionAction string
const (
	ActionAnswer AttentionAction = "answer"
	ActionReview AttentionAction = "review"
	ActionReply  AttentionAction = "reply"
)

type AttentionItem

type AttentionItem struct {
	ThreadID      string          `json:"thread_id"`
	ProjectKey    string          `json:"project_key"`
	Title         string          `json:"title"`
	Status        Status          `json:"status"`
	Action        AttentionAction `json:"action"`
	WaitingSince  int64           `json:"waiting_since"`
	JobID         string          `json:"job_id,omitempty"`
	InteractionID string          `json:"interaction_id,omitempty"`
	SessionID     string          `json:"session_id,omitempty"`
	DecisionID    string          `json:"decision_id,omitempty"`
}

type Counts

type Counts struct {
	Total         int `json:"total"`
	Blocked       int `json:"blocked"`
	Working       int `json:"working"`
	Review        int `json:"review"`
	Done          int `json:"done"`
	Idle          int `json:"idle"`
	OrphanBlocked int `json:"orphan_blocked"`
	OrphanReview  int `json:"orphan_review"`
}

type DiffSource

type DiffSource string
const (
	DiffSourceLive     DiffSource = "live"
	DiffSourceCaptured DiffSource = "captured"
)

type ImageJobs added in v0.177.0

type ImageJobs interface {
	SessionAcceptsImages(jobID string) (bool, error)
	SaySessionBlocks(jobID, text string, images []job.ImageInput) error
}

ImageJobs is the image-carrying side of the job service.

type JobTurn

type JobTurn struct {
	JobID     string     `json:"job_id"`
	Status    string     `json:"status"`
	StartedAt int64      `json:"started_at"`
	EndedAt   int64      `json:"ended_at,omitempty"`
	Usage     *job.Usage `json:"usage,omitempty"`
}

type Jobs

type Jobs interface {
	ResumeJob(jobID, prompt, runner, callerID string) (job.JobResult, error)
	// ResumeJobWithImages continues a session with image paths riding the continuation's
	// argv (image_input: arg).
	ResumeJobWithImages(jobID, prompt, runner, callerID string, imagePaths []string) (job.JobResult, error)
	SaySession(jobID, message string) error
}

type Layout

type Layout struct {
	Version int64           `json:"version"`
	Body    json.RawMessage `json:"body"`
}

type LayoutVersionConflict

type LayoutVersionConflict struct {
	Current Layout
}

LayoutVersionConflict carries the server value a client must adopt after a stale optimistic write.

func (*LayoutVersionConflict) Error

func (e *LayoutVersionConflict) Error() string

type PatchInput

type PatchInput struct {
	Title  *string
	Seen   *bool
	Pinned *bool
}

type Placer added in v0.177.0

type Placer interface {
	PutAndWait(ctx context.Context, caller, runner, projectKey, srcPath, dest string, timeout time.Duration) (string, error)
}

Placer puts a local file onto the executing machine (xfer.Manager.PutAndWait).

type ProjectGroup

type ProjectGroup struct {
	ProjectKey string   `json:"project_key"`
	Status     Status   `json:"status"`
	Counts     Counts   `json:"counts"`
	Threads    []Thread `json:"threads"`
}

type Query

type Query struct {
	Project string
	Status  Status
	Q       string
	Since   int64
	// IncludeInternal also lists web session-messenger delivery jobs (all=1).
	IncludeInternal bool
}

type Relay

type Relay interface {
	Say(sessionID, answer, callerID string) (jobstore.PlanDecision, error)
}

type RelayDeliveryError added in v0.177.1

type RelayDeliveryError struct{ Err error }

RelayDeliveryError is the cause of a failed terminal-session message; it matches ErrRelayDelivery and unwraps to the relay's own error (so sessionrelay.DeliverReason works).

func (*RelayDeliveryError) Error added in v0.177.1

func (e *RelayDeliveryError) Error() string

func (*RelayDeliveryError) Is added in v0.177.1

func (e *RelayDeliveryError) Is(target error) bool

func (*RelayDeliveryError) Unwrap added in v0.177.1

func (e *RelayDeliveryError) Unwrap() error

type RelayMessenger added in v0.177.1

type RelayMessenger interface {
	// SendMessage takes the display label (operator) and the caller-scope ceiling owner of the
	// message (origin) separately; see sessionrelay's ceiling_origin.go.
	SendMessage(ctx context.Context, sid, text, operator, origin string) (jobstore.SessionMessage, error)
	CheckDeliverable(sid string) error
	FollowWeb(sid, actor string)
}

RelayMessenger is what the session drawer's web message calls (sessionrelay.Service): a session waiting for a reply is answered, one with a Claude SendMessage address goes through the messenger, any other takes the deliver_command / tmux ladder. A Relay that has it is used for workbench turns instead of Say, which only answers an OPEN turn.

type RelaySessions added in v0.177.0

type RelaySessions interface {
	Session(sid string) (jobstore.AgentSession, error)
}

RelaySessions is the optional lookup of a terminal session's executor.

type RelaySummary

type RelaySummary struct {
	SessionID   string `json:"session_id"`
	State       string `json:"state"`
	RelayMode   string `json:"relay_mode"`
	LastEvent   string `json:"last_event,omitempty"`
	LastMessage string `json:"last_message,omitempty"`
}

type Response

type Response struct {
	Projects  []ProjectGroup  `json:"projects"`
	Attention []AttentionItem `json:"attention"`
	Total     int             `json:"total"`
	Since     int64           `json:"since"`
}

func (Response) Summary added in v0.176.0

func (r Response) Summary(full ...string) Response

Summary returns a copy of the response whose threads carry only the fields a list view reads: the heavy per-thread parts (jobs, pending_interactions, cwd, interactive and the relay's last event / message) are left out. job_ids stays (a few bytes per thread; the web maps a freshly launched job back to its thread with it). Threads whose id is in full are kept complete. Counts, attention and everything else are unchanged. The receiver is not modified.

type ReviewComment

type ReviewComment struct {
	Path string     `json:"path"`
	Line int        `json:"line"`
	Side ReviewSide `json:"side"`
	Text string     `json:"text"`
}

type ReviewInput

type ReviewInput struct {
	Summary  string          `json:"summary,omitempty"`
	Comments []ReviewComment `json:"comments,omitempty"`
}

type ReviewSide

type ReviewSide string
const (
	ReviewSideNew ReviewSide = "new"
	ReviewSideOld ReviewSide = "old"
)

type Route added in v0.177.0

type Route struct {
	Mode   AttachMode
	Reason string
}

Route is the delivery decision; Reason is set only for AttachNone.

func RouteAttachments added in v0.177.0

func RouteAttachments(in RouteInput) Route

RouteAttachments is the pure delivery-mode table:

pty job                                  -> none ("pty 会话不支持附图")
live ACP session accepting images        -> inline
agent cannot take images at all          -> none ("<agent> 暂不支持读取图片")
no runner or no project to place into    -> none ("会话没有执行机信息")
agent takes images as argv flags (arg)   -> arg
otherwise                                -> file

type RouteInput added in v0.177.0

type RouteInput struct {
	Kind    ThreadKind
	Agent   string
	Runner  string
	Project string
	// Pty marks an interactive pty job: it takes no images at all.
	Pty bool
	// ACPAccepts: the thread is a live resident ACP session whose agent advertised
	// promptCapabilities.image (job.SessionAcceptsImages).
	ACPAccepts bool
	// FilePath: the agent can read an image by absolute path (config image_input = path).
	FilePath bool
	// Arg: the agent takes an image path as an argv flag (config image_input = arg, agent
	// image_args), so the placement result rides the next job's argv instead of the text.
	Arg bool
}

RouteInput is everything RouteAttachments decides on; the callers fill it from a thread (List) or from the concrete target of a Turn.

type Service

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

func NewService

func NewService(store Store, jobs Jobs, relay Relay) *Service

func (*Service) Diff

func (s *Service) Diff(threadID string) (ThreadDiff, error)

Diff returns the changes made by a thread since its recorded Git base — the first turn's, or the latest turn's own baseline when it is a continuation (see threadDiffBase). Git is consulted only for a server-local latest turn whose cwd still exists; remote and vanished working directories use the latest captured artifact.

func (*Service) GetLayout

func (s *Service) GetLayout(callerID string) (Layout, error)

func (*Service) List

func (s *Service) List(callerID string, query Query) (Response, error)

func (*Service) Patch

func (s *Service) Patch(callerID, threadID string, input PatchInput) (jobstore.WorkbenchThreadPref, error)

func (*Service) PutLayout

func (s *Service) PutLayout(callerID string, expectedVersion int64, body json.RawMessage) (Layout, error)

func (*Service) Review

func (s *Service) Review(callerID, threadID string, input ReviewInput) (TurnResult, error)

Review converts structured inline comments into one ordinary workbench turn. Turn remains the only dispatch owner, so its session, runner, and state gates apply unchanged to review continuations.

func (*Service) SeenAll

func (s *Service) SeenAll(callerID string) (int64, error)

func (*Service) SetAttachments added in v0.177.0

func (s *Service) SetAttachments(d AttachmentDeps)

SetAttachments injects the attachment dependencies (the server wires them once its attachment store and transfer manager exist).

func (*Service) Turn

func (s *Service) Turn(callerID, threadID, text string) (TurnResult, error)

func (*Service) TurnWithAttachments added in v0.177.0

func (s *Service) TurnWithAttachments(callerID, threadID, text string, attachmentIDs []string) (TurnResult, error)

TurnWithAttachments is Turn with images: attachmentIDs are uploaded attachments of callerID that were not sent yet. They are delivered inline or by file (see RouteAttachments) or, when the receiver takes no images, the whole send is refused with ErrAttachmentsUnsupported; a failed placement sends nothing (ErrAttachmentDelivery).

type Status

type Status string
const (
	StatusBlocked       Status = "blocked"
	StatusWorking       Status = "working"
	StatusReview        Status = "review"
	StatusDone          Status = "done"
	StatusIdle          Status = "idle"
	StatusAwaitingInput Status = "awaiting_input"
)

type Store

type Store interface {
	LoadWorkbenchSnapshot(callerID string, since int64, includeInternal bool) (jobstore.WorkbenchSnapshot, error)
	ListWorkbenchThreadPrefs(callerID string) ([]jobstore.WorkbenchThreadPref, error)
	UpsertWorkbenchThreadPref(pref jobstore.WorkbenchThreadPref) error
	GetOrCreateWorkbenchSeenBaseline(callerID string, observedAt int64) (int64, error)
	SetWorkbenchSeenBaseline(callerID string, observedAt int64) (int64, error)
	GetWorkbenchLayout(callerID string) (jobstore.WorkbenchLayout, bool, error)
	PutWorkbenchLayout(callerID string, expectedVersion int64, bodyJSON string, updatedAt int64) (jobstore.WorkbenchLayout, bool, error)
	ListJobs(query jobstore.ListQuery) ([]jobstore.JobRecord, error)
	GetJob(id string) (jobstore.JobRecord, bool, error)
}

type Thread

type Thread struct {
	ID                  string            `json:"id"`
	Kind                ThreadKind        `json:"kind"`
	Status              Status            `json:"status"`
	RawStatus           string            `json:"raw_status,omitempty"`
	Stalled             bool              `json:"stalled,omitempty"`
	Title               string            `json:"title"`
	ProjectKey          string            `json:"project_key"`
	Agent               string            `json:"agent,omitempty"`
	Runner              string            `json:"runner,omitempty"`
	Cwd                 string            `json:"cwd,omitempty"`
	Interactive         bool              `json:"interactive,omitempty"`
	Resumable           bool              `json:"resumable"`
	Pinned              bool              `json:"pinned,omitempty"`
	SeenAt              int64             `json:"seen_at,omitempty"`
	StartedAt           int64             `json:"started_at"`
	UpdatedAt           int64             `json:"updated_at"`
	WaitingSince        int64             `json:"waiting_since,omitempty"`
	Turns               int               `json:"turns"`
	Usage               *Usage            `json:"usage,omitempty"`
	LatestJobID         string            `json:"latest_job_id,omitempty"`
	JobIDs              []string          `json:"job_ids,omitempty"`
	Jobs                []JobTurn         `json:"jobs,omitempty"`
	PendingInteractions []job.Interaction `json:"pending_interactions,omitempty"`
	Relay               *RelaySummary     `json:"relay,omitempty"`
	// Attachments is how images sent to this thread would be delivered (inline | file |
	// none); AttachmentsReason says why when it is none. Both are absent while the
	// attachment store is not wired.
	Attachments       AttachMode `json:"attachments,omitempty"`
	AttachmentsReason string     `json:"attachments_reason,omitempty"`
}

type ThreadDiff

type ThreadDiff struct {
	Source    DiffSource       `json:"source"`
	Base      string           `json:"base"`
	Head      string           `json:"head,omitempty"`
	Files     []ThreadDiffFile `json:"files"`
	Patch     string           `json:"patch"`
	Truncated bool             `json:"truncated"`
	Commits   []job.Commit     `json:"commits,omitempty"`
	Notice    string           `json:"notice,omitempty"`
}

ThreadDiff is the conversation-level review snapshot. Captured responses are explicitly scoped to the latest turn; live responses span base..working-tree.

type ThreadDiffFile

type ThreadDiffFile struct {
	Path      string `json:"path"`
	Status    string `json:"status"`
	Additions int    `json:"additions"`
	Deletions int    `json:"deletions"`
	Binary    bool   `json:"binary"`
}

ThreadDiffFile is one path changed since the thread's first Git baseline. Untracked files use status "?" and deliberately carry no content or line counts.

type ThreadKind

type ThreadKind string
const (
	KindAgent ThreadKind = "agent"
	KindJob   ThreadKind = "job"
	KindRelay ThreadKind = "relay"
)

func ParseThreadID

func ParseThreadID(id string) (ThreadKind, string, error)

type TurnResult

type TurnResult struct {
	ThreadID   string `json:"thread_id"`
	JobID      string `json:"job_id,omitempty"`
	DecisionID string `json:"decision_id,omitempty"`
	// MessageID is the session outbox message a terminal (relay) thread's turn recorded.
	MessageID string `json:"message_id,omitempty"`
	// Path is how a message to a terminal (relay) thread was delivered: turn | command |
	// tmux | takeover (sessionrelay.Path*). Empty for every other thread kind.
	Path string `json:"path,omitempty"`
	// Delivering: the text was handed to an internal job that was still on its way when the
	// wait window elapsed (the session outbox says how it ended).
	Delivering bool `json:"delivering,omitempty"`
}

type Usage

type Usage struct {
	InputTokens      int64   `json:"input_tokens,omitempty"`
	OutputTokens     int64   `json:"output_tokens,omitempty"`
	CacheReadTokens  int64   `json:"cache_read_tokens,omitempty"`
	CacheWriteTokens int64   `json:"cache_write_tokens,omitempty"`
	TotalTokens      int64   `json:"total_tokens,omitempty"`
	CostUSD          float64 `json:"cost_usd,omitempty"`
}

Jump to

Keyboard shortcuts

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