Schedule chat prompts: send_at holds a queued prompt until its time

A chat_prompt with a future send_at (epoch ms) is always queued, durable in
chat_prompt_queue (new send_at column, added to older databases on Open),
listed with send_at in chat_queue frames, and delivered by the room's runner
once the time passes, waking on a timer. The queue stays FIFO: prompts queued
after a scheduled one wait behind it. A past or zero send_at behaves as before;
chat_unqueue cancels as for any queued prompt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 00:51:06 +00:00
parent f72c46d599
commit 1ea1e5b73c
7 changed files with 258 additions and 12 deletions
+26 -7
View File
@@ -24,6 +24,9 @@ type ChatQueuedPrompt struct {
FilesJSON string
PartsJSON string
CreatedAt time.Time
// SendAt is when a scheduled prompt becomes deliverable; zero means as
// soon as the session is free.
SendAt time.Time
}
// initChatPromptQueue creates the additive queue table. A prompt belongs to
@@ -42,9 +45,15 @@ client TEXT NOT NULL DEFAULT '',
files_json TEXT NOT NULL DEFAULT '[]',
parts_json TEXT NOT NULL DEFAULT '[]',
created_at INTEGER NOT NULL,
send_at INTEGER NOT NULL DEFAULT 0,
UNIQUE(session_id, operation_id));
CREATE INDEX IF NOT EXISTS chat_prompt_queue_session ON chat_prompt_queue(session_id, id);`)
return err
if err != nil {
return err
}
// send_at (epoch ms, 0 = unscheduled) arrived after the table; an older
// database gains it with every existing row unscheduled.
return s.addColumnIfMissing("chat_prompt_queue", "send_at", "INTEGER NOT NULL DEFAULT 0")
}
// EnqueueChatPrompt appends prompt to its session's queue. When the session
@@ -81,10 +90,10 @@ func (s *Store) EnqueueChatPrompt(ctx context.Context, prompt ChatQueuedPrompt,
prompt.PartsJSON = "[]"
}
result, err := tx.ExecContext(ctx, `INSERT INTO chat_prompt_queue
(session_id, operation_id, message_id, native_message_id, text, client, files_json, parts_json, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
(session_id, operation_id, message_id, native_message_id, text, client, files_json, parts_json, created_at, send_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
prompt.SessionID, prompt.OperationID, prompt.MessageID, prompt.NativeID, prompt.Text, prompt.Client,
prompt.FilesJSON, prompt.PartsJSON, prompt.CreatedAt.UnixMilli())
prompt.FilesJSON, prompt.PartsJSON, prompt.CreatedAt.UnixMilli(), unixMilliOrZero(prompt.SendAt))
if err != nil {
return ChatQueuedPrompt{}, false, err
}
@@ -151,7 +160,7 @@ func (s *Store) ChatQueuedSessions(ctx context.Context) ([]string, error) {
return sessions, rows.Err()
}
const chatQueueSelect = `SELECT id, session_id, operation_id, message_id, native_message_id, text, client, files_json, parts_json, created_at FROM chat_prompt_queue`
const chatQueueSelect = `SELECT id, session_id, operation_id, message_id, native_message_id, text, client, files_json, parts_json, created_at, send_at FROM chat_prompt_queue`
type chatQueueScanner interface {
Scan(...any) error
@@ -159,12 +168,22 @@ type chatQueueScanner interface {
func scanChatQueuedPrompt(row chatQueueScanner) (ChatQueuedPrompt, error) {
var prompt ChatQueuedPrompt
var created int64
var created, sendAt int64
err := row.Scan(&prompt.ID, &prompt.SessionID, &prompt.OperationID, &prompt.MessageID, &prompt.NativeID,
&prompt.Text, &prompt.Client, &prompt.FilesJSON, &prompt.PartsJSON, &created)
&prompt.Text, &prompt.Client, &prompt.FilesJSON, &prompt.PartsJSON, &created, &sendAt)
if err != nil {
return ChatQueuedPrompt{}, err
}
prompt.CreatedAt = time.UnixMilli(created)
if sendAt > 0 {
prompt.SendAt = time.UnixMilli(sendAt)
}
return prompt, nil
}
func unixMilliOrZero(t time.Time) int64 {
if t.IsZero() {
return 0
}
return t.UnixMilli()
}
@@ -5,8 +5,62 @@ import (
"errors"
"path/filepath"
"testing"
"time"
)
// A database whose queue table predates send_at gains the column on Open,
// keeps its rows unscheduled, and round-trips a scheduled prompt.
func TestChatPromptQueueSendAtMigratesAndRoundTrips(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "queue.db")
store, err := Open(path)
if err != nil {
t.Fatal(err)
}
// Rebuild the table in its pre-send_at shape with one existing row.
if _, err := store.db.Exec(`DROP TABLE chat_prompt_queue;
CREATE TABLE chat_prompt_queue (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
operation_id TEXT NOT NULL,
message_id TEXT NOT NULL,
native_message_id TEXT NOT NULL DEFAULT '',
text TEXT NOT NULL,
client TEXT NOT NULL DEFAULT '',
files_json TEXT NOT NULL DEFAULT '[]',
parts_json TEXT NOT NULL DEFAULT '[]',
created_at INTEGER NOT NULL,
UNIQUE(session_id, operation_id));
INSERT INTO chat_prompt_queue (session_id, operation_id, message_id, text, created_at) VALUES ('ses_1', 'old', 'm-old', 'old', 1000);`); err != nil {
t.Fatal(err)
}
store.Close()
store, err = Open(path)
if err != nil {
t.Fatal(err)
}
at := time.UnixMilli(time.Now().Add(time.Hour).UnixMilli())
if _, created, err := store.EnqueueChatPrompt(ctx, ChatQueuedPrompt{SessionID: "ses_1", OperationID: "new", MessageID: "m-new", Text: "new", SendAt: at}, 0); err != nil || !created {
t.Fatalf("enqueue scheduled: %v %v", created, err)
}
store.Close()
store, err = Open(path) // the migration is idempotent across Opens
if err != nil {
t.Fatal(err)
}
defer store.Close()
rows, err := store.ChatQueuedPrompts(ctx, "ses_1")
if err != nil || len(rows) != 2 {
t.Fatalf("rows = %+v %v", rows, err)
}
if rows[0].OperationID != "old" || !rows[0].SendAt.IsZero() {
t.Fatalf("migrated row = %+v", rows[0])
}
if rows[1].OperationID != "new" || !rows[1].SendAt.Equal(at) {
t.Fatalf("scheduled row = %+v, want send_at %v", rows[1], at)
}
}
func TestChatPromptQueueOrderDedupeAndBound(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "queue.db")
+9
View File
@@ -539,6 +539,12 @@ type ChatPromptRequest struct {
// for a server on another machine; Data is standard base64 and the server
// writes it to a private temporary file before prompting the agent.
Attachments []ChatAttachment `json:"attachments,omitempty"`
// SendAt (epoch milliseconds) schedules the prompt: a time in the future
// always queues it, and the server delivers it once that time has passed
// and the session is otherwise free. Zero or a past time sends as usual.
// The queue stays FIFO, so prompts queued after a scheduled one wait
// behind it.
SendAt int64 `json:"send_at,omitempty"`
}
// ChatQueuedPrompt is one prompt the server holds for a session until its
@@ -552,6 +558,9 @@ type ChatQueuedPrompt struct {
Client string `json:"client,omitempty"`
Attachments []ChatPart `json:"attachments,omitempty"`
QueuedAt int64 `json:"queued_at,omitempty"`
// SendAt (epoch milliseconds) is set on a scheduled prompt: the earliest
// time the server will deliver it.
SendAt int64 `json:"send_at,omitempty"`
}
// ChatQueueFrame is a session's current server-side prompt queue, in delivery
+15 -3
View File
@@ -21,6 +21,11 @@ import (
// forwarded at once and the harness reads it at its next step. Otherwise it is
// written to the durable chat_prompt_queue and delivered in order when the turn
// ends, whether or not any client is still attached, and after a restart.
//
// A prompt with a future send_at is scheduled: it is always queued (never run
// or steered at once) and the runner delivers it once that time has passed and
// the session is free, waking on a timer rather than polling. The queue stays
// strictly FIFO, so a prompt queued after a scheduled one waits behind it.
// chatQueueBusyPoll is how often a room holding queued prompts re-checks a
// harness that reports its own turn in flight. TurnRunning performs no I/O.
@@ -81,8 +86,10 @@ func (h *chatHub) admitPrompt(ctx context.Context, sessionID string, broker chat
if room.broker == nil {
room.broker = broker
}
busy := room.running || len(room.queue) > 0 || room.observedTurn
queuedAhead := len(room.queue) > 0
// A prompt scheduled for later is always queued: never run or steered now.
scheduled := p.sendAt.After(h.clock())
busy := scheduled || room.running || len(room.queue) > 0 || room.observedTurn
queuedAhead := scheduled || len(room.queue) > 0
h.mu.Unlock()
if !busy {
busy = brokerTurnRunning(broker, sessionID)
@@ -166,6 +173,7 @@ func chatQueueRow(sessionID string, p *chatQueuedPrompt) pipeline.ChatQueuedProm
FilesJSON: string(filesJSON),
PartsJSON: string(partsJSON),
CreatedAt: p.queuedAt,
SendAt: p.sendAt,
}
}
@@ -182,6 +190,7 @@ func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) {
acked: true,
durable: true,
queuedAt: row.CreatedAt,
sendAt: row.SendAt,
}
_ = json.Unmarshal([]byte(row.PartsJSON), &p.parts)
var stored []chatStoredFile
@@ -233,7 +242,7 @@ func (h *chatHub) queueFrame(sessionID string) protocol.ChatQueueFrame {
return frame
}
for _, row := range rows {
p := &chatQueuedPrompt{text: row.Text, operationID: row.OperationID, messageID: row.MessageID, nativeID: row.NativeID, client: row.Client, queuedAt: row.CreatedAt}
p := &chatQueuedPrompt{text: row.Text, operationID: row.OperationID, messageID: row.MessageID, nativeID: row.NativeID, client: row.Client, queuedAt: row.CreatedAt, sendAt: row.SendAt}
_ = json.Unmarshal([]byte(row.PartsJSON), &p.parts)
frame.Prompts = append(frame.Prompts, p.wire())
}
@@ -252,6 +261,9 @@ func (p *chatQueuedPrompt) wire() protocol.ChatQueuedPrompt {
if !p.queuedAt.IsZero() {
out.QueuedAt = p.queuedAt.UnixMilli()
}
if !p.sendAt.IsZero() {
out.SendAt = p.sendAt.UnixMilli()
}
return out
}
+138
View File
@@ -0,0 +1,138 @@
package server
import (
"context"
"path/filepath"
"slices"
"testing"
"time"
"github.com/coder/websocket"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func sendScheduled(t *testing.T, ctx context.Context, conn *websocket.Conn, id, text, operation string, at time.Time) protocol.Message {
t.Helper()
writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: id, ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: text, OperationID: operation, Client: "Phone", SendAt: at.UnixMilli()}})
return readUntil(t, ctx, conn, protocol.ChatPrompt)
}
// A prompt scheduled for later is queued even on an idle session, listed with
// its send_at, held until that time, and a prompt queued after it waits
// behind it (FIFO).
func TestChatScheduledPromptWaitsForItsTime(t *testing.T) {
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := newChannelChat()
server := startQueueServer(t, broker, store)
conn := dialChatConn(t, server.ctx, server.srv)
at := time.Now().Add(400 * time.Millisecond)
if ack := sendScheduled(t, server.ctx, conn, "p1", "later", "op-1", at); !ack.ChatQueued {
t.Fatalf("scheduled prompt not queued: %+v", ack)
}
if ack := sendPrompt(t, server.ctx, conn, "p2", "after", "op-2"); !ack.ChatQueued {
t.Fatalf("prompt behind a scheduled one not queued: %+v", ack)
}
rows, err := store.ChatQueuedPrompts(context.Background(), "ses_1")
if err != nil || len(rows) != 2 || rows[0].SendAt.UnixMilli() != at.UnixMilli() || !rows[1].SendAt.IsZero() {
t.Fatalf("stored rows = %+v %v", rows, err)
}
writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}})
sub := readUntil(t, server.ctx, conn, protocol.ChatSubscribe)
if sub.ChatQueue == nil || len(sub.ChatQueue.Prompts) != 2 || sub.ChatQueue.Prompts[0].SendAt != at.UnixMilli() || sub.ChatQueue.Prompts[1].SendAt != 0 {
t.Fatalf("subscribe queue = %+v", sub.ChatQueue)
}
time.Sleep(150 * time.Millisecond)
if n := broker.promptCount(); n != 0 {
t.Fatalf("scheduled prompt delivered early: %v", broker.promptTexts())
}
waitFor(t, "scheduled prompt delivered", func() bool { return broker.promptCount() == 1 })
if time.Now().Before(at) {
t.Fatalf("delivered before send_at")
}
if texts := broker.promptTexts(); !slices.Equal(texts, []string{"later"}) {
t.Fatalf("delivered = %v", texts)
}
endTurn(broker)
waitFor(t, "follow-up delivered", func() bool {
return slices.Equal(broker.promptTexts(), []string{"later", "after"})
})
waitFor(t, "rows deleted", func() bool { return len(queuedOps(t, store)) == 0 })
}
// A send_at already in the past sends exactly as an unscheduled prompt.
func TestChatScheduledPromptInThePastSendsNow(t *testing.T) {
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := newChannelChat()
server := startQueueServer(t, broker, store)
conn := dialChatConn(t, server.ctx, server.srv)
if ack := sendScheduled(t, server.ctx, conn, "p1", "now", "op-1", time.Now().Add(-time.Minute)); ack.ChatQueued {
t.Fatalf("past send_at was queued: %+v", ack)
}
waitFor(t, "prompt delivered", func() bool { return broker.promptCount() == 1 })
if ops := queuedOps(t, store); len(ops) != 0 {
t.Fatalf("past send_at stored: %v", ops)
}
}
// chat_unqueue cancels a scheduled prompt: it is never delivered.
func TestChatScheduledPromptUnqueueCancels(t *testing.T) {
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
broker := newChannelChat()
server := startQueueServer(t, broker, store)
conn := dialChatConn(t, server.ctx, server.srv)
at := time.Now().Add(300 * time.Millisecond)
if ack := sendScheduled(t, server.ctx, conn, "p1", "later", "op-1", at); !ack.ChatQueued {
t.Fatalf("scheduled prompt not queued: %+v", ack)
}
writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatUnqueue, ID: "rm", ChatUnqueue: &protocol.ChatUnqueueRequest{SessionID: "ses_1", OperationID: "op-1"}})
removed := readUntil(t, server.ctx, conn, protocol.ChatUnqueue)
if removed.ChatQueue == nil || removed.ChatQueue.Removed != "op-1" || len(removed.ChatQueue.Prompts) != 0 {
t.Fatalf("unqueue reply = %+v", removed.ChatQueue)
}
time.Sleep(time.Until(at) + 200*time.Millisecond)
if n := broker.promptCount(); n != 0 {
t.Fatalf("cancelled scheduled prompt delivered: %v", broker.promptTexts())
}
if ops := queuedOps(t, store); len(ops) != 0 {
t.Fatalf("cancelled row kept: %v", ops)
}
}
// A scheduled prompt survives a restart and is delivered at its time, not at
// recovery.
func TestChatScheduledPromptSurvivesRestart(t *testing.T) {
previous := chatQueueRecoverySettle
chatQueueRecoverySettle = 10 * time.Millisecond
t.Cleanup(func() { chatQueueRecoverySettle = previous })
path := filepath.Join(t.TempDir(), "queue.db")
first := openQueueStore(t, path)
broker := newChannelChat()
server := startQueueServer(t, broker, first)
conn := dialChatConn(t, server.ctx, server.srv)
at := time.Now().Add(700 * time.Millisecond)
if ack := sendScheduled(t, server.ctx, conn, "p1", "later", "op-1", at); !ack.ChatQueued {
t.Fatalf("scheduled prompt not queued: %+v", ack)
}
server.stop()
first.Close()
reopened := openQueueStore(t, path)
rows, err := reopened.ChatQueuedPrompts(context.Background(), "ses_1")
if err != nil || len(rows) != 1 || rows[0].SendAt.UnixMilli() != at.UnixMilli() {
t.Fatalf("rows after restart = %+v %v", rows, err)
}
restarted := newChannelChat()
startQueueServer(t, restarted, reopened)
time.Sleep(100 * time.Millisecond)
if time.Now().Before(at) && restarted.promptCount() != 0 {
t.Fatalf("recovered scheduled prompt delivered early")
}
waitFor(t, "recovered scheduled prompt delivered", func() bool {
return slices.Equal(restarted.promptTexts(), []string{"later"})
})
if time.Now().Before(at) {
t.Fatalf("delivered before send_at")
}
waitFor(t, "recovered row deleted", func() bool { return len(queuedOps(t, reopened)) == 0 })
}
+9 -2
View File
@@ -120,6 +120,9 @@ type chatQueuedPrompt struct {
acked bool
durable bool
queuedAt time.Time
// sendAt schedules the prompt: the runner holds it (and, FIFO, everything
// queued behind it) until this time. Zero means deliver when free.
sendAt time.Time
}
type chatObservation struct {
@@ -777,7 +780,11 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{},
}
var wait time.Duration
if len(room.queue) > 0 {
switch {
switch now := h.clock(); {
case room.queue[0].sendAt.After(now):
// A scheduled head waits for its time; the queue is FIFO, so
// later prompts wait behind it. A timer wakes the runner then.
wait = room.queue[0].sendAt.Sub(now)
case room.observedTurn:
wait = chatQueueBusyPoll
case time.Until(room.notBefore) > 0:
@@ -789,7 +796,7 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{},
h.mu.Lock()
if busy {
wait = chatQueueBusyPoll
} else if len(room.queue) > 0 && !room.observedTurn && room.ctx.Err() == nil {
} else if len(room.queue) > 0 && !room.observedTurn && room.ctx.Err() == nil && !room.queue[0].sendAt.After(h.clock()) {
p := room.queue[0]
room.queue = room.queue[1:]
room.running = true
+7
View File
@@ -123,6 +123,13 @@ func admitChatPrompt(ctx context.Context, request protocol.Message, broker chatB
requestID: request.ID,
write: write,
}
if prompt.SendAt > 0 {
// Only a future time schedules; a past one sends exactly as an
// unscheduled prompt.
if at := time.UnixMilli(prompt.SendAt); at.After(hub.clock()) {
queuedPrompt.sendAt = at
}
}
// Claim the operation before admission so a concurrent retry of the same
// prompt is acknowledged rather than delivered twice.
hub.rememberOp(sessionID, operationID)