sendqueue

package
v0.164.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 15 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 sendqueue is the SERVER-SIDE SEND QUEUE (migration 0019): messages a user queued for a mirrored Claude Code window, which the server sends ONE AT A TIME, each only once that window's Claude Code session has been idle for a while (Dispatcher). The queue is per user and stored, so it survives the page that queued it closing, and every device of the owner sees (and can cancel) the same queue.

🔴 THE STORE HAS TWO HALVES AND THEY RUN UNDER DIFFERENT PRINCIPALS. Enqueue, List, Get, Cancel, Retry, Delete and NotePaste run under the CALLER's principal: send_queue is under FORCE row-level security, so a request sees, queues into and cancels only its own user's rows, and the owner of a new row is the principal's user (owner_id's default), never a parameter. Recover, Heads, Claim, Renew, Finish, Prune and CancelOwner run under the system scope (sys): they read and move every owner's rows, and hand each row to the delivery, which acts as that row's owner.

🔴 A MESSAGE IS CLAIMED ONCE AND NEVER RETRIED AFTER ANYTHING REACHED THE HOST — BUT ONE IT REACHED THAT CLAUDE CODE PROVABLY REJECTED. Claim moves a row from queued to sending in one conditional UPDATE: a send that fails is failed, and a process that dies mid-send leaves a row that Recover marks failed (may have been delivered) once its claim's lease has expired. The ONE way back to queued is a send the hub refused as superseded (Outcome.Superseded: another paste got into the window between the decision and the paste), which by construction wrote nothing to the host. A message is never pasted twice by the queue on its own: a failed row stays failed — a SENT row a usage limit bounced is failed too (Reject; limit.go), never re-sent automatically — and a person's Retry (PGStore.Retry) queues its text again as a NEW row — its own id, so its own delivery nonce — once per failed row.

🔴 A CLAIM IS A LEASE, HELD BY ONE INSTANCE. Claim records the claiming dispatcher (claimed_by) and lease_until, Renew extends it while the send runs, Recover fails only a row whose lease has expired, and Finish records an outcome only for the row's own claimant. Two muster pods overlap during a rolling update, and neither may fail or finish the other's live send.

Index

Constants

View Source
const (
	// DefaultIdleFor is how long a target must have been idle (MUSTER_SEND_QUEUE_IDLE).
	DefaultIdleFor = 30 * time.Second
	// DefaultInterval is how often the dispatcher looks.
	DefaultInterval = 2 * time.Second
	// MinIdleFor and MaxIdleFor bound a configured IdleFor.
	MinIdleFor = time.Second
	MaxIdleFor = time.Hour
	// DefaultLease is how long a claim holds without a renewal, and
	// DefaultRenewEvery how often a sender renews it: a sender that stops
	// (its pod was killed) has its row failed about a lease later.
	DefaultLease      = 30 * time.Second
	DefaultRenewEvery = 10 * time.Second
)

The defaults.

View Source
const (
	// LimitMargin is how long after a usage limit's reset the queue waits
	// before sending: the reset is the limit's own minute, and a clock a few
	// seconds off either side must not send into it.
	LimitMargin = time.Minute
	// BreakerAfter is how many turns in a row must each fail at once before
	// the breaker holds the queue.
	BreakerAfter = 2
	// BounceWithin is how long after its claim a sent message may still be
	// found refused: a refusal is written within a second or two, and the
	// host reports it within a refresh.
	BounceWithin = 10 * time.Minute
)
View Source
const (
	// LimitHeldText: a usage limit that names its reset.
	LimitHeldText = "Held — usage limit, resumes"
	// LimitHeldNoReset: a usage limit that names no reset time this can place.
	LimitHeldNoReset = "Held — usage limit; no reset time given. Resumes once Claude Code answers a message, or tap Send now."
	// RejectedLimitDetail is the detail of a sent message a usage limit
	// refused, marked failed (Reject).
	RejectedLimitDetail = "Rejected: usage limit — Claude Code refused it before working on it. Retry it once the limit resets."
)

What a held queue says (Decision.Why). The time it resumes, when there is one, is Decision.ResumeAt — drawn after these words in the READER's zone (internal/ui), never in the server's.

View Source
const AuthorizedFor = 7 * 24 * time.Hour

AuthorizedFor is how long a person's queued message stays authorized by the sign-in that queued it, counted from when it was QUEUED (CreatedAt): the operator's decision. A message authorized when it was queued stays so until it is sent, for at most this long; a delivery past it fails as expired, and the owner can Retry it under a sign-in of their own. Routed messages are gated by their route instead.

View Source
const EditHold = 10 * time.Minute

EditHold is how long an Edit holds its row: long enough to rewrite a message on a phone, short enough that an abandoned edit does not stall the queue for long.

View Source
const FailedShown = MaxOpenPerTarget

FailedShown bounds the failed messages List returns beside the open ones: the FailedShown most recent of a person's own failures not yet retried, newest first. A sent or cancelled message is never listed — it has been handled — nor a routed message or a chief nudge that failed (its outcome goes back to the chief, which is its handling). A person's own failure is listed until they Retry or Delete it, or Prune deletes it Retention after it failed, and only the newest FailedShown of them; an older one beyond that is not shown. The bound is the open bound's size (TestFailedShownCoversAWholeQueue), so a whole queue that failed is shown whole.

View Source
const HeldWhy = "it is being edited; nothing for this window is sent until the edit is saved or cancelled (or its hold runs out)"

HeldWhy is what a held head is waiting for (Decide).

View Source
const MaxDetail = 1024

MaxDetail bounds an outcome's detail (0019's send_queue_detail_cap).

View Source
const MaxOpenPerTarget = 20

MaxOpenPerTarget bounds the messages one target may have queued (or being sent) at once. A target that is never idle — a host that stopped reporting, a session that is always busy — would otherwise collect without limit.

View Source
const RecoveredDetail = "muster stopped while sending this message, so it may or may not have been delivered; it was not sent again"

RecoveredDetail is the outcome of a message whose sender stopped in the middle of sending it (Recover).

View Source
const Retention = 7 * 24 * time.Hour

Retention is how long a finished message is kept (a person's own failure is listed under the composer, List) before Prune deletes it.

Variables

View Source
var (
	// ErrNotEditable: the message is no longer queued (sent, failed or
	// cancelled), so there is nothing to edit.
	ErrNotEditable = errors.New("sendqueue: only a queued message can be edited")
	// ErrEditSending: the message is being sent right now; it is past editing.
	// An ErrNotEditable (errors.Is).
	ErrEditSending = fmt.Errorf("%w: this one is being sent right now", ErrNotEditable)
	// ErrRoutedNotEditable: the chief routed it; its text is the chief's. An
	// ErrNotEditable (errors.Is).
	ErrRoutedNotEditable = fmt.Errorf("%w: a message your chief routed is not edited here", ErrNotEditable)
	// ErrNudgeNotEditable: a chief nudge or a relayed answer (ChiefNudgeID) is
	// sent as decided, or cancelled — never edited.
	ErrNudgeNotEditable = fmt.Errorf("%w: a chief nudge is not edited here", ErrNotEditable)
	// ErrHoldLapsed: Save (or Cancel) presented a hold that is no longer the
	// row's live one — it ran out, or a later Edit took the row over. The row
	// is still queued, with the text it had.
	ErrHoldLapsed = errors.New("sendqueue: the edit's hold ran out (or the message was opened for editing again), so the edit was not saved")
	// ErrEditTooLate: Save found the row no longer queued — its hold ran out
	// and it was sent (or is being sent) with its original text, or it was
	// cancelled. Item.State says which.
	ErrEditTooLate = errors.New("sendqueue: the message is no longer queued, so the edit was not saved")
)
View Source
var (
	// ErrFull refuses a message past MaxOpenPerTarget.
	ErrFull = fmt.Errorf("sendqueue: at most %d messages can be queued for one target; wait for some to send, or cancel one", MaxOpenPerTarget)
	// ErrNotFound: no such message the caller can see (absent, or another
	// user's — the two answer identically).
	ErrNotFound = errors.New("sendqueue: no such queued message")
	// ErrNotCancellable: the message is no longer queued (it is being sent, or
	// already finished).
	ErrNotCancellable = errors.New("sendqueue: the message is no longer queued, so it cannot be cancelled")
	// ErrNotDeletable: the message is not finished — still queued (Cancel it
	// first) or being sent (a send in flight is never deleted from under its
	// claim).
	ErrNotDeletable = errors.New("sendqueue: only a finished message can be deleted: cancel a queued one first; one being sent cannot be deleted")
	// ErrEmpty refuses a message with no text.
	ErrEmpty = errors.New("sendqueue: nothing to queue: type a message first")
	// ErrNotRetryable: the message did not fail, or was already retried.
	ErrNotRetryable = errors.New("sendqueue: only a failed message can be retried, and only once")
	// ErrRoutedNotRetryable: the message was routed by the chief (RouteID).
	// Its failed route goes back to the chief; a Retry would requeue it as
	// the person's own, with no route and no session binding. It is an
	// ErrNotRetryable (errors.Is), so a caller that maps that one maps this.
	ErrRoutedNotRetryable = fmt.Errorf("%w: a message your chief routed is not retried here; its failed route goes back to the chief", ErrNotRetryable)
	// ErrNudgeNotRetryable: the message is a chief nudge or a relayed answer
	// (ChiefNudgeID). Requeued as the person's own it would lose the decision
	// its delivery is gated on. An ErrNotRetryable (errors.Is).
	ErrNudgeNotRetryable = fmt.Errorf("%w: a chief nudge is not retried here", ErrNotRetryable)
)
View Source
var BreakerBackoff = []time.Duration{time.Minute, 2 * time.Minute, 5 * time.Minute, 15 * time.Minute}

BreakerBackoff is how long the breaker holds: the first trip (BreakerAfter quick failures in a row) for the first entry, each further quick failure the next, the last repeating. Counted on muster's clock from when muster first saw the failing turn's status (AgentState.Observed), never the host's.

View Source
var ErrNotClaimed = errors.New("sendqueue: the message is no longer queued, or another message for its window is being sent")

ErrNotClaimed: SendNow could not claim the message — it is no longer queued (sent, cancelled, or claimed by the dispatcher first), or its target already has a message being sent. Nothing was sent.

View Source
var ExpiredDetail = "Not sent: it was queued more than " + authorizedText + " ago, and a queued message is sent only within " +
	authorizedText + " of being queued. Retry it to queue it again."

ExpiredDetail is the outcome of a person's message that was not sent within AuthorizedFor of being queued: the delivery's refusal (internal/api sendQueueAuthorization) and Expire's, the same words either way.

Functions

func Bounced

func Bounced(it Item, pastedIn string, st AgentState) bool

Bounced reports whether sent message it — pasted into Claude Code session pastedIn — was REFUSED by Claude Code before it worked on it, as st shows its window now. Every one of these, or the row stays sent:

  • the refused turn is in the SAME Claude Code session the message was pasted into (st.Session == pastedIn, both known): a fresh `claude` in the same pane, whose first prompt happens to be the message's text, has nothing before it in ITS transcript (PrevAt 0), and is not the message's refusal;
  • the window is idle, on a status newer than the one it was pasted on (it.AfterSince: the turn after the paste has ended);
  • the latest turn ended in an error the CLI wrote itself that was its prompt's ONLY reply (TurnError.Rejected: no tool ran, nothing written);
  • that prompt's text is this message's (TurnError.Prompt, a digest);
  • 🔴 NOTHING CAME BETWEEN this paste and that prompt: the newest record before the refused prompt (TurnError.PrevAt) is no newer than the status the message was pasted on. Both are the CLI's own times, on the host's clock. A message that was ANSWERED, followed by another prompt typed in the terminal that hit the limit, has its answer there — after its paste — and stays sent, restart or not (the hub's Pasted, checked as well, lives in memory and a restart forgets it).

func BreakerHeldText

func BreakerHeldText(e *mirror.TurnError) string

BreakerHeldText is what a queue the circuit breaker holds says, before the time it retries.

func RejectedDetail

func RejectedDetail(kind string) string

RejectedDetail is the detail of a sent message Claude Code refused with a turn error of kind (Reject): RejectedLimitDetail for a usage limit.

Types

type AgentState

type AgentState struct {
	// Idle: the target is known to be idle (not busy, not waiting on the
	// person).
	Idle bool
	// Since is Claude Code's own time for its current status, Unix ms ON THE
	// HOST'S CLOCK. Set when Idle.
	Since int64
	// Observed is when the server first saw that status, on MUSTER's clock:
	// what IdleFor is measured from. Set when Idle.
	Observed time.Time
	// Pasted is the status time (host clock) the window held at its latest
	// paste that the server remembers in memory; 0 for none.
	Pasted int64
	// Why says, when not Idle, why the target is not sendable now — busy, or
	// unknown and why. Shown to the owner.
	Why string
	// TurnError is how the target's latest turn ended when it ended in an
	// error Claude Code wrote itself — a usage limit, "Not logged in", an API
	// error (mirror.TurnError, read on the host from the transcript); nil when
	// it ended in a real answer, or the host does not say. Set when Idle.
	TurnError *mirror.TurnError
	// HostLimit is a usage limit the target's host reports for all its Claude
	// windows (mirror.HostLimit): the account's limit, which holds this window
	// too. nil for none. Set when Idle.
	HostLimit *mirror.HostLimit
	// Session is the Claude Code session id of the conversation in the target
	// (mirror.Window.ClaudeSession) — the one its TurnError was read from — ""
	// when the host does not say.
	Session string
}

AgentState is what the server can see of a target right now.

type AsOwner

type AsOwner func(ctx context.Context, owner int64) context.Context

AsOwner is ctx acting as user owner: what Probe and Send are handed.

type Claim

type Claim struct {
	By    string
	Lease time.Duration
	Since int64
}

Claim is a dispatcher's claim on a message: who claims it, how long the claim holds unless renewed (from Postgres's now()), and the status time (host clock) the target held when the dispatcher decided to send it.

type Decision

type Decision struct {
	Send bool
	// Why says, when not Send, what the head is waiting for.
	Why string
	// Held: the queue is HELD on how the latest turn failed (holdFor): a
	// usage limit, or the circuit breaker. Only Send now sends while it is.
	Held bool
	// ResumeAt is, for a usage limit that names its reset, the reset time:
	// the queue sends again LimitMargin after it. Zero otherwise.
	ResumeAt time.Time
}

Decision is what Decide made of one head.

func Decide

func Decide(h Head, st AgentState, now time.Time, idleFor time.Duration) Decision

Decide is the dispatcher's whole rule for one head, given the target's state now. It is a pure function so that what a composer shows ("waiting: …") and what the dispatcher does are the same decision.

type DispatchStore

type DispatchStore interface {
	Recover(ctx context.Context, now time.Time) (int, error)
	Expire(ctx context.Context, now time.Time) (int, error)
	ClearLapsedHolds(ctx context.Context) (int, error)
	Heads(ctx context.Context) ([]Head, error)
	Claim(ctx context.Context, id int64, now time.Time, c Claim) (Item, bool, error)
	Renew(ctx context.Context, id int64, by string, lease time.Duration) (bool, error)
	Finish(ctx context.Context, id int64, by string, o Outcome, now time.Time) error
	Prune(ctx context.Context, before time.Time) (int, error)
	RecentSent(ctx context.Context, after time.Time) ([]Item, error)
	Reject(ctx context.Context, id int64, detail string) (bool, error)
}

DispatchStore is the store half the dispatcher drives (PGStore's).

type Dispatcher

type Dispatcher struct {
	Store   DispatchStore
	Probe   Probe
	Send    Sender
	AsOwner AsOwner
	IdleFor time.Duration
	Now     func() time.Time
	Logger  *log.Logger
	// Instance names this dispatcher in its claims (claimed_by); "" is a
	// random one, made once (InstanceID). Two dispatchers must never share one.
	Instance string
	// Lease and RenewEvery are the claim's lease and how often a send in
	// progress renews it; 0 takes the defaults.
	Lease      time.Duration
	RenewEvery time.Duration
	// contains filtered or unexported fields
}

Dispatcher sends queued messages. Zero durations take the defaults.

func (*Dispatcher) Decide

func (d *Dispatcher) Decide(h Head, st AgentState) Decision

Decide is the package Decide with this dispatcher's durations and clock.

func (*Dispatcher) Init

func (d *Dispatcher) Init()

Init makes Kick usable; call it before Run and before anything may Kick.

func (*Dispatcher) InstanceID

func (d *Dispatcher) InstanceID() string

InstanceID is d's claim name: Instance, or — unset — the host name and 8 random bytes, made once.

func (*Dispatcher) Kick

func (d *Dispatcher) Kick()

Kick asks Run for a pass now (a message was queued). It never blocks.

func (*Dispatcher) Run

func (d *Dispatcher) Run(ctx context.Context, interval time.Duration)

Run recovers, then ticks every interval (and on each Kick) until ctx ends, pruning finished messages older than Retention once an hour.

func (*Dispatcher) SendNow

func (d *Dispatcher) SendNow(ctx, octx context.Context, id int64, since int64, send Sender) (Item, Outcome, error)

SendNow is a person's "Send now" of queued message id: claimed (queued → sending) under this dispatcher's instance, exactly as Tick claims a head, so the dispatcher can never also send it, and sent through send — renewing the claim while it runs — WITHOUT Decide: the person chose not to wait for idle. since is the window's status time (host clock) now, recorded as the claim's so the next message waits for the turn this one starts. The outcome is recorded (Finish) and returned; ErrNotClaimed when the claim failed.

🔴 ONE CLAIM, ONE SEND. The claim is the same conditional UPDATE the dispatcher's is (Store.Claim): whichever of the two claims first sends, the other's claim finds the row no longer queued — and a target's one-sending index refuses a claim while another of its rows is being sent.

func (*Dispatcher) Start

func (d *Dispatcher) Start(ctx context.Context) error

Start fails what a stopped sender left mid-send (a lease that expired). Every Tick does the same first; Start does it once before the first.

func (*Dispatcher) Tick

func (d *Dispatcher) Tick(ctx context.Context) (int, error)

Tick makes one pass: fail what a stopped sender left mid-send, fail what was queued too long ago to be sent (expire), then for every target whose head Decide says to send, claim it, send it (renewing the claim while it runs), and record the outcome. It returns how many it sent or failed (an expired message is not counted).

type Head struct {
	Item
	// TurnAfter is the newest status time (host clock, Unix ms) the target held
	// at a paste this table knows of: the head's own AfterSince, or that of a
	// message of the target that was sent or may have been delivered. 0 when
	// there is none. The next message waits for the host to report a status
	// time strictly newer than it (Decide).
	TurnAfter int64
}

Head is one target's next message (its oldest open row), with what the dispatcher decides on.

type Item

type Item struct {
	ID     int64
	Owner  int64
	Target Target
	Body   string
	// StepUpAt is the sign-in time of the session that queued the message (the
	// step-up decision, recorded). It was inside the step-up window when the
	// message was queued (the queue route's gate); the delivery checks that
	// again against CreatedAt, and the account's cutoffs against it, and then
	// sends for up to AuthorizedFor after CreatedAt (internal/api sendQueueSend).
	StepUpAt         time.Time
	State            State
	Detail           string
	MayHaveDelivered bool
	CreatedAt        time.Time
	ClaimedAt        time.Time
	FinishedAt       time.Time
	// AfterSince is the window's Claude Code status time, Unix ms ON THE
	// HOST'S CLOCK, held at the latest paste into the window this row knows of
	// (0: none): the next message waits for a newer one (Decide).
	AfterSince int64
	// ClaimedBy and LeaseUntil are the claim: the dispatcher instance sending
	// the row, and until when its claim holds unless renewed (on Postgres's
	// clock).
	ClaimedBy  string
	LeaseUntil time.Time
	// ClaimSince is the status time (host clock) the claim was decided on:
	// folded into AfterSince when the row finishes (or is recovered), dropped
	// when the send was superseded and the row goes back to queued.
	ClaimSince int64
	// RouteID marks a ROUTED message (session routing, internal/plugins'
	// session_routes): "" for a person's. Its delivery is gated on the route,
	// not on a sign-in (internal/api's sendQueueSend).
	RouteID string
	// ChiefNudgeID marks a message the CHIEF NUDGE sweep queued — a labelled
	// nudge or the owner's relayed answer (migration 0064, internal/chiefnudge):
	// 0 for any other. Like RouteID it is gated on its origin, not on a sign-in
	// (internal/api's sendQueueNudgeGate), and is never edited or retried. A row
	// never carries both (0064's send_queue_one_origin).
	ChiefNudgeID int64
	// RetriedAs is, on a failed row that was retried, the row its Retry queued
	// (0: not retried). A row is retried at most once (Retry).
	RetriedAs int64
	// HeldUntil is the end of the row's edit hold (Hold), on Postgres's clock;
	// zero for none. Once it has passed, the dispatcher's next pass (or a
	// claim) takes it off the row (ClearLapsedHolds).
	HeldUntil time.Time
	// Held: an edit hold that has not run out yet (held_until > now(), read on
	// Postgres's clock). The dispatcher never claims a held row.
	Held bool
	// HoldLapsed: the row had an edit hold that ran out before it was saved or
	// cancelled, so the row is queued again with its original text — whether
	// or not the dispatcher has cleared the lapsed hold yet (hold_lapsed_at).
	HoldLapsed bool
	// HoldToken names the live hold: what a Save or a release must present.
	HoldToken string
	// EditedAt and EditStepUpAt are the latest saved edit: when, and the
	// sign-in time of the request that saved it (zero: never edited). The
	// delivery checks EditStepUpAt as it checks StepUpAt.
	EditedAt     time.Time
	EditStepUpAt time.Time
}

Item is one queued message.

func (Item) HoldsTurn

func (it Item) HoldsTurn() bool

HoldsTurn reports whether it is a message the NEXT message of its target waits behind: one that was pasted (sent), or may have been (failed, may have been delivered). It is heads' TurnAfter predicate, in Go.

type Outcome

type Outcome struct {
	// Sent: the target accepted the message.
	Sent bool
	// MayHaveDelivered: the message may have reached the target even though
	// the send did not succeed (the host never confirmed). Always true when
	// Sent.
	MayHaveDelivered bool
	// Detail is the outcome in words, shown to the owner: why it failed, or
	// how it was delivered. Never the message.
	Detail string
	// Superseded: the hub refused the paste because another paste got into
	// the window (or its status moved) after the decision (mirror.ErrSuperseded).
	// NOTHING reached the host, so the row goes back to queued — the one way
	// back — waiting behind AfterSince (the window's Pasted at the refusal).
	// internal/api's chief-nudge gate uses the same way back, with AfterSince
	// 0, for a row whose session state could not be read (SendQueueNudgeWait).
	Superseded bool
	AfterSince int64
	// Pasted: the text was pasted into the agent's input box and Enter
	// withheld (the Claude prompt guard): not submitted, and not to be resent
	// blindly.
	Pasted bool
}

Outcome is how a send ended.

type PGStore

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

PGStore is the queue on Postgres.

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG returns a store on pool.

func (*PGStore) Cancel

func (s *PGStore) Cancel(ctx context.Context, id int64, now time.Time) (Item, error)

Cancel cancels the caller's message id, which must still be queued: one being sent is past cancelling (ErrNotCancellable), and another user's is not found.

func (*PGStore) CancelOwner

func (s *PGStore) CancelOwner(ctx context.Context, owner int64, now time.Time, detail string) (int, error)

CancelOwner cancels every message user owner still has queued, saying why (detail): the account was disabled, or signed out everywhere. A message already being sent is past cancelling; its delivery re-checks the account. Under the system scope: an admin disables another user.

func (*PGStore) Claim

func (s *PGStore) Claim(ctx context.Context, id int64, now time.Time, c Claim) (Item, bool, error)

Claim moves message id from queued to sending at now under claim c, and returns it — or false when it is no longer queued (cancelled, or claimed by another dispatcher), it is HELD for an edit (Hold; notHeld, in the same conditional UPDATE, so a hold and a claim cannot both win), or its target already has a message being sent. A lapsed hold is cleared by the claim. c.Since is recorded as the row's ClaimSince, which becomes its AfterSince when the row finishes or is recovered — so a sender that dies mid-paste still leaves the next message waiting for a newer status — and is dropped if the send is superseded (nothing was pasted).

func (*PGStore) ClearLapsedHolds

func (s *PGStore) ClearLapsedHolds(ctx context.Context) (int, error)

ClearLapsedHolds takes every hold that has run out off its row, across every owner (the system scope), recording that it ran out (hold_lapsed_at), and returns how many. The dispatcher runs it on every pass: a row then carries held_until and hold_token only while its hold is live, which bounds what an older image (whose statements do not clear them, and so trip 0040's send_queue_hold_check on a held row) can meet during a rollout or rollback.

func (*PGStore) Delete

func (s *PGStore) Delete(ctx context.Context, id int64) error

Delete deletes the caller's FINISHED message id (State.Finished): a queued one is refused (ErrNotDeletable; Cancel it first), and so is one being sent — its claimant still holds a lease on the row and will Finish it, so the row must outlive the send. Another user's message is not found (row-level security: the two answer identically).

🔴 A DELETED MESSAGE'S TURN IS NOT FORGOTTEN. A sent message (or one that may have been delivered) is what the target's next message waits behind: heads reads its after_since as TurnAfter. Deleting the row would drop that turn and could release the next message into the turn the deleted one started. So, in the same transaction and under the row's lock, its after_since is first carried onto the target's open rows (as NotePaste does). ⚠ With no open row to carry it to, it goes with the row — as Prune's deletes do — and a message queued afterwards waits on the hub's in-memory record of the paste alone, which a restart forgets.

A ROUTED message is deleted like a person's: its route (session_routes) names the row by send_queue_id with no foreign key, and the one thing that reads it back — the route sweep's Cancel on a timeout — finds nothing and still hands the route back to the chief.

func (*PGStore) Enqueue

func (s *PGStore) Enqueue(ctx context.Context, it Item) (Item, error)

Enqueue queues it for its target, as the caller, and returns the stored row. Only its Target, Body, StepUpAt, AfterSince (the status time the window held at its latest paste, as the hub knows it; 0 for none), RouteID (a routed message's route, "" for a person's) and ChiefNudgeID (a chief nudge's decision, 0 for none) are read.

The per-target bound is checked AFTER the insert, in the same transaction, serialised per owner by an advisory lock, so two concurrent messages cannot both pass it (internal/pins' shape; TestTwoConcurrentEnqueuesCannotBothPassTheBound).

func (*PGStore) Expire

func (s *PGStore) Expire(ctx context.Context, now time.Time) (int, error)

Expire fails, at now, every PERSON's message still queued that was queued more than AuthorizedFor before now — as expired (ExpiredDetail), never delivered, so it offers Retry — and returns how many. The delivery refuses such a row anyway, but only once its window goes idle: a window that never does would show it "queued" past the bound and keep holding one of its MaxOpenPerTarget slots. A routed message is gated by its route, not by this bound, and is left alone; so is one being sent (its claimant finishes it). now is muster's clock, as the delivery's check is (created_at is Postgres's; a skew of seconds is immaterial at a bound of days). The row's claimed_at is stamped now too, unclaimed (claimed_by NULL): a failed row carries one (0019's send_queue_claimed_check), and this sweep is what processed it.

func (*PGStore) Finish

func (s *PGStore) Finish(ctx context.Context, id int64, by string, o Outcome, now time.Time) error

Finish records how instance by's send of message id ended, at now. Only a message being sent, and only by its claimant, is finished: a slow sender whose row was recovered meanwhile does not rewrite the recorded outcome. A Superseded outcome puts the row back to queued instead, unclaimed, its AfterSince raised to o.AfterSince and its ClaimSince dropped.

func (*PGStore) Get

func (s *PGStore) Get(ctx context.Context, id int64) (Item, error)

Get is the caller's message id.

func (*PGStore) HeadOf

func (s *PGStore) HeadOf(ctx context.Context, t Target) (Head, bool, error)

HeadOf is the caller's head for target t (false when t has nothing open): what a composer's queue shows the dispatcher deciding on. Under the CALLER's principal.

func (*PGStore) Heads

func (s *PGStore) Heads(ctx context.Context) ([]Head, error)

Heads is every target's next message, across every owner: a target's row being sent if it has one, else its oldest queued row.

func (*PGStore) Hold

func (s *PGStore) Hold(ctx context.Context, id int64) (Item, error)

Hold holds the caller's QUEUED message id for an edit, for EditHold on Postgres's clock, and returns it with its new HoldToken. A row that is already held is taken over (a new token: the earlier editor's Save is then refused with ErrHoldLapsed). Refused: one being sent (ErrEditSending), one that has finished (ErrNotEditable), a routed one (ErrRoutedNotEditable); another user's is not found.

func (*PGStore) InjectedBodies added in v0.112.0

func (s *PGStore) InjectedBodies(ctx context.Context, since time.Time, limit int) ([]string, error)

InjectedBodies is the text of every message muster itself queued for the caller's windows since since — a routed message (RouteID) or a chief nudge or relayed answer (ChiefNudgeID), whatever became of it — newest first, at most limit. A queued message lands in Claude Code's transcript as an ordinary user prompt; the chief nudge sweep reads this to tell those apart from the owner's own words.

func (*PGStore) List

func (s *PGStore) List(ctx context.Context, t Target) ([]Item, error)

List is the caller's messages for t that still need something: every open one (queued or being sent), oldest first, then the FailedShown most recently failed of the person's own (no route, no chief nudge) that were not retried, newest first. A sent or cancelled message is not listed, nor a failed one already retried (its retry row, a new message of its own, carries it), nor a failed routed message or chief nudge (handed back to the chief).

func (*PGStore) NotePaste

func (s *PGStore) NotePaste(ctx context.Context, t Target, since int64) error

NotePaste records, as the caller, that something was pasted into target t while the window held status time since (host clock, Unix ms): every open row of t then waits for a newer one. It is what keeps a person's Send across a restart — the hub's own record of it is in memory.

func (*PGStore) Prune

func (s *PGStore) Prune(ctx context.Context, before time.Time) (int, error)

Prune deletes every message that finished before before.

func (*PGStore) RecentSent

func (s *PGStore) RecentSent(ctx context.Context, after time.Time) ([]Item, error)

RecentSent is, for every target of every owner whose most recently CLAIMED message was claimed after `after`, that message — when it is sent. What the dispatcher checks for a usage limit's bounce (rejectBounced): only a target's latest send can be the one its latest turn answered, and it has to be found whether or not anything else is still queued for the target (a Heads pass sees only targets with an open row).

func (*PGStore) Recover

func (s *PGStore) Recover(ctx context.Context, now time.Time) (int, error)

Recover marks every message left 'sending' whose claim's lease has expired — its sender stopped mid-send and stopped renewing — as failed, may have been delivered, finished at now. It never returns a message to queued, and it leaves a row whose lease is live alone: another instance is sending it.

🔴 THE LEASE IS ON POSTGRES'S CLOCK, BOTH SIDES. Claim and Renew write lease_until as now() plus the lease and Recover compares it with now(), so two pods whose own clocks disagree (a rolling update across nodes) can neither fail the other's live send nor keep a dead one's row (TestALeaseIsOnTheDatabasesClockNotThePods). now only stamps finished_at.

func (*PGStore) Reject

func (s *PGStore) Reject(ctx context.Context, id int64, detail string) (bool, error)

Reject marks SENT message id failed because a usage limit bounced it before Claude Code worked on it (limit.go): not delivered, detail saying why. It is then an ordinary failed row — its Retry (PGStore.Retry) queues the text again as a new row, by hand; nothing re-sends it on its own. Its after_since (the status time it was pasted on) is kept, so the next message still waits for a newer one. false when the row is no longer sent: one Reject per send, whoever else tries.

func (*PGStore) ReleaseEdit

func (s *PGStore) ReleaseEdit(ctx context.Context, id int64, token string) (it Item, released bool, err error)

ReleaseEdit releases the caller's hold token on message id, leaving its text as it was: an edit's Cancel. released is false when the token is no longer the row's live hold — it ran out, was taken over, or the row moved on — and the row is returned as it is now; there is then nothing to release.

func (*PGStore) Renew

func (s *PGStore) Renew(ctx context.Context, id int64, by string, lease time.Duration) (bool, error)

Renew extends instance by's claim on message id to lease from Postgres's now(). False when the row is no longer by's to send (it was finished, or recovered after the lease lapsed).

func (*PGStore) Retry

func (s *PGStore) Retry(ctx context.Context, id int64, stepUpAt time.Time, afterSince int64) (Item, error)

Retry queues the caller's FAILED message id again, as a new row with the same target and body, under stepUpAt — the sign-in time of the request that retried it, which the caller has checked is fresh — waiting behind afterSince as Enqueue's does. The failed row stays failed and records the new row (RetriedAs), in the same transaction and under the row's lock, so it is retried at most once (ErrNotRetryable after). A ROUTED message is never retried (ErrRoutedNotRetryable): requeued as the person's own it would carry no route and no session binding, so nothing would check the route its delivery is gated on (internal/api sendQueueRoutedGate); its failed route goes back to the chief instead. Another user's message is not found; the per-target bound applies (ErrFull). Whether a message that may already have been delivered may be retried is the caller's decision.

func (*PGStore) SaveEdit

func (s *PGStore) SaveEdit(ctx context.Context, id int64, token, body string, stepUpAt time.Time) (Item, error)

SaveEdit replaces the text of the caller's message id with body, under the live hold token, and releases the hold — in one UPDATE, so the row is never claimed with half of an edit. stepUpAt is the sign-in time of the request that saved it, which the caller has checked is fresh; it is stored (edit_stepup_at) for the delivery to check again. The row keeps its place (id) and its queued time (created_at). Refused: an empty or unpasteable body; a hold that is no longer live (ErrHoldLapsed: the row is unchanged); a row no longer queued (ErrEditTooLate, with the row as it is now).

type Probe

type Probe func(ctx context.Context, h Head) AgentState

Probe reads one head's target's state now. ctx acts as the head's owner.

type Sender

type Sender func(ctx context.Context, it Item, st AgentState) Outcome

Sender sends one claimed message through the manual send path. ctx acts as the message's owner; st is the target's state the decision to send was made on, which the send path must refuse to paste on if it has moved since (Outcome.Superseded).

type State

type State string

State is where a queued message is.

const (
	Queued    State = "queued"
	Sending   State = "sending"
	Sent      State = "sent"
	Failed    State = "failed"
	Cancelled State = "cancelled"
)

func (State) Finished

func (s State) Finished() bool

Finished reports whether a message in state s has ended — sent, failed (an expired message included: it is failed, saying so) or cancelled — and so whether its owner may delete it (Delete). Named states only: a state this list does not know is not finished, so a new open state added to the schema is never deletable by default.

func (State) Open

func (s State) Open() bool

Open reports whether a message in state s is still to be sent (or being sent).

type Target

type Target struct {
	Host    string
	Session string
	Window  string
}

Target addresses what messages are queued for: a mirrored window by (host, session, tmux window id) — "" being a per-session host's session. It is the queue's identity: messages for one target are sent in the order they were queued, one at a time. A queued message always lands in the window's Claude Code pane (mirror.PasteClaude), never whatever else is active there.

func (Target) String

func (t Target) String() string

String is t for a log line: ids and names, never anything sent to it.

func (Target) Valid

func (t Target) Valid() error

Valid reports whether t is a target the table can hold.

Jump to

Keyboard shortcuts

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