fix: make pending message queues manageable (#2239)

This commit is contained in:
José Almeida
2026-08-04 08:49:46 +01:00
committed by GitHub
parent 257fffdcc1
commit d6b95500eb
71 changed files with 4151 additions and 263 deletions
@@ -157,6 +157,7 @@ func provideGateway(
orchestratorSvc.GetEventBus(),
log,
orchestratorSvc,
taskSvc,
referenceValidator,
)
queueHandlers.RegisterHandlers(gateway.Dispatcher)
+1
View File
@@ -825,6 +825,7 @@ func startGatewayAndServe(
BuildTime: BuildTime,
}, systemsvc.Wiring{
OrchestratorShutdown: func() { _ = orchestratorSvc.Stop() },
MessageQueue: orchestratorSvc.GetMessageQueue(),
})
storageComposition, err := provideStorageComposition(
cfg, dbPool, systemSvc.Jobs, lifecycleMgr, services.WorktreeMgr, services.Task,
@@ -0,0 +1,56 @@
package backendapp
import (
"context"
"testing"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"github.com/kandev/kandev/internal/db"
"github.com/kandev/kandev/internal/system/queuesettings"
systemsettings "github.com/kandev/kandev/internal/system/settings"
)
func TestResolveQueueMaxPerSessionPrecedence(t *testing.T) {
tests := []struct {
name string
persisted int
env string
want int
}{
{name: "persisted setting", persisted: 6, want: 6},
{name: "environment wins", persisted: 6, env: "20", want: 20},
{name: "invalid environment falls back to setting", persisted: 6, env: "many", want: 6},
{name: "negative environment means unlimited", persisted: 6, env: "-3", want: 0},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
pool := newMessageQueueSettingsTestPool(t)
raw, err := systemsettings.NewStore(pool)
if err != nil {
t.Fatalf("new system settings store: %v", err)
}
store := queuesettings.NewStore(raw)
if err := store.Save(context.Background(), queuesettings.Settings{MaxPerSession: tc.persisted}); err != nil {
t.Fatalf("save setting: %v", err)
}
t.Setenv(queuesettings.EnvironmentVariable, tc.env)
if got := resolveQueueMaxPerSession(pool, testLogger(t)); got != tc.want {
t.Fatalf("max = %d, want %d", got, tc.want)
}
})
}
}
func newMessageQueueSettingsTestPool(t *testing.T) *db.Pool {
t.Helper()
connection, err := sqlx.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
connection.SetMaxOpenConns(1)
t.Cleanup(func() { _ = connection.Close() })
return db.NewPool(connection, connection)
}
@@ -6,9 +6,7 @@ import (
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"go.uber.org/zap"
@@ -33,6 +31,8 @@ import (
"github.com/kandev/kandev/internal/repoclone"
"github.com/kandev/kandev/internal/secrets"
sentrypkg "github.com/kandev/kandev/internal/sentry"
"github.com/kandev/kandev/internal/system/queuesettings"
systemsettings "github.com/kandev/kandev/internal/system/settings"
taskmodels "github.com/kandev/kandev/internal/task/models"
sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite"
taskservice "github.com/kandev/kandev/internal/task/service"
@@ -90,7 +90,7 @@ func provideOrchestrator(
if err != nil {
return nil, nil, fmt.Errorf("init message queue repo: %w", err)
}
maxPerSession := resolveQueueMaxPerSession(log)
maxPerSession := resolveQueueMaxPerSession(pool, log)
msgQueue := messagequeue.NewService(queueRepo, maxPerSession, log)
log.Info("Message queue initialized",
zap.Int("max_per_session", maxPerSession))
@@ -244,19 +244,30 @@ func githubCredentialBrokerEndpoint(cfg *config.Config) string {
// falling back to messagequeue.DefaultMaxPerSession (10) when unset or invalid.
// Values <= 0 disable the cap entirely (callers can still flood queues — only
// useful in tests / specialized deployments).
func resolveQueueMaxPerSession(log *logger.Logger) int {
raw := strings.TrimSpace(os.Getenv("KANDEV_QUEUE_MAX_PER_SESSION"))
if raw == "" {
return messagequeue.DefaultMaxPerSession
func resolveQueueMaxPerSession(pool *db.Pool, log *logger.Logger) int {
var configured *queuesettings.Settings
if pool != nil {
rawStore, err := systemsettings.NewStore(pool)
if err != nil {
log.Warn("Failed to initialize message queue settings store", zap.Error(err))
} else {
configured, err = queuesettings.NewStore(rawStore).Load(context.Background())
if err != nil {
log.Warn("Ignoring invalid persisted message queue settings", zap.Error(err))
configured = nil
}
}
}
n, err := strconv.Atoi(raw)
resolution, err := queuesettings.Resolve(configured, queuesettings.ReadEnvironment())
if err != nil {
log.Warn("KANDEV_QUEUE_MAX_PER_SESSION is not a number, using default",
zap.String("value", raw),
zap.Int("default", messagequeue.DefaultMaxPerSession))
log.Warn("Failed to resolve message queue capacity, using default", zap.Error(err))
return messagequeue.DefaultMaxPerSession
}
return n
if resolution.InvalidEnvironment {
log.Warn("Ignoring invalid message queue capacity environment value",
zap.String("environment_variable", queuesettings.EnvironmentVariable))
}
return resolution.Effective.MaxPerSession
}
func resolveEventNamespace(cfg *config.Config) string {
@@ -111,38 +111,9 @@ func (s *Service) requeueMessage(ctx context.Context, queuedMsg *messagequeue.Qu
s.requeueLifecycleMessage(ctx, queuedMsg, queuedBy, coalesceKey)
return
}
var (
requeuedMsg *messagequeue.QueuedMessage
replaced bool
queueErr error
requeuedMsg, replaced, queueErr := s.messageQueue.RequeueMessage(
ctx, queuedMsg, queuedBy, coalesceKey,
)
if coalesceKey != "" {
requeuedMsg, replaced, queueErr = s.messageQueue.QueueMessageWithCoalesceKey(
ctx,
queuedMsg.SessionID,
queuedMsg.TaskID,
queuedMsg.Content,
queuedMsg.Model,
queuedBy,
queuedMsg.PlanMode,
queuedMsg.Attachments,
queuedMsg.Metadata,
coalesceKey,
true,
)
} else {
requeuedMsg, queueErr = s.messageQueue.QueueMessageWithMetadata(
ctx,
queuedMsg.SessionID,
queuedMsg.TaskID,
queuedMsg.Content,
queuedMsg.Model,
queuedBy,
queuedMsg.PlanMode,
queuedMsg.Attachments,
queuedMsg.Metadata,
)
}
if queueErr != nil {
s.logger.Error("failed to requeue message",
zap.String("session_id", queuedMsg.SessionID),
@@ -709,10 +709,10 @@ func TestDispatchTaskPRAgentPrompt_ArchivePurgesBusyAcceptedLifecycleEntry(t *te
}
}
// Lifecycle rows are server-owned: an untrusted client cannot remove one by
// guessing its ID, but the task-deletion path has privileged authority to
// purge it together with the task so no orphan work survives.
func TestHandleTaskDeleted_PrivilegedCleanupPurgesLifecycleRowsWithoutClientDeleteAuthority(t *testing.T) {
// Pending lifecycle rows are visible and cancellable by an authorized session
// owner. Task deletion independently purges any remaining lifecycle work so no
// orphan prompt survives after the task is gone.
func TestHandleTaskDeleted_PurgesLifecycleRowsAfterUserCancellation(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedSession(t, repo, "t1", "s1", "step1")
@@ -724,8 +724,17 @@ func TestHandleTaskDeleted_PrivilegedCleanupPurgesLifecycleRowsWithoutClientDele
if err != nil || !accepted {
t.Fatalf("queue lifecycle prompt: accepted=%v err=%v", accepted, err)
}
if err := svc.messageQueue.RemoveEntry(ctx, "s1", queued.ID); !errors.Is(err, messagequeue.ErrEntryNotFound) {
t.Fatalf("client lifecycle removal error = %v, want ErrEntryNotFound", err)
if err := svc.messageQueue.RemoveEntry(ctx, "s1", queued.ID); err != nil {
t.Fatalf("remove visible lifecycle row: %v", err)
}
if got := svc.messageQueue.GetStatus(ctx, "s1").Count; got != 0 {
t.Fatalf("user cancellation retained %d lifecycle queue rows, want 0", got)
}
if _, _, accepted, err := svc.messageQueue.QueueLifecycleMessageWithCoalesceKey(
ctx, "s1", "t1", "remaining lifecycle prompt", "", messagequeue.QueuedByWorkflow,
false, nil, map[string]interface{}{"origin": githubPRAutomationOrigin}, "github-pr:repo:2:merged", true,
); err != nil || !accepted {
t.Fatalf("queue lifecycle prompt for task cleanup: accepted=%v err=%v", accepted, err)
}
if err := repo.DeleteTask(ctx, "t1"); err != nil {
t.Fatalf("delete task: %v", err)
@@ -26,6 +26,7 @@ const (
// rejected atomically instead of dropping persisted references.
queueErrorCodeMergeReferenceOverflow = "merge_reference_overflow"
queueInvalidReferences = "Invalid entity references"
queueAccessDenied = "Session not found"
// Payload field names — extracted to satisfy goconst (≥3 occurrences).
fieldSessionID = "session_id"
@@ -51,10 +52,17 @@ type QueueDrainer interface {
DrainQueuedMessage(ctx context.Context, sessionID string) (bool, error)
}
// QueueAccessAuthorizer scopes queue reads and mutations to visible sessions.
type QueueAccessAuthorizer interface {
AuthorizeSessionAccess(ctx context.Context, sessionID string) error
AuthorizeTaskSessionAccess(ctx context.Context, taskID, sessionID string) error
}
// QueueHandlers handles WebSocket message-queue operations.
type QueueHandlers struct {
queueService QueueService
queueDrainer QueueDrainer
accessAuthorizer QueueAccessAuthorizer
eventBus bus.EventBus
logger *logger.Logger
referenceValidator entityrefs.SubmissionValidator
@@ -66,6 +74,7 @@ func NewQueueHandlers(
eventBus bus.EventBus,
log *logger.Logger,
queueDrainer QueueDrainer,
accessAuthorizer QueueAccessAuthorizer,
validators ...entityrefs.SubmissionValidator,
) *QueueHandlers {
var referenceValidator entityrefs.SubmissionValidator
@@ -75,6 +84,7 @@ func NewQueueHandlers(
return &QueueHandlers{
queueService: queueService,
queueDrainer: queueDrainer,
accessAuthorizer: accessAuthorizer,
eventBus: eventBus,
logger: log.WithFields(zap.String("component", "queue-handlers")),
referenceValidator: referenceValidator,
@@ -116,6 +126,9 @@ func (h *QueueHandlers) wsQueueMessage(ctx context.Context, msg *ws.Message) (*w
if req.TaskID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
}
if denied := h.authorizeTaskSession(ctx, msg, req.TaskID, req.SessionID); denied != nil {
return denied, nil
}
if req.Content == "" && len(req.Attachments) == 0 {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "content or attachments are required", nil)
}
@@ -171,6 +184,9 @@ func (h *QueueHandlers) wsCancelAll(ctx context.Context, msg *ws.Message) (*ws.M
if req.SessionID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
}
if denied := h.authorizeSession(ctx, msg, req.SessionID); denied != nil {
return denied, nil
}
removed, err := h.queueService.CancelAll(ctx, req.SessionID)
if err != nil {
@@ -196,6 +212,9 @@ func (h *QueueHandlers) wsDrainQueue(ctx context.Context, msg *ws.Message) (*ws.
if req.SessionID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
}
if denied := h.authorizeSession(ctx, msg, req.SessionID); denied != nil {
return denied, nil
}
if h.queueDrainer == nil {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Queue drain is unavailable", nil)
}
@@ -233,6 +252,9 @@ func (h *QueueHandlers) wsGetQueueStatus(ctx context.Context, msg *ws.Message) (
if req.SessionID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
}
if denied := h.authorizeSession(ctx, msg, req.SessionID); denied != nil {
return denied, nil
}
status := h.queueService.GetStatus(ctx, req.SessionID)
return ws.NewResponse(msg.ID, msg.Action, status)
@@ -257,6 +279,9 @@ func (h *QueueHandlers) wsUpdateMessage(ctx context.Context, msg *ws.Message) (*
// connected clients; without it they'd be left with a stale view.
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
}
if denied := h.authorizeSession(ctx, msg, req.SessionID); denied != nil {
return denied, nil
}
if req.EntryID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "entry_id is required", nil)
}
@@ -345,13 +370,16 @@ func (h *QueueHandlers) wsRemoveEntry(ctx context.Context, msg *ws.Message) (*ws
// Required so publishStatus can broadcast the post-removal list.
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
}
if denied := h.authorizeSession(ctx, msg, req.SessionID); denied != nil {
return denied, nil
}
if req.EntryID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "entry_id is required", nil)
}
if err := h.queueService.RemoveEntry(ctx, req.SessionID, req.EntryID); err != nil {
if errors.Is(err, messagequeue.ErrEntryNotFound) {
return ws.NewError(msg.ID, msg.Action, queueErrorCodeEntryNotFound, "Queue entry was already drained or not owned by caller", nil)
return ws.NewError(msg.ID, msg.Action, queueErrorCodeEntryNotFound, "Queue entry is no longer pending", nil)
}
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
}
@@ -381,6 +409,9 @@ func (h *QueueHandlers) wsMergeIntoAbove(ctx context.Context, msg *ws.Message) (
// Required so publishStatus can broadcast the post-merge list.
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
}
if denied := h.authorizeSession(ctx, msg, req.SessionID); denied != nil {
return denied, nil
}
if req.EntryID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "entry_id is required", nil)
}
@@ -434,6 +465,9 @@ func (h *QueueHandlers) wsAppendToQueue(ctx context.Context, msg *ws.Message) (*
if req.TaskID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
}
if denied := h.authorizeTaskSession(ctx, msg, req.TaskID, req.SessionID); denied != nil {
return denied, nil
}
if req.Content == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "content is required", nil)
}
@@ -473,6 +507,35 @@ func reservedIdentityError(queuedBy string) string {
return "user_id may not impersonate a reserved identity"
}
func (h *QueueHandlers) authorizeSession(ctx context.Context, msg *ws.Message, sessionID string) *ws.Message {
if h.accessAuthorizer == nil {
return queueAccessDeniedResponse(msg)
}
if err := h.accessAuthorizer.AuthorizeSessionAccess(ctx, sessionID); err != nil {
return queueAccessDeniedResponse(msg)
}
return nil
}
func (h *QueueHandlers) authorizeTaskSession(
ctx context.Context,
msg *ws.Message,
taskID, sessionID string,
) *ws.Message {
if h.accessAuthorizer == nil {
return queueAccessDeniedResponse(msg)
}
if err := h.accessAuthorizer.AuthorizeTaskSessionAccess(ctx, taskID, sessionID); err != nil {
return queueAccessDeniedResponse(msg)
}
return nil
}
func queueAccessDeniedResponse(msg *ws.Message) *ws.Message {
response, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, queueAccessDenied, nil)
return response
}
// publishStatus emits the latest QueueStatus on the event bus so the frontend
// updates its store after every mutation.
func (h *QueueHandlers) publishStatus(ctx context.Context, sessionID string) {
@@ -19,9 +19,12 @@ import (
)
// mockEventBus is a no-op event bus for handler tests.
type mockEventBus struct{}
type mockEventBus struct {
published int
}
func (m *mockEventBus) Publish(_ context.Context, _ string, _ *bus.Event) error {
m.published++
return nil
}
func (m *mockEventBus) Subscribe(_ string, _ bus.EventHandler) (bus.Subscription, error) {
@@ -36,6 +39,30 @@ func (m *mockEventBus) Request(_ context.Context, _ string, _ *bus.Event, _ time
func (m *mockEventBus) Close() {}
func (m *mockEventBus) IsConnected() bool { return true }
type allowQueueAccess struct{}
func (allowQueueAccess) AuthorizeSessionAccess(context.Context, string) error { return nil }
func (allowQueueAccess) AuthorizeTaskSessionAccess(context.Context, string, string) error {
return nil
}
type fakeQueueAccessAuthorizer struct {
sessionErr error
pairErr error
sessionCalls int
pairCalls int
}
func (f *fakeQueueAccessAuthorizer) AuthorizeSessionAccess(context.Context, string) error {
f.sessionCalls++
return f.sessionErr
}
func (f *fakeQueueAccessAuthorizer) AuthorizeTaskSessionAccess(context.Context, string, string) error {
f.pairCalls++
return f.pairErr
}
type mockQueueDrainer struct {
calls int
sessionID string
@@ -81,7 +108,7 @@ func setupQueueHandlersWithDrainer(t *testing.T, drainer QueueDrainer) (*QueueHa
})
require.NoError(t, err)
svc := messagequeue.NewServiceMemory(log)
return NewQueueHandlers(svc, &mockEventBus{}, log, drainer), svc
return NewQueueHandlers(svc, &mockEventBus{}, log, drainer, allowQueueAccess{}), svc
}
func setupQueueHandlersWithValidator(t *testing.T, validator entityrefs.SubmissionValidator) (*QueueHandlers, *messagequeue.Service) {
@@ -93,7 +120,7 @@ func setupQueueHandlersWithValidator(t *testing.T, validator entityrefs.Submissi
})
require.NoError(t, err)
svc := messagequeue.NewServiceMemory(log)
return NewQueueHandlers(svc, &mockEventBus{}, log, nil, validator), svc
return NewQueueHandlers(svc, &mockEventBus{}, log, nil, allowQueueAccess{}, validator), svc
}
func createTestMessage(t *testing.T, action string, payload interface{}) *ws.Message {
@@ -115,6 +142,87 @@ func parseError(t *testing.T, response *ws.Message) ws.ErrorPayload {
return errorPayload
}
func TestQueueHandlersDenyUnauthorizedSessionActions(t *testing.T) {
tests := []struct {
name string
action string
call func(*QueueHandlers, context.Context, *ws.Message) (*ws.Message, error)
body func(string) map[string]interface{}
}{
{name: "clear", action: ws.ActionMessageQueueCancel, call: (*QueueHandlers).wsCancelAll, body: func(string) map[string]interface{} { return map[string]interface{}{"session_id": "s"} }},
{name: "get", action: ws.ActionMessageQueueGet, call: (*QueueHandlers).wsGetQueueStatus, body: func(string) map[string]interface{} { return map[string]interface{}{"session_id": "s"} }},
{name: "update", action: ws.ActionMessageQueueUpdate, call: (*QueueHandlers).wsUpdateMessage, body: func(id string) map[string]interface{} {
return map[string]interface{}{"session_id": "s", "entry_id": id, "content": "changed"}
}},
{name: "drain", action: ws.ActionMessageQueueDrain, call: (*QueueHandlers).wsDrainQueue, body: func(string) map[string]interface{} { return map[string]interface{}{"session_id": "s"} }},
{name: "remove", action: ws.ActionMessageQueueRemove, call: (*QueueHandlers).wsRemoveEntry, body: func(id string) map[string]interface{} {
return map[string]interface{}{"session_id": "s", "entry_id": id}
}},
{name: "merge", action: ws.ActionMessageQueueMerge, call: (*QueueHandlers).wsMergeIntoAbove, body: func(id string) map[string]interface{} {
return map[string]interface{}{"session_id": "s", "entry_id": id}
}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console", OutputPath: "stderr"})
require.NoError(t, err)
svc := messagequeue.NewServiceMemory(log)
_, err = svc.QueueMessage(context.Background(), "s", "t", "first", "", messagequeue.QueuedByUser, false, nil)
require.NoError(t, err)
second, err := svc.QueueMessage(context.Background(), "s", "t", "second", "", messagequeue.QueuedByUser, false, nil)
require.NoError(t, err)
access := &fakeQueueAccessAuthorizer{sessionErr: errors.New("secret denial")}
events := &mockEventBus{}
drainer := &mockQueueDrainer{drained: true}
handlers := NewQueueHandlers(svc, events, log, drainer, access)
response, err := tc.call(handlers, context.Background(), createTestMessage(t, tc.action, tc.body(second.ID)))
require.NoError(t, err)
assert.Equal(t, ws.MessageTypeError, response.Type)
assert.Equal(t, ws.ErrorCodeNotFound, parseError(t, response).Code)
assert.NotContains(t, string(response.Payload), "secret denial")
assert.Equal(t, 1, access.sessionCalls)
assert.Equal(t, 0, access.pairCalls)
assert.Equal(t, 0, events.published)
assert.Equal(t, 0, drainer.calls)
assert.Equal(t, 2, svc.GetStatus(context.Background(), "s").Count)
})
}
}
func TestQueueHandlersDenyUnauthorizedTaskSessionPairActions(t *testing.T) {
for _, tc := range []struct {
name string
action string
call func(*QueueHandlers, context.Context, *ws.Message) (*ws.Message, error)
}{
{name: "add", action: ws.ActionMessageQueueAdd, call: (*QueueHandlers).wsQueueMessage},
{name: "append", action: ws.ActionMessageQueueAppend, call: (*QueueHandlers).wsAppendToQueue},
} {
t.Run(tc.name, func(t *testing.T) {
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console", OutputPath: "stderr"})
require.NoError(t, err)
svc := messagequeue.NewServiceMemory(log)
access := &fakeQueueAccessAuthorizer{pairErr: errors.New("secret denial")}
events := &mockEventBus{}
handlers := NewQueueHandlers(svc, events, log, nil, access)
response, err := tc.call(handlers, context.Background(), createTestMessage(t, tc.action, map[string]interface{}{
"session_id": "s", "task_id": "other-task", "content": "secret",
}))
require.NoError(t, err)
assert.Equal(t, ws.MessageTypeError, response.Type)
assert.Equal(t, ws.ErrorCodeNotFound, parseError(t, response).Code)
assert.NotContains(t, string(response.Payload), "secret denial")
assert.Equal(t, 0, access.sessionCalls)
assert.Equal(t, 1, access.pairCalls)
assert.Equal(t, 0, events.published)
assert.Equal(t, 0, svc.GetStatus(context.Background(), "s").Count)
})
}
}
func TestWsQueueMessage(t *testing.T) {
t.Run("queues a message", func(t *testing.T) {
handlers, _ := setupQueueHandlers(t)
@@ -729,7 +837,7 @@ func TestWsRemoveEntry(t *testing.T) {
assert.Equal(t, "entry_not_found", parseError(t, response).Code)
})
t.Run("returns entry_not_found for agent-authored entries", func(t *testing.T) {
t.Run("removes agent-authored entries", func(t *testing.T) {
handlers, svc := setupQueueHandlers(t)
ctx := context.Background()
@@ -742,15 +850,13 @@ func TestWsRemoveEntry(t *testing.T) {
"entry_id": queued.ID,
}))
require.NoError(t, err)
assert.Equal(t, ws.MessageTypeError, response.Type)
assert.Equal(t, "entry_not_found", parseError(t, response).Code)
assert.Equal(t, ws.MessageTypeResponse, response.Type)
status := svc.GetStatus(ctx, "s")
assert.Equal(t, 1, status.Count)
assert.Equal(t, "agent prompt", status.Entries[0].Content)
assert.Equal(t, 0, status.Count)
})
t.Run("returns entry_not_found for workflow-authored entries", func(t *testing.T) {
t.Run("removes workflow-authored entries", func(t *testing.T) {
handlers, svc := setupQueueHandlers(t)
ctx := context.Background()
@@ -766,11 +872,10 @@ func TestWsRemoveEntry(t *testing.T) {
"entry_id": queued.ID,
}))
require.NoError(t, err)
assert.Equal(t, ws.MessageTypeError, response.Type)
assert.Equal(t, ws.MessageTypeResponse, response.Type)
status := svc.GetStatus(ctx, "s")
require.Equal(t, 1, status.Count)
assert.Equal(t, "lifecycle prompt", status.Entries[0].Content)
assert.Equal(t, 0, status.Count)
})
t.Run("rejects missing session_id", func(t *testing.T) {
@@ -96,12 +96,13 @@ type Repository interface {
// is mandatory so a caller can't delete an entry by guessing its UUID across
// sessions — the queue_full MCP payload deliberately discloses sibling-task
// entry IDs, so without this guard a hostile agent could prune another
// task's queue. Server-owned entries are immutable from this path and
// return ErrEntryNotFound.
// task's queue. A durable lifecycle entry already reserved in flight is not
// pending and returns ErrEntryNotFound.
DeleteByID(ctx context.Context, sessionID, entryID string) error
// DeleteAllBySession removes every user-owned entry for a session. Reserved
// agent/workflow/server entries remain. Returns the count removed.
// DeleteAllBySession removes every pending entry for a session, regardless
// of provenance. Durable lifecycle entries already reserved in flight remain.
// Returns the exact count removed.
DeleteAllBySession(ctx context.Context, sessionID string) (int, error)
// TransferSession moves all entries (and any pending move) from oldSessionID
@@ -421,7 +421,7 @@ func (r *memoryRepository) DeleteByID(_ context.Context, sessionID, entryID stri
if m.ID != entryID {
continue
}
if IsReservedQueuedBy(m.QueuedBy) {
if m.IsReservedInFlight() {
return ErrEntryNotFound
}
r.entries[sessionID] = append(list[:i], list[i+1:]...)
@@ -441,7 +441,7 @@ func (r *memoryRepository) DeleteAllBySession(_ context.Context, sessionID strin
kept := list[:0]
removed := 0
for _, msg := range list {
if IsReservedQueuedBy(msg.QueuedBy) {
if msg.IsReservedInFlight() {
kept = append(kept, msg)
continue
}
@@ -102,3 +102,32 @@ func TestPostgresRepository_MergeIntoAbove_ReferenceOverflow(t *testing.T) {
t.Errorf("count after rejected overflow merge = %d, want 2", count)
}
}
func TestPostgresRepository_CancellationIncludesAllOriginsAndPreservesReservation(t *testing.T) {
repo := newTestPostgresRepo(t)
ctx := context.Background()
reservedEntry := insertDurableLifecycleEntry(t, repo, "s1")
reserved, err := repo.ReserveHead(ctx, "s1")
if err != nil || reserved == nil {
t.Fatalf("reserve lifecycle entry: msg=%+v err=%v", reserved, err)
}
for _, queuedBy := range []string{QueuedByUser, QueuedByAgent, QueuedByWorkflow, QueuedByServer} {
if err := repo.Insert(ctx, &QueuedMessage{
SessionID: "s1", TaskID: "t1", Content: queuedBy, QueuedBy: queuedBy,
}, 0); err != nil {
t.Fatalf("insert %s entry: %v", queuedBy, err)
}
}
removed, err := repo.DeleteAllBySession(ctx, "s1")
if err != nil {
t.Fatalf("clear queue: %v", err)
}
if removed != 4 {
t.Fatalf("removed = %d, want 4", removed)
}
if err := repo.AcknowledgeByID(ctx, "s1", reservedEntry.ID); err != nil {
t.Fatalf("reserved entry did not survive clear: %v", err)
}
}
@@ -605,7 +605,7 @@ func (r *sqliteRepository) ReserveHead(ctx context.Context, sessionID string) (*
ORDER BY position ASC
LIMIT 1
`), sessionID)
msg, err := scanQueuedRow(row)
msg, storedMetadataJSON, err := scanQueuedRowWithMetadataJSON(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
@@ -621,11 +621,20 @@ func (r *sqliteRepository) ReserveHead(ctx context.Context, sessionID string) (*
if err != nil {
return nil, err
}
if _, err := tx.ExecContext(ctx, r.db.Rebind(`
UPDATE queued_messages SET metadata_json = ? WHERE id = ? AND session_id = ?
`), reservedJSON, msg.ID, sessionID); err != nil {
res, err := tx.ExecContext(ctx, r.db.Rebind(`
UPDATE queued_messages SET metadata_json = ?
WHERE id = ? AND session_id = ? AND metadata_json = ?
`), reservedJSON, msg.ID, sessionID, storedMetadataJSON)
if err != nil {
return nil, fmt.Errorf("mark lifecycle reservation in flight: %w", err)
}
affected, err := res.RowsAffected()
if err != nil {
return nil, fmt.Errorf("mark lifecycle reservation rows affected: %w", err)
}
if affected == 0 {
return nil, nil
}
if err := tx.Commit(); err != nil {
return nil, err
}
@@ -923,12 +932,37 @@ func applyMergeWrites(ctx context.Context, r *sqliteRepository, tx *sqlx.Tx, tar
}
func (r *sqliteRepository) DeleteByID(ctx context.Context, sessionID, entryID string) error {
res, err := r.db.ExecContext(ctx, r.db.Rebind(`
unlock := r.withSessionLock(sessionID)
defer unlock()
tx, err := r.db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("begin delete queued tx: %w", err)
}
defer func() { _ = tx.Rollback() }()
var metadataJSON string
err = tx.GetContext(ctx, &metadataJSON, r.db.Rebind(`
SELECT metadata_json FROM queued_messages WHERE id = ? AND session_id = ?
`), entryID, sessionID)
if errors.Is(err, sql.ErrNoRows) {
return ErrEntryNotFound
}
if err != nil {
return fmt.Errorf("read queued cancellation candidate: %w", err)
}
reserved, err := isReservedMetadataJSON(metadataJSON)
if err != nil {
return err
}
if reserved {
return ErrEntryNotFound
}
res, err := tx.ExecContext(ctx, r.db.Rebind(`
DELETE FROM queued_messages
WHERE id = ?
AND session_id = ?
AND queued_by NOT IN (?, ?, ?)
`), entryID, sessionID, QueuedByAgent, QueuedByWorkflow, QueuedByServer)
WHERE id = ? AND session_id = ? AND metadata_json = ?
`), entryID, sessionID, metadataJSON)
if err != nil {
return fmt.Errorf("delete queued: %w", err)
}
@@ -939,19 +973,90 @@ func (r *sqliteRepository) DeleteByID(ctx context.Context, sessionID, entryID st
if n == 0 {
return ErrEntryNotFound
}
return nil
return tx.Commit()
}
func (r *sqliteRepository) DeleteAllBySession(ctx context.Context, sessionID string) (int, error) {
res, err := r.db.ExecContext(ctx, r.db.Rebind(`
DELETE FROM queued_messages
WHERE session_id = ? AND queued_by NOT IN (?, ?, ?)
`), sessionID, QueuedByAgent, QueuedByWorkflow, QueuedByServer)
unlock := r.withSessionLock(sessionID)
defer unlock()
tx, err := r.db.BeginTxx(ctx, nil)
if err != nil {
return 0, fmt.Errorf("delete all queued: %w", err)
return 0, fmt.Errorf("begin delete all queued tx: %w", err)
}
n, err := res.RowsAffected()
return int(n), err
defer func() { _ = tx.Rollback() }()
candidates, err := cancellationCandidates(ctx, tx, sessionID)
if err != nil {
return 0, err
}
removed := 0
for _, candidate := range candidates {
res, err := tx.ExecContext(ctx, r.db.Rebind(`
DELETE FROM queued_messages
WHERE id = ? AND session_id = ? AND metadata_json = ?
`), candidate.id, sessionID, candidate.metadataJSON)
if err != nil {
return 0, fmt.Errorf("delete queued candidate: %w", err)
}
affected, err := res.RowsAffected()
if err != nil {
return 0, fmt.Errorf("delete queued candidate rows affected: %w", err)
}
removed += int(affected)
}
if err := tx.Commit(); err != nil {
return 0, err
}
return removed, nil
}
type cancellationCandidate struct {
id string
metadataJSON string
}
func cancellationCandidates(
ctx context.Context,
tx *sqlx.Tx,
sessionID string,
) ([]cancellationCandidate, error) {
rows, err := tx.QueryxContext(ctx, tx.Rebind(`
SELECT id, metadata_json FROM queued_messages WHERE session_id = ?
`), sessionID)
if err != nil {
return nil, fmt.Errorf("list queued cancellation candidates: %w", err)
}
defer func() { _ = rows.Close() }()
candidates := make([]cancellationCandidate, 0)
for rows.Next() {
var candidate cancellationCandidate
if err := rows.Scan(&candidate.id, &candidate.metadataJSON); err != nil {
return nil, fmt.Errorf("scan queued cancellation candidate: %w", err)
}
reserved, err := isReservedMetadataJSON(candidate.metadataJSON)
if err != nil {
return nil, err
}
if !reserved {
candidates = append(candidates, candidate)
}
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate queued cancellation candidates: %w", err)
}
return candidates, nil
}
func isReservedMetadataJSON(metadataJSON string) (bool, error) {
metadata := make(map[string]interface{})
if metadataJSON != "" && metadataJSON != "{}" {
if err := json.Unmarshal([]byte(metadataJSON), &metadata); err != nil {
return false, fmt.Errorf("unmarshal cancellation metadata: %w", err)
}
}
return (&QueuedMessage{Metadata: metadata}).IsReservedInFlight(), nil
}
func (r *sqliteRepository) TransferSession(ctx context.Context, oldSessionID, newSessionID string) error {
@@ -1176,6 +1281,13 @@ func (r *sqliteRepository) findCoalesced(ctx context.Context, tx *sqlx.Tx, sessi
// scanQueuedRow scans a single queued_messages row from any sqlx-compatible row source.
func scanQueuedRow(scanner interface{ Scan(dest ...any) error }) (*QueuedMessage, error) {
msg, _, err := scanQueuedRowWithMetadataJSON(scanner)
return msg, err
}
func scanQueuedRowWithMetadataJSON(
scanner interface{ Scan(dest ...any) error },
) (*QueuedMessage, string, error) {
var (
msg QueuedMessage
planModeInt int
@@ -1185,20 +1297,20 @@ func scanQueuedRow(scanner interface{ Scan(dest ...any) error }) (*QueuedMessage
&msg.ID, &msg.SessionID, &msg.TaskID, &msg.Position, &msg.Content, &msg.Model,
&planModeInt, &attachmentsJSON, &metaJSON, &msg.QueuedAt, &msg.QueuedBy,
); err != nil {
return nil, err
return nil, "", err
}
msg.PlanMode = planModeInt != 0
if attachmentsJSON != "" && attachmentsJSON != "[]" {
if err := json.Unmarshal([]byte(attachmentsJSON), &msg.Attachments); err != nil {
return nil, fmt.Errorf("unmarshal attachments: %w", err)
return nil, "", fmt.Errorf("unmarshal attachments: %w", err)
}
}
if metaJSON != "" && metaJSON != "{}" {
if err := json.Unmarshal([]byte(metaJSON), &msg.Metadata); err != nil {
return nil, fmt.Errorf("unmarshal metadata: %w", err)
return nil, "", fmt.Errorf("unmarshal metadata: %w", err)
}
}
return &msg, nil
return &msg, metaJSON, nil
}
func marshalAttachments(att []MessageAttachment) (string, error) {
@@ -150,6 +150,50 @@ func TestSQLiteRepository_ReserveHeadMarksLifecycleRowInFlight(t *testing.T) {
}
}
func TestSQLiteRepository_ReserveHeadUsesStoredMetadataGuard(t *testing.T) {
repo := newTestSQLiteRepo(t)
ctx := context.Background()
msg := &QueuedMessage{
SessionID: "s1", TaskID: "t1", Content: "pr merged", QueuedBy: QueuedByWorkflow,
Metadata: map[string]interface{}{
MetadataLifecycleDurable: true,
"priority": float64(1),
},
}
if err := repo.Insert(ctx, msg, 0); err != nil {
t.Fatalf("insert: %v", err)
}
sqliteRepo, ok := repo.(*sqliteRepository)
if !ok {
t.Fatalf("repository type = %T, want *sqliteRepository", repo)
}
const storedMetadata = `{ "priority": 1.0, "lifecycle_durable_until_accepted": true }`
if _, err := sqliteRepo.db.ExecContext(ctx, sqliteRepo.db.Rebind(`
UPDATE queued_messages SET metadata_json = ? WHERE id = ?
`), storedMetadata, msg.ID); err != nil {
t.Fatalf("rewrite metadata representation: %v", err)
}
reserved, err := repo.ReserveHead(ctx, "s1")
if err != nil {
t.Fatalf("reserve: %v", err)
}
if reserved == nil {
t.Fatal("reserve returned nil for semantically valid non-canonical metadata JSON")
}
if !reserved.IsReservedLifecycleDelivery() {
t.Fatal("reserved copy lost process-local lifecycle reservation evidence")
}
entries, err := repo.ListBySession(ctx, "s1")
if err != nil {
t.Fatalf("list: %v", err)
}
if len(entries) != 1 || !entries[0].IsReservedInFlight() {
t.Fatalf("stored row was not marked in flight: %+v", entries)
}
}
func TestSQLiteRepository_ReserveAfterRestartReturnsRetryableLifecycleMetadata(t *testing.T) {
ctx := context.Background()
dbPath := filepath.Join(t.TempDir(), "queue.db")
@@ -430,16 +474,16 @@ func TestSQLiteRepository_DeleteByID(t *testing.T) {
if err := repo.Insert(ctx, agentMsg, 0); err != nil {
t.Fatalf("insert agent message: %v", err)
}
if err := repo.DeleteByID(ctx, "s1", agentMsg.ID); !errors.Is(err, ErrEntryNotFound) {
t.Errorf("expected ErrEntryNotFound for agent-authored entry delete, got %v", err)
if err := repo.DeleteByID(ctx, "s1", agentMsg.ID); err != nil {
t.Errorf("delete agent-authored entry: %v", err)
}
count, _ = repo.CountBySession(ctx, "s1")
if count != 1 {
t.Errorf("agent-authored entry should survive delete attempt, got count=%d", count)
if count != 0 {
t.Errorf("agent-authored entry should be deleted, got count=%d", count)
}
}
func TestSQLiteRepository_ClientMutationsRejectWorkflowOwnedEntry(t *testing.T) {
func TestSQLiteRepository_WorkflowEntryCanBeRemovedButNotEdited(t *testing.T) {
repo := newTestSQLiteRepo(t)
ctx := context.Background()
@@ -459,19 +503,105 @@ func TestSQLiteRepository_ClientMutationsRejectWorkflowOwnedEntry(t *testing.T)
); !errors.Is(err, ErrEntryNotFound) {
t.Errorf("workflow-owned update error = %v, want ErrEntryNotFound", err)
}
if err := repo.DeleteByID(ctx, "s1", msg.ID); !errors.Is(err, ErrEntryNotFound) {
t.Errorf("workflow-owned delete error = %v, want ErrEntryNotFound", err)
if err := repo.DeleteByID(ctx, "s1", msg.ID); err != nil {
t.Errorf("workflow-owned delete error = %v", err)
}
entries, err := repo.ListBySession(ctx, "s1")
if err != nil {
t.Fatalf("list workflow entries: %v", err)
}
if len(entries) != 1 || entries[0].Content != "lifecycle prompt" {
t.Fatalf("workflow entry changed after hostile mutations: %+v", entries)
if len(entries) != 0 {
t.Fatalf("workflow entry survived removal: %+v", entries)
}
}
func TestSQLiteRepository_DeletePreservesReservedLifecycleEntry(t *testing.T) {
repo := newTestSQLiteRepo(t)
ctx := context.Background()
msg := &QueuedMessage{
SessionID: "s1",
TaskID: "t1",
Content: "lifecycle prompt",
QueuedBy: QueuedByWorkflow,
Metadata: map[string]interface{}{
MetadataLifecycleDurable: true,
"origin": "github_pr_automation",
},
}
if err := repo.Insert(ctx, msg, 0); err != nil {
t.Fatalf("insert workflow entry: %v", err)
}
reserved, err := repo.ReserveHead(ctx, "s1")
if err != nil || reserved == nil {
t.Fatalf("reserve lifecycle entry: msg=%+v err=%v", reserved, err)
}
if err := repo.DeleteByID(ctx, "s1", msg.ID); !errors.Is(err, ErrEntryNotFound) {
t.Fatalf("delete reserved entry error = %v, want ErrEntryNotFound", err)
}
removed, err := repo.DeleteAllBySession(ctx, "s1")
if err != nil {
t.Fatalf("clear queue: %v", err)
}
if removed != 0 {
t.Fatalf("clear removed %d reserved entries, want 0", removed)
}
if err := repo.AcknowledgeByID(ctx, "s1", msg.ID); err != nil {
t.Fatalf("acknowledge reserved entry after cancellation attempts: %v", err)
}
}
func TestSQLiteRepository_CancellationReservationOrdering(t *testing.T) {
t.Run("individual cancellation wins before reservation", func(t *testing.T) {
repo := newTestSQLiteRepo(t)
ctx := context.Background()
msg := insertDurableLifecycleEntry(t, repo, "cancel-first")
if err := repo.DeleteByID(ctx, "cancel-first", msg.ID); err != nil {
t.Fatalf("cancel: %v", err)
}
reserved, err := repo.ReserveHead(ctx, "cancel-first")
if err != nil || reserved != nil {
t.Fatalf("reserve after cancel: msg=%+v err=%v", reserved, err)
}
})
t.Run("reservation wins before clear", func(t *testing.T) {
repo := newTestSQLiteRepo(t)
ctx := context.Background()
msg := insertDurableLifecycleEntry(t, repo, "reserve-first")
reserved, err := repo.ReserveHead(ctx, "reserve-first")
if err != nil || reserved == nil {
t.Fatalf("reserve: msg=%+v err=%v", reserved, err)
}
removed, err := repo.DeleteAllBySession(ctx, "reserve-first")
if err != nil || removed != 0 {
t.Fatalf("clear after reserve: removed=%d err=%v", removed, err)
}
if err := repo.AcknowledgeByID(ctx, "reserve-first", msg.ID); err != nil {
t.Fatalf("acknowledge: %v", err)
}
})
}
func insertDurableLifecycleEntry(t *testing.T, repo Repository, sessionID string) *QueuedMessage {
t.Helper()
msg := &QueuedMessage{
SessionID: sessionID,
TaskID: "t1",
Content: "lifecycle prompt",
QueuedBy: QueuedByWorkflow,
Metadata: map[string]interface{}{MetadataLifecycleDurable: true},
}
if err := repo.Insert(context.Background(), msg, 0); err != nil {
t.Fatalf("insert durable lifecycle entry: %v", err)
}
return msg
}
// TestSQLiteRepository_TakeByID covers TakeByID's cross-session guard,
// out-of-FIFO-order removal, idempotent re-take of an already-taken id, and
// (unlike DeleteByID) that agent-authored entries are takeable.
@@ -549,8 +679,8 @@ func TestSQLiteRepository_DeleteAllBySession(t *testing.T) {
repo := newTestSQLiteRepo(t)
ctx := context.Background()
for i := 0; i < 5; i++ {
_ = repo.Insert(ctx, &QueuedMessage{SessionID: "s1", TaskID: "t1", QueuedBy: "u"}, 0)
for _, queuedBy := range []string{QueuedByUser, QueuedByAgent, QueuedByWorkflow, QueuedByServer} {
_ = repo.Insert(ctx, &QueuedMessage{SessionID: "s1", TaskID: "t1", QueuedBy: queuedBy}, 0)
}
_ = repo.Insert(ctx, &QueuedMessage{SessionID: "s2", TaskID: "t1", QueuedBy: "u"}, 0)
@@ -558,8 +688,8 @@ func TestSQLiteRepository_DeleteAllBySession(t *testing.T) {
if err != nil {
t.Fatalf("delete all: %v", err)
}
if n != 5 {
t.Errorf("deleted: got %d, want 5", n)
if n != 4 {
t.Errorf("deleted: got %d, want 4", n)
}
count, _ := repo.CountBySession(ctx, "s1")
if count != 0 {
@@ -13,6 +13,7 @@ import (
"context"
"errors"
"fmt"
"sync/atomic"
"github.com/kandev/kandev/internal/common/logger"
"go.uber.org/zap"
@@ -21,7 +22,7 @@ import (
// Service manages queued messages for sessions, backed by Repository.
type Service struct {
repo Repository
maxPerSession int
maxPerSession atomic.Int64
logger *logger.Logger
}
@@ -29,11 +30,12 @@ type Service struct {
// is the per-session cap (entries beyond this return ErrQueueFull on insert);
// pass 0 to disable the cap.
func NewService(repo Repository, maxPerSession int, log *logger.Logger) *Service {
return &Service{
repo: repo,
maxPerSession: maxPerSession,
logger: log.WithFields(zap.String("component", "message-queue")),
service := &Service{
repo: repo,
logger: log.WithFields(zap.String("component", "message-queue")),
}
service.SetMaxPerSession(maxPerSession)
return service
}
// NewServiceMemory returns a Service backed by an in-memory repository.
@@ -43,7 +45,16 @@ func NewServiceMemory(log *logger.Logger) *Service {
}
// MaxPerSession returns the configured per-session cap.
func (s *Service) MaxPerSession() int { return s.maxPerSession }
func (s *Service) MaxPerSession() int { return int(s.maxPerSession.Load()) }
// SetMaxPerSession applies a new admission cap without pruning existing rows.
// Non-positive values disable the cap.
func (s *Service) SetMaxPerSession(maxPerSession int) {
if maxPerSession < 0 {
maxPerSession = 0
}
s.maxPerSession.Store(int64(maxPerSession))
}
// QueueMessage appends a new entry to the session's FIFO queue. Returns
// ErrQueueFull when the cap is exceeded.
@@ -55,6 +66,13 @@ func (s *Service) QueueMessage(ctx context.Context, sessionID, taskID, content,
// is propagated to the resulting Message row when the queued message is
// drained (e.g. sender_task_id for messages sent via message_task_kandev).
func (s *Service) QueueMessageWithMetadata(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment, metadata map[string]interface{}) (*QueuedMessage, error) {
return s.queueMessageWithMetadata(
ctx, sessionID, taskID, content, model, userID, planMode, attachments, metadata,
s.MaxPerSession(),
)
}
func (s *Service) queueMessageWithMetadata(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment, metadata map[string]interface{}, maxPerSession int) (*QueuedMessage, error) {
metadataCopy := copyMessageMetadata(metadata, 0)
msg := &QueuedMessage{
SessionID: sessionID,
@@ -66,11 +84,11 @@ func (s *Service) QueueMessageWithMetadata(ctx context.Context, sessionID, taskI
Metadata: metadataCopy,
QueuedBy: userID,
}
if err := s.repo.Insert(ctx, msg, s.maxPerSession); err != nil {
if err := s.repo.Insert(ctx, msg, maxPerSession); err != nil {
if errors.Is(err, ErrQueueFull) {
s.logger.Info("queue full",
zap.String("session_id", sessionID),
zap.Int("max", s.maxPerSession))
zap.Int("max", maxPerSession))
}
return nil, err
}
@@ -92,7 +110,7 @@ func (s *Service) RestoreMessage(ctx context.Context, msg *QueuedMessage) (*Queu
}
restored := *msg
restored.Metadata = copyMessageMetadata(msg.Metadata, 0)
if err := s.repo.Restore(ctx, &restored, s.maxPerSession); err != nil {
if err := s.repo.Restore(ctx, &restored, 0); err != nil {
return nil, err
}
s.logger.Info("message restored at original queue position",
@@ -108,6 +126,13 @@ func (s *Service) RestoreMessage(ctx context.Context, msg *QueuedMessage) (*Queu
// inserts a new tail entry if allowInsert is true; otherwise ErrEntryNotFound is
// returned. The returned bool is true when an existing entry was replaced.
func (s *Service) QueueMessageWithCoalesceKey(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment, metadata map[string]interface{}, coalesceKey string, allowInsert bool) (*QueuedMessage, bool, error) {
return s.queueMessageWithCoalesceKey(
ctx, sessionID, taskID, content, model, userID, planMode, attachments, metadata,
coalesceKey, allowInsert, s.MaxPerSession(),
)
}
func (s *Service) queueMessageWithCoalesceKey(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment, metadata map[string]interface{}, coalesceKey string, allowInsert bool, maxPerSession int) (*QueuedMessage, bool, error) {
metadataCopy := copyMessageMetadata(metadata, 1)
metadataCopy[MetadataCoalesceKey] = coalesceKey
msg := &QueuedMessage{
@@ -120,12 +145,12 @@ func (s *Service) QueueMessageWithCoalesceKey(ctx context.Context, sessionID, ta
Metadata: metadataCopy,
QueuedBy: userID,
}
queued, replaced, err := s.repo.InsertOrReplaceByCoalesceKey(ctx, msg, coalesceKey, s.maxPerSession, allowInsert)
queued, replaced, err := s.repo.InsertOrReplaceByCoalesceKey(ctx, msg, coalesceKey, maxPerSession, allowInsert)
if err != nil {
if errors.Is(err, ErrQueueFull) {
s.logger.Info("queue full",
zap.String("session_id", sessionID),
zap.Int("max", s.maxPerSession))
zap.Int("max", maxPerSession))
}
return nil, false, err
}
@@ -140,6 +165,26 @@ func (s *Service) QueueMessageWithCoalesceKey(ctx context.Context, sessionID, ta
return queued, replaced, nil
}
// RequeueMessage retries work that was already admitted. It bypasses the
// current admission cap so lowering capacity while a message is in flight
// cannot discard that message. Coalesced retries retain replacement semantics.
func (s *Service) RequeueMessage(ctx context.Context, msg *QueuedMessage, queuedBy, coalesceKey string) (*QueuedMessage, bool, error) {
if msg == nil {
return nil, false, errors.New("queued message is nil")
}
if coalesceKey != "" {
return s.queueMessageWithCoalesceKey(
ctx, msg.SessionID, msg.TaskID, msg.Content, msg.Model, queuedBy, msg.PlanMode,
msg.Attachments, msg.Metadata, coalesceKey, true, 0,
)
}
queued, err := s.queueMessageWithMetadata(
ctx, msg.SessionID, msg.TaskID, msg.Content, msg.Model, queuedBy, msg.PlanMode,
msg.Attachments, msg.Metadata, 0,
)
return queued, false, err
}
// QueueLifecycleMessageWithCoalesceKey accepts a lifecycle entry only while
// its task remains active. accepted is false for a normal archive/delete win.
func (s *Service) QueueLifecycleMessageWithCoalesceKey(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment, metadata map[string]interface{}, coalesceKey string, allowInsert bool) (*QueuedMessage, bool, bool, error) {
@@ -175,7 +220,11 @@ func (s *Service) queueLifecycleMessageWithCoalesceKey(ctx context.Context, sess
metadataCopy[MetadataLifecycleDurable] = true
metadataCopy[MetadataLifecycleGeneration] = generation
msg := &QueuedMessage{SessionID: sessionID, TaskID: taskID, Content: content, Model: model, PlanMode: planMode, Attachments: attachments, Metadata: metadataCopy, QueuedBy: userID}
queued, replaced, err := s.repo.InsertOrReplaceLifecycleByCoalesceKey(ctx, msg, coalesceKey, s.maxPerSession, allowInsert)
maxPerSession := s.MaxPerSession()
if isRetry {
maxPerSession = 0
}
queued, replaced, err := s.repo.InsertOrReplaceLifecycleByCoalesceKey(ctx, msg, coalesceKey, maxPerSession, allowInsert)
if errors.Is(err, ErrTaskInactive) || errors.Is(err, ErrLifecycleCancelled) {
return nil, false, false, nil
}
@@ -273,7 +322,8 @@ func copyMessageMetadata(metadata map[string]interface{}, extraCapacity int) map
// queued_by matches userID. Otherwise inserts a new entry. Returns
// ErrQueueFull when an insert would exceed the cap.
func (s *Service) AppendContent(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment) (*QueuedMessage, bool, error) {
msg, appended, err := s.repo.AppendOrInsertTail(ctx, sessionID, taskID, content, model, userID, planMode, attachments, nil, s.maxPerSession)
maxPerSession := s.MaxPerSession()
msg, appended, err := s.repo.AppendOrInsertTail(ctx, sessionID, taskID, content, model, userID, planMode, attachments, nil, maxPerSession)
if err != nil {
return nil, false, err
}
@@ -396,12 +446,13 @@ func (s *Service) CancelAll(ctx context.Context, sessionID string) (int, error)
// GetStatus returns the full pending list and capacity info for a session.
func (s *Service) GetStatus(ctx context.Context, sessionID string) *QueueStatus {
maxPerSession := s.MaxPerSession()
entries, err := s.repo.ListBySession(ctx, sessionID)
if err != nil {
s.logger.Error("list queued failed",
zap.String("session_id", sessionID),
zap.Error(err))
return &QueueStatus{Entries: []QueuedMessage{}, Count: 0, Max: s.maxPerSession}
return &QueueStatus{Entries: []QueuedMessage{}, Count: 0, Max: maxPerSession}
}
pending := make([]QueuedMessage, 0, len(entries))
for _, entry := range entries {
@@ -415,7 +466,7 @@ func (s *Service) GetStatus(ctx context.Context, sessionID string) *QueueStatus
return &QueueStatus{
Entries: pending,
Count: len(pending),
Max: s.maxPerSession,
Max: maxPerSession,
}
}
@@ -83,6 +83,158 @@ func TestQueueMessage(t *testing.T) {
})
}
func TestLoweredQueueCapacityBlocksAdmissionsWithoutPruning(t *testing.T) {
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console", OutputPath: "stderr"})
require.NoError(t, err)
svc := NewService(NewMemoryRepository(), 2, log)
ctx := context.Background()
for _, content := range []string{"first", "second"} {
_, err := svc.QueueMessage(ctx, "s", "t", content, "", QueuedByUser, false, nil)
require.NoError(t, err)
}
svc.SetMaxPerSession(1)
assert.Equal(t, 2, svc.GetStatus(ctx, "s").Count)
_, err = svc.QueueMessage(ctx, "s", "t", "blocked", "", QueuedByUser, false, nil)
assert.ErrorIs(t, err, ErrQueueFull)
}
func TestRestoreMessageBypassesLoweredCapacity(t *testing.T) {
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console", OutputPath: "stderr"})
require.NoError(t, err)
svc := NewService(NewMemoryRepository(), 2, log)
ctx := context.Background()
_, err = svc.QueueMessage(ctx, "s", "t", "first", "", QueuedByUser, false, nil)
require.NoError(t, err)
_, err = svc.QueueMessage(ctx, "s", "t", "second", "", QueuedByUser, false, nil)
require.NoError(t, err)
first, ok := svc.TakeQueued(ctx, "s")
require.True(t, ok)
svc.SetMaxPerSession(1)
_, err = svc.RestoreMessage(ctx, first)
require.NoError(t, err)
status := svc.GetStatus(ctx, "s")
require.Equal(t, 2, status.Count)
assert.Equal(t, "first", status.Entries[0].Content)
assert.Equal(t, "second", status.Entries[1].Content)
}
func TestRequeueMessageBypassesLoweredCapacity(t *testing.T) {
for _, tc := range []struct {
name string
coalesceKey string
}{
{name: "ordinary"},
{name: "coalesced", coalesceKey: "retry-key"},
} {
t.Run(tc.name, func(t *testing.T) {
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console", OutputPath: "stderr"})
require.NoError(t, err)
svc := NewService(NewMemoryRepository(), 2, log)
ctx := context.Background()
var first *QueuedMessage
if tc.coalesceKey == "" {
first, err = svc.QueueMessage(ctx, "s", "t", "first", "", QueuedByUser, false, nil)
} else {
first, _, err = svc.QueueMessageWithCoalesceKey(
ctx, "s", "t", "first", "", QueuedByWorkflow, false, nil, nil,
tc.coalesceKey, true,
)
}
require.NoError(t, err)
_, err = svc.QueueMessage(ctx, "s", "t", "second", "", QueuedByUser, false, nil)
require.NoError(t, err)
dequeued, ok := svc.TakeQueued(ctx, "s")
require.True(t, ok)
require.Equal(t, first.ID, dequeued.ID)
svc.SetMaxPerSession(1)
requeued, replaced, err := svc.RequeueMessage(
ctx, dequeued, dequeued.QueuedBy, tc.coalesceKey,
)
require.NoError(t, err)
require.NotNil(t, requeued)
assert.False(t, replaced)
status := svc.GetStatus(ctx, "s")
require.Equal(t, 2, status.Count)
assert.Equal(t, "second", status.Entries[0].Content)
assert.Equal(t, "first", status.Entries[1].Content)
})
}
}
func TestLifecycleRetryBypassesCurrentCapacity(t *testing.T) {
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console", OutputPath: "stderr"})
require.NoError(t, err)
repo := &maxRecordingRepository{Repository: NewMemoryRepository()}
svc := NewService(repo, 3, log)
ctx := context.Background()
queued, _, accepted, err := svc.QueueLifecycleMessageWithCoalesceKey(
ctx, "s", "t", "initial", "", QueuedByWorkflow, false, nil, nil, "lifecycle:1", true,
)
require.NoError(t, err)
require.True(t, accepted)
svc.SetMaxPerSession(1)
_, _, accepted, err = svc.RequeueLifecycleMessageWithCoalesceKey(
ctx, "s", "t", "retry", "", QueuedByWorkflow, false, nil,
queued.Metadata, "lifecycle:1", true,
)
require.NoError(t, err)
require.True(t, accepted)
assert.Equal(t, []int{3, 0}, repo.lifecycleMaxima())
}
func TestQueueCapacityConcurrentReadWrite(t *testing.T) {
svc := setupService(t)
var wait sync.WaitGroup
for worker := 0; worker < 8; worker++ {
wait.Add(1)
go func(offset int) {
defer wait.Done()
for i := 0; i < 500; i++ {
svc.SetMaxPerSession((i + offset) % 20)
_ = svc.MaxPerSession()
_ = svc.GetStatus(context.Background(), "s")
}
}(worker)
}
wait.Wait()
}
func TestLiveCapacityCoversEveryNewAdmissionPath(t *testing.T) {
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console", OutputPath: "stderr"})
require.NoError(t, err)
svc := NewService(NewMemoryRepository(), 1, log)
ctx := context.Background()
_, err = svc.QueueMessage(ctx, "s", "t", "first", "", QueuedByUser, false, nil)
require.NoError(t, err)
_, appended, err := svc.AppendContent(ctx, "s", "t", "same sender", "", QueuedByUser, false, nil)
require.NoError(t, err)
assert.True(t, appended)
_, _, err = svc.AppendContent(ctx, "s", "t", "new sender", "", QueuedByAgent, false, nil)
assert.ErrorIs(t, err, ErrQueueFull)
_, _, err = svc.QueueMessageWithCoalesceKey(
ctx, "s", "t", "coalesced", "", QueuedByWorkflow, false, nil, nil, "key", true,
)
assert.ErrorIs(t, err, ErrQueueFull)
_, _, accepted, err := svc.QueueLifecycleMessageWithCoalesceKey(
ctx, "s", "t", "lifecycle", "", QueuedByWorkflow, false, nil, nil, "lifecycle", true,
)
assert.ErrorIs(t, err, ErrQueueFull)
assert.False(t, accepted)
svc.SetMaxPerSession(0)
_, err = svc.QueueMessage(ctx, "s", "t", "unlimited", "", QueuedByServer, false, nil)
require.NoError(t, err)
assert.Equal(t, 0, svc.GetStatus(ctx, "s").Max)
}
func TestAppendContent(t *testing.T) {
t.Run("appends to tail when same sender", func(t *testing.T) {
svc := setupService(t)
@@ -216,7 +368,7 @@ func TestTakeQueued(t *testing.T) {
}
// TestTakeQueuedEntry covers TakeQueuedEntry: out-of-FIFO-order removal,
// takeability of agent-authored entries (unlike RemoveEntry), the
// takeability of agent-authored entries, the
// not-found (nil, false, nil) shape for a missing or foreign-session id,
// and — distinctly — a genuine repository error propagating as a non-nil
// error rather than being collapsed into the not-found shape.
@@ -249,7 +401,7 @@ func TestTakeQueuedEntry(t *testing.T) {
assert.False(t, ok)
})
t.Run("takes agent-authored entries unlike RemoveEntry", func(t *testing.T) {
t.Run("takes agent-authored entries", func(t *testing.T) {
svc := setupService(t)
ctx := context.Background()
@@ -314,6 +466,33 @@ type errInjectingRepository struct {
takeByIDErr error
}
type maxRecordingRepository struct {
Repository
mu sync.Mutex
lifecycleMaxSeen []int
}
func (r *maxRecordingRepository) InsertOrReplaceLifecycleByCoalesceKey(
ctx context.Context,
msg *QueuedMessage,
coalesceKey string,
maxPerSession int,
allowInsert bool,
) (*QueuedMessage, bool, error) {
r.mu.Lock()
r.lifecycleMaxSeen = append(r.lifecycleMaxSeen, maxPerSession)
r.mu.Unlock()
return r.Repository.InsertOrReplaceLifecycleByCoalesceKey(
ctx, msg, coalesceKey, maxPerSession, allowInsert,
)
}
func (r *maxRecordingRepository) lifecycleMaxima() []int {
r.mu.Lock()
defer r.mu.Unlock()
return append([]int(nil), r.lifecycleMaxSeen...)
}
// TakeByID returns the configured error if set, otherwise delegates to the
// embedded Repository so the remaining repository operations (Insert,
// ListBySession, CountBySession, ...) still work against the real
@@ -462,19 +641,36 @@ func TestRemoveEntry(t *testing.T) {
assert.Equal(t, 1, status.Count)
})
t.Run("rejects deletion of agent-authored entries", func(t *testing.T) {
t.Run("removes visible entries from every origin", func(t *testing.T) {
svc := setupService(t)
ctx := context.Background()
agentEntry, err := svc.QueueMessageWithMetadata(ctx, "s", "t", "agent entry", "", QueuedByAgent, false, nil, nil)
for _, queuedBy := range []string{QueuedByUser, QueuedByAgent, QueuedByWorkflow, QueuedByServer} {
entry, err := svc.QueueMessageWithMetadata(
ctx, "s", "t", queuedBy+" entry", "", queuedBy, false, nil, nil,
)
require.NoError(t, err)
require.NoError(t, svc.RemoveEntry(ctx, "s", entry.ID), queuedBy)
}
assert.Equal(t, 0, svc.GetStatus(ctx, "s").Count)
})
t.Run("preserves a durable entry already reserved in flight", func(t *testing.T) {
svc := setupService(t)
ctx := context.Background()
_, _, accepted, err := svc.QueueLifecycleMessageWithCoalesceKey(
ctx, "s", "t", "lifecycle", "", QueuedByWorkflow, false, nil,
map[string]interface{}{"origin": "github_pr_automation"}, "lifecycle:1", true,
)
require.NoError(t, err)
require.True(t, accepted)
err = svc.RemoveEntry(ctx, "s", agentEntry.ID)
assert.ErrorIs(t, err, ErrEntryNotFound)
status := svc.GetStatus(ctx, "s")
assert.Equal(t, 1, status.Count)
assert.Equal(t, "agent entry", status.Entries[0].Content)
reserved, ok := svc.ReserveQueued(ctx, "s")
require.True(t, ok)
assert.ErrorIs(t, svc.RemoveEntry(ctx, "s", reserved.ID), ErrEntryNotFound)
require.NoError(t, svc.AcknowledgeQueued(ctx, "s", reserved.ID))
})
}
@@ -482,8 +678,8 @@ func TestCancelAll(t *testing.T) {
svc := setupService(t)
ctx := context.Background()
for i := 0; i < 4; i++ {
_, err := svc.QueueMessage(ctx, "s", "t", "x", "", "u", false, nil)
for _, queuedBy := range []string{QueuedByUser, QueuedByAgent, QueuedByWorkflow, QueuedByServer} {
_, err := svc.QueueMessage(ctx, "s", "t", "x", "", queuedBy, false, nil)
require.NoError(t, err)
}
n, err := svc.CancelAll(ctx, "s")
@@ -494,6 +690,31 @@ func TestCancelAll(t *testing.T) {
assert.Equal(t, 0, status.Count)
}
func TestCancelAllPreservesDurableEntryReservedInFlight(t *testing.T) {
svc := setupService(t)
ctx := context.Background()
_, _, accepted, err := svc.QueueLifecycleMessageWithCoalesceKey(
ctx, "s", "t", "lifecycle", "", QueuedByWorkflow, false, nil,
map[string]interface{}{"origin": "github_pr_automation"}, "lifecycle:1", true,
)
require.NoError(t, err)
require.True(t, accepted)
reserved, ok := svc.ReserveQueued(ctx, "s")
require.True(t, ok)
for _, queuedBy := range []string{QueuedByAgent, QueuedByWorkflow, QueuedByServer} {
_, err := svc.QueueMessage(ctx, "s", "t", "visible", "", queuedBy, false, nil)
require.NoError(t, err)
}
removed, err := svc.CancelAll(ctx, "s")
require.NoError(t, err)
assert.Equal(t, 3, removed)
assert.Equal(t, 0, svc.GetStatus(ctx, "s").Count)
require.NoError(t, svc.AcknowledgeQueued(ctx, "s", reserved.ID))
}
func TestGetStatus(t *testing.T) {
t.Run("empty queue returns zero count and configured max", func(t *testing.T) {
svc := setupService(t)
@@ -0,0 +1,49 @@
package queuesettings
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
)
const responseErrorKey = "error"
func RegisterRoutes(read, admin *gin.RouterGroup, service *Service) {
read.GET("/message-queue/settings", handleGet(service))
admin.PATCH("/message-queue/settings", handleUpdate(service))
}
func handleGet(service *Service) gin.HandlerFunc {
return func(ctx *gin.Context) {
response, err := service.Get(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: "failed to load message queue settings"})
return
}
ctx.JSON(http.StatusOK, response)
}
}
func handleUpdate(service *Service) gin.HandlerFunc {
return func(ctx *gin.Context) {
var settings Settings
if err := ctx.ShouldBindJSON(&settings); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "invalid request"})
return
}
response, err := service.Update(ctx.Request.Context(), settings)
if err != nil {
switch {
case errors.Is(err, ErrValidation):
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: err.Error()})
case errors.Is(err, ErrEnvironmentLocked):
ctx.JSON(http.StatusConflict, gin.H{responseErrorKey: err.Error()})
default:
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: "failed to save message queue settings"})
}
return
}
ctx.JSON(http.StatusOK, response)
}
}
@@ -0,0 +1,357 @@
package queuesettings
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/kandev/kandev/internal/common/logger"
)
func TestResolvePrecedenceAndNormalization(t *testing.T) {
tests := []struct {
name string
configured *Settings
environment Environment
want Response
invalidEnv bool
}{
{name: "default", want: responseFor(10, 10, SourceDefault, false)},
{name: "setting", configured: &Settings{MaxPerSession: 6}, want: responseFor(6, 6, SourceSetting, false)},
{name: "environment", configured: &Settings{MaxPerSession: 6}, environment: Environment{Value: "20", Present: true}, want: responseFor(6, 20, SourceEnvironment, true)},
{name: "zero environment is unlimited", configured: &Settings{MaxPerSession: 6}, environment: Environment{Value: "0", Present: true}, want: responseFor(6, 0, SourceEnvironment, true)},
{name: "negative environment is unlimited", configured: &Settings{MaxPerSession: 6}, environment: Environment{Value: "-3", Present: true}, want: responseFor(6, 0, SourceEnvironment, true)},
{name: "invalid environment is ignored", configured: &Settings{MaxPerSession: 6}, environment: Environment{Value: "many", Present: true}, want: responseFor(6, 6, SourceSetting, false), invalidEnv: true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := Resolve(tc.configured, tc.environment)
if err != nil {
t.Fatalf("resolve: %v", err)
}
if got.Response != tc.want || got.InvalidEnvironment != tc.invalidEnv {
t.Fatalf("resolution = %+v, want response=%+v invalid=%v", got, tc.want, tc.invalidEnv)
}
})
}
}
func TestResolveRejectsNegativePersistedValue(t *testing.T) {
_, err := Resolve(&Settings{MaxPerSession: -1}, Environment{})
if !errors.Is(err, ErrValidation) {
t.Fatalf("error = %v, want ErrValidation", err)
}
}
func TestStoreRoundTripAndValidation(t *testing.T) {
raw := &fakeRawStore{}
store := NewStore(raw)
loaded, err := store.Load(context.Background())
if err != nil || loaded != nil {
t.Fatalf("missing load = %+v, %v", loaded, err)
}
if err := store.Save(context.Background(), Settings{MaxPerSession: 8}); err != nil {
t.Fatalf("save: %v", err)
}
loaded, err = store.Load(context.Background())
if err != nil || loaded == nil || loaded.MaxPerSession != 8 {
t.Fatalf("round trip = %+v, %v", loaded, err)
}
if err := store.Save(context.Background(), Settings{MaxPerSession: -1}); !errors.Is(err, ErrValidation) {
t.Fatalf("negative save error = %v, want validation", err)
}
}
func TestServiceUpdatePersistsBeforeLiveApply(t *testing.T) {
raw := &fakeRawStore{}
target := &fakeTarget{max: 10}
service := NewService(NewStore(raw), target, func() Environment { return Environment{} }, testLogger(t))
response, err := service.Update(context.Background(), Settings{MaxPerSession: 4})
if err != nil {
t.Fatalf("update: %v", err)
}
if target.max != 4 || response.Effective.MaxPerSession != 4 || response.Effective.Source != SourceSetting {
t.Fatalf("update result=%+v target=%d", response, target.max)
}
raw.saveErr = errors.New("disk full")
_, err = service.Update(context.Background(), Settings{MaxPerSession: 2})
if err == nil {
t.Fatal("expected persistence error")
}
if target.max != 4 {
t.Fatalf("target applied before failed save: %d", target.max)
}
}
func TestServiceRecoversFromInvalidPersistedSettingAndAllowsReplacement(t *testing.T) {
tests := []struct {
name string
raw string
}{
{name: "malformed JSON", raw: `{`},
{name: "negative value", raw: `{"max_per_session":-2}`},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
raw := &fakeRawStore{raw: []byte(tc.raw), found: true}
target := &fakeTarget{max: 10}
service := NewService(
NewStore(raw), target, func() Environment { return Environment{} }, testLogger(t),
)
response, err := service.Get(context.Background())
if err != nil {
t.Fatalf("get with invalid persisted setting: %v", err)
}
if response != responseFor(10, 10, SourceDefault, false) {
t.Fatalf("fallback response = %+v", response)
}
response, err = service.Update(context.Background(), Settings{MaxPerSession: 7})
if err != nil {
t.Fatalf("replace invalid persisted setting: %v", err)
}
if response != responseFor(7, 7, SourceSetting, false) || target.max != 7 {
t.Fatalf("replacement response=%+v target=%d", response, target.max)
}
})
}
}
func TestServiceSerializesPersistenceAndLiveApply(t *testing.T) {
raw := newBlockingRawStore()
target := &atomicTarget{}
target.max.Store(10)
service := NewService(
NewStore(raw), target, func() Environment { return Environment{} }, testLogger(t),
)
firstDone := make(chan error, 1)
go func() {
_, err := service.Update(context.Background(), Settings{MaxPerSession: 7})
firstDone <- err
}()
<-raw.firstSaveWritten
secondDone := make(chan error, 1)
go func() {
_, err := service.Update(context.Background(), Settings{MaxPerSession: 9})
secondDone <- err
}()
select {
case <-raw.secondSaveEntered:
close(raw.releaseFirst)
<-firstDone
<-secondDone
t.Fatal("second update persisted before first update finished applying live")
case <-time.After(250 * time.Millisecond):
close(raw.releaseFirst)
}
if err := <-firstDone; err != nil {
t.Fatalf("first update: %v", err)
}
if err := <-secondDone; err != nil {
t.Fatalf("second update: %v", err)
}
configured, err := NewStore(raw).Load(context.Background())
if err != nil || configured == nil {
t.Fatalf("load final setting: %+v, %v", configured, err)
}
if configured.MaxPerSession != 9 || target.MaxPerSession() != 9 {
t.Fatalf("final configured=%d live=%d, want both 9", configured.MaxPerSession, target.MaxPerSession())
}
}
func TestServiceEnvironmentLockRejectsUpdate(t *testing.T) {
raw := &fakeRawStore{}
target := &fakeTarget{max: 20}
service := NewService(NewStore(raw), target, func() Environment {
return Environment{Value: "20", Present: true}
}, testLogger(t))
_, err := service.Update(context.Background(), Settings{MaxPerSession: 4})
if !errors.Is(err, ErrEnvironmentLocked) {
t.Fatalf("update error = %v, want environment lock", err)
}
if raw.saveCalls != 0 || target.max != 20 {
t.Fatalf("locked update mutated state: saves=%d target=%d", raw.saveCalls, target.max)
}
}
func TestHandlerReturnsConflictForEnvironmentLock(t *testing.T) {
gin.SetMode(gin.TestMode)
raw := &fakeRawStore{}
service := NewService(NewStore(raw), &fakeTarget{max: 20}, func() Environment {
return Environment{Value: "20", Present: true}
}, testLogger(t))
router := gin.New()
group := router.Group("/api/v1/system")
RegisterRoutes(group, group, service)
body, _ := json.Marshal(Settings{MaxPerSession: 4})
request := httptest.NewRequest(http.MethodPatch, "/api/v1/system/message-queue/settings", bytes.NewReader(body))
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusConflict {
t.Fatalf("status = %d, want 409; body=%s", response.Code, response.Body.String())
}
}
func TestHandlerGetReturnsConfiguredAndEffectiveValues(t *testing.T) {
gin.SetMode(gin.TestMode)
raw := &fakeRawStore{}
store := NewStore(raw)
if err := store.Save(context.Background(), Settings{MaxPerSession: 6}); err != nil {
t.Fatalf("save baseline: %v", err)
}
service := NewService(store, &fakeTarget{max: 20}, func() Environment {
return Environment{Value: "20", Present: true}
}, testLogger(t))
router := gin.New()
group := router.Group("/api/v1/system")
RegisterRoutes(group, group, service)
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(
http.MethodGet, "/api/v1/system/message-queue/settings", nil,
))
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", response.Code, response.Body.String())
}
var payload Response
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatalf("decode response: %v", err)
}
want := responseFor(6, 20, SourceEnvironment, true)
if payload != want {
t.Fatalf("response = %+v, want %+v", payload, want)
}
}
func TestHandlerRejectsNegativeCapacity(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
group := router.Group("/api/v1/system")
RegisterRoutes(group, group, NewService(
NewStore(&fakeRawStore{}), &fakeTarget{max: 10},
func() Environment { return Environment{} }, testLogger(t),
))
request := httptest.NewRequest(
http.MethodPatch, "/api/v1/system/message-queue/settings",
bytes.NewBufferString(`{"max_per_session":-1}`),
)
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body=%s", response.Code, response.Body.String())
}
}
func responseFor(configured, effective int, source Source, locked bool) Response {
return Response{
Settings: Settings{MaxPerSession: configured},
Effective: Effective{MaxPerSession: effective, Source: source, Locked: locked},
}
}
type fakeRawStore struct {
raw []byte
found bool
saveErr error
saveCalls int
}
func (f *fakeRawStore) Get(context.Context, string) ([]byte, bool, error) {
return f.raw, f.found, nil
}
func (f *fakeRawStore) Save(_ context.Context, _ string, value []byte) error {
f.saveCalls++
if f.saveErr != nil {
return f.saveErr
}
f.raw = append([]byte(nil), value...)
f.found = true
return nil
}
type fakeTarget struct {
max int
}
func (f *fakeTarget) MaxPerSession() int { return f.max }
func (f *fakeTarget) SetMaxPerSession(n int) { f.max = n }
type blockingRawStore struct {
mu sync.Mutex
raw []byte
found bool
saveCalls int
firstSaveWritten chan struct{}
secondSaveEntered chan struct{}
releaseFirst chan struct{}
}
func newBlockingRawStore() *blockingRawStore {
return &blockingRawStore{
firstSaveWritten: make(chan struct{}),
secondSaveEntered: make(chan struct{}),
releaseFirst: make(chan struct{}),
}
}
func (s *blockingRawStore) Get(context.Context, string) ([]byte, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
return append([]byte(nil), s.raw...), s.found, nil
}
func (s *blockingRawStore) Save(_ context.Context, _ string, value []byte) error {
s.mu.Lock()
s.saveCalls++
call := s.saveCalls
s.raw = append([]byte(nil), value...)
s.found = true
switch call {
case 1:
close(s.firstSaveWritten)
case 2:
close(s.secondSaveEntered)
}
s.mu.Unlock()
if call == 1 {
<-s.releaseFirst
}
return nil
}
type atomicTarget struct {
max atomic.Int64
}
func (t *atomicTarget) MaxPerSession() int { return int(t.max.Load()) }
func (t *atomicTarget) SetMaxPerSession(n int) { t.max.Store(int64(n)) }
func testLogger(t *testing.T) *logger.Logger {
t.Helper()
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console", OutputPath: "stderr"})
if err != nil {
t.Fatalf("logger: %v", err)
}
return log
}
@@ -0,0 +1,46 @@
package queuesettings
import (
"strconv"
"strings"
)
// Resolve combines persisted configuration with an optional environment
// override. A malformed environment value is reported but ignored so the
// persisted/default setting remains effective.
func Resolve(configured *Settings, environment Environment) (Resolution, error) {
settings := DefaultSettings()
source := SourceDefault
if configured != nil {
if err := Validate(*configured); err != nil {
return Resolution{}, err
}
settings = *configured
source = SourceSetting
}
resolution := Resolution{Response: Response{
Settings: settings,
Effective: Effective{
MaxPerSession: settings.MaxPerSession,
Source: source,
},
}}
raw := strings.TrimSpace(environment.Value)
if !environment.Present || raw == "" {
return resolution, nil
}
value, err := strconv.Atoi(raw)
if err != nil {
resolution.InvalidEnvironment = true
return resolution, nil
}
if value <= 0 {
value = 0
}
resolution.Effective = Effective{
MaxPerSession: value,
Source: SourceEnvironment,
Locked: true,
}
return resolution, nil
}
@@ -0,0 +1,110 @@
package queuesettings
import (
"context"
"errors"
"os"
"sync"
"github.com/kandev/kandev/internal/common/logger"
"go.uber.org/zap"
)
type Target interface {
MaxPerSession() int
SetMaxPerSession(int)
}
type EnvironmentReader func() Environment
type Service struct {
mu sync.Mutex
store *Store
target Target
readEnvironment EnvironmentReader
logger *logger.Logger
}
func NewService(store *Store, target Target, readEnvironment EnvironmentReader, log *logger.Logger) *Service {
if readEnvironment == nil {
readEnvironment = ReadEnvironment
}
return &Service{store: store, target: target, readEnvironment: readEnvironment, logger: log}
}
func ReadEnvironment() Environment {
value, present := os.LookupEnv(EnvironmentVariable)
return Environment{Value: value, Present: present}
}
func (s *Service) Get(ctx context.Context) (Response, error) {
s.mu.Lock()
defer s.mu.Unlock()
configured, err := s.loadConfigured(ctx)
if err != nil {
return Response{}, err
}
resolution, err := Resolve(configured, s.readEnvironment())
if err != nil {
return Response{}, err
}
s.warnInvalidEnvironment(resolution)
return resolution.Response, nil
}
func (s *Service) Update(ctx context.Context, settings Settings) (Response, error) {
s.mu.Lock()
defer s.mu.Unlock()
if err := Validate(settings); err != nil {
return Response{}, err
}
environment := s.readEnvironment()
current, err := s.loadConfigured(ctx)
if err != nil {
return Response{}, err
}
resolution, err := Resolve(current, environment)
if err != nil {
return Response{}, err
}
s.warnInvalidEnvironment(resolution)
if resolution.Effective.Locked {
return Response{}, ErrEnvironmentLocked
}
if s.target == nil {
return Response{}, ErrTargetUnavailable
}
if err := s.store.Save(ctx, settings); err != nil {
return Response{}, err
}
s.target.SetMaxPerSession(settings.MaxPerSession)
updated, err := Resolve(&settings, environment)
if err != nil {
return Response{}, err
}
return updated.Response, nil
}
func (s *Service) loadConfigured(ctx context.Context) (*Settings, error) {
configured, err := s.store.Load(ctx)
if err == nil {
return configured, nil
}
if !errors.Is(err, ErrInvalidPersisted) {
return nil, err
}
if s.logger != nil {
s.logger.Warn("Ignoring invalid persisted message queue settings", zap.Error(err))
}
return nil, nil
}
func (s *Service) warnInvalidEnvironment(resolution Resolution) {
if !resolution.InvalidEnvironment || s.logger == nil {
return
}
s.logger.Warn("Ignoring invalid message queue capacity environment value",
zap.String("environment_variable", EnvironmentVariable))
}
@@ -0,0 +1,52 @@
package queuesettings
import (
"context"
"encoding/json"
"fmt"
)
type RawStore interface {
Get(ctx context.Context, key string) ([]byte, bool, error)
Save(ctx context.Context, key string, value []byte) error
}
type Store struct {
raw RawStore
}
func NewStore(raw RawStore) *Store {
return &Store{raw: raw}
}
func (s *Store) Load(ctx context.Context) (*Settings, error) {
raw, found, err := s.raw.Get(ctx, SettingsKey)
if err != nil {
return nil, fmt.Errorf("load message queue settings: %w", err)
}
if !found {
return nil, nil
}
var settings Settings
if err := json.Unmarshal(raw, &settings); err != nil {
return nil, fmt.Errorf("%w: decode JSON: %v", ErrInvalidPersisted, err)
}
if err := Validate(settings); err != nil {
return nil, fmt.Errorf("%w: %v", ErrInvalidPersisted, err)
}
return &settings, nil
}
func (s *Store) Save(ctx context.Context, settings Settings) error {
if err := Validate(settings); err != nil {
return err
}
raw, err := json.Marshal(settings)
if err != nil {
return fmt.Errorf("encode message queue settings: %w", err)
}
if err := s.raw.Save(ctx, SettingsKey, raw); err != nil {
return fmt.Errorf("save message queue settings: %w", err)
}
return nil
}
@@ -0,0 +1,65 @@
package queuesettings
import (
"errors"
"fmt"
"github.com/kandev/kandev/internal/orchestrator/messagequeue"
)
const (
SettingsKey = "message_queue"
EnvironmentVariable = "KANDEV_QUEUE_MAX_PER_SESSION"
DefaultMaxPerSession = messagequeue.DefaultMaxPerSession
)
type Source string
const (
SourceDefault Source = "default"
SourceSetting Source = "setting"
SourceEnvironment Source = "environment"
)
var (
ErrValidation = errors.New("message queue settings validation")
ErrInvalidPersisted = errors.New("invalid persisted message queue settings")
ErrEnvironmentLocked = errors.New("message queue capacity is controlled by the environment")
ErrTargetUnavailable = errors.New("message queue live target is unavailable")
)
type Settings struct {
MaxPerSession int `json:"max_per_session"`
}
type Effective struct {
MaxPerSession int `json:"max_per_session"`
Source Source `json:"source"`
Locked bool `json:"locked"`
}
type Response struct {
Settings Settings `json:"settings"`
Effective Effective `json:"effective"`
}
type Environment struct {
Value string
Present bool
}
type Resolution struct {
Response
InvalidEnvironment bool
}
func DefaultSettings() Settings {
return Settings{MaxPerSession: DefaultMaxPerSession}
}
func Validate(settings Settings) error {
if settings.MaxPerSession < 0 {
return fmt.Errorf("%w: max_per_session must be zero or greater", ErrValidation)
}
return nil
}
+13
View File
@@ -30,6 +30,7 @@ import (
"github.com/kandev/kandev/internal/system/jobs"
"github.com/kandev/kandev/internal/system/logbundle"
"github.com/kandev/kandev/internal/system/metrics"
"github.com/kandev/kandev/internal/system/queuesettings"
"github.com/kandev/kandev/internal/system/restart"
systemsettings "github.com/kandev/kandev/internal/system/settings"
"github.com/kandev/kandev/internal/system/storage"
@@ -54,6 +55,7 @@ type BuildInfo struct {
// no in-process re-exec is performed.
type Wiring struct {
OrchestratorShutdown func()
MessageQueue queuesettings.Target
}
// Service exposes the composed system sub-services. Each field is
@@ -68,6 +70,7 @@ type Service struct {
LogBundles *logbundle.Service
FrontendErrors *frontenderrors.Service
Metrics *metrics.Service
MessageQueue *queuesettings.Service
Updates *updates.Service
Restart restart.Manager
Storage *storage.Handler
@@ -101,10 +104,16 @@ func Provide(cfg *config.Config, log *logger.Logger, pool *db.Pool, eventBus bus
log.Error("Failed to initialize system settings store", zap.Error(err))
}
var metricsSvc *metrics.Service
var queueSettingsSvc *queuesettings.Service
updatesOpts := []updates.Option{updates.WithHomeDir(homeDir), updates.WithJobs(tracker)}
if settingsStore != nil {
metricsStore := metrics.NewStore(settingsStore)
metricsSvc = metrics.NewService(metricsStore, metrics.NewCollector())
if wiring.MessageQueue != nil {
queueSettingsSvc = queuesettings.NewService(
queuesettings.NewStore(settingsStore), wiring.MessageQueue, nil, log,
)
}
updatesOpts = append(updatesOpts, updates.WithSettingsStore(settingsStore))
}
@@ -125,6 +134,7 @@ func Provide(cfg *config.Config, log *logger.Logger, pool *db.Pool, eventBus bus
}),
FrontendErrors: frontenderrors.New(log, nil),
Metrics: metricsSvc,
MessageQueue: queueSettingsSvc,
Updates: updatesSvc,
Restart: restart.NewManagerFromEnv(),
}
@@ -173,6 +183,9 @@ func (s *Service) RegisterRoutes(router *gin.Engine, log *logger.Logger) {
if s.Metrics != nil {
metrics.RegisterRoutes(g, s.Metrics)
}
if s.MessageQueue != nil {
queuesettings.RegisterRoutes(g, admin, s.MessageQueue)
}
g.GET("/updates", updates.HandleGet(s.Updates))
admin.POST("/updates/check", updates.HandleCheck(s.Updates))
@@ -2,6 +2,8 @@ package system
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
@@ -10,6 +12,7 @@ import (
"github.com/kandev/kandev/internal/auth/authn"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/system/frontenderrors"
"github.com/kandev/kandev/internal/system/queuesettings"
"go.uber.org/zap"
)
@@ -39,3 +42,77 @@ func TestRegisterRoutesAllowsMemberFrontendErrorReports(t *testing.T) {
t.Fatalf("member report status = %d, body = %s", response.Code, response.Body.String())
}
}
func TestRegisterRoutesMessageQueueSettingsPermissions(t *testing.T) {
gin.SetMode(gin.TestMode)
log, err := logger.NewFromZap(zap.NewNop())
if err != nil {
t.Fatal(err)
}
target := &queueSettingsTarget{max: 10}
queueService := queuesettings.NewService(
queuesettings.NewStore(&queueSettingsRawStore{}), target,
func() queuesettings.Environment { return queuesettings.Environment{} }, log,
)
memberRouter := systemRouterForRole(authn.RoleMember)
(&Service{MessageQueue: queueService}).RegisterRoutes(memberRouter, log)
getResponse := httptest.NewRecorder()
memberRouter.ServeHTTP(getResponse, httptest.NewRequest(
http.MethodGet, "/api/v1/system/message-queue/settings", nil,
))
if getResponse.Code != http.StatusOK {
t.Fatalf("member GET status = %d, want 200; body=%s", getResponse.Code, getResponse.Body.String())
}
patchResponse := httptest.NewRecorder()
memberRouter.ServeHTTP(patchResponse, queueSettingsPatchRequest(4))
if patchResponse.Code != http.StatusForbidden {
t.Fatalf("member PATCH status = %d, want 403; body=%s", patchResponse.Code, patchResponse.Body.String())
}
adminRouter := systemRouterForRole(authn.RoleAdmin)
(&Service{MessageQueue: queueService}).RegisterRoutes(adminRouter, log)
adminResponse := httptest.NewRecorder()
adminRouter.ServeHTTP(adminResponse, queueSettingsPatchRequest(4))
if adminResponse.Code != http.StatusOK || target.max != 4 {
t.Fatalf("admin PATCH status=%d target=%d body=%s", adminResponse.Code, target.max, adminResponse.Body.String())
}
}
func systemRouterForRole(role authn.Role) *gin.Engine {
router := gin.New()
router.Use(func(ctx *gin.Context) {
authn.SetOnGin(ctx, authn.Identity{UserID: "user-1", Role: role})
ctx.Next()
})
return router
}
func queueSettingsPatchRequest(max int) *http.Request {
body := bytes.NewBufferString(`{"max_per_session":` + fmt.Sprint(max) + `}`)
request := httptest.NewRequest(http.MethodPatch, "/api/v1/system/message-queue/settings", body)
request.Header.Set("Content-Type", "application/json")
return request
}
type queueSettingsRawStore struct {
raw []byte
found bool
}
func (s *queueSettingsRawStore) Get(context.Context, string) ([]byte, bool, error) {
return s.raw, s.found, nil
}
func (s *queueSettingsRawStore) Save(_ context.Context, _ string, value []byte) error {
s.raw = append([]byte(nil), value...)
s.found = true
return nil
}
type queueSettingsTarget struct {
max int
}
func (t *queueSettingsTarget) MaxPerSession() int { return t.max }
func (t *queueSettingsTarget) SetMaxPerSession(n int) { t.max = n }
@@ -129,6 +129,23 @@ func (s *Service) AuthorizeSessionAccess(ctx context.Context, sessionID string)
return s.authorizeTaskID(ctx, session.TaskID)
}
// AuthorizeTaskSessionAccess checks that both identifiers are visible to the
// caller and that the session belongs to the supplied task. Mismatches use the
// task not-found sentinel so callers cannot enumerate another task's sessions.
func (s *Service) AuthorizeTaskSessionAccess(ctx context.Context, taskID, sessionID string) error {
if err := s.AuthorizeTaskAccess(ctx, taskID); err != nil {
return err
}
session, err := s.sessions.GetTaskSession(ctx, sessionID)
if err != nil {
return err
}
if session == nil || session.TaskID != taskID {
return repoerrors.ErrTaskNotFound
}
return nil
}
// AuthorizeEnvironmentAccess checks visibility of a task environment via its
// task's workspace. Used by the terminal environment-shell route, which
// resolves executions by environment ID rather than session ID.
@@ -194,6 +194,31 @@ func TestAuthorizeSessionAccess(t *testing.T) {
}
}
func TestAuthorizeTaskSessionAccessRejectsMismatchedPair(t *testing.T) {
svc, _, repo := createTestService(t)
seedScopedWorkspaces(t, repo)
if err := repo.CreateTask(context.Background(), &models.Task{
ID: "task-b-other", WorkspaceID: "ws-b", WorkflowID: "wf-b", WorkflowStepID: "step-1",
Title: "B's other task", State: v1.TaskStateCreated, Priority: "medium",
}); err != nil {
t.Fatalf("create other task: %v", err)
}
for name, ctx := range map[string]context.Context{
"owner": ctxAs("user-b"),
"internal": context.Background(),
} {
err := svc.AuthorizeTaskSessionAccess(ctx, "task-b-other", "sess-b")
if !errors.Is(err, repoerrors.ErrTaskNotFound) {
t.Fatalf("%s mismatched pair error = %v, want ErrTaskNotFound", name, err)
}
}
if err := svc.AuthorizeTaskSessionAccess(ctxAs("user-b"), "task-b", "sess-b"); err != nil {
t.Fatalf("matching pair: %v", err)
}
}
// TestMessageScopingBlocksForeignSession covers the read/search paths the
// security audit flagged as unscoped (agent-conversation cross-user read).
func TestMessageScopingBlocksForeignSession(t *testing.T) {
@@ -0,0 +1,17 @@
"use client";
import { useTranslation } from "react-i18next";
import { MessageQueueSettings } from "@/components/settings/system/message-queue-settings";
import { SystemPageShell } from "@/components/settings/system/system-page-shell";
export default function MessageQueueSettingsPage() {
const { t } = useTranslation();
return (
<SystemPageShell
title={t("system:messageQueueTitle")}
description={t("system:messageQueueDescription")}
>
<MessageQueueSettings />
</SystemPageShell>
);
}
@@ -0,0 +1,5 @@
import { redirect } from "@/lib/routing/server-navigation";
export default function MessageQueueSettingsPage() {
redirect("/settings/general/message-queue");
}
@@ -87,6 +87,8 @@ vi.mock("@kandev/ui/collapsible", async () => {
});
import { SettingsTree } from "./settings-tree";
import { GeneralGroup } from "./general-group";
import { SystemGroup } from "./system-group";
import { WorkspacesGroup } from "./workspaces-group";
describe("SettingsTree rendering", () => {
@@ -258,6 +260,24 @@ describe("SettingsTree standalone leaves", () => {
});
});
describe("Message Queue settings navigation", () => {
afterEach(cleanup);
it("exposes Message Queue under General in the shared desktop and mobile settings tree", () => {
render(<GeneralGroup pathname="/settings/general/message-queue" expanded />);
const link = screen.getByRole("link", { name: "Message Queue" });
expect(link.getAttribute("href")).toBe("/settings/general/message-queue");
expect(link.className).toContain("before:bg-primary");
});
it("does not expose Message Queue under System", () => {
render(<SystemGroup pathname="/settings/system/status" expanded />);
expect(screen.queryByRole("link", { name: "Message Queue" })).toBeNull();
});
});
describe("WorkspacesGroup active workspace presentation", () => {
beforeEach(() => {
state.workspaces.activeId = MAIN_WORKSPACE_ID;
@@ -5,6 +5,7 @@ import {
IconCommand,
IconCode,
IconLayoutDashboard,
IconMessage,
IconPalette,
IconTerminal2,
} from "@tabler/icons-react";
@@ -60,6 +61,12 @@ export const GENERAL_NAV_ITEMS: GeneralNavItem[] = [
descriptionKey: "settings:mcpTaskDefaultsAndArchiveSafeguards",
icon: IconArchive,
},
{
href: "/settings/general/message-queue",
labelKey: "system:messageQueueTitle",
descriptionKey: "system:messageQueueDescription",
icon: IconMessage,
},
];
/** A nav item with its copy already translated, ready to render. */
@@ -50,6 +50,7 @@ vi.mock("@/components/integrations/integration-copy-config-menu", () => ({
import { SettingsLayoutClient } from "./settings-layout-client";
import { useSettingsSaveContributor } from "./settings-save-provider";
import { i18n } from "@/lib/i18n";
function DirtySettings() {
useSettingsSaveContributor({
@@ -137,4 +138,23 @@ describe("SettingsLayoutClient integrations actions", () => {
"app-status-bar-height",
);
});
it("translates the Message Queue breadcrumb and keeps the shared scroll owner", async () => {
pathname = "/settings/general/message-queue";
await i18n.changeLanguage("pseudo");
try {
render(
<SettingsLayoutClient>
<div>Queue settings</div>
</SettingsLayoutClient>,
);
expect(screen.getByTestId("page-topbar-title").textContent).toBe("Ḿēśśàĝē Qũēũē");
expect(screen.getByTestId("settings-scroll-container").className).toContain(
"overflow-y-auto",
);
} finally {
await i18n.changeLanguage("en");
}
});
});
@@ -58,6 +58,7 @@ const SEGMENT_LABEL_KEYS: Record<string, string> = {
integrations: "common:integrations",
"keyboard-shortcuts": "settings:keyboardShortcuts",
layouts: "settings:layouts",
"message-queue": "system:messageQueueTitle",
new: "settings:new",
notifications: "settings:notifications",
plugins: "common:plugins",
@@ -0,0 +1,179 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { SettingsSaveContributor } from "../settings-save-provider";
import type { MessageQueueSettingsResponse } from "@/lib/types/system";
const fetchSettingsMock = vi.fn();
const updateSettingsMock = vi.fn();
let saveContributor: SettingsSaveContributor | null = null;
let currentRole: "admin" | "member" | undefined;
const MAXIMUM_LABEL = "Maximum messages per session";
const EFFECTIVE_VALUE_ID = "message-queue-effective-value";
vi.mock("@/lib/api/domains/settings-api", () => ({
fetchMessageQueueSettings: (...args: unknown[]) => fetchSettingsMock(...args),
updateMessageQueueSettings: (...args: unknown[]) => updateSettingsMock(...args),
}));
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: { auth: { user?: { role: string } } }) => unknown) =>
selector({ auth: { user: currentRole ? { role: currentRole } : undefined } }),
}));
vi.mock("../settings-save-provider", () => ({
useSettingsSaveContributor: (contributor: SettingsSaveContributor) => {
saveContributor = contributor;
},
}));
import { MessageQueueSettings } from "./message-queue-settings";
function response(
configured = 10,
effective = configured,
source: MessageQueueSettingsResponse["effective"]["source"] = "default",
locked = false,
): MessageQueueSettingsResponse {
return {
settings: { max_per_session: configured },
effective: { max_per_session: effective, source, locked },
};
}
beforeEach(() => {
fetchSettingsMock.mockReset();
updateSettingsMock.mockReset();
fetchSettingsMock.mockResolvedValue(response());
currentRole = "admin";
saveContributor = null;
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe("MessageQueueSettings", () => {
it("shows loading, configured, effective, and default-source states", async () => {
let resolveLoad: (value: MessageQueueSettingsResponse) => void = () => {};
fetchSettingsMock.mockReturnValueOnce(
new Promise<MessageQueueSettingsResponse>((resolve) => {
resolveLoad = resolve;
}),
);
render(<MessageQueueSettings />);
expect(screen.getByText("Loading message queue settings…")).toBeTruthy();
resolveLoad(response());
const input = await screen.findByLabelText(MAXIMUM_LABEL);
expect(input.getAttribute("value")).toBe("10");
expect(screen.getByTestId(EFFECTIVE_VALUE_ID).textContent).toBe("10");
expect(screen.getByTestId("message-queue-source").textContent).toBe("Default");
});
it("explains unlimited mode and keeps a mobile-safe single-column surface", async () => {
fetchSettingsMock.mockResolvedValueOnce(response(0, 0, "setting"));
render(<MessageQueueSettings />);
const input = await screen.findByLabelText(MAXIMUM_LABEL);
expect(screen.getByTestId(EFFECTIVE_VALUE_ID).textContent).toBe("Unlimited");
expect(screen.getByText(/Set 0 for unlimited/)).toBeTruthy();
expect(input.className).toContain("h-11");
const root = screen.getByTestId("message-queue-settings");
expect(root.className).toContain("min-w-0");
expect(root.querySelectorAll(".overflow-y-auto")).toHaveLength(0);
});
it("stages an admin edit until the shared contributor saves it", async () => {
updateSettingsMock.mockResolvedValueOnce(response(25, 25, "setting"));
render(<MessageQueueSettings />);
const input = await screen.findByLabelText(MAXIMUM_LABEL);
fireEvent.change(input, { target: { value: "25" } });
expect(updateSettingsMock).not.toHaveBeenCalled();
expect(saveContributor?.isDirty).toBe(true);
expect(screen.queryByRole("button", { name: "Save" })).toBeNull();
expect(screen.queryByRole("button", { name: "Cancel" })).toBeNull();
if (!saveContributor) throw new Error("save contributor was not registered");
await act(async () => saveContributor?.save(saveContributor.revision));
expect(updateSettingsMock).toHaveBeenCalledWith({ max_per_session: 25 });
expect(screen.getByTestId(EFFECTIVE_VALUE_ID).textContent).toBe("25");
await waitFor(() => expect(saveContributor?.isDirty).toBe(false));
});
it.each(["-1", "2.5", ""])("rejects invalid draft %j", async (draft) => {
render(<MessageQueueSettings />);
const input = await screen.findByLabelText(MAXIMUM_LABEL);
fireEvent.change(input, { target: { value: draft } });
expect(saveContributor?.isDirty).toBe(true);
expect(saveContributor?.canSave).toBe(false);
expect(saveContributor?.invalidReason).toBe("Enter a whole number of 0 or greater.");
});
it("shows the effective environment value and locks editing", async () => {
fetchSettingsMock.mockResolvedValueOnce(response(25, 50, "environment", true));
render(<MessageQueueSettings />);
const input = await screen.findByLabelText(MAXIMUM_LABEL);
expect(input).toHaveProperty("disabled", true);
expect(input.getAttribute("value")).toBe("25");
expect(screen.getByTestId(EFFECTIVE_VALUE_ID).textContent).toBe("50");
expect(screen.getByTestId("message-queue-source").textContent).toBe("Environment");
expect(screen.getByText(/KANDEV_QUEUE_MAX_PER_SESSION/)).toBeTruthy();
});
it("keeps members read-only while showing the setting", async () => {
currentRole = "member";
render(<MessageQueueSettings />);
const input = await screen.findByLabelText(MAXIMUM_LABEL);
expect(input).toHaveProperty("disabled", true);
expect(screen.getByText("Only administrators can change this setting.")).toBeTruthy();
expect(saveContributor?.isDirty).toBe(false);
});
it("shows a retryable load error", async () => {
fetchSettingsMock.mockRejectedValueOnce(new Error("offline"));
render(<MessageQueueSettings />);
expect(await screen.findByText("Message queue settings could not be loaded.")).toBeTruthy();
fetchSettingsMock.mockResolvedValueOnce(response());
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(await screen.findByLabelText(MAXIMUM_LABEL)).toBeTruthy();
});
it("reports save failure and keeps the draft dirty", async () => {
updateSettingsMock.mockRejectedValueOnce(new Error("save failed"));
render(<MessageQueueSettings />);
const input = await screen.findByLabelText(MAXIMUM_LABEL);
fireEvent.change(input, { target: { value: "20" } });
if (!saveContributor) throw new Error("save contributor was not registered");
await act(async () => {
await expect(saveContributor?.save(saveContributor.revision)).rejects.toThrow("save failed");
});
expect(screen.getByText("Failed to save message queue settings.")).toBeTruthy();
expect(saveContributor?.isDirty).toBe(true);
});
it("discards a draft back to the authoritative configured value", async () => {
fetchSettingsMock.mockResolvedValueOnce(response(12, 12, "setting"));
render(<MessageQueueSettings />);
const input = await screen.findByLabelText(MAXIMUM_LABEL);
fireEvent.change(input, { target: { value: "30" } });
if (!saveContributor) throw new Error("save contributor was not registered");
act(() => saveContributor?.discard());
expect(input.getAttribute("value")).toBe("12");
expect(saveContributor?.isDirty).toBe(false);
});
});
@@ -0,0 +1,240 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { Alert, AlertDescription, AlertTitle } from "@kandev/ui/alert";
import { Badge } from "@kandev/ui/badge";
import { Button } from "@kandev/ui/button";
import { CardContent, CardHeader, CardTitle } from "@kandev/ui/card";
import { Input } from "@kandev/ui/input";
import { Label } from "@kandev/ui/label";
import { Spinner } from "@kandev/ui/spinner";
import { IconAlertCircle, IconLock } from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
import { useAppStore } from "@/components/state-provider";
import { SettingsCard } from "@/components/settings/settings-card";
import { useSettingsSaveContributor } from "@/components/settings/settings-save-provider";
import {
fetchMessageQueueSettings,
updateMessageQueueSettings,
} from "@/lib/api/domains/settings-api";
import type { MessageQueueSettingsResponse, MessageQueueSettingsSource } from "@/lib/types/system";
const ENVIRONMENT_VARIABLE = "KANDEV_QUEUE_MAX_PER_SESSION";
function parseMaximum(value: string): number | null {
const trimmed = value.trim();
if (!/^\d+$/.test(trimmed)) return null;
const parsed = Number(trimmed);
return Number.isSafeInteger(parsed) ? parsed : null;
}
function sourceLabelKey(source: MessageQueueSettingsSource): string {
switch (source) {
case "setting":
return "system:messageQueueSourceSetting";
case "environment":
return "system:messageQueueSourceEnvironment";
default:
return "system:messageQueueSourceDefault";
}
}
function useMessageQueueSettingsDraft() {
const { t } = useTranslation();
const role = useAppStore((state) => state.auth.user?.role);
const [snapshot, setSnapshot] = useState<MessageQueueSettingsResponse | null>(null);
const [draft, setDraft] = useState("");
const [loading, setLoading] = useState(true);
const [loadFailed, setLoadFailed] = useState(false);
const [saveFailed, setSaveFailed] = useState(false);
const loadVersion = useRef(0);
const reload = useCallback(async () => {
const version = ++loadVersion.current;
setLoading(true);
setLoadFailed(false);
try {
const response = await fetchMessageQueueSettings();
if (version !== loadVersion.current) return;
setSnapshot(response);
setDraft(String(response.settings.max_per_session));
} catch {
if (version === loadVersion.current) setLoadFailed(true);
} finally {
if (version === loadVersion.current) setLoading(false);
}
}, []);
useEffect(() => {
void reload();
return () => {
loadVersion.current += 1;
};
}, [reload]);
const parsed = parseMaximum(draft);
const baseline = snapshot?.settings.max_per_session;
const isDirty = baseline !== undefined && draft !== String(baseline);
const isAdmin = role === undefined || role === "admin";
const isLocked = snapshot?.effective.locked === true;
const canEdit = isAdmin && !isLocked;
let invalidReason: string | undefined;
if (parsed === null) invalidReason = t("system:messageQueueValidation");
else if (!isAdmin) invalidReason = t("system:messageQueueAdminOnly");
else if (isLocked) {
invalidReason = t("system:messageQueueEnvironmentLocked", {
variable: ENVIRONMENT_VARIABLE,
});
}
useSettingsSaveContributor({
id: "system-message-queue",
revision: draft,
isDirty,
canSave: parsed !== null && canEdit,
invalidReason,
save: async () => {
if (parsed === null || !canEdit) throw new Error(invalidReason);
const submitted = draft;
setSaveFailed(false);
try {
const response = await updateMessageQueueSettings({ max_per_session: parsed });
setSnapshot(response);
setDraft((current) =>
current === submitted ? String(response.settings.max_per_session) : current,
);
} catch (error) {
setSaveFailed(true);
throw error;
}
},
discard: () => {
if (baseline !== undefined) setDraft(String(baseline));
setSaveFailed(false);
},
});
return {
snapshot,
draft,
setDraft,
loading,
loadFailed,
saveFailed,
isDirty,
isAdmin,
isLocked,
reload,
};
}
export function MessageQueueSettings() {
const { t } = useTranslation();
const state = useMessageQueueSettingsDraft();
if (state.loading && !state.snapshot) {
return (
<SettingsCard>
<CardContent className="flex items-center gap-2 py-6 text-sm text-muted-foreground">
<Spinner className="size-4" />
{t("system:messageQueueLoading")}
</CardContent>
</SettingsCard>
);
}
if (state.loadFailed && !state.snapshot) {
return <MessageQueueLoadError onRetry={() => void state.reload()} />;
}
if (!state.snapshot) return null;
const { settings, effective } = state.snapshot;
const effectiveValue =
effective.max_per_session === 0
? t("system:messageQueueUnlimited")
: String(effective.max_per_session);
return (
<SettingsCard
isDirty={state.isDirty}
className="min-w-0 w-full max-w-3xl"
data-testid="message-queue-settings"
>
<CardHeader>
<CardTitle className="text-base">{t("system:messageQueueLimitTitle")}</CardTitle>
</CardHeader>
<CardContent className="min-w-0 space-y-5">
<p className="text-sm text-muted-foreground">{t("system:messageQueueLimitDescription")}</p>
<div className="min-w-0 space-y-2">
<Label htmlFor="message-queue-max-per-session">
{t("system:messageQueueMaximumLabel")}
</Label>
<Input
id="message-queue-max-per-session"
data-testid="message-queue-max-per-session"
type="number"
inputMode="numeric"
min={0}
step={1}
value={state.draft}
disabled={!state.isAdmin || state.isLocked}
onChange={(event) => state.setDraft(event.target.value)}
className="h-11 w-full max-w-xs"
/>
<p className="text-xs text-muted-foreground">{t("system:messageQueueUnlimitedHelp")}</p>
</div>
<div className="rounded-md border border-border/70 bg-muted/20 p-3 text-sm">
<div className="flex flex-wrap items-center gap-2">
<span className="text-muted-foreground">{t("system:messageQueueConfigured")}</span>
<span>{settings.max_per_session}</span>
<span className="text-muted-foreground">{t("system:messageQueueEffective")}</span>
<strong data-testid="message-queue-effective-value">{effectiveValue}</strong>
<Badge variant="secondary" data-testid="message-queue-source">
{t(sourceLabelKey(effective.source))}
</Badge>
</div>
<p className="mt-2 text-xs text-muted-foreground">
{t("system:messageQueueEffectiveHelp")}
</p>
</div>
{state.isLocked && (
<Alert>
<IconLock className="size-4" />
<AlertTitle>{t("system:messageQueueEnvironmentLockTitle")}</AlertTitle>
<AlertDescription>
{t("system:messageQueueEnvironmentLocked", { variable: ENVIRONMENT_VARIABLE })}
</AlertDescription>
</Alert>
)}
{!state.isAdmin && (
<p className="text-sm text-muted-foreground">{t("system:messageQueueAdminOnly")}</p>
)}
{state.saveFailed && (
<Alert variant="destructive">
<IconAlertCircle className="size-4" />
<AlertDescription>{t("system:messageQueueSaveFailed")}</AlertDescription>
</Alert>
)}
</CardContent>
</SettingsCard>
);
}
function MessageQueueLoadError({ onRetry }: { onRetry: () => void }) {
const { t } = useTranslation();
return (
<SettingsCard>
<CardContent className="space-y-3 py-6">
<Alert variant="destructive">
<IconAlertCircle className="size-4" />
<AlertDescription>{t("system:messageQueueLoadFailed")}</AlertDescription>
</Alert>
<Button variant="outline" className="h-11 cursor-pointer" onClick={onRetry}>
{t("system:messageQueueRetry")}
</Button>
</CardContent>
</SettingsCard>
);
}
@@ -42,6 +42,8 @@ const CHIP_ID = "queue-chip";
const PANEL_ID = "queued-ghost-list";
const QUEUED_BY_USER = "user";
const MERGE_BUTTON_ID = "queue-entry-merge";
const EDIT_BUTTON_ID = "queue-entry-edit";
const REMOVE_BUTTON_ID = "queue-entry-remove";
function entry(overrides: Partial<QueuedMessage> = {}): QueuedMessage {
return {
@@ -223,6 +225,26 @@ describe("QueueAffordance", () => {
});
});
describe("QueueAffordance positions", () => {
it("compacts displayed positions when persisted queue positions contain gaps", () => {
const initialEntries = [
entry({ id: "q-1", position: 1 }),
entry({ id: "q-2", position: 2 }),
entry({ id: "q-3", position: 3 }),
];
useQueueMock.mockReturnValue(queueState(initialEntries));
const { rerender } = render(<QueueAffordance sessionId={SESSION_ID}>{CHILD}</QueueAffordance>);
fireEvent.click(screen.getByTestId(CHIP_ID));
useQueueMock.mockReturnValue(queueState([initialEntries[0], initialEntries[2]]));
rerender(<QueueAffordance sessionId={SESSION_ID}>{CHILD}</QueueAffordance>);
expect(screen.getByLabelText("Position #1")).toBeTruthy();
expect(screen.getByLabelText("Position #2")).toBeTruthy();
expect(screen.queryByLabelText("Position #3")).toBeNull();
});
});
describe("QueueAffordance Escape handling", () => {
it("collapses an open panel without reaching an outer dialog", () => {
useQueueMock.mockReturnValue(queueState([entry()]));
@@ -280,26 +302,42 @@ describe("QueueAffordance — renderStatusBar prop", () => {
});
});
describe("QueueAffordance — workflow entries", () => {
it("workflow queued entries are read-only", () => {
useQueueMock.mockReturnValue(
queueState([
entry({
queued_by: "workflow",
metadata: {
workflow_message: true,
workflow_step_name: "Review",
},
}),
]),
);
describe("QueueAffordance — provenance actions", () => {
it("offers Remove for every visible origin and Edit only for user rows", () => {
const state = queueState([
entry({ id: "q-user", queued_by: "user" }),
entry({ id: "q-agent", queued_by: "agent" }),
entry({
id: "q-workflow",
queued_by: "workflow",
metadata: { workflow_message: true, workflow_step_name: "Review" },
}),
entry({ id: "q-server", queued_by: "server" }),
]);
useQueueMock.mockReturnValue(state);
render(<QueueAffordance sessionId={SESSION_ID}>{CHILD}</QueueAffordance>);
fireEvent.click(screen.getByTestId(CHIP_ID));
expect(screen.getByTestId("workflow-message-badge").textContent).toContain("Review");
expect(screen.queryByTitle("Edit queued message")).toBeNull();
expect(screen.queryByTitle("Remove queued message")).toBeNull();
expect(screen.getAllByTestId(REMOVE_BUTTON_ID)).toHaveLength(4);
expect(screen.getAllByTestId(EDIT_BUTTON_ID)).toHaveLength(1);
fireEvent.click(screen.getAllByTestId(REMOVE_BUTTON_ID)[1]);
expect(state.removeEntry).toHaveBeenCalledWith("q-agent");
});
it("keeps one queue scroll owner and touch-sizes clear and close controls", () => {
useQueueMock.mockReturnValue(queueState([entry()]));
render(<QueueAffordance sessionId={SESSION_ID}>{CHILD}</QueueAffordance>);
fireEvent.click(screen.getByTestId(CHIP_ID));
const panel = screen.getByTestId(PANEL_ID);
expect(panel.querySelectorAll(".overflow-y-auto")).toHaveLength(1);
for (const testId of ["queue-clear-all", "queue-close"]) {
expect(screen.getByTestId(testId).className).toContain("[@media(pointer:coarse)]:h-11");
}
});
});
@@ -12,19 +12,15 @@ import { cn } from "@/lib/utils";
import { stripSystemTags } from "@/lib/utils/system-tags";
import { MergeReferenceOverflowError, QueueEntryNotFoundError } from "@/lib/api/domains/queue-api";
import { useQueue } from "@/hooks/domains/session/use-queue";
import {
canMergeWithAbove,
isWorkflowQueuedMessage,
QueuedGhostMessage,
} from "./queued-ghost-message";
import { canMergeWithAbove, QueuedGhostMessage } from "./queued-ghost-message";
import type { QueuedMessage } from "@/lib/state/slices/session/types";
import type { EntityReference } from "@/lib/types/entity-reference";
const HEAD_PREVIEW_MAX = 80;
/** Inter-task entries are dispatched with queued_by="agent" and stay read-only. */
/** Only WebSocket-authored user rows use the editable `user` provenance. */
function canUserEditEntry(entry: QueuedMessage): boolean {
return entry.queued_by !== "agent" && !isWorkflowQueuedMessage(entry);
return entry.queued_by === "user";
}
function headPreviewText(entries: QueuedMessage[]): string {
@@ -114,10 +110,10 @@ function useQueuePanelHandlers({
await removeEntry(entryId);
} catch (err) {
console.error("Failed to remove queued entry:", err);
toast.error("Failed to remove queued message.");
toast.error(t("chat:failedToRemoveQueuedMessage"));
}
},
[removeEntry],
[removeEntry, t],
);
const handleMerge = useCallback(
async (entryId: string) => {
@@ -145,15 +141,15 @@ function useQueuePanelHandlers({
const handleClear = useCallback(() => {
clearAll().catch((err) => {
console.error("Failed to clear queued messages:", err);
toast.error("Failed to clear queued messages.");
toast.error(t("chat:failedToClearQueuedMessages"));
});
}, [clearAll]);
}, [clearAll, t]);
const handleDrain = useCallback(() => {
drainNext().catch((err) => {
console.error("Failed to run queued message:", err);
toast.error("Failed to run queued message.");
toast.error(t("chat:failedToRunQueuedMessage"));
});
}, [drainNext]);
}, [drainNext, t]);
return { handleSave, handleRemove, handleMerge, handleClear, handleDrain };
}
@@ -285,6 +281,7 @@ function chipPalette(isFull: boolean): string {
}
function QueueChip({ count, isFull, previewText, onToggle }: QueueChipProps) {
const { t } = useTranslation();
// aria-expanded/aria-controls are intentionally omitted: the chip and the
// expanded panel are mutually exclusive in the DOM (clicking the chip swaps
// it for the panel header, which carries its own collapse controls). Pointing
@@ -295,17 +292,18 @@ function QueueChip({ count, isFull, previewText, onToggle }: QueueChipProps) {
type="button"
data-testid="queue-chip"
data-full={isFull ? "true" : "false"}
aria-label={`${count} queued message${count === 1 ? "" : "s"}, click to expand`}
aria-label={t("chat:queueChipExpand", { count })}
onClick={onToggle}
className={cn(
"inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5",
"text-[11px] font-medium cursor-pointer transition-colors",
"[@media(pointer:coarse)]:min-h-11 [@media(pointer:coarse)]:px-3",
chipPalette(isFull),
)}
>
<IconLayoutList className="h-3 w-3" />
<span>{count} queued</span>
{isFull && <span className="opacity-80">· full</span>}
<span>{t("chat:queuedCount", { count })}</span>
{isFull && <span className="opacity-80">{t("chat:queueFullSuffix")}</span>}
</button>
);
if (!previewText) return button;
@@ -348,11 +346,12 @@ function QueuePanel({
onRemove,
onMerge,
}: QueuePanelProps) {
const { t } = useTranslation();
return (
<div
id="queue-panel"
role="region"
aria-label="Queued messages"
aria-label={t("chat:queuedMessages")}
data-testid="queued-ghost-list"
className={cn(
"flex max-h-[min(40dvh,32rem)] flex-shrink-0 flex-col px-3 pt-1.5 pb-1",
@@ -380,6 +379,7 @@ function QueuePanel({
entry={entry}
index={index}
canEdit={canUserEditEntry(entry)}
canRemove
canMerge={canMergeWithAbove(entry, entries[index - 1])}
onSave={(content, entityReferences) => onSave(entry.id, content, entityReferences)}
onRemove={() => onRemove(entry.id)}
@@ -412,49 +412,50 @@ function QueuePanelHeader({
onDrain,
onClose,
}: QueuePanelHeaderProps) {
const capacityText = max > 0 ? `${count} of ${max}` : `${count}`;
const { t } = useTranslation();
const capacityText =
max > 0
? t(isFull ? "chat:queueCapacityFull" : "chat:queueCapacity", { count, max })
: t("chat:queueCount", { count });
return (
<div className="flex shrink-0 items-center justify-between gap-3 py-1">
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<IconLayoutList className="h-3.5 w-3.5" />
<span className="uppercase tracking-wide">Queued</span>
<span className={cn(isFull && "text-amber-600 dark:text-amber-400")}>
{capacityText}
{isFull ? " · full" : ""}
</span>
<span className="uppercase tracking-wide">{t("chat:queued")}</span>
<span className={cn(isFull && "text-amber-600 dark:text-amber-400")}>{capacityText}</span>
</div>
<div className="flex items-center gap-1">
{canDrain && (
<Button
variant="ghost"
size="sm"
className="h-6 px-1.5 text-xs text-muted-foreground hover:text-foreground cursor-pointer"
className="h-6 px-1.5 text-xs text-muted-foreground hover:text-foreground cursor-pointer [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:px-3"
onClick={onDrain}
disabled={isLoading}
title="Run next queued message"
title={t("chat:runNextQueuedMessage")}
data-testid="queue-drain-next"
>
<IconPlayerPlay className="mr-1 h-3 w-3" />
Run next
{t("chat:runNext")}
</Button>
)}
<Button
variant="ghost"
size="sm"
className="h-6 px-1.5 text-xs text-muted-foreground hover:text-foreground cursor-pointer"
className="h-6 px-1.5 text-xs text-muted-foreground hover:text-foreground cursor-pointer [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:px-3"
onClick={onClear}
title="Clear all queued messages"
title={t("chat:clearAllQueuedMessages")}
data-testid="queue-clear-all"
>
<IconTrash className="mr-1 h-3 w-3" />
Clear all
{t("chat:clearAll")}
</Button>
<button
type="button"
onClick={onClose}
aria-label="Collapse queued messages"
aria-label={t("chat:collapseQueuedMessages")}
data-testid="queue-close"
className="text-muted-foreground hover:text-foreground cursor-pointer rounded p-1"
className="inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground cursor-pointer rounded p-1 [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
>
<IconX className="h-3.5 w-3.5" />
</button>
@@ -26,6 +26,8 @@ const ATTACHMENT_1_ALT = "Attachment 1";
const OPEN_ATTACHMENT_1_LABEL = "Open Attachment 1";
const FULL_SIZE_ATTACHMENT_1_ALT = "Full size Attachment 1";
const MERGE_TESTID = "queue-entry-merge";
const EDIT_TESTID = "queue-entry-edit";
const REMOVE_TESTID = "queue-entry-remove";
const EDIT_TITLE = "Edit queued message";
const MERGE_TITLE = "Merge with above";
@@ -344,6 +346,59 @@ describe("QueuedGhostMessage merge control", () => {
});
});
describe("QueuedGhostMessage row actions", () => {
it("shows Remove independently when an entry is not editable", () => {
const onRemove = vi.fn();
render(
<QueuedGhostMessage
entry={entry({ queued_by: "agent" })}
canEdit={false}
canRemove
onSave={async () => {}}
onRemove={onRemove}
/>,
);
expect(screen.queryByTestId(EDIT_TESTID)).toBeNull();
fireEvent.click(screen.getByTestId(REMOVE_TESTID));
expect(onRemove).toHaveBeenCalledTimes(1);
});
it("keeps Edit independent from Remove", () => {
render(
<QueuedGhostMessage
entry={entry()}
canEdit
canRemove={false}
onSave={async () => {}}
onRemove={() => {}}
/>,
);
expect(screen.getByTestId(EDIT_TESTID)).toBeTruthy();
expect(screen.queryByTestId(REMOVE_TESTID)).toBeNull();
});
it("keeps compact desktop controls but provides coarse-pointer visibility and 44px targets", () => {
render(
<QueuedGhostMessage
entry={entry({ queued_by: "workflow" })}
canEdit={false}
canRemove
onSave={async () => {}}
onRemove={() => {}}
/>,
);
const remove = screen.getByTestId(REMOVE_TESTID);
expect(remove.className).toContain("h-6");
expect(remove.className).toContain("w-6");
expect(remove.className).toContain("[@media(pointer:coarse)]:h-11");
expect(remove.className).toContain("[@media(pointer:coarse)]:w-11");
expect(remove.parentElement?.className).toContain("[@media(pointer:coarse)]:opacity-100");
});
});
describe("canMergeEntry / canMergeWithAbove gating", () => {
it("treats user entries as mergeable", () => {
expect(canMergeEntry(entry({ queued_by: "user-1" }))).toBe(true);
@@ -291,6 +291,7 @@ type DisplayViewProps = {
entityReferences: readonly EntityReference[];
positionLabel: string;
canEdit: boolean;
canRemove: boolean;
canMerge: boolean;
onStartEdit: () => void;
onRemove: () => void;
@@ -312,6 +313,7 @@ type RowActionsProps = {
expanded: boolean;
canMerge: boolean;
canEdit: boolean;
canRemove: boolean;
onToggleExpand: () => void;
onMerge?: () => void | Promise<void>;
onStartEdit: () => void;
@@ -323,6 +325,7 @@ function RowActions({
expanded,
canMerge,
canEdit,
canRemove,
onToggleExpand,
onMerge,
onStartEdit,
@@ -337,13 +340,14 @@ function RowActions({
// visible on touch surfaces where there's no hover affordance.
"opacity-0 group-hover:opacity-100 focus-within:opacity-100",
"[@media(hover:none)]:opacity-100",
"[@media(pointer:coarse)]:opacity-100",
)}
>
{canExpand && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onToggleExpand}
title={expanded ? t("chat:collapseMessage") : t("chat:expandMessage")}
data-testid="queue-entry-expand"
@@ -360,7 +364,7 @@ function RowActions({
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onMerge}
title={t("chat:mergeWithAbove")}
data-testid="queue-entry-merge"
@@ -369,26 +373,28 @@ function RowActions({
</Button>
)}
{canEdit && (
<>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground"
onClick={onStartEdit}
title={t("chat:editQueuedMessage")}
>
<IconEdit className="h-3.5 w-3.5" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground"
onClick={onRemove}
title={t("chat:removeQueuedMessage")}
>
<IconX className="h-4 w-4" />
</Button>
</>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onStartEdit}
title={t("chat:editQueuedMessage")}
data-testid="queue-entry-edit"
>
<IconEdit className="h-3.5 w-3.5" />
</Button>
)}
{canRemove && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onRemove}
title={t("chat:removeQueuedMessage")}
data-testid="queue-entry-remove"
>
<IconX className="h-4 w-4" />
</Button>
)}
</div>
);
@@ -399,6 +405,7 @@ function DisplayView({
entityReferences,
positionLabel,
canEdit,
canRemove,
canMerge,
onStartEdit,
onRemove,
@@ -415,7 +422,7 @@ function DisplayView({
[entityReferences],
);
return (
<div className="group flex items-start gap-2 py-1.5">
<div className="group flex items-start gap-2 py-1.5" data-testid="queue-entry">
<span className="flex items-center gap-1.5 mt-0.5 text-muted-foreground">
<span
aria-label={`Position ${positionLabel}`}
@@ -451,6 +458,7 @@ function DisplayView({
expanded={expanded}
canMerge={canMerge}
canEdit={canEdit}
canRemove={canRemove}
onToggleExpand={() => setExpanded((v) => !v)}
onMerge={onMerge}
onStartEdit={onStartEdit}
@@ -469,6 +477,8 @@ type QueuedGhostMessageProps = {
* entry's queued_by. Inter-task entries are visible but read-only.
*/
canEdit: boolean;
/** Removal is independent from edit ownership and applies to every visible row. */
canRemove?: boolean;
/**
* Merge-with-above control; only shown when this row and the one above it
* share a sender kind. Optional so standalone renders (tests) can omit it.
@@ -482,11 +492,34 @@ type QueuedGhostMessageProps = {
onEditComplete?: () => void;
};
function useFocusQueuedEdit(
editing: boolean,
textareaRef: React.RefObject<HTMLTextAreaElement | null>,
): void {
useEffect(() => {
if (!editing || !textareaRef.current) return;
const textarea = textareaRef.current;
textarea.focus();
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
}, [editing, textareaRef]);
}
export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGhostMessageProps>(
function QueuedGhostMessage(
{ entry, index, canEdit, canMerge = false, onSave, onRemove, onMerge, onEditComplete },
{
entry,
index,
canEdit,
canRemove = true,
canMerge = false,
onSave,
onRemove,
onMerge,
onEditComplete,
},
ref,
) {
const { t } = useTranslation();
const [editing, setEditing] = useState(false);
const [value, setValue] = useState(entry.content);
const [saving, setSaving] = useState(false);
@@ -495,23 +528,13 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
() => entityReferencesFromMetadata(entry.metadata),
[entry.metadata],
);
// A row is mergeable only when both the caller gate and the entry itself
// pass: workflow/server/system rows are reserved and never mergeable, even
// if a parent computed canMerge for a different row.
const effectiveCanMerge = canMerge && canMergeEntry(entry);
useFocusQueuedEdit(editing, textareaRef);
useEffect(() => {
if (!editing) setValue(entry.content);
}, [entry.content, editing]);
useEffect(() => {
if (editing && textareaRef.current) {
const el = textareaRef.current;
el.focus();
el.setSelectionRange(el.value.length, el.value.length);
}
}, [editing]);
const startEdit = useCallback(() => {
if (!canEdit) return;
setValue(entry.content);
@@ -540,22 +563,23 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
onEditComplete?.();
} catch (err) {
console.error("Failed to update queued entry:", err);
// Exit edit mode so the user sees the current state instead of being
// stuck in a textarea with no signal that the save failed (drain race
// or transient network error).
// Exit edit mode after both drain races and transient failures.
if (err instanceof QueueEntryNotFoundError) {
toast.error("Message already sent — agent picked it up before your edit landed.");
toast.error(t("chat:queueEditAlreadySent"));
} else {
toast.error("Failed to save edit. Please try again.");
toast.error(t("chat:queueEditSaveFailed"));
}
setEditing(false);
onEditComplete?.();
} finally {
setSaving(false);
}
}, [value, entry.content, onSave, onEditComplete, entityReferences]);
}, [value, entry.content, onSave, onEditComplete, entityReferences, t]);
const positionNumber = entry.position ?? (index ?? 0) + 1;
// Persisted positions are durable FIFO keys and intentionally retain gaps
// after a remove or merge. The panel index is the compact user-facing
// ordinal, so prefer it whenever this row belongs to a rendered list.
const positionNumber = index === undefined ? (entry.position ?? 1) : index + 1;
const positionLabel = `#${positionNumber}`;
return (
@@ -581,6 +605,7 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
entityReferences={entityReferences}
positionLabel={positionLabel}
canEdit={canEdit}
canRemove={canRemove}
canMerge={effectiveCanMerge}
onStartEdit={startEdit}
onRemove={onRemove}
@@ -101,18 +101,20 @@ async function createIdleTarget(
return { id: task.id, sessionId: task.session_id };
}
/** Create a sender task whose initial prompt fires off a single message_task
* call against the supplied target and then exits with a final text. */
/** Create a sender task whose initial prompt fires one or more message_task
* calls against the supplied target and then exits with a final text. */
async function createSenderTaskingTarget(
apiClient: ApiClient,
seedData: SeedData,
title: string,
targetTaskId: string,
prompt: string,
prompt: string | string[],
): Promise<{ id: string; sessionId: string }> {
const description = [mcpScript({ task_id: targetTaskId, prompt }), 'e2e:message("done")'].join(
"\n",
);
const prompts = Array.isArray(prompt) ? prompt : [prompt];
const description = [
...prompts.map((message) => mcpScript({ task_id: targetTaskId, prompt: message })),
'e2e:message("done")',
].join("\n");
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
title,
@@ -136,6 +138,83 @@ async function openTask(testPage: Page, taskId: string): Promise<SessionPage> {
}
test.describe("Cross-task agent message attribution", () => {
test("full agent-origin queue supports remove, clear-all, and new admission", async ({
testPage,
apiClient,
seedData,
}) => {
test.setTimeout(120_000);
const target = await createIdleTarget(
apiClient,
seedData,
"Target — full agent queue",
["e2e:delay(90000)", 'e2e:message("target finished")'].join("\n"),
);
const session = await openTask(testPage, target.id);
await expect
.poll(
async () => {
const { sessions } = await apiClient.listTaskSessions(target.id);
return sessions.find((candidate) => candidate.id === target.sessionId)?.state;
},
{ timeout: 20_000, message: "Target did not stay busy for queue seeding" },
)
.toBe("RUNNING");
await createSenderTaskingTarget(
apiClient,
seedData,
"Sender — first five queue rows",
target.id,
Array.from({ length: 5 }, (_, index) => `agent queued ${index + 1}`),
);
await createSenderTaskingTarget(
apiClient,
seedData,
"Sender — final five queue rows",
target.id,
Array.from({ length: 5 }, (_, index) => `agent queued ${index + 6}`),
);
const chat = session.activeChat();
const chip = chat.getByTestId("queue-chip");
await expect(chip).toContainText("10 queued", { timeout: 30_000 });
await chip.click();
const panel = chat.getByTestId("queued-ghost-list");
const entries = panel.getByTestId("queue-entry-text");
await expect(entries).toHaveCount(10, { timeout: 30_000 });
await expect(panel).toContainText("10 of 10");
await expect(panel.getByTestId("sender-task-badge")).toHaveCount(10);
await expect(panel.getByTestId("queue-entry-edit")).toHaveCount(0);
await expect(panel.getByTestId("queue-entry-remove")).toHaveCount(10);
const firstAgentEntry = panel.getByTestId("queue-entry").filter({
has: testPage.getByTestId("queue-entry-text").filter({ hasText: /^agent queued 1$/ }),
});
await firstAgentEntry.getByTestId("queue-entry-remove").click();
await expect(entries).toHaveCount(9, { timeout: 10_000 });
await expect(panel).toContainText("9 of 10");
await panel.getByTestId("queue-clear-all").click();
await expect(panel).not.toBeVisible({ timeout: 10_000 });
await expect(chat.getByTestId("queue-chip")).not.toBeVisible();
await createSenderTaskingTarget(
apiClient,
seedData,
"Sender — capacity reopened",
target.id,
"accepted after clear",
);
await expect(chat.getByTestId("queue-chip")).toContainText("1 queued", {
timeout: 30_000,
});
await chat.getByTestId("queue-chip").click();
await expect(chat.getByTestId("queue-entry-text")).toHaveText("accepted after clear");
});
test("running target task: queued message shows sender badge in chat", async ({
testPage,
apiClient,
@@ -0,0 +1,51 @@
import { expect, type Locator } from "@playwright/test";
import { test } from "../../fixtures/test-base";
import { expectFullQueueScrolls, seedFullQueueTask } from "./message-queue-scroll-helpers";
async function expectTouchTarget(locator: Locator): Promise<void> {
await expect(locator).toBeVisible();
const box = await locator.boundingBox();
expect(box).not.toBeNull();
expect(box!.width).toBeGreaterThanOrEqual(44);
expect(box!.height).toBeGreaterThanOrEqual(44);
}
test("mobile full queue stays usable while removing and clearing messages", async ({
testPage,
apiClient,
seedData,
}) => {
const session = await seedFullQueueTask(testPage, apiClient, seedData, "Mobile queue management");
await expectFullQueueScrolls(session);
const chat = session.activeChat();
const panel = chat.getByTestId("queued-ghost-list");
const entries = panel.getByTestId("queue-entry-text");
const remove = panel.getByTestId("queue-entry-remove").nth(4);
const clear = panel.getByTestId("queue-clear-all");
const close = panel.getByTestId("queue-close");
await remove.scrollIntoViewIfNeeded();
await expectTouchTarget(remove);
await expectTouchTarget(clear);
await expectTouchTarget(close);
await remove.tap();
await expect(entries).toHaveCount(9, { timeout: 10_000 });
await expect(panel).toContainText("9 of 10");
await expect(panel.locator('[aria-label^="Position #"]').nth(4)).toHaveAttribute(
"aria-label",
"Position #5",
);
await expect(panel.locator('[aria-label^="Position #"]').last()).toHaveAttribute(
"aria-label",
"Position #9",
);
await expect(chat.getByTestId("chat-input-editor-shell")).toBeVisible();
await clear.tap();
await expect(panel).not.toBeVisible({ timeout: 10_000 });
await expect(chat.getByTestId("queue-chip")).not.toBeVisible();
await expect(chat.getByTestId("chat-input-editor-shell")).toBeVisible();
});
@@ -1,17 +0,0 @@
import { test } from "../../fixtures/test-base";
import { expectFullQueueScrolls, seedFullQueueTask } from "./message-queue-scroll-helpers";
test("mobile full queue scrolls internally without hiding the composer", async ({
testPage,
apiClient,
seedData,
}) => {
const session = await seedFullQueueTask(
testPage,
apiClient,
seedData,
"Mobile full queue scrolling",
);
await expectFullQueueScrolls(session);
});
@@ -0,0 +1,117 @@
import { test, expect } from "../../fixtures/test-base";
import type { ApiClient } from "../../helpers/api-client";
import type { MessageQueueSettingsResponse } from "../../../lib/types/system";
const SETTINGS_PATH = "/api/v1/system/message-queue/settings";
async function requestSettings(
apiClient: ApiClient,
method: "GET" | "PATCH",
maxPerSession?: number,
): Promise<MessageQueueSettingsResponse> {
const response = await apiClient.rawRequest(
method,
SETTINGS_PATH,
maxPerSession === undefined ? undefined : { max_per_session: maxPerSession },
);
if (!response.ok) {
throw new Error(
`${method} ${SETTINGS_PATH} failed (${response.status}): ${await response.text()}`,
);
}
return response.json() as Promise<MessageQueueSettingsResponse>;
}
test.describe.serial("Message Queue general settings", () => {
let baseline: number | undefined;
test.beforeEach(async ({ apiClient }) => {
baseline = (await requestSettings(apiClient, "GET")).settings.max_per_session;
});
test.afterEach(async ({ apiClient }) => {
if (baseline === undefined) return;
await requestSettings(apiClient, "PATCH", baseline);
baseline = undefined;
});
test("admin navigates to Message Queue, saves, and reloads the live setting", async ({
testPage,
}) => {
const updated = baseline === 17 ? 18 : 17;
await testPage.goto("/settings/general/appearance");
const settingsNav = testPage.getByTestId("app-sidebar-settings-mode");
await settingsNav.getByRole("link", { name: "Message Queue" }).click();
await expect(testPage).toHaveURL(
(url) => new URL(url).pathname === "/settings/general/message-queue",
);
await expect(testPage.getByTestId("system-page-title")).toHaveText("Message Queue");
const input = testPage.getByTestId("message-queue-max-per-session");
await expect(input).toHaveValue(String(baseline));
await input.fill(String(updated));
await expect(testPage.getByTestId("settings-floating-save")).toBeVisible();
const saveResponse = testPage.waitForResponse(
(response) =>
response.request().method() === "PATCH" &&
new URL(response.url()).pathname === SETTINGS_PATH,
);
await testPage.getByRole("button", { name: "Save changes" }).click();
expect((await saveResponse).status()).toBe(200);
await expect(testPage.getByTestId("message-queue-effective-value")).toHaveText(String(updated));
await expect(testPage.getByTestId("message-queue-source")).toHaveText("Saved setting");
await testPage.reload();
await expect(input).toHaveValue(String(updated));
await expect(testPage.getByTestId("message-queue-effective-value")).toHaveText(String(updated));
});
test("environment override is visible and read-only", async ({ testPage }) => {
await testPage.route(`**${SETTINGS_PATH}`, async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
settings: { max_per_session: baseline },
effective: { max_per_session: 41, source: "environment", locked: true },
} satisfies MessageQueueSettingsResponse),
});
});
await testPage.goto("/settings/general/message-queue");
await expect(testPage.getByTestId("message-queue-max-per-session")).toBeDisabled();
await expect(testPage.getByTestId("message-queue-effective-value")).toHaveText("41");
await expect(testPage.getByTestId("message-queue-source")).toHaveText("Environment");
await expect(testPage.getByText(/KANDEV_QUEUE_MAX_PER_SESSION/).first()).toBeVisible();
await expect(testPage.getByTestId("settings-floating-save")).toHaveCount(0);
});
test("member can navigate to the setting but cannot edit it", async ({ testPage }) => {
await testPage.goto("/settings/general/appearance");
await testPage.waitForFunction(() => Boolean(window.__KANDEV_E2E_STORE__));
await testPage.evaluate(() => {
const store = window.__KANDEV_E2E_STORE__;
if (!store) throw new Error("E2E store bridge is unavailable");
store.getState().setAuthState({
mode: "enabled",
authenticated: true,
user: {
id: "e2e-member",
email: "member@e2e.dev",
display_name: "E2E Member",
role: "member",
status: "active",
},
ssoProviders: [],
});
});
const settingsNav = testPage.getByTestId("app-sidebar-settings-mode");
await settingsNav.getByRole("link", { name: "Message Queue" }).click();
await expect(testPage.getByTestId("message-queue-max-per-session")).toBeDisabled();
await expect(testPage.getByText("Only administrators can change this setting.")).toBeVisible();
await expect(testPage.getByTestId("settings-floating-save")).toHaveCount(0);
});
});
@@ -0,0 +1,50 @@
import { test, expect } from "../../fixtures/test-base";
import { MobileKanbanPage } from "../../pages/mobile-kanban-page";
test("mobile navigation reaches Message Queue with touch-safe shared settings layout", async ({
testPage,
}) => {
const mobile = new MobileKanbanPage(testPage);
await mobile.goto();
await mobile.mobileMenuButton.click();
const homeMenu = testPage.getByTestId("mobile-home-menu-card");
await homeMenu.getByRole("link", { name: "Settings" }).click();
await testPage.getByTestId("settings-mobile-menu-button").click();
const menu = testPage.getByTestId("settings-mobile-menu");
await menu.getByRole("button", { name: "Expand General" }).click();
await menu.getByRole("link", { name: "Message Queue" }).click();
await expect(testPage).toHaveURL(
(url) => new URL(url).pathname === "/settings/general/message-queue",
);
await expect(testPage.getByTestId("system-page-title")).toHaveText("Message Queue");
const input = testPage.getByTestId("message-queue-max-per-session");
await expect(input).toBeVisible();
const inputBox = await input.boundingBox();
expect(inputBox).not.toBeNull();
expect(inputBox!.height).toBeGreaterThanOrEqual(44);
await expect
.poll(() => testPage.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth))
.toBe(true);
await expect(testPage.getByTestId("settings-scroll-container")).toHaveCSS("overflow-y", "auto");
const nestedScrollOwners = await testPage.getByTestId("message-queue-settings").evaluate(
(root) =>
Array.from(root.querySelectorAll("*")).filter((element) => {
const overflow = getComputedStyle(element).overflowY;
return overflow === "auto" || overflow === "scroll";
}).length,
);
expect(nestedScrollOwners).toBe(0);
const current = await input.inputValue();
await input.fill(current === "23" ? "24" : "23");
const saveBar = testPage.getByTestId("settings-floating-save");
await expect(saveBar).toBeVisible();
const [inputAfterEdit, saveBox] = await Promise.all([input.boundingBox(), saveBar.boundingBox()]);
expect(inputAfterEdit).not.toBeNull();
expect(saveBox).not.toBeNull();
expect(inputAfterEdit!.y + inputAfterEdit!.height).toBeLessThan(saveBox!.y);
});
@@ -265,10 +265,47 @@ describe("useQueue clearAll", () => {
beforeEach(() => {
resetMockState();
setDocumentVisibility("visible");
queueApiMock.clearQueue.mockReset();
queueApiMock.getQueueStatus.mockResolvedValue({ entries: [], count: 0, max: 10 });
queueApiMock.clearQueue.mockResolvedValue(undefined);
});
it("refetches authoritative status after a successful clear", async () => {
const { result } = renderHook(() => useQueue(SESSION_ID));
await waitFor(() => expect(queueApiMock.getQueueStatus).toHaveBeenCalled());
queueApiMock.getQueueStatus.mockClear();
await act(async () => {
await result.current.clearAll();
});
expect(queueApiMock.clearQueue).toHaveBeenCalledWith(SESSION_ID);
expect(queueApiMock.getQueueStatus).toHaveBeenCalledWith(SESSION_ID);
});
it("refetches authoritative status and rethrows when clear fails", async () => {
queueApiMock.clearQueue.mockRejectedValueOnce(new Error("clear failed"));
const authoritative = entry({ id: "still-queued" });
const { result } = renderHook(() => useQueue(SESSION_ID));
await waitFor(() => expect(queueApiMock.getQueueStatus).toHaveBeenCalled());
queueApiMock.getQueueStatus.mockClear();
queueApiMock.getQueueStatus.mockResolvedValueOnce({
entries: [authoritative],
count: 1,
max: 10,
});
await act(async () => {
await expect(result.current.clearAll()).rejects.toThrow("clear failed");
});
expect(queueApiMock.getQueueStatus).toHaveBeenCalledWith(SESSION_ID);
expect(mockState.setQueueEntries).toHaveBeenCalledWith(SESSION_ID, [authoritative], {
count: 1,
max: 10,
});
});
it("discards an in-flight refetch that resolves after the clear", async () => {
const { result } = renderHook(() => useQueue(SESSION_ID));
await waitFor(() => expect(queueApiMock.getQueueStatus).toHaveBeenCalled());
@@ -306,3 +343,64 @@ describe("useQueue clearAll", () => {
);
});
});
describe("useQueue removeEntry", () => {
beforeEach(() => {
resetMockState();
setDocumentVisibility("visible");
queueApiMock.removeQueuedEntry.mockReset();
queueApiMock.getQueueStatus.mockResolvedValue({ entries: [], count: 0, max: 10 });
});
it("optimistically removes then refetches authoritative status after success", async () => {
queueApiMock.removeQueuedEntry.mockResolvedValueOnce({ entry_id: "q-1" });
const { result } = renderHook(() => useQueue(SESSION_ID));
await waitFor(() => expect(queueApiMock.getQueueStatus).toHaveBeenCalled());
queueApiMock.getQueueStatus.mockClear();
await act(async () => {
await result.current.removeEntry("q-1");
});
expect(mockState.removeQueueEntry).toHaveBeenCalledWith(SESSION_ID, "q-1");
expect(queueApiMock.getQueueStatus).toHaveBeenCalledWith(SESSION_ID);
});
it("refetches after a drain race without surfacing a benign error", async () => {
queueApiMock.removeQueuedEntry.mockRejectedValueOnce(
new queueApiMock.QueueEntryNotFoundError(),
);
const { result } = renderHook(() => useQueue(SESSION_ID));
await waitFor(() => expect(queueApiMock.getQueueStatus).toHaveBeenCalled());
queueApiMock.getQueueStatus.mockClear();
await act(async () => {
await expect(result.current.removeEntry("q-1")).resolves.toBeUndefined();
});
expect(queueApiMock.getQueueStatus).toHaveBeenCalledWith(SESSION_ID);
});
it("refetches and rethrows a failed removal", async () => {
queueApiMock.removeQueuedEntry.mockRejectedValueOnce(new Error("remove failed"));
const authoritative = entry({ id: "q-1" });
const { result } = renderHook(() => useQueue(SESSION_ID));
await waitFor(() => expect(queueApiMock.getQueueStatus).toHaveBeenCalled());
queueApiMock.getQueueStatus.mockClear();
queueApiMock.getQueueStatus.mockResolvedValueOnce({
entries: [authoritative],
count: 1,
max: 10,
});
await act(async () => {
await expect(result.current.removeEntry("q-1")).rejects.toThrow("remove failed");
});
expect(queueApiMock.getQueueStatus).toHaveBeenCalledWith(SESSION_ID);
expect(mockState.setQueueEntries).toHaveBeenCalledWith(SESSION_ID, [authoritative], {
count: 1,
max: 10,
});
});
});
+43 -13
View File
@@ -139,21 +139,34 @@ function useQueueActions({
const clearAll = useCallback(async () => {
if (!sessionId) return;
setQueueLoading(sessionId, true);
let mutationFailed = false;
let mutationError: unknown;
try {
await clearQueue(sessionId);
// Invalidate any in-flight refetch so a pre-clear getQueueStatus
// response cannot land after the empty snapshot and restore the
// entries that were just drained.
refetchVersion.current[sessionId] = (refetchVersion.current[sessionId] ?? 0) + 1;
// Reset to a neutral capacity snapshot; the next status_changed event
// will replace it with the authoritative server value. Using the
// pre-clear entry count as a fallback for `max` was wrong (it would
// pretend the cap equals "however many were queued").
setQueueEntries(sessionId, [], { count: 0, max: metaMax ?? 0 });
try {
await clearQueue(sessionId);
// Invalidate any pre-clear status request before publishing the
// optimistic empty state. The explicit refetch below then owns the
// newest version and replaces it with the backend's exact result.
refetchVersion.current[sessionId] = (refetchVersion.current[sessionId] ?? 0) + 1;
setQueueEntries(sessionId, [], { count: 0, max: metaMax ?? 0 });
} catch (err) {
mutationFailed = true;
mutationError = err;
}
try {
await refetch(sessionId);
} catch (reconcileError) {
// Preserve the mutation error when both operations fail; it best
// explains why the requested action did not complete.
if (mutationFailed) throw mutationError;
throw reconcileError;
}
if (mutationFailed) throw mutationError;
} finally {
setQueueLoading(sessionId, false);
}
}, [sessionId, setQueueEntries, setQueueLoading, metaMax]);
}, [sessionId, setQueueEntries, setQueueLoading, metaMax, refetch]);
const drainNext = useDrainNextAction(sessionId, setQueueLoading, refetch);
@@ -206,12 +219,29 @@ function useEntryMutations({ sessionId, removeQueueEntry, refetch }: EntryMutati
async (entryId: string) => {
if (!sessionId) return;
removeQueueEntry(sessionId, entryId);
let mutationFailed = false;
let mutationError: unknown;
try {
await removeQueuedEntry({ session_id: sessionId, entry_id: entryId });
} catch (err) {
if (err instanceof QueueEntryNotFoundError) return;
mutationFailed = true;
mutationError = err;
}
try {
await refetch(sessionId);
throw err;
} catch (reconcileError) {
if (mutationFailed && !(mutationError instanceof QueueEntryNotFoundError)) {
throw mutationError;
}
throw reconcileError;
}
// A drain/remove race is already reflected by the authoritative status,
// so it is a successful UI outcome. Other failures restore state above
// and remain actionable to the caller.
if (mutationFailed && !(mutationError instanceof QueueEntryNotFoundError)) {
throw mutationError;
}
},
[sessionId, refetch, removeQueueEntry],
@@ -0,0 +1,68 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/config", () => ({
getBackendConfig: () => ({ apiBaseUrl: "http://api.test" }),
}));
import { fetchMessageQueueSettings, updateMessageQueueSettings } from "./settings-api";
const BASE = "http://api.test/api/v1/system/message-queue/settings";
type FetchInput = Parameters<typeof fetch>[0];
type FetchInit = Parameters<typeof fetch>[1];
const fetchSpy = vi.fn<(...args: [FetchInput, FetchInit?]) => Promise<Response>>();
beforeEach(() => {
fetchSpy.mockReset();
vi.stubGlobal("fetch", fetchSpy);
});
afterEach(() => vi.unstubAllGlobals());
function jsonResponse(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
function lastCall(): { url: string; init: FetchInit | undefined } {
const call = fetchSpy.mock.calls.at(-1);
if (!call) throw new Error("expected fetch to have been called");
return { url: String(call[0]), init: call[1] };
}
describe("message queue settings api", () => {
it("fetches the current setting without cache", async () => {
fetchSpy.mockResolvedValueOnce(
jsonResponse({
settings: { max_per_session: 10 },
effective: { max_per_session: 10, source: "default", locked: false },
}),
);
const response = await fetchMessageQueueSettings({ cache: "force-cache" });
expect(lastCall().url).toBe(BASE);
expect((lastCall().init?.method ?? "GET").toUpperCase()).toBe("GET");
expect(lastCall().init?.cache).toBe("no-store");
expect(response.effective.source).toBe("default");
});
it("PATCHes the requested per-session maximum", async () => {
fetchSpy.mockResolvedValueOnce(
jsonResponse({
settings: { max_per_session: 25 },
effective: { max_per_session: 25, source: "setting", locked: false },
}),
);
await updateMessageQueueSettings(
{ max_per_session: 25 },
{ init: { method: "GET", body: JSON.stringify({ max_per_session: 2 }) } },
);
expect(lastCall().url).toBe(BASE);
expect(lastCall().init?.method).toBe("PATCH");
expect(lastCall().init?.body).toBe(JSON.stringify({ max_per_session: 25 }));
});
});
+27
View File
@@ -21,6 +21,8 @@ import type {
DynamicModelsResponse,
} from "@/lib/types/http";
import type {
MessageQueueSettingsResponse,
MessageQueueSettingsValue,
SystemMetricsGlobalSettings,
SystemMetricsSettingsResponse,
} from "@/lib/types/system";
@@ -57,6 +59,31 @@ export async function updateSystemMetricsSettings(
});
}
const MESSAGE_QUEUE_SETTINGS_PATH = "/api/v1/system/message-queue/settings";
export async function fetchMessageQueueSettings(
options?: ApiRequestOptions,
): Promise<MessageQueueSettingsResponse> {
return fetchJsonWithRetry<MessageQueueSettingsResponse>(MESSAGE_QUEUE_SETTINGS_PATH, {
...options,
cache: "no-store",
});
}
export async function updateMessageQueueSettings(
payload: MessageQueueSettingsValue,
options?: ApiRequestOptions,
): Promise<MessageQueueSettingsResponse> {
return fetchJson<MessageQueueSettingsResponse>(MESSAGE_QUEUE_SETTINGS_PATH, {
...options,
init: {
...(options?.init ?? {}),
method: "PATCH",
body: JSON.stringify(payload),
},
});
}
// Executors
export async function listExecutors(options?: ApiRequestOptions): Promise<ListExecutorsResponse> {
return fetchJson<ListExecutorsResponse>("/api/v1/executors", options);
+16
View File
@@ -186,6 +186,22 @@ export interface SystemMetricsSettingsResponse {
settings: SystemMetricsGlobalSettings;
}
export interface MessageQueueSettingsValue {
max_per_session: number;
}
export type MessageQueueSettingsSource = "default" | "setting" | "environment";
export interface MessageQueueEffectiveSettings extends MessageQueueSettingsValue {
source: MessageQueueSettingsSource;
locked: boolean;
}
export interface MessageQueueSettingsResponse {
settings: MessageQueueSettingsValue;
effective: MessageQueueEffectiveSettings;
}
export interface SystemMetricSample {
id: SystemMetricId | string;
label: string;
+23
View File
@@ -1,11 +1,34 @@
{
"collapseMessage": "Collapse message",
"collapseQueuedMessages": "Collapse queued messages",
"clearAll": "Clear all",
"clearAllQueuedMessages": "Clear all queued messages",
"editQueuedMessage": "Edit queued message",
"expandMessage": "Expand message",
"failedToClearQueuedMessages": "Failed to clear queued messages.",
"failedToMergeQueuedMessages": "Failed to merge queued messages.",
"failedToRemoveQueuedMessage": "Failed to remove queued message.",
"failedToRunQueuedMessage": "Failed to run queued message.",
"mergeReferenceOverflow": "Too many entity references to merge these queued messages.",
"mergeWithAbove": "Merge with above",
"queueCapacity_one": "{{count}} of {{max}}",
"queueCapacity_other": "{{count}} of {{max}}",
"queueCapacityFull_one": "{{count}} of {{max}} · full",
"queueCapacityFull_other": "{{count}} of {{max}} · full",
"queueChipExpand_one": "{{count}} queued message, click to expand",
"queueChipExpand_other": "{{count}} queued messages, click to expand",
"queueCount_one": "{{count}}",
"queueCount_other": "{{count}}",
"queueEditAlreadySent": "Message already sent — agent picked it up before your edit landed.",
"queueEditSaveFailed": "Failed to save edit. Please try again.",
"queueFullSuffix": "· full",
"queued": "Queued",
"queuedCount_one": "{{count}} queued",
"queuedCount_other": "{{count}} queued",
"queuedMessages": "Queued messages",
"removeQueuedMessage": "Remove queued message",
"runNext": "Run next",
"runNextQueuedMessage": "Run next queued message",
"technicalDetails": "Technical details",
"providerQuotaTitle": "{{provider}} usage limit reached",
"providerQuotaModel": "Model: {{model}}",
+21
View File
@@ -155,6 +155,27 @@
"licensesStaleWarning": "Go license entries were reused from the committed manifest because generation failed. Regenerate licenses when go-licenses is healthy to refresh Go dependency data.",
"licensesTitle": "Third-party licenses",
"licensesToggleLabel": "Show license text for {{name}}",
"messageQueueAdminOnly": "Only administrators can change this setting.",
"messageQueueConfigured": "Configured:",
"messageQueueDescription": "Control how many pending messages each session can hold before new work is rejected.",
"messageQueueEffective": "Effective:",
"messageQueueEffectiveHelp": "The effective value is used for new admissions now. Existing queue entries are not pruned when this value is lowered.",
"messageQueueEnvironmentLockTitle": "Managed by environment",
"messageQueueEnvironmentLocked": "{{variable}} overrides the saved setting. Change the environment value and restart Kandev to edit it here again.",
"messageQueueLimitDescription": "This limit applies immediately to newly admitted messages. Lowering it never removes messages already waiting, and accepted delivery retries remain safe.",
"messageQueueLimitTitle": "Per-session queue limit",
"messageQueueLoadFailed": "Message queue settings could not be loaded.",
"messageQueueLoading": "Loading message queue settings…",
"messageQueueMaximumLabel": "Maximum messages per session",
"messageQueueRetry": "Retry",
"messageQueueSaveFailed": "Failed to save message queue settings.",
"messageQueueSourceDefault": "Default",
"messageQueueSourceEnvironment": "Environment",
"messageQueueSourceSetting": "Saved setting",
"messageQueueTitle": "Message Queue",
"messageQueueUnlimited": "Unlimited",
"messageQueueUnlimitedHelp": "Set 0 for unlimited. A positive whole number rejects new messages after that many are pending in one session.",
"messageQueueValidation": "Enter a whole number of 0 or greater.",
"navAbout": "About",
"navBackups": "Backups",
"navDatabase": "Database",
+23
View File
@@ -1,11 +1,34 @@
{
"collapseMessage": "Ćōĺĺàƥśē ḿēśśàĝē",
"collapseQueuedMessages": "Ćōĺĺàƥśē qũēũēď ḿēśśàĝēś",
"clearAll": "Ćĺēàŕ àĺĺ",
"clearAllQueuedMessages": "Ćĺēàŕ àĺĺ qũēũēď ḿēśśàĝēś",
"editQueuedMessage": "Ēďĩţ qũēũēď ḿēśśàĝē",
"expandMessage": "Ēxƥàńď ḿēśśàĝē",
"failedToClearQueuedMessages": "Ƒàĩĺēď ţō ćĺēàŕ qũēũēď ḿēśśàĝēś.",
"failedToMergeQueuedMessages": "Ƒàĩĺēď ţō ḿēŕĝē qũēũēď ḿēśśàĝēś.",
"failedToRemoveQueuedMessage": "Ƒàĩĺēď ţō ŕēḿōvē qũēũēď ḿēśśàĝē.",
"failedToRunQueuedMessage": "Ƒàĩĺēď ţō ŕũń qũēũēď ḿēśśàĝē.",
"mergeReferenceOverflow": "Ţōō ḿàńŷ ēńţĩţŷ ŕēƒēŕēńćēś ţō ḿēŕĝē ţĥēśē qũēũēď ḿēśśàĝēś.",
"mergeWithAbove": "Ḿēŕĝē ŵĩţĥ àƀōvē",
"queueCapacity_one": "{{count}} ōƒ {{max}}",
"queueCapacity_other": "{{count}} ōƒ {{max}}",
"queueCapacityFull_one": "{{count}} ōƒ {{max}} · ƒũĺĺ",
"queueCapacityFull_other": "{{count}} ōƒ {{max}} · ƒũĺĺ",
"queueChipExpand_one": "{{count}} qũēũēď ḿēśśàĝē, ćĺĩćķ ţō ēxƥàńď",
"queueChipExpand_other": "{{count}} qũēũēď ḿēśśàĝēś, ćĺĩćķ ţō ēxƥàńď",
"queueCount_one": "{{count}}",
"queueCount_other": "{{count}}",
"queueEditAlreadySent": "Ḿēśśàĝē àĺŕēàďŷ śēńţ — àĝēńţ ƥĩćķēď ĩţ ũƥ ƀēƒōŕē ŷōũŕ ēďĩţ ĺàńďēď.",
"queueEditSaveFailed": "Ƒàĩĺēď ţō śàvē ēďĩţ. Ƥĺēàśē ţŕŷ àĝàĩń.",
"queueFullSuffix": "· ƒũĺĺ",
"queued": "Qũēũēď",
"queuedCount_one": "{{count}} qũēũēď",
"queuedCount_other": "{{count}} qũēũēď",
"queuedMessages": "Qũēũēď ḿēśśàĝēś",
"removeQueuedMessage": "Ŕēḿōvē qũēũēď ḿēśśàĝē",
"runNext": "Ŕũń ńēxţ",
"runNextQueuedMessage": "Ŕũń ńēxţ qũēũēď ḿēśśàĝē",
"technicalDetails": "Ţēćĥńĩćàĺ ďēţàĩĺś",
"providerQuotaTitle": "{{provider}} ũśàĝē ĺĩḿĩţ ŕēàćĥēď",
"providerQuotaModel": "Ḿōďēĺ: {{model}}",
+21
View File
@@ -155,6 +155,27 @@
"licensesStaleWarning": "Ĝō ĺĩćēńśē ēńţŕĩēś ŵēŕē ŕēũśēď ƒŕōḿ ţĥē ćōḿḿĩţţēď ḿàńĩƒēśţ ƀēćàũśē ĝēńēŕàţĩōń ƒàĩĺēď. Ŕēĝēńēŕàţē ĺĩćēńśēś ŵĥēń ĝō-ĺĩćēńśēś ĩś ĥēàĺţĥŷ ţō ŕēƒŕēśĥ Ĝō ďēƥēńďēńćŷ ďàţà.",
"licensesTitle": "Ţĥĩŕď-ƥàŕţŷ ĺĩćēńśēś",
"licensesToggleLabel": "Śĥōŵ ĺĩćēńśē ţēxţ ƒōŕ {{name}}",
"messageQueueAdminOnly": "Ōńĺŷ àďḿĩńĩśţŕàţōŕś ćàń ćĥàńĝē ţĥĩś śēţţĩńĝ.",
"messageQueueConfigured": "Ćōńƒĩĝũŕēď:",
"messageQueueDescription": "Ćōńţŕōĺ ĥōŵ ḿàńŷ ƥēńďĩńĝ ḿēśśàĝēś ēàćĥ śēśśĩōń ćàń ĥōĺď ƀēƒōŕē ńēŵ ŵōŕķ ĩś ŕēĵēćţēď.",
"messageQueueEffective": "Ēƒƒēćţĩvē:",
"messageQueueEffectiveHelp": "Ţĥē ēƒƒēćţĩvē vàĺũē ĩś ũśēď ƒōŕ ńēŵ àďḿĩśśĩōńś ńōŵ. Ēxĩśţĩńĝ qũēũē ēńţŕĩēś àŕē ńōţ ƥŕũńēď ŵĥēń ţĥĩś vàĺũē ĩś ĺōŵēŕēď.",
"messageQueueEnvironmentLockTitle": "Ḿàńàĝēď ƀŷ ēńvĩŕōńḿēńţ",
"messageQueueEnvironmentLocked": "{{variable}} ōvēŕŕĩďēś ţĥē śàvēď śēţţĩńĝ. Ćĥàńĝē ţĥē ēńvĩŕōńḿēńţ vàĺũē àńď ŕēśţàŕţ Ķàńďēv ţō ēďĩţ ĩţ ĥēŕē àĝàĩń.",
"messageQueueLimitDescription": "Ţĥĩś ĺĩḿĩţ àƥƥĺĩēś ĩḿḿēďĩàţēĺŷ ţō ńēŵĺŷ àďḿĩţţēď ḿēśśàĝēś. Ĺōŵēŕĩńĝ ĩţ ńēvēŕ ŕēḿōvēś ḿēśśàĝēś àĺŕēàďŷ ŵàĩţĩńĝ, àńď àććēƥţēď ďēĺĩvēŕŷ ŕēţŕĩēś ŕēḿàĩń śàƒē.",
"messageQueueLimitTitle": "Ƥēŕ-śēśśĩōń qũēũē ĺĩḿĩţ",
"messageQueueLoadFailed": "Ḿēśśàĝē qũēũē śēţţĩńĝś ćōũĺď ńōţ ƀē ĺōàďēď.",
"messageQueueLoading": "Ĺōàďĩńĝ ḿēśśàĝē qũēũē śēţţĩńĝś…",
"messageQueueMaximumLabel": "Ḿàxĩḿũḿ ḿēśśàĝēś ƥēŕ śēśśĩōń",
"messageQueueRetry": "Ŕēţŕŷ",
"messageQueueSaveFailed": "Ƒàĩĺēď ţō śàvē ḿēśśàĝē qũēũē śēţţĩńĝś.",
"messageQueueSourceDefault": "Ďēƒàũĺţ",
"messageQueueSourceEnvironment": "Ēńvĩŕōńḿēńţ",
"messageQueueSourceSetting": "Śàvēď śēţţĩńĝ",
"messageQueueTitle": "Ḿēśśàĝē Qũēũē",
"messageQueueUnlimited": "Ũńĺĩḿĩţēď",
"messageQueueUnlimitedHelp": "Śēţ 0 ƒōŕ ũńĺĩḿĩţēď. À ƥōśĩţĩvē ŵĥōĺē ńũḿƀēŕ ŕēĵēćţś ńēŵ ḿēśśàĝēś àƒţēŕ ţĥàţ ḿàńŷ àŕē ƥēńďĩńĝ ĩń ōńē śēśśĩōń.",
"messageQueueValidation": "Ēńţēŕ à ŵĥōĺē ńũḿƀēŕ ōƒ 0 ōŕ ĝŕēàţēŕ.",
"navAbout": "Àƀōũţ",
"navBackups": "Ɓàćķũƥś",
"navDatabase": "Ďàţàƀàśē",
+21
View File
@@ -129,6 +129,27 @@ describe("buildSettingsInitialStateForRoute", () => {
});
});
describe("message queue settings route", () => {
it("registers the Message Queue General settings leaf", () => {
const route = renderSettingsRoute("/settings/general/message-queue");
expect(isValidElement(route)).toBe(true);
expect(((route as ReactElement).type as { name?: string }).name).toBe(
"MessageQueueSettingsPage",
);
});
it("redirects the former System URL to the General settings leaf", () => {
const route = renderSettingsRoute("/settings/system/message-queue") as ReactElement<{
to: string;
}>;
expect(isValidElement(route)).toBe(true);
expect((route.type as { name?: string }).name).toBe("SettingsRedirect");
expect(route.props.to).toBe("/settings/general/message-queue");
});
});
describe("renderSettingsRoute", () => {
it("directs update notification settings to Notifications", () => {
render(renderSettingsRoute("/settings/system/updates"));
+3
View File
@@ -22,6 +22,7 @@ import IntegrationsSentryPage from "@/app/settings/integrations/sentry/page";
import IntegrationsSlackPage from "@/app/settings/integrations/slack/page";
import PluginsSettingsPage from "@/app/settings/plugins/page";
import PluginDetailPage from "@/app/settings/plugins/[pluginId]/page";
import MessageQueueSettingsPage from "@/app/settings/general/message-queue/page";
import StoragePage from "@/app/settings/system/storage/page";
import UtilityAgentsSettingsPage from "@/app/settings/utility-agents/page";
import AutomationsPage from "@/app/settings/workspace/[id]/automations/page";
@@ -141,6 +142,7 @@ const SETTINGS_ROUTES: Record<string, RouteRenderer> = {
"/settings/general/editors": () => <EditorsSettings />,
"/settings/general/keyboard-shortcuts": () => <KeyboardShortcutsSettings />,
"/settings/general/layouts": () => <LayoutSettings />,
"/settings/general/message-queue": () => <MessageQueueSettingsPage />,
"/settings/general/notifications": () => <NotificationsSettings />,
"/settings/general/resource-metrics": () => (
<SettingsRedirect to="/settings/general/appearance" />
@@ -230,6 +232,7 @@ const SETTINGS_ROUTES: Record<string, RouteRenderer> = {
<LogViewer />
</SystemRouteShell>
),
"/settings/system/message-queue": () => <SettingsRedirect to="/settings/general/message-queue" />,
"/settings/system/status": () => (
<SystemRouteShell titleKey="common:status" descriptionKey="system:statusPageDescription">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
@@ -209,3 +209,14 @@ target whose `queued_by` equals the caller's identity.
Workflow- and server-owned rows remain entirely non-mergeable, and the reference-
overflow guard (a merge is rejected atomically when the combined entity
references exceed the per-message cap) applies to every sender kind.
## Supersession: session-owner queue cancellation
**Date:** 2026-08-03
[ADR-2026-08-03-separate-message-queue-provenance-cancellation-and-capacity](2026-08-03-separate-message-queue-provenance-cancellation-and-capacity.md)
supersedes this ADR only where it prohibited authorized clients from deleting
agent-, workflow-, or server-owned **pending** queue rows. Provenance still
governs editing and merging. Durable lifecycle rows already reserved in flight
remain hidden and non-cancellable, and all acknowledgement, retry, purge, and
generation guarantees in this ADR remain unchanged.
@@ -0,0 +1,103 @@
# ADR-2026-08-03-separate-message-queue-provenance-cancellation-and-capacity: Separate Message Queue Provenance, Cancellation, and Capacity
**Status:** accepted
**Date:** 2026-08-03
**Area:** backend, frontend, protocol, security
## Context
Queued messages carry a `queued_by` identity that records their provenance:
user, agent, workflow, or server. ADR 0051 also used that provenance as a
client-mutation boundary, allowing clients to remove only user-owned rows.
That coupling made an authorized task owner unable to discard visible work
sent by another task. The queue panel still offered **Clear all**, but the
backend silently retained every agent-, workflow-, and server-owned row. A
queue containing ten inter-task messages therefore stayed full after the
user's explicit clear action.
The per-session capacity is also an operational policy. It currently comes
only from `KANDEV_QUEUE_MAX_PER_SESSION`, so changing it requires access to the
launch environment and a backend restart. Users need an install-wide setting
without weakening environment-controlled deployments or risking already
accepted delivery work when the limit is lowered.
## Decision
Treat provenance, content mutation, cancellation, and capacity as separate
concerns.
- `queued_by` remains immutable provenance. It continues to govern content
editing and the existing merge rules; it does not grant a pending message an
exemption from an authorized user's explicit discard action.
- A caller authorized for the target session may remove any **visible pending**
queue entry, regardless of whether it came from a user, agent, workflow, or
server. **Clear all** removes every visible pending message in that session.
- A durable lifecycle row marked `lifecycle_reserved_in_flight` is already in
the delivery protocol, is omitted from queue status, and is not cancellable
through either user action. Cancellation and reservation serialize per
session and use persisted compare guards so whichever operation wins does so
completely. Backend archive/delete purge remains the privileged operation
that may remove reserved rows and advance lifecycle generation.
- Every user-facing WebSocket queue operation authorizes the named session in
its handler. Session scoping remains mandatory on every row mutation, so a
disclosed or guessed entry UUID cannot mutate another session.
- Queue capacity is an install-wide setting exposed under **Settings > General
> Message Queue**. The effective value uses this precedence:
```text
valid KANDEV_QUEUE_MAX_PER_SESSION > persisted install setting > default 10
```
A positive integer is the maximum number of persisted messages per session;
`0` means unlimited. For compatibility, a non-positive environment value is
normalized to `0`. An invalid environment value is logged and ignored so a
valid persisted value or the default can apply.
- A valid environment value locks the UI control. Otherwise an admin may save
a non-negative integer to the install-wide `settings` store. The saved value
applies live through a concurrency-safe queue-service setter; no restart is
required.
- Changing the limit never deletes existing rows. Lowering it below a current
queue size blocks new admissions until the count falls below the limit.
Restoration and retry of work accepted before a dequeue bypass the admission
cap, so a failed delivery cannot lose work merely because the setting was
lowered.
This decision supersedes ADR 0051 only where that ADR prohibited an authorized
client from deleting agent-, workflow-, or server-owned **pending** rows. ADR
0051's provenance, durable reservation, acknowledgement, archive-generation,
and delivery guarantees remain in force.
## Consequences
- **Clear all** matches its visible promise and can recover a queue filled by
inter-task or automation messages.
- Individual removal works consistently for every pending row while editing
and merging retain stricter provenance rules.
- A reservation that wins the race may still be delivered, but hidden
in-flight work cannot be silently deleted between executor handoff and
acknowledgement.
- Operators can tune queue pressure without rebuilding launch configuration;
managed deployments keep environment authority.
- The queue service's cap becomes runtime mutable and all admission paths must
read one atomic snapshot per operation.
- Queue-setting reads are available to signed-in users; mutations are
admin-only. Authentication-disabled installs retain their synthetic-admin
behavior.
## Alternatives Considered
1. **Keep backend-origin rows undeletable and relabel the button.** Rejected
because it leaves users unable to recover a queue filled by stale inter-task
messages.
2. **Clear agent rows but preserve workflow/server rows.** Rejected because
**Clear all** would still have origin-dependent hidden exceptions and the
user owns the target session, not the sender's provenance.
3. **Delete reserved in-flight lifecycle rows too.** Rejected because those
rows participate in at-least-once handoff and acknowledgement; deletion can
corrupt delivery state after work has already reached the executor.
4. **Require restart after a capacity change.** Rejected because the cap is an
admission-time integer and can be updated safely without reconstructing the
orchestrator.
5. **Make capacity per workspace or per session.** Rejected for this change.
The existing policy is install-wide, and finer scopes add inheritance and
override semantics without evidence they are needed.
+1
View File
@@ -112,3 +112,4 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-08-02-class-aware-git-subprocess-admission | [Class-Aware Git Subprocess Admission](2026-08-02-class-aware-git-subprocess-admission.md) | accepted | backend, agentctl, observability | 2026-08-02 |
| 2026-08-02-isolate-replaceable-session-stream-traffic | [Isolate Replaceable Session Stream Traffic](2026-08-02-isolate-replaceable-session-stream-traffic.md) | accepted | backend, frontend, protocol | 2026-08-02 |
| 2026-08-03-backend-owned-cancellation-progress | [Keep Cancellation Progress Backend Owned](2026-08-03-backend-owned-cancellation-progress.md) | accepted | backend, frontend, protocol | 2026-08-03 |
| 2026-08-03-separate-message-queue-provenance-cancellation-and-capacity | [Separate Message Queue Provenance, Cancellation, and Capacity](2026-08-03-separate-message-queue-provenance-cancellation-and-capacity.md) | accepted | backend, frontend, protocol, security | 2026-08-03 |
+188
View File
@@ -0,0 +1,188 @@
---
spec: docs/specs/ui/message-queue-management.md
decision: docs/decisions/2026-08-03-separate-message-queue-provenance-cancellation-and-capacity.md
created: 2026-08-03
status: implemented
---
# Fix Plan: Message Queue Management
## Overview
Make the queue panel's **Clear all** promise literal, add removal for every
visible pending message, and expose the per-session queue limit under
**Settings > General > Message Queue**. Preserve durable in-flight delivery,
session isolation, message provenance, and already accepted retries.
## Confirmed Root Cause
The reported Bitbucket Integration task has ten persisted queue rows. Every row
has `queued_by='agent'`. The frontend sends `message.queue.cancel`, whose
handler calls `messagequeue.Service.CancelAll`; the SQLite and memory
repositories then delete only rows whose `queued_by` is not `agent`,
`workflow`, or `server`. The response therefore says `removed: 0`. The hook's
optimistic empty state is replaced by the next authoritative status event, so
the full queue immediately reappears.
Individual removal has the same repository guard. The React row action also
uses one `canEdit` flag for both **Edit** and **Remove**, hiding removal on
agent/workflow rows. This behavior implemented ADR 0051's prior ownership
boundary, so the repair requires an explicit contract change rather than only
a frontend patch.
The live installation was inspected read-only. No queued row, task, session,
or setting was mutated during diagnosis.
## Behavioral Contract
- An authorized session owner may remove any pending entry returned by queue
status and may clear all such entries, regardless of provenance.
- `queued_by` continues to control editing and merge compatibility.
- The visible queue uses compact one-based ordinals after remove, merge, or
drain; durable FIFO position keys remain unchanged.
- A durable lifecycle row already marked in flight remains hidden and
non-cancellable. Cancellation and reservation must be race-safe.
- Every user-facing queue WebSocket handler authorizes its session. Queue add
and append additionally validate that `task_id` belongs to `session_id`.
- Capacity resolves as valid environment value, then persisted install
setting, then default `10`. `0` means unlimited.
- Saving capacity applies live, does not prune existing rows, and limits only
new admissions. Restore/retry of already accepted work bypasses the cap.
## Backend Design
### Pending-row cancellation
- Change the `Repository.DeleteByID` and `DeleteAllBySession` contracts from
user-origin deletion to visible-pending deletion.
- In both SQLite/Postgres-compatible and memory repositories, serialize with
the existing per-session mutation lock and skip
`lifecycle_reserved_in_flight` rows.
- Use persisted compare guards and affected-row counts so an out-of-process
reserve or update that wins cannot be deleted or counted afterward.
- Preserve the mandatory `(session_id, entry_id)` scope and the privileged
`PurgeTask`/`AcknowledgeByID` paths.
- Update service logging and error text to remove the obsolete "not owned by
caller" implication.
### Queue action authorization
- Add a task-service authorization method for a `(task_id, session_id)` pair:
authorize both resources, load the session, and fail closed when the pair is
inconsistent.
- Inject a queue access authorizer into `QueueHandlers` from backend
composition.
- Guard get, add, append, update, remove, merge, clear, and drain before any
queue read or mutation. Add/append use pair authorization; session-only
actions use session authorization.
- Return the existing non-enumerating error shape and test that unauthorized
calls neither reveal status nor publish a mutation event.
### Runtime capacity setting
- Add `internal/system/queuesettings` with typed settings, generic-settings
adapter, environment resolver, live target interface, service, and HTTP
handlers.
- Persist `{"max_per_session": N}` under install-wide key `message_queue`.
- Resolve the setting before the orchestrator queue starts. Extend system
wiring with the live `messagequeue.Service` so GET/PATCH use the same target
and register under `/api/v1/system/message-queue/settings`.
- Register GET on the signed-in system group and PATCH on its admin subgroup.
PATCH validates `N >= 0`, returns `409` while a valid environment override is
active, persists first, then live-applies the response value.
- Replace the queue service's plain integer with a concurrency-safe runtime
value and add `SetMaxPerSession`. Each admission snapshots it once for the
repository call, log, and `queue_full` response.
- Normalize non-positive environment values to effective `0`; ignore and warn
on malformed values. Preserve `KANDEV_QUEUE_MAX_PER_SESSION` compatibility.
- Make ordinary restore and durable lifecycle retry bypass the current
admission cap. Initial user/agent/workflow/server insertions still obey it.
## Frontend Design
### Queue panel
- Split `canEdit` from `canRemove` in `QueuedGhostMessage` and `RowActions`.
Every visible row gets remove; editing remains user-only and merge rules stay
unchanged.
- Keep optimistic behavior only when the hook can reconcile it. On removal or
clear failure/race, refetch authoritative status and show localized feedback.
- Replace touched queue-header literals with `chat` namespace keys.
- Keep compact hover controls on pointer devices. On coarse-pointer viewports,
make remove, clear, close, expand, merge, and run-next actions at least 44px
high/wide and always visible.
### General settings page
- Add API types and fetch/update helpers for the configured/effective response.
- Add a client settings card with a numeric `min=0` input, explicit unlimited
help, source badge/help, loading/error states, environment lock state, and
member read-only state.
- Register the draft with `useSettingsSaveContributor`; do not add local
Save/Cancel controls.
- Add `/settings/general/message-queue` to the Vite route registry, app-page
composition, General sidebar, breadcrumb label map, and sidebar-navigation
tests. Redirect the former `/settings/system/message-queue` URL to preserve
existing bookmarks.
- Add all new copy to translation catalogs and regenerate/check pseudo locale.
Avoid module-scope `t()` by storing label keys and translating during render.
## Responsive and Mobile Contract
The nearest shipped queue exemplar is
`apps/web/e2e/tests/chat/mobile-message-queue-management.spec.ts`: retain its inline
panel and single queue scroll region so the composer stays visible. The new
controls must not depend on hover and must meet the 44px coarse-pointer target.
The settings page uses the existing left-side mobile Settings sheet and shared
`settings-scroll-container`. Render one column with no nested page scroller;
keep the numeric field at least 44px high and above the existing save bar plus
safe-area padding. Desktop and mobile expose identical values and permissions.
## TDD and Verification Strategy
1. Change existing backend tests to expect agent/workflow/server pending rows to
be removable and add in-flight/race/security regressions. Run them RED
against unchanged production code.
2. Implement cancellation and handler authorization; run memory, SQLite, and
env-gated Postgres package tests GREEN.
3. Add capacity resolver/store/service/handler tests, including live apply,
environment precedence, lower-than-current behavior, and retry restoration.
Run RED, then implement and rerun GREEN.
4. Add frontend component/hook/settings tests first, including split
edit/remove permissions and environment/member locks. Implement minimal UI
changes, then run typecheck, lint, and i18n gates.
5. Add desktop and mobile Playwright scenarios for mixed/agent provenance and
settings navigation/save. Preserve and restore the install-wide cap in test
teardown so parallel specs cannot inherit modified state.
6. Update public queue/configuration/operations docs and run their validators.
## Implementation Waves
- [x] [Task 01: Make pending queue cancellation authoritative](task-01-authoritative-queue-cancellation.md) — wave 1
- [x] [Task 02: Add live install-wide queue capacity settings](task-02-live-queue-capacity-settings.md) — wave 2, after Task 01
- [x] [Task 03: Expose removal for every visible queue row](task-03-visible-queue-removal-ui.md) — wave 3, after Task 01
- [x] [Task 04: Add the Message Queue General settings page](task-04-message-queue-settings-ui.md) — wave 3, after Task 02
- [x] [Task 05: Prove end-to-end behavior and update public docs](task-05-e2e-and-public-docs.md) — wave 4, after Tasks 03 and 04
Tasks 03 and 04 are file-disjoint enough to run in parallel after their backend
dependencies, but this package does not authorize subagents. Implementation
remains in the user-controlled primary session unless the user later delegates.
## Environment Prerequisite
If `apps/node_modules` is absent, run `pnpm install --frozen-lockfile` from
`apps/` before frontend RED tests. Do not change the lockfile.
## Risks and Boundaries
- A clear/remove request may lose to reservation; that message can still be
delivered. The UI must reconcile rather than claim it cancelled in-flight
work.
- Dynamic lowering must not make restore or lifecycle retry lossy.
- Settings tests mutate install-wide state and must restore their baseline even
after failure.
- Queue contents from the diagnosed live Bitbucket task remain untouched until
this package is implemented and deployed.
- Editing backend-origin content, changing merge rules, queue reordering,
per-workspace limits, and automatic pruning remain out of scope.
@@ -0,0 +1,93 @@
---
id: "01-authoritative-queue-cancellation"
title: "Make pending queue cancellation authoritative"
status: completed
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/ui/message-queue-management.md"
---
# Task 01: Make Pending Queue Cancellation Authoritative
## Acceptance
- Individual remove succeeds for visible user, agent, workflow, and server
entries while preserving session scope and FIFO order.
- Clear-all removes every visible pending entry and returns the exact affected
count.
- A hidden durable in-flight row survives individual and bulk cancellation.
- Reserve/remove and reserve/clear races have one complete winner; no row is
both delivered and reported removed.
- Every queue WebSocket action authorizes its session before access. Add and
append also reject an authorized session paired with a different task.
- Unauthorized calls expose no queue state, mutate nothing, and publish no
status event.
## TDD Sequence
1. Reverse the existing agent/workflow removal expectations in service and
handler tests; add server-origin, mixed clear-all, and in-flight cases.
2. Add deterministic SQLite/memory reservation race tests and an env-gated
Postgres parity case. Run focused packages and record RED.
3. Add handler authorization tests for session-only and task/session-pair
actions, including non-enumerating failure behavior. Run RED.
4. Change repository contracts and implementations with per-session locks,
persisted compare guards, and affected-row accounting.
5. Add the task/session pair authorizer, inject it into queue handlers, and
guard all entry points before queue access.
6. Rerun focused packages GREEN and inspect logs/error strings for obsolete
origin-ownership wording.
## Verification
```bash
cd apps/backend
go test ./internal/orchestrator/messagequeue ./internal/orchestrator/handlers ./internal/task/service ./internal/backendapp
KANDEV_TEST_POSTGRES_DSN="$KANDEV_TEST_POSTGRES_DSN" go test ./internal/orchestrator/messagequeue
```
The Postgres command skips when `KANDEV_TEST_POSTGRES_DSN` is unset.
## Files Likely Touched
- `apps/backend/internal/orchestrator/messagequeue/repository.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_sqlite.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_memory.go`
- `apps/backend/internal/orchestrator/messagequeue/service.go`
- `apps/backend/internal/orchestrator/messagequeue/types.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_sqlite_test.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_postgres_*_test.go`
- `apps/backend/internal/orchestrator/messagequeue/service_test.go`
- `apps/backend/internal/orchestrator/handlers/queue_handlers.go`
- `apps/backend/internal/orchestrator/handlers/queue_handlers_test.go`
- `apps/backend/internal/task/service/service_access.go`
- `apps/backend/internal/task/service/service_access_test.go`
- `apps/backend/internal/backendapp/gateway.go`
## Parallelism
Sequential. Repository race semantics, service expectations, and handler
authorization share one RED-GREEN cycle.
## Output Contract
Report RED/GREEN commands and counts, SQLite/Postgres status, authorization
coverage, changed files, and any residual race or compatibility risk. Update
this task and `plan.md` status in the same implementation conversation.
## Results
- RED: `go test ./internal/orchestrator/messagequeue -run 'Test(RemoveEntry|CancelAll)' -count=1`
failed because agent/workflow/server rows remained.
- RED: `go test ./internal/task/service -run TestAuthorizeTaskSessionAccessRejectsMismatchedPair -count=1`
failed because a same-owner mismatched task/session pair passed.
- RED: `go test ./internal/orchestrator/handlers -run 'TestQueueHandlersDenyUnauthorized' -count=1`
failed because every handler reached queue dependencies.
- GREEN: `go test -race ./internal/orchestrator/messagequeue -count=1`.
- GREEN: full `internal/orchestrator/handlers` and `internal/backendapp`; focused
task-service access tests.
- PostgreSQL parity test is present and skipped locally because
`KANDEV_TEST_POSTGRES_DSN` is unset.
- The full task-service package was attempted; unrelated existing filesystem
tests fail with `parent directory cannot be accessed` in this executor.
@@ -0,0 +1,99 @@
---
id: "02-live-queue-capacity-settings"
title: "Add live install-wide queue capacity settings"
status: completed
wave: 2
depends_on: ["01-authoritative-queue-cancellation"]
plan: "plan.md"
spec: "../../specs/ui/message-queue-management.md"
---
# Task 02: Add Live Install-Wide Queue Capacity Settings
## Acceptance
- Effective capacity resolves as valid environment, persisted setting, then
default `10`; malformed environment data is ignored with a warning.
- Non-positive environment values normalize to unlimited `0`; persisted
negative values are rejected.
- GET returns configured and effective values, source, and lock state. PATCH is
admin-only, rejects an environment lock, persists, and applies live.
- Queue status and every new-admission path observe one concurrency-safe live
cap snapshot.
- Lowering capacity never removes rows. New admission blocks until below cap,
while restore and durable retry of accepted work remain possible.
- Restart resolution applies the same value before the orchestrator accepts
work.
## TDD Sequence
1. Add pure resolver and store tests for default, setting, environment,
malformed data, unlimited normalization, and validation. Run RED.
2. Add service/handler tests for GET, admin PATCH, member rejection,
environment lock, persistence failure, and live-target application. Run RED.
3. Add queue-service tests that change the cap concurrently, lower it below a
current queue, and restore/retry accepted work. Run RED.
4. Implement `internal/system/queuesettings`, the atomic queue-service setter,
startup resolver, and system route wiring.
5. Rerun focused tests GREEN, then run backend package tests covering startup
composition and system routes.
## Verification
```bash
cd apps/backend
go test ./internal/system/queuesettings ./internal/system ./internal/orchestrator/messagequeue ./internal/backendapp
go test -race ./internal/system/queuesettings ./internal/orchestrator/messagequeue
```
## Files Likely Touched
- `apps/backend/internal/system/queuesettings/types.go`
- `apps/backend/internal/system/queuesettings/store.go`
- `apps/backend/internal/system/queuesettings/service.go`
- `apps/backend/internal/system/queuesettings/handler.go`
- matching `*_test.go` files
- `apps/backend/internal/system/system.go`
- `apps/backend/internal/system/system_routes_test.go`
- `apps/backend/internal/orchestrator/messagequeue/service.go`
- `apps/backend/internal/orchestrator/messagequeue/service_test.go`
- `apps/backend/internal/backendapp/orchestrator.go`
- `apps/backend/internal/backendapp/main.go`
- `apps/backend/internal/backendapp/helpers_test.go`
## Dependencies
Task 01 lands first so this task can update queue-service tests without
conflicting with cancellation contract changes.
## Parallelism
Sequential after Task 01. Startup resolution, HTTP service, and live queue
target form one consistency boundary.
## Output Contract
Report resolver precedence, auth/lock behavior, race-test result, live cap and
restore evidence, changed files, and any startup fallback. Update this task and
`plan.md` status in the same implementation conversation.
## Results
- RED: queue restore failed with `queue full` after the cap was lowered.
- RED: resolver ignored valid, unlimited, malformed, and locking environment
values; the HTTP lock case returned `200` instead of `409`.
- RED: startup resolution ignored persisted settings and returned negative
environment values unchanged.
- RED: System Message Queue routes returned `404` before registration.
- GREEN: `go test ./internal/system/queuesettings ./internal/system ./internal/orchestrator/messagequeue ./internal/backendapp -count=1`.
- GREEN: `go test -race ./internal/system/queuesettings ./internal/orchestrator/messagequeue -count=1`.
- Verified live lowering without pruning, all new-admission paths, unlimited
mode, restore/retry bypass, environment precedence/lock, persistence-before-
apply, and member/admin routing.
- Final spec audit added a RED/GREEN regression for malformed JSON and negative
persisted values: GET now falls back to the default with a warning, and an
admin PATCH can replace the invalid record without restarting.
- Final concurrency audit added a deterministic RED/GREEN regression for two
overlapping admin saves: persistence and live application now share one
serialized service boundary, so an older request cannot overwrite the live
value after a newer request has persisted.
@@ -0,0 +1,97 @@
---
id: "03-visible-queue-removal-ui"
title: "Expose removal for every visible queue row"
status: completed
wave: 3
depends_on: ["01-authoritative-queue-cancellation"]
plan: "plan.md"
spec: "../../specs/ui/message-queue-management.md"
---
# Task 03: Expose Removal for Every Visible Queue Row
## Acceptance
- User, agent, workflow, and server rows all render an individual Remove
action; only user rows render Edit.
- Existing merge eligibility and sender-provenance rendering remain unchanged.
- Clear-all and individual removal reconcile to authoritative queue status on
success, race, and error; localized feedback replaces stale optimistic state.
- Visible positions compact to `#1` through `#N` after remove, merge, or drain,
even when durable FIFO position keys retain gaps.
- On coarse-pointer/mobile viewports, queue actions are always visible and
expose at least 44px hit areas. Desktop keeps compact hover behavior.
- The queue keeps one internal scroll region and never pushes the composer off
the phone viewport.
## TDD Sequence
1. Add component tests proving `canRemove` is independent from `canEdit` for
each provenance kind. Add hook tests for clear/remove success and refetch on
failure. Run RED.
2. Split the row-action props and render Remove outside the edit-only branch.
3. Update clear/remove reconciliation and localize all newly touched queue
labels, titles, and errors.
4. Add coarse-pointer responsive classes and focused assertions for visible
44px controls without changing the queue scroll owner.
5. Run focused unit tests, typecheck, lint, and i18n checks GREEN.
## Verification
```bash
cd apps
pnpm --filter @kandev/web exec vitest run \
components/task/chat/queued-ghost-list.test.tsx \
components/task/chat/queued-ghost-message.test.tsx \
hooks/domains/session/use-queue.test.ts
pnpm --filter @kandev/web run typecheck
pnpm --filter @kandev/web run lint
pnpm --filter @kandev/web run i18n:check
pnpm --filter @kandev/web run i18n:ratchet
```
## Files Likely Touched
- `apps/web/components/task/chat/queued-ghost-list.tsx`
- `apps/web/components/task/chat/queued-ghost-list.test.tsx`
- `apps/web/components/task/chat/queued-ghost-message.tsx`
- `apps/web/components/task/chat/queued-ghost-message.test.tsx`
- `apps/web/hooks/domains/session/use-queue.ts`
- `apps/web/hooks/domains/session/use-queue.test.ts`
- `apps/web/src/locales/en/chat.json`
- generated pseudo-locale catalog
## Dependencies
Task 01 supplies the backend behavior this UI exposes.
## Parallelism
Parallel-safe with Task 04 after backend dependencies. They touch separate
components, API domains, and translation namespaces. No subagent is authorized
by this task file.
## Output Contract
Report RED/GREEN unit evidence, provenance matrix, mobile hit-area result,
typecheck/lint/i18n status, changed files, and residual UX risks. Update this
task and `plan.md` status in the same implementation conversation.
## Results
- RED: the focused component/hook suite failed 9 tests because removal was
coupled to editability, coarse-pointer hit-area classes were absent, and
clear/remove skipped authoritative reconciliation paths.
- GREEN: 73 focused tests pass across `queued-ghost-list`,
`queued-ghost-message`, and `use-queue`.
- User, agent, workflow, and server rows expose Remove; only `queued_by=user`
exposes Edit. Existing merge eligibility is unchanged.
- Clear and Remove refetch authoritative status after success, drain races,
and failures; non-race failures restore state and surface localized errors.
- Desktop row controls remain 24px hover actions. Coarse-pointer controls are
always visible with 44px hit areas; the existing queue list remains the one
panel scroll owner.
- GREEN: web typecheck, lint, `i18n:check`, and `i18n:ratchet`.
- Follow-up RED/GREEN: a sparse-position render failed with `#1, #3`; the
queue panel now derives display ordinals from rendered order and shows
`#1, #2` without mutating durable FIFO keys.
@@ -0,0 +1,105 @@
---
id: "04-message-queue-settings-ui"
title: "Add the Message Queue General settings page"
status: completed
wave: 3
depends_on: ["02-live-queue-capacity-settings"]
plan: "plan.md"
spec: "../../specs/ui/message-queue-management.md"
---
# Task 04: Add the Message Queue General Settings Page
## Acceptance
- `/settings/general/message-queue` is reachable through desktop and mobile
General navigation and has a translated breadcrumb/title. The former System
URL redirects to the canonical General route.
- The page shows configured/effective values, source, unlimited explanation,
loading/error state, environment lock, and member read-only state.
- Admin edits accept integers `>= 0`, register with the shared settings save
coordinator, persist through PATCH, and reconcile the returned effective
value. No local Save/Cancel button exists.
- The page is single-column, uses the shared page scroll owner, has no
horizontal overflow, and keeps the numeric input at least 44px high.
- API types, helpers, route registry, sidebar tests, and i18n catalogs cover the
new surface.
## TDD Sequence
1. Add API helper tests and component tests for default, unlimited, dirty save,
validation, environment lock, member read-only, failure, and discard. Run
RED.
2. Add route/sidebar/breadcrumb tests for the new leaf and mobile Settings tree.
Run RED.
3. Implement typed API helpers, settings component/page, route registration,
translated nav label, and save-contributor wiring.
4. Apply mobile layout and input sizing from the shared System page language.
5. Run focused tests, typecheck, lint, and i18n gates GREEN.
## Verification
```bash
cd apps
pnpm --filter @kandev/web exec vitest run \
components/settings/system/message-queue-settings.test.tsx \
components/app-sidebar/sections/settings/settings-tree-render.test.tsx \
components/settings/settings-layout-client.test.tsx \
lib/api/domains/settings-api.test.ts
pnpm --filter @kandev/web run typecheck
pnpm --filter @kandev/web run lint
pnpm --filter @kandev/web run i18n:check
pnpm --filter @kandev/web run i18n:ratchet
```
## Files Likely Touched
- `apps/web/components/settings/system/message-queue-settings.tsx`
- `apps/web/components/settings/system/message-queue-settings.test.tsx`
- `apps/web/app/settings/general/message-queue/page.tsx`
- `apps/web/app/settings/system/message-queue/page.tsx` (legacy redirect)
- `apps/web/src/settings-routes.tsx`
- `apps/web/components/app-sidebar/sections/settings/system-group.tsx`
- `apps/web/components/app-sidebar/sections/settings/settings-tree-render.test.tsx`
- `apps/web/components/settings/settings-layout-client.tsx`
- `apps/web/components/settings/settings-layout-client.test.tsx`
- `apps/web/lib/api/domains/settings-api.ts`
- `apps/web/lib/api/domains/settings-api.test.ts`
- `apps/web/lib/types/system.ts`
- `apps/web/src/locales/en/system.json`
- generated pseudo-locale catalog
## Dependencies
Task 02 supplies the typed HTTP contract and live behavior.
## Parallelism
Parallel-safe with Task 03 after backend dependencies. No subagent is
authorized by this task file.
## Output Contract
Report RED/GREEN unit evidence, save-coordinator behavior, desktop/mobile route
coverage, typecheck/lint/i18n status, changed files, and residual UX risks.
Update this task and `plan.md` status in the same implementation conversation.
## Results
- RED: the five focused files reported one unresolved component suite and five
failures for missing API helpers, route, translated breadcrumb, and System
navigation leaf.
- GREEN: 54 focused tests pass across the settings component, API, route,
sidebar tree, and layout.
- The shared save contributor stages valid admin changes, PATCHes only on the
global Save changes action, reconciles the response, and restores the
authoritative configured value on discard. Invalid drafts block shared save.
- Environment overrides show their effective value and lock explanation;
members receive the same read surface with a disabled field. Load and save
failures stay visible and retryable/actionable.
- The same translated General leaf feeds desktop and mobile navigation. The
page uses the shared safe-area-aware scroll container, adds no nested page
scroller, and gives the numeric input a 44px height.
- Follow-up RED/GREEN: navigation and route tests proved the leaf was still
under System; it now lives under General and the old URL redirects.
- GREEN: web typecheck, lint, `i18n:check`, and `i18n:ratchet`.
@@ -0,0 +1,127 @@
---
id: "05-e2e-and-public-docs"
title: "Prove end-to-end behavior and update public docs"
status: completed
wave: 4
depends_on:
- "03-visible-queue-removal-ui"
- "04-message-queue-settings-ui"
plan: "plan.md"
spec: "../../specs/ui/message-queue-management.md"
---
# Task 05: Prove End-to-End Behavior and Update Public Docs
## Acceptance
- Desktop Playwright creates agent-origin queued messages through the mock MCP
path, removes one, clears the remainder, and proves capacity is available.
- Mobile Playwright performs individual remove and clear-all through touch-sized
controls while the composer remains visible, the queue scrolls internally,
and displayed positions compact after a middle-row removal.
- Desktop and mobile General Settings navigation reach Message Queue; an admin
change saves and reloads, while environment/member states remain read-only.
- Any test changing the install-wide cap captures and restores its baseline in
teardown, including failure paths.
- Public coordination, configuration, sessions/review, and operations docs
explain visible-origin removal, UI configuration, environment precedence,
`0` unlimited, live application, and non-pruning.
## TDD Sequence
1. Extend the cross-task message fixture to hold a target busy while multiple
sender tasks queue agent-origin rows. Add desktop remove/clear assertions and
run RED.
2. Add a mobile management scenario based on the shipped queue-scroll helper;
assert coarse-pointer hit boxes, one scroll owner, and visible composer. Run
RED.
3. Add settings navigation/save/reload scenarios with baseline restoration and
run RED.
4. Complete any missing wiring discovered by E2E, rerun all focused scenarios,
and record GREEN.
5. Update public docs and run both documentation validators.
## Verification
```bash
cd apps/web
pnpm e2e:run tests/chat/message-queue.spec.ts tests/chat/agent-message-attribution.spec.ts
pnpm e2e:run --project mobile-chrome tests/chat/mobile-message-queue-management.spec.ts
pnpm e2e:run tests/system/message-queue-settings.spec.ts
pnpm e2e:run --project mobile-chrome tests/system/mobile-message-queue-settings.spec.ts
cd ../../
node --test scripts/validate-public-docs.test.mjs
node scripts/validate-public-docs.mjs
git diff --check
```
## Files Likely Touched
- `apps/web/e2e/tests/chat/message-queue.spec.ts`
- `apps/web/e2e/tests/chat/agent-message-attribution.spec.ts`
- `apps/web/e2e/tests/chat/mobile-message-queue-management.spec.ts`
- `apps/web/e2e/tests/system/message-queue-settings.spec.ts`
- `apps/web/e2e/tests/system/mobile-message-queue-settings.spec.ts`
- shared E2E API/page helpers only if needed
- `docs/public/coordination.md`
- `docs/public/configuration.md`
- `docs/public/sessions-and-review.md`
- `docs/public/operations.md`
## Dependencies
Tasks 03 and 04 must be complete so browser tests exercise production UI
rather than mocked components.
## Parallelism
Sequential final integration task. It mutates shared install-wide E2E state and
must own its setup/restore lifecycle.
## Output Contract
Report desktop/mobile scenario results, baseline restoration evidence, public
docs validation, changed files, and any residual flake or release risk. Update
this task, `plan.md`, and spec status when the feature is genuinely complete.
## Results
- GREEN: 19 desktop queue tests. The new mock-MCP scenario filled a busy
target with ten agent-origin rows from two sender tasks, removed one, cleared
the other nine, then admitted a fresh agent message.
- GREEN: one mobile queue-management test. The queue retained its single
internal scroll owner and visible composer; row removal, clear-all, and close
controls measured at least 44 by 44 CSS pixels.
- GREEN: three desktop settings tests and one mobile settings test. Desktop
navigation, admin save/reload, environment lock, and member read-only states
passed; mobile navigation and the shared single-scroll layout passed.
- The settings suite captures the install-wide baseline with GET before every
test and restores it with PATCH in `afterEach`, so restoration also runs on a
failed assertion.
- GREEN: 58 public-doc validator tests, 41 published pages validated, and
`git diff --check`.
- GREEN: web lint, typecheck, `i18n:check`, and `i18n:ratchet` after the E2E and
documentation changes.
- No additional production wiring gap appeared in the final browser wave. A
subsequent spec audit found and fixed invalid persisted-setting replacement
and overlapping-save ordering; the focused race-enabled backend suite is
green. The browser tests use the shipped mock agent; repository races remain
covered by Tasks 01 and 02.
- Follow-up RED: mobile middle-row removal displayed `#6` in the fifth visible
slot, while desktop/mobile settings tests could not find Message Queue under
General.
- Follow-up GREEN: three desktop General settings tests and two mobile
queue/settings tests pass with retries disabled. Middle-row removal compacts
the final visible label to `#9`; desktop and mobile navigation use General.
- Follow-up GREEN: 113 focused frontend tests, typecheck, lint, both i18n gates,
58 public-doc tests, the 41-page docs validator, and `git diff --check` pass.
- The retained isolated evaluation target has four agent-origin rows with
durable positions `4–7`; the live feature UI displays compact positions
`#1–#4`. General navigation, the legacy redirect, and browser console are
clean.
- PR fixup GREEN: synced current `main`; preserved raw SQLite metadata guards;
made ordinary accepted-message retries bypass a lowered cap; corrected the
General route, redirect coverage, drain compaction, and environment
precedence docs; and scoped strict Playwright locators. Focused Go tests, 40
frontend unit tests, typecheck, both i18n gates, 58 public-doc tests, the
exact desktop queue scenario, and both mobile queue/settings scenarios pass.
+3 -3
View File
@@ -333,13 +333,13 @@ Profile environment variables are eventually injected into agent subprocesses or
## Advanced operator tuning
These startup-only variables are supported by specific runtime components but are not YAML fields. Leave them at defaults unless diagnosing a measured problem.
These variables are supported by specific runtime components but are not YAML fields. Most are startup-only; the message queue limit also has a live database-backed setting described below. Leave them at defaults unless diagnosing a measured problem.
| Variable | Default | Parsing and effect |
|---|---:|---|
| `KANDEV_GH_MAX_CONCURRENT` | `8` | Positive integer process-wide cap for `gh` subprocesses; invalid/non-positive uses default. |
| `KANDEV_GIT_MAX_CONCURRENT` | `12` | Positive integer process-wide cap for `git` subprocesses; invalid/non-positive uses default. |
| `KANDEV_QUEUE_MAX_PER_SESSION` | `10` | Queued user messages per session. Invalid uses default; zero/negative disables the cap. |
| `KANDEV_QUEUE_MAX_PER_SESSION` | `10` | Pending messages per session. A valid value overrides and locks the saved UI setting; zero/negative means unlimited, while invalid falls through to the saved setting or default. |
| `KANDEV_ACP_IDLE_TIMEOUT` | `1h` | Go duration after which idle agentctl instances are reaped; `0` disables. Invalid uses default. |
| `KANDEV_ACP_IDLE_REAPER_INTERVAL` | `1m` | Go duration between idle scans. Intended mainly for testing; use the default in production. |
| `KANDEV_ACP_NOTIF_QUEUE` | `131072` | Per-connection ACP inbound notification capacity; positive values clamp to `1024`-`131072`, invalid uses default. |
@@ -348,7 +348,7 @@ These startup-only variables are supported by specific runtime components but ar
| `KANDEV_MCP_LOG_FILE` | unset | File path for per-agentctl MCP debug logs. Logs tool names, arguments, session IDs, results for tool errors, and timings; invalid paths warn and disable this sink. |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | unset | Enables OTLP/HTTP tracing for backend and agentctl spans; unset uses a no-op tracer. See the transport warning below. |
Changing concurrency/queue values trades memory and process pressure against throughput. Values are captured during process/component initialization and need a restart.
Changing concurrency values trades process pressure against throughput and requires a restart. The queue environment value is also read at startup. Without that environment override, an admin can use **Settings > General > Message Queue** to save an install-wide limit that applies live. `0` means unlimited. Lowering the live limit does not prune existing rows; new admissions remain blocked until the pending count drops below the limit, while retries of already accepted work remain eligible.
The current OTLP exporter strips an `http://` or `https://` prefix from the configured endpoint and always uses `WithInsecure()`. Treat this as implementation-bound cleartext transport: send it only to a trusted private collector over a protected network, not directly across an untrusted network. The service name is `kandev-agentctl`, and spans can include task/session/execution IDs plus raw agent-event JSON truncated to 8192 characters. That payload can contain prompts, files, and tool data. Use collector-side access controls and retention accordingly.
+3 -1
View File
@@ -120,7 +120,9 @@ For predictable top-level creation, pass `repository_url`, `repository_id`, or `
| Created but not started | Starts the session with the message. |
| Failed or cancelled | Returns an error. |
The default delivery mode is queued. Each session accepts 10 queued messages by default; operators can change it with `KANDEV_QUEUE_MAX_PER_SESSION`, and a value of `0` or less disables the limit. Only one queued message drains per agent turn. When the cap is reached, the sender receives a structured `queue_full` error and should retry after a target turn completes.
The default delivery mode is queued. Each session accepts 10 queued messages by default. An admin can change the install-wide limit under **Settings > General > Message Queue**; `0` means unlimited. The saved value applies immediately to new admissions without removing messages already waiting. `KANDEV_QUEUE_MAX_PER_SESSION` has higher precedence, locks the UI field, and requires a restart when changed; zero or a negative value means unlimited. Only one queued message drains per agent turn. When the cap is reached, the sender receives a structured `queue_full` error and should retry after space becomes available.
In the task workbench, expand the queue chip to manage pending messages. Every visible pending row has **Remove**, whether it came from a user, another agent, workflow automation, or a server action. **Clear all** removes all visible pending rows in that session and releases their capacity. After removal, merge, or drain, displayed positions compact to `#1` through `#N` while FIFO order stays unchanged. Provenance still matters for editing and merging: only user-origin content can be edited. A row already reserved for delivery is hidden from the panel and cannot be cancelled there.
Choose the control by intent:
+7 -1
View File
@@ -270,21 +270,26 @@
"docs": ["operations", "configuration", "feature-status"],
"sources": [
"apps/backend/internal/system/settings/store.go",
"apps/backend/internal/system/queuesettings/service.go",
"apps/backend/internal/system/storage/handler.go",
"apps/backend/internal/system/logbundle/service.go",
"apps/backend/internal/mcp/handlers/diagnostic_bundle.go",
"apps/web/components/settings/system/feature-toggles-settings.tsx",
"apps/web/components/settings/system/message-queue-settings.tsx",
"apps/web/components/settings/system/storage/storage-maintenance-settings.tsx"
],
"tests": [
"apps/backend/internal/system/settings/store_test.go",
"apps/backend/internal/system/queuesettings/queuesettings_test.go",
"apps/backend/internal/system/storage/handler_test.go",
"apps/backend/internal/system/logbundle/service_test.go",
"apps/backend/internal/mcp/handlers/diagnostic_bundle_test.go",
"apps/web/components/settings/system/feature-toggles-settings.test.tsx",
"apps/web/components/settings/system/message-queue-settings.test.tsx",
"apps/web/components/settings/system/storage/storage-maintenance-settings.test.tsx"
],
"settingsRoutes": [
"/settings/general/message-queue",
"/settings/system/about",
"/settings/system/backups",
"/settings/system/database",
@@ -355,7 +360,8 @@
{ "route": "/settings/general/resource-metrics", "reason": "Legacy redirect to Appearance." },
{ "route": "/settings/general/shell", "reason": "Legacy redirect to Terminal." },
{ "route": "/settings/plugins", "reason": "Experimental feature intentionally omitted until its public contract stabilizes." },
{ "route": "/settings/system", "reason": "Redirect to System status." }
{ "route": "/settings/system", "reason": "Redirect to System status." },
{ "route": "/settings/system/message-queue", "reason": "Legacy redirect to General Message Queue." }
],
"mcpTools": []
}
+8
View File
@@ -60,6 +60,14 @@ kandev service logs -f
Add `--system` to both commands for a system service.
## Message queue capacity
Open **Settings > General > Message Queue** to set the install-wide number of pending messages allowed in each session. The default is `10`; `0` means unlimited. Admin saves apply immediately to later admissions. Lowering the limit does not prune rows already waiting, so a queue at or above the new limit rejects new work until messages run or are removed. Delivery retries for work accepted before the change are not discarded by the lower cap.
`KANDEV_QUEUE_MAX_PER_SESSION` has higher precedence than the saved setting. A valid environment value makes the UI field read-only; zero or a negative value means unlimited. Invalid text is logged and ignored in favor of the saved setting or default. Environment changes require a backend restart, while UI changes do not.
To recover capacity in one session, expand its queue chip in the task workbench. **Remove** deletes one visible pending row and **Clear all** deletes all visible pending rows, including user-, agent-, workflow-, and server-origin work. After removal, merge, or drain, displayed positions immediately compact to `#1` through `#N`; durable FIFO ordering is unchanged. A row already reserved for delivery is hidden and is not cancelled by either action.
## State and storage
`KANDEV_HOME_DIR` relocates the Kandev home. Its default is `~/.kandev`; the derived data directory is always `<home>/data`.
+4 -2
View File
@@ -63,6 +63,8 @@ Stopping is not deletion. Resume succeeds only while the executor still has the
Stopping a turn does not itself run the next queued message. Expand the queue and select **Run next** when you want processing to continue.
The expanded queue also lets you discard stale work. **Remove** is available for every visible pending row, including messages from users, peer agents, workflows, and server actions; **Clear all** removes all visible pending rows in that session. Only user-origin rows remain editable. A message already reserved for delivery is hidden from the queue and cannot be cancelled with these controls.
A CLI-passthrough profile displays the agent's native terminal interface in a PTY. It still belongs to the task, but it does not provide Kandev's structured chat messages and tool-call presentation.
<details>
@@ -83,7 +85,7 @@ Delivery follows the target state:
- a created session starts with the message as its first prompt;
- a failed or cancelled session rejects the message.
The default pending-message limit is 10 per session. Operators can change it with `KANDEV_QUEUE_MAX_PER_SESSION`; a value of `0` or less removes the cap, so the queue can grow without that bound. Interrupt delivery is restricted to a direct parent task messaging its child. Other senders must queue.
The default pending-message limit is 10 per session. An admin can change it live under **Settings > General > Message Queue**; `0` removes the cap. A valid `KANDEV_QUEUE_MAX_PER_SESSION` value takes precedence and makes the UI field read-only; changing the environment still requires a restart. Malformed environment values are logged and ignored, so the saved setting or default applies instead. Lowering the saved limit does not delete entries already waiting. Interrupt delivery is restricted to a direct parent task messaging its child. Other senders must queue.
For urgent replacement work, the parent should use `message_task_kandev` with `delivery_mode: "interrupt"`; this cancels the current approach and immediately tries to dispatch the new prompt, with a safe queued fallback. Use `stop_task_kandev` only for halt-only intent. A successful stop marks every accepted live child session `CANCELLED` and schedules graceful teardown asynchronously. Kandev then attempts to move an eligible unarchived, non-Office task from `IN_PROGRESS` or `SCHEDULING` to `REVIEW`; other task states remain unchanged. A child with no live execution returns idempotent `not_running`, and its worktrees, environment, commits, task record, descendants, and queued messages are preserved. See [Coordination](coordination.md) for the complete authority and lifecycle contract.
@@ -274,7 +276,7 @@ Before moving a task to done:
- **New Agent has no profiles:** create a profile compatible with the task executor. A profile for another executor is intentionally hidden.
- **Summary or generated text fails:** configure the corresponding utility agent and a reachable model in **Settings > Utility Agents**.
- **Resume fails:** start fresh when the executor no longer has resumable session state, then supply a summary or copy the relevant context.
- **A peer message never arrives:** check the target session state and ID. Running sessions queue messages; failed or cancelled sessions reject them; a full queue must drain before another message can be accepted.
- **A peer message never arrives:** check the target session state and ID. Running sessions queue messages; failed or cancelled sessions reject them. For a full queue, expand its chip and run, remove, or clear pending work before retrying; an admin can also review the install-wide limit under **Settings > General > Message Queue**.
- **Changes is empty:** select the correct repository and comparison, then confirm the agent wrote inside the materialized task path.
- **Review marks became stale:** the underlying diff changed. Re-review the new hash before marking the file complete.
- **Walkthrough does not appear:** confirm an active task-MCP session exists and that the saved `changes-walkthrough` prompt was not removed or made invalid.
+1
View File
@@ -147,6 +147,7 @@ Subscription quota tracking and per-agent cheap-model profile routing.
| [entity-reference-composer](ui/entity-reference-composer.md) | draft |
| [agent-launch-prompt-composer](ui/agent-launch-prompt-composer.md) | shipped |
| [mermaid-rendering](ui/mermaid-rendering.md) | shipped |
| [message-queue-management](ui/message-queue-management.md) | shipped |
| [message-queue-merge](ui/message-queue-merge.md) | shipped |
| [settings-manual-save](ui/settings-manual-save.md) | shipped |
| [executor-settings-card-spacing](ui/executor-settings-card-spacing.md) | shipped |
+7
View File
@@ -109,6 +109,8 @@ GET /api/v1/system/updates - { current, latest, latest_ur
POST /api/v1/system/updates/check - force selected-source re-poll; rate-limited 30s
PATCH /api/v1/system/updates/channel - persist Stable/Nightly for a verified managed npm/npx user service; body { channel }
POST /api/v1/system/updates/apply - queue service-only self-update; body { confirm: "UPDATE", target_version }
GET /api/v1/system/message-queue/settings - configured/effective queue limit and source
PATCH /api/v1/system/message-queue/settings - save and live-apply admin queue limit
```
The System API has no global casing convention. Updates and Info use the snake_case JSON fields
@@ -198,6 +200,10 @@ The page reads the JSON statically; no backend endpoint is needed.
- **GIVEN** the user clicks **Check now** twice within 30 seconds, **WHEN** the second click fires, **THEN** the endpoint returns `429 Too Many Requests` and the UI shows "Already checked, try again in <N>s".
- **GIVEN** retained backend logs and a connected browser with local console history, **WHEN** the user downloads diagnostics from `/settings/system/logs`, **THEN** one ZIP contains separate backend/frontend directories and a manifest describing both captures.
- **GIVEN** the user opens `/settings/system/licenses` while offline, **WHEN** the page renders, **THEN** every dependency's license text is available locally (no network calls).
- **GIVEN** no queue-limit environment variable is set, **WHEN** an admin saves
a new limit on `/settings/general/message-queue`, **THEN** later queue
admissions use it immediately without deleting existing messages or
requiring a restart.
## Data model
@@ -226,6 +232,7 @@ guard covers database vacuum/optimize/reset, manual update checks, update-channe
update apply. Backup create/restore/delete and disk-usage
refresh currently remain on the base authenticated group. Reset and restore additionally validate
their confirmation bodies server-side as defence in depth.
The Message Queue settings GET is readable by members, while its PATCH is admin-only.
## Failure modes
+222
View File
@@ -0,0 +1,222 @@
---
status: shipped
created: 2026-08-03
owner: kandev
---
# Manage Pending Message Queues
## Why
Long-running tasks can receive messages faster than their active session can
drain them. Users need to discard stale messages and tune the queue capacity
without shell access. Today the queue panel promises **Clear all**, but the
backend removes only user-origin rows. A queue filled with ten inter-task
agent messages reports success with zero removals, immediately reappears, and
remains full. Those same rows have no individual remove action.
## What
### Queue controls
- Every visible pending message offers **Remove**, regardless of whether its
provenance is user, agent, workflow, or server.
- **Clear all** removes every visible pending message in the current session
and returns the exact number removed.
- Removal does not change provenance rules for other operations. Only
user-owned messages may be edited. Merge behavior remains defined by
[Merge Enqueued Messages Individually](message-queue-merge.md).
- Successful removal publishes the existing
`message.queue.status_changed` event. All connected views reconcile to the
backend result; the initiating view may update optimistically but must
refetch on a race or failure.
- Displayed queue positions are compact one-based ordinals derived from the
current visible order. After remove, merge, or drain leaves gaps in durable
FIFO position keys, the panel still displays `#1` through `#N` without gaps.
- An entry already reserved for durable lifecycle delivery is not visible and
cannot be removed by these controls. Task archive/delete retains its separate
privileged purge behavior.
### Capacity setting
- **Settings > General > Message Queue** exposes the maximum number of persisted
messages allowed per session.
- The default is `10`. A positive integer sets a cap; `0` means unlimited.
- A saved setting applies immediately to later admissions. Existing entries
are never trimmed. If a queue already exceeds a newly lowered limit, new
messages are rejected with `queue_full` until its persisted count is below
the limit.
- Previously accepted work may be restored or retried after a delivery
failure even when the new cap is lower. Capacity limits new work; it does not
turn a failed delivery into message loss.
- `KANDEV_QUEUE_MAX_PER_SESSION` remains supported and has higher precedence
than the saved setting. A valid environment value makes the field read-only
and the page explains the lock. Values at or below zero mean unlimited. An
invalid value is logged and ignored.
- Signed-in members may view the effective setting. Admins may change it. With
authentication disabled, the synthetic single user remains an admin.
- The settings route participates in the shared settings save coordinator. It
does not add a page-local Save or Cancel button.
## API Surface
Existing WebSocket actions retain their payloads:
```text
message.queue.remove
request: { session_id: string, entry_id: string }
response: { entry_id: string }
message.queue.cancel
request: { session_id: string }
response: { session_id: string, removed: number }
```
Both actions require access to `session_id`. `message.queue.remove` returns
`entry_not_found` when the entry does not exist in that session, was drained,
was reserved before cancellation won, or was removed concurrently. Clear-all
is idempotent and returns `removed: 0` when no visible pending entries remain.
New HTTP endpoints:
```text
GET /api/v1/system/message-queue/settings
PATCH /api/v1/system/message-queue/settings
```
GET response and PATCH response:
```json
{
"settings": { "max_per_session": 10 },
"effective": {
"max_per_session": 10,
"source": "default",
"locked": false
}
}
```
`source` is `default`, `setting`, or `environment`. `settings` contains the
persisted value, or the default when no override exists. PATCH accepts:
```json
{ "max_per_session": 25 }
```
PATCH rejects negative values with `400`, rejects a valid environment lock
with `409`, and requires the admin role. GET requires an authenticated install
user under the existing system-route middleware.
## Data Model
No queue-table migration is required. Capacity uses the existing install-wide
`settings` table under key `message_queue` with JSON value:
```json
{ "max_per_session": 25 }
```
`queued_by` stays unchanged as immutable provenance. The existing
`metadata.lifecycle_reserved_in_flight` marker distinguishes a durable row
already being delivered from a pending row the user may discard.
## State and Concurrency
For one visible row:
```text
pending --reserve wins--> in flight --acknowledge--> removed
|
+--user remove wins-----------------------------> removed
```
Clear-all applies the same rule to every pending row in one session. Queue
repository mutations serialize per session and compare the persisted row state
before deletion. A concurrent reserve or content mutation may win; cancellation
must never delete an entry after it becomes in-flight and must never report a
row it did not remove.
The effective capacity is held by the queue service in concurrency-safe memory.
Each admission reads one value and uses that same snapshot for its repository
operation and error response. A successful settings PATCH persists first and
then applies the value live; after a process restart the same resolver applies
environment, persisted setting, and default precedence before the orchestrator
starts accepting work.
## Responsive and Mobile Behavior
- The existing inline queue panel remains the phone composition; the queue
list remains its single internal scroll owner and the composer stays visible.
- Remove and clear controls are always discoverable on touch devices. Their
interactive hit areas are at least 44 by 44 CSS pixels on coarse-pointer
viewports; desktop may retain compact hover-revealed controls.
- The Message Queue settings page uses the existing mobile settings sheet for
navigation and the shared `settings-scroll-container` as its only page scroll
owner. Content is one column; the numeric input is at least 44 pixels high
and remains visible above the shared save bar and safe-area inset.
- Desktop and mobile expose the same queue removal and capacity behavior.
## Failure Modes
- **Drain or reserve wins:** individual remove returns `entry_not_found`; the
frontend refreshes status without showing a stale row. Clear-all reports only
rows it actually deleted.
- **Backend mutation fails:** the UI restores/refetches queue state and shows a
localized error. It does not leave an optimistic empty queue on screen.
- **Queue setting is environment-locked:** the input is disabled and PATCH
returns `409` if called directly.
- **Invalid saved data:** the backend logs the problem, uses the default, and
allows an admin to replace it with a valid value.
- **Invalid environment data:** the backend logs the value, ignores it, and
falls through to the persisted setting or default.
- **Concurrent settings writes:** last successful persisted write wins; the
response carries the value applied to the running service.
## Scenarios
- **GIVEN** a session queue contains ten agent-origin messages, **WHEN** its
owner clicks **Clear all**, **THEN** all ten pending rows are removed, the
queue panel disappears, and a new message can be admitted.
- **GIVEN** one visible agent-origin message, **WHEN** the owner clicks its
**Remove** action, **THEN** that entry disappears and other entries retain
FIFO order and provenance, with displayed positions compacted to `#1`
through `#N`.
- **GIVEN** visible user, agent, workflow, and server messages in one queue,
**WHEN** the owner clicks **Clear all**, **THEN** every visible pending row is
removed regardless of origin.
- **GIVEN** a durable lifecycle head is reserved while a later pending message
remains visible, **WHEN** the owner clears the queue, **THEN** the later
message is removed and the hidden in-flight row remains available for
acknowledgement.
- **GIVEN** a caller cannot access another user's session, **WHEN** they submit
its session ID and a disclosed queue-entry ID, **THEN** the operation reveals
no queue contents and performs no mutation.
- **GIVEN** the saved limit is `20` and no environment override exists, **WHEN**
an admin changes it to `3`, **THEN** subsequent status reports `max: 3` and
new admissions are rejected once three persisted rows are present.
- **GIVEN** a queue already contains ten rows, **WHEN** the admin lowers the
limit to `3`, **THEN** all ten remain, removals and draining still work, and
new admissions remain blocked until fewer than three rows persist.
- **GIVEN** an accepted message is dequeued and delivery fails after the limit
was lowered below the current count, **WHEN** the orchestrator restores it,
**THEN** the original message identity and FIFO position are preserved.
- **GIVEN** `KANDEV_QUEUE_MAX_PER_SESSION=50`, **WHEN** the page loads, **THEN**
it shows effective value `50`, identifies the environment source, and keeps
the input read-only.
- **GIVEN** an admin saves `0`, **WHEN** they enqueue more than ten messages,
**THEN** no capacity error is produced solely by queue length and the page
explains that the queue is unlimited.
- **GIVEN** a phone viewport, **WHEN** the user opens the queue panel and the
General settings menu, **THEN** remove/clear are touch-sized and Message Queue
is reachable without horizontal overflow or a second page scroll owner.
## Out of Scope
- Editing agent-, workflow-, or server-origin message content.
- Changing the shipped merge compatibility rules.
- Cancelling a prompt after it has entered in-flight delivery or reached the
executor.
- Per-workspace, per-task, or per-session capacity overrides.
- Automatically pruning old messages when a lower limit is saved.
- Queue reordering or bulk selection beyond **Clear all**.
+8 -3
View File
@@ -6,6 +6,10 @@ owner: kandev
# Merge Enqueued Messages Individually
Queue-wide removal and capacity behavior is defined separately by
[Manage Pending Message Queues](message-queue-management.md). This spec governs
only the merge operation.
## Why
When a session is busy, users queue follow-up prompts that drain one-per-turn. A
@@ -118,9 +122,10 @@ No schema change. The merge reuses the existing `queued_messages` table:
one-way prompts from a single inter-task agent preserves the reserved row's
provenance (the merged entry keeps the target's identity and the source's
`sender_task_id`-matched lineage) while reducing deliveries. The gate is
strict — identical non-empty `sender_task_id`, never caller-tunable — so a
client still cannot move, delete, or reorder agent-owned rows outside that
exact fold.
strict — identical non-empty `sender_task_id`, never caller-tunable — so the
merge operation cannot move, reorder, or combine unrelated agent-owned rows.
Authorized pending-row deletion is a separate operation governed by
[Manage Pending Message Queues](message-queue-management.md).
- Workflow and system messages are never a merge source or target.
- The WS handler rejects client-supplied reserved `user_id` values, exactly like
the update handler.