Documentation
¶
Overview ¶
Package chatqueue holds each session's queue of messages waiting to be sent from the phone, persisted on the Mac, and the rules for how an item moves from waiting to sent. The dispatcher (another file) decides when; this package decides what is allowed.
Index ¶
- Constants
- Variables
- func SamePrompt(saved, text string) bool
- type ACP
- type Auditor
- type Config
- type Dispatcher
- type Item
- type Queue
- type Store
- func (s *Store) Add(session, text, key string) (Item, error)
- func (s *Store) BindTerminal(session string) error
- func (s *Store) Changes() <-chan string
- func (s *Store) ClaimNow(session, item string) (Item, error)
- func (s *Store) Close()
- func (s *Store) Delete(session, item string) error
- func (s *Store) Done(session, item string) error
- func (s *Store) DoneNow(session, item string) error
- func (s *Store) Edit(session, item, text string) error
- func (s *Store) Get(session string) Queue
- func (s *Store) MarkAnswering(session, item string) error
- func (s *Store) MarkSending(session, item string) (Item, error)
- func (s *Store) Move(session, item string, position int) error
- func (s *Store) Next(session string) (Item, bool)
- func (s *Store) Pause(session, reason string) error
- func (s *Store) Release(session, item string) error
- func (s *Store) ReleaseNow(session, item string)
- func (s *Store) Resume(session string) error
- func (s *Store) Sessions() []string
- func (s *Store) Terminal(session string) bool
- func (s *Store) Typing(session string) bool
- type Terminal
- type Turn
Constants ¶
const ( ReasonNoAnswer = "No answer seen yet" ReasonUsedOnMac = "You used this session on your Mac" ReasonClosed = "This session closed on your Mac" ReasonInBox = "Your message is in the input box on your Mac" ReasonClearBox = "Clear the input box on your Mac, then resume" ReasonInTerminal = "This session is open in a terminal on your Mac" ReasonBoxNotEmpty = "The input box on your Mac isn't empty. Clear it, then resume." ReasonBoxHasUnsent = "Your earlier message is still in the box on your Mac. Retry it in the chat, or clear the box, then resume." ReasonUnsentUnconfirmed = "" /* 135-byte string literal not displayed */ ReasonNotClaude = "Claude Code isn't running in this session's terminal" ReasonAutomationDenied = "macOS isn't letting aimux type into iTerm2" ReasonNoDriver = "Only sessions in iTerm2 can take queued messages" ReasonDisabled = "Typing into terminal sessions is off on the Mac" ReasonNotRunning = "Session not running" ReasonTurnFailed = "Claude stopped with an error. Check the session, then resume." ReasonNoHistory = "Couldn't read this session on your Mac" ReasonSendFailed = "This message couldn't be sent. Check the session, then resume." ReasonReadFailed = "Couldn't read the session on your Mac. Check iTerm2, then resume." )
Reasons a dispatcher pauses a queue with. Fixed lines: clients show them.
const ( StateWaiting = "waiting" StateSending = "sending" // being typed or sent StateAnswering = "answering" // sent; its answer is not finished // StateDone is never stored. Add answers it for a retry whose key // belongs to an item already sent or deleted, so a retry never queues // the same message twice. StateDone = "done" )
Item states. An item is in flight while sending or answering; at most one per session is, and it is always the first item.
const ( QueueRunning = "running" QueuePaused = "paused" )
Queue states.
const ( // MaxItems is the most items one session's queue holds. MaxItems = 20 // MaxTextBytes caps an item's text: the cap on a terminal message body // (remoteapi.maxTerminalBody), so an item fits any send path. MaxTextBytes = 64 << 10 )
const NoteMacInUse = "Waiting: you're using this session on your Mac"
NoteMacInUse is the waiting line (not a pause) while the guard holds the next item back.
const NoteWorking = "Waiting: Claude is working"
NoteWorking is the waiting line while Claude works in the session and the next item waits for it, so a working state that never ends shows.
const ReasonMaybeSent = "This message may have been sent. Check the session, then resume or delete it."
ReasonMaybeSent pauses a queue whose item was in flight when the server stopped.
const ReasonNotAllowed = "This message is no longer allowed. Edit or delete it."
ReasonNotAllowed pauses a queue whose next item fails the text rules when it is about to be sent (a hand-edited file, or slash commands turned off since it was added).
Variables ¶
var ( ErrNotFree = errors.New("chatqueue: the session cannot take a turn yet") ErrNotRunning = errors.New("chatqueue: the session is not running") // ErrInTerminal: the session is open in a terminal although the // registry read said it was not; it waits a while, then pauses. ErrInTerminal = errors.New("chatqueue: the session is open in a terminal") )
ErrNotFree and ErrNotRunning are what an ACP sender answers when the session cannot take a turn now (it waits) or at all (the queue pauses).
var ( ErrFull = errors.New("chatqueue: the queue holds the most items it can") ErrItemSending = errors.New("chatqueue: the item is being sent") ErrBadText = errors.New("chatqueue: the text is empty, too long, holds control characters, or starts with ! or /") ErrNotFound = errors.New("chatqueue: no such item in this session's queue") ErrWrongState = errors.New("chatqueue: the item is not in the state this step needs") // ErrBusy: another message of the session is being typed (an item // sending, or another Send now), so Send now waits. ErrBusy = errors.New("chatqueue: another message is being typed into this session") )
Functions ¶
func SamePrompt ¶
SamePrompt reports whether saved, a history turn's user text as Claude Code saved it, is the message text: Claude Code's wrappers removed, white space folded, and saved perhaps cut short with a trailing "…". It is the clients' rule (web timeline.mjs pendingShownInHistory, iOS Timeline.swift), pinned by api/testdata/clients/terminal/saved-prompt-match.json.
Types ¶
type ACP ¶
type ACP interface {
Busy(session string) bool
// Start begins a turn; the same key returns the same turn. Errors:
// ErrNotFree, ErrInTerminal, ErrNotRunning, anything else.
Start(session, text, key string) (turn string, err error)
// TurnEnded reports whether turn is over, and whether it ended in error.
TurnEnded(session, turn string) (ended, failed bool)
}
ACP runs turns for sessions not open in a terminal (the broker).
type Auditor ¶
type Auditor interface{ Write(devicelogin.AuditEntry) }
Auditor takes audit lines (devicelogin.Audit).
type Config ¶
type Config struct {
Store *Store
ACP ACP
Terminal Terminal
TerminalEnabled bool
Audit Auditor
// Typed, if set, is told after the dispatcher typed into a terminal
// session, so a cached status is dropped.
Typed func(session string)
// NoteChanged, if set, is told when a session's waiting line (Note)
// changes. Called from Run's goroutine, outside the dispatcher's locks.
NoteChanged func(session string)
Now func() time.Time // default time.Now
After func(d time.Duration) <-chan time.Time // default time.After
}
Config is what a Dispatcher drives. Store is required; a nil ACP or Terminal leaves those sessions alone, as does TerminalEnabled false for sessions open in a terminal.
type Dispatcher ¶
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher sends each session's queued items into the session, one at a time: the next only once the answer to the one before has finished. One goroutine (Run) does all the work, so its per-session state needs no lock.
func (*Dispatcher) Kick ¶
func (d *Dispatcher) Kick()
Kick makes Run look at the queues now: after a queue change or a turn's end. It never blocks.
func (*Dispatcher) Note ¶
func (d *Dispatcher) Note(session string) string
Note is session's waiting line, "" when there is none.
func (*Dispatcher) NoteSentNow ¶
func (d *Dispatcher) NoteSentNow(session, text string, at time.Time) (forget func())
NoteSentNow records that text is about to be typed into session with Send now at at (a queued item or the composer's text), so its history turn does not pause the queue as the owner's. Taken before typing, so a read right after Enter already knows it; forget drops it when the send fails (safe to call more than once). Each call also drops every session's expired notes, so they stay bounded. Safe from any goroutine.
func (*Dispatcher) Run ¶
func (d *Dispatcher) Run(ctx context.Context)
Run works until ctx ends: every 2 s, and at once after Kick.
type Item ¶
type Item struct {
ID string `json:"id"`
Text string `json:"text"`
Key string `json:"key,omitempty"` // the client's idempotency key
Created time.Time `json:"created"`
State string `json:"state"`
}
Item is one queued message.
type Queue ¶
type Queue struct {
State string `json:"state"`
Reason string `json:"reason,omitempty"`
Items []Item `json:"items"`
}
Queue is one session's queue as clients see it.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store holds every session's queue and saves each change to its file before the change takes effect: a change that cannot be saved is refused and leaves the queue as it was. Safe for concurrent use.
func Open ¶
Open loads the queues stored at path (none when it does not exist) and starts the Changes feed; Close stops it. allowSlash lets items start with "/". A file that cannot be read or holds an unknown state is an error naming path: the caller decides, the store never starts empty silently. Items in flight when the file was written wait again in a queue paused with ReasonMaybeSent.
func (*Store) Add ¶
Add appends a waiting item. A retry with the key of an item already in the queue returns that item; with the key of one already sent or deleted, a copy in StateDone without text. Errors: ErrBadText, ErrFull.
func (*Store) BindTerminal ¶
BindTerminal records that session's queue sends through a terminal. It persists for as long as the queue holds items: a terminal queue never moves to ACP.
func (*Store) Changes ¶
Changes yields the id of each session whose queue changed. Changes made while nobody reads are coalesced per session, so the store never waits on the reader. One reader only.
func (*Store) ClaimNow ¶
ClaimNow claims a waiting item for Send now: it stays at its place and waiting, but the dispatcher cannot take it and it cannot be edited, moved or deleted until DoneNow or ReleaseNow. One claim per session at a time. The claim is saved before the caller types (SendingNow), so after a restart before DoneNow the queue pauses as "may have been sent". Errors: ErrNotFound, ErrItemSending (the item in flight or already claimed), ErrBusy (another message is being typed: an item sending, or another claim), a save failure (nothing claimed).
func (*Store) Close ¶
func (s *Store) Close()
Close stops the Changes feed and closes its channel. The store keeps working without it.
func (*Store) Delete ¶
Delete removes an item; the item in flight only while the queue is paused. Errors: ErrNotFound, ErrItemSending.
func (*Store) Done ¶
Done removes an item in flight whose answer finished. Errors: ErrNotFound, ErrWrongState.
func (*Store) DoneNow ¶
DoneNow ends a claim whose send went through: the item leaves the queue and its key is retired. A change that cannot be saved keeps the claim, so the item is never sent again before a restart. Errors: ErrWrongState (not claimed).
func (*Store) Edit ¶
Edit replaces a waiting item's text. Errors: ErrBadText, ErrNotFound, ErrItemSending.
func (*Store) MarkAnswering ¶
MarkAnswering records that a sending item was sent and its answer is running. Errors: ErrNotFound, ErrWrongState.
func (*Store) MarkSending ¶
MarkSending claims item for sending and returns it as it is now (its text may have been edited since Next): send that text. Only the item Next would return can be claimed. Text the rules no longer allow pauses the queue with ReasonNotAllowed and answers ErrBadText. Errors: ErrNotFound, ErrWrongState, ErrBadText.
func (*Store) Move ¶
Move puts a waiting item at position, 0-based among the items not in flight and clamped to them. Errors: ErrNotFound, ErrItemSending.
func (*Store) Next ¶
Next returns the item to send now: the first, when the queue runs and no item is in flight. The dispatcher claims it with MarkSending.
func (*Store) Pause ¶
Pause stops the queue with reason (the latest reason wins). Items keep their states; only Resume starts the queue again, or its last item going: a queue with no items is always running.
func (*Store) Release ¶
Release returns a sending item to waiting: the dispatcher claimed it but sent nothing (the session was not free yet). Errors: ErrNotFound, ErrWrongState.
func (*Store) ReleaseNow ¶
ReleaseNow ends a claim whose send was refused; the item waits on where it was. Clearing the saved claim is best effort: if it cannot be saved, a restart pauses the queue as "may have been sent" (never a second send).
type Terminal ¶
type Terminal interface {
// Open reports whether a terminal process holds session, and its status
// in Claude's registry ("busy", "idle" or "").
Open(session string) (registryStatus string, ok bool)
Status(ctx context.Context, session, registryStatus string) terminput.Status
Send(ctx context.Context, session, text, key string) error
// Submit presses Enter for text left in the input box (terminput.Service.Submit).
Submit(ctx context.Context, session, text string) error
// Turns returns the session's latest person turns.
Turns(ctx context.Context, session string) ([]Turn, error)
// LeftInBox reports whether the input box holds a message a send typed
// but did not submit, as of the latest screen read: it answers from
// terminput's record without reading the screen again
// (terminput.Service.LeftInBox).
LeftInBox(session string) bool
}
Terminal reaches sessions open in a terminal (terminput.Service plus Claude's registry and the session's history).