fix: protect queued FIFO dispatch admission (#3702)
This commit is contained in:
@@ -106,24 +106,26 @@ func dialTestWSWithAuth(t *testing.T, server *httptest.Server, token string) *we
|
||||
return conn
|
||||
}
|
||||
|
||||
// assertConnectionClosedByServer reads from conn and requires the read to
|
||||
// fail with something other than a deadline timeout. A bare "err == nil
|
||||
// means still open" check cannot tell a deliberate server-side close apart
|
||||
// from an untouched connection that simply outlived `within`: both produce
|
||||
// a non-nil error from ReadMessage, but only the timeout case means the
|
||||
// fencing mechanism never fired. Confirmed empirically: an identical dial
|
||||
// with no rotation at all still errors with "i/o timeout" once `within`
|
||||
// elapses, which a bare nil check would have accepted as proof of closure.
|
||||
// assertConnectionClosedByServer drains any frames queued before the server
|
||||
// close and requires a non-timeout read error. A PTY-backed stream can finish
|
||||
// writing buffered output concurrently with credential invalidation, so the
|
||||
// first read after rotation may still return a frame. A timeout means the
|
||||
// fencing mechanism never fired; an identical dial with no rotation reaches
|
||||
// that path once `within` elapses.
|
||||
func assertConnectionClosedByServer(t *testing.T, conn *websocket.Conn, within time.Duration) {
|
||||
t.Helper()
|
||||
_ = conn.SetReadDeadline(time.Now().Add(within))
|
||||
_, _, err := conn.ReadMessage()
|
||||
if err == nil {
|
||||
t.Fatal("ReadMessage after credential rotation = nil error, want the server to have closed the connection")
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||
t.Fatalf("ReadMessage after credential rotation timed out waiting for the server to close (%v), want the server to close immediately", err)
|
||||
deadline := time.Now().Add(within)
|
||||
_ = conn.SetReadDeadline(deadline)
|
||||
for {
|
||||
_, _, err := conn.ReadMessage()
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||
t.Fatalf("ReadMessage after credential rotation timed out waiting for the server to close (%v), want the server to close immediately", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1749,7 +1749,7 @@ func TestClarificationRecoveryCancellationFrameRejectsNormalAgentActivity(t *tes
|
||||
// test for the production hang where a clarification-timeout recovery left a
|
||||
// session permanently unstoppable. retryClarificationAfterCancel used to send
|
||||
// its retry prompt inline while holding the per-session cancelInFlight guard.
|
||||
// executor.Prompt blocks until a jammed agent accepts the prompt (observed:
|
||||
// executor.Prompt blocks after a jammed agent accepts the prompt (observed:
|
||||
// minutes, stuck in an MCP call), so the guard stayed held the whole time —
|
||||
// and every user Cancel-button click TryLocks that same guard, so it was
|
||||
// starved and silently no-op'd ("cancel already in flight; skipping
|
||||
@@ -1763,16 +1763,21 @@ func TestRetryClarificationAfterCancel_DoesNotStarveUserCancel(t *testing.T) {
|
||||
repo := setupTestRepo(t)
|
||||
retryPromptBlock := make(chan struct{})
|
||||
retryPromptEntered := make(chan struct{})
|
||||
agentMgr := &mockAgentManager{
|
||||
baseAgentMgr := &mockAgentManager{
|
||||
isAgentRunning: true,
|
||||
repoForExecutionLookup: repo,
|
||||
}
|
||||
agentMgr := &callbackAfterPromptEntryAgentManager{
|
||||
mockAgentManager: baseAgentMgr,
|
||||
promptEntries: []<-chan struct{}{retryPromptEntered},
|
||||
}
|
||||
taskRepo := newMockTaskRepo()
|
||||
svc := createTestServiceWithAgent(repo, newMockStepGetter(), taskRepo, agentMgr)
|
||||
svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{})
|
||||
|
||||
// The retry prompt (the only prompt this test dispatches) blocks in-flight,
|
||||
// standing in for a jammed agent that never accepts the resume prompt.
|
||||
// The retry prompt (the only prompt this test dispatches) blocks in-flight
|
||||
// after its provider-acceptance callback, standing in for a jammed agent
|
||||
// whose turn remains open while it is stuck in an MCP call.
|
||||
var enteredOnce sync.Once
|
||||
agentMgr.promptAgentFunc = func(context.Context, string, string, []v1.MessageAttachment, bool) (*executor.PromptResult, error) {
|
||||
enteredOnce.Do(func() { close(retryPromptEntered) })
|
||||
|
||||
@@ -189,7 +189,7 @@ func TestWorkflowAutoStartPromptClaimRejectsSessionTerminalizedAfterPromotion(t
|
||||
svc.repo = barrierRepo
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, _, _, _, _, claimErr := svc.claimSessionRunningForPrompt(
|
||||
_, _, _, _, _, _, claimErr := svc.claimSessionRunningForPrompt(
|
||||
ctx, session.TaskID, session.ID, "", false, nil, nil, "", true, nil,
|
||||
)
|
||||
errCh <- claimErr
|
||||
|
||||
@@ -371,7 +371,7 @@ func TestResetAgentContext_ResetMarkerPrecedesCancellationWait(t *testing.T) {
|
||||
|
||||
cancelledCtx, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
_, _, _, _, _, err := svc.claimSessionRunningForPrompt(
|
||||
_, _, _, _, _, _, err := svc.claimSessionRunningForPrompt(
|
||||
cancelledCtx, session.TaskID, session.ID, "", false, nil, nil, "", false, nil,
|
||||
)
|
||||
if !errors.Is(err, ErrSessionResetInProgress) {
|
||||
@@ -444,7 +444,7 @@ func TestResetAgentContext_SerializesPromptAdmission(t *testing.T) {
|
||||
promptDone := make(chan error, 1)
|
||||
go func() {
|
||||
close(promptStarted)
|
||||
_, _, _, _, _, err := svc.claimSessionRunningForPrompt(
|
||||
_, _, _, _, _, _, err := svc.claimSessionRunningForPrompt(
|
||||
ctx, session.TaskID, session.ID, "", false, nil, nil, "", false, nil,
|
||||
)
|
||||
promptDone <- err
|
||||
|
||||
@@ -3,13 +3,28 @@ package orchestrator
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/orchestrator/executor"
|
||||
"github.com/kandev/kandev/internal/orchestrator/messagequeue"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
type modelSwitchGateAgentManager struct {
|
||||
*mockAgentManager
|
||||
switchEntered chan struct{}
|
||||
allowSwitch chan struct{}
|
||||
}
|
||||
|
||||
func (m *modelSwitchGateAgentManager) SetSessionModelBySessionID(context.Context, string, string) error {
|
||||
close(m.switchEntered)
|
||||
<-m.allowSwitch
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestPromptTaskExpectedIdentityRejectsReplacementAfterClaim(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
@@ -48,3 +63,177 @@ func TestPromptTaskExpectedIdentityRejectsReplacementAfterClaim(t *testing.T) {
|
||||
t.Fatalf("replacement session prompts = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPromptTaskReleasesDispatchGuardBeforeMissingExecutionRecovery(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
const taskID, sessionID = "task-prompt-identity-recovery", "session-prompt-identity-recovery"
|
||||
repo := setupTestRepo(t)
|
||||
seedTaskAndSession(t, repo, taskID, sessionID, models.TaskSessionStateWaitingForInput)
|
||||
session, err := repo.GetTaskSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("get session: %v", err)
|
||||
}
|
||||
session.AgentProfileID = "profile-prompt-identity-recovery"
|
||||
if err := repo.UpdateTaskSession(ctx, session); err != nil {
|
||||
t.Fatalf("set session profile: %v", err)
|
||||
}
|
||||
|
||||
taskRepo := newMockTaskRepo()
|
||||
taskRepo.tasks[taskID] = &v1.Task{ID: taskID, Title: "Recovery task", State: v1.TaskStateInProgress}
|
||||
var executionLookups atomic.Int32
|
||||
agentMgr := &mockAgentManager{
|
||||
isAgentRunning: true,
|
||||
repoForExecutionLookup: repo,
|
||||
getExecutionIDForSessionFunc: func(context.Context, string) (string, error) {
|
||||
if executionLookups.Add(1) <= 2 {
|
||||
return "execution-prompt-identity-recovery", nil
|
||||
}
|
||||
return "", executor.ErrExecutionNotFound
|
||||
},
|
||||
launchAgentFunc: func(context.Context, *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) {
|
||||
return nil, errors.New("fallback launch failed")
|
||||
},
|
||||
}
|
||||
svc := createTestServiceWithScheduler(repo, newMockStepGetter(), taskRepo, agentMgr)
|
||||
svc.messageQueue = newAuthoritativeMemoryQueue(repo, testLogger())
|
||||
svc.messageCreator = &mockMessageCreator{}
|
||||
identity, err := svc.messageQueue.ResolveSessionIdentity(ctx, taskID, sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve session identity: %v", err)
|
||||
}
|
||||
if err := svc.messageQueue.SetAutoRun(ctx, sessionID, true); err != nil {
|
||||
t.Fatalf("enable auto-run: %v", err)
|
||||
}
|
||||
if _, err := svc.messageQueue.QueueMessageWithMetadata(
|
||||
ctx, sessionID, taskID, "queued prompt", "", messagequeue.QueuedByUser, false, nil, nil,
|
||||
); err != nil {
|
||||
t.Fatalf("queue prompt: %v", err)
|
||||
}
|
||||
queued, ok, _, err := svc.messageQueue.ReserveQueuedWithAutoRunForSession(ctx, identity)
|
||||
if err != nil || !ok || queued == nil {
|
||||
t.Fatalf("reserve queued prompt: queued=%+v ok=%v err=%v", queued, ok, err)
|
||||
}
|
||||
if reservation := svc.markQueuedDispatchInFlightWithIdentityLocked(identity, queued.ID, queued); reservation == nil {
|
||||
t.Fatal("mark queued dispatch in flight returned nil")
|
||||
}
|
||||
|
||||
attempt, owner, err := svc.beginResumeAttempt(ctx, taskID, sessionID)
|
||||
if err != nil || !owner || attempt == nil {
|
||||
t.Fatalf("begin resume attempt: attempt=%v owner=%v err=%v", attempt, owner, err)
|
||||
}
|
||||
attempt.setExecutionID("execution-prompt-identity-recovery")
|
||||
t.Cleanup(func() { attempt.finish(svc.resumeAttemptStore()) })
|
||||
|
||||
promptDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, promptErr := svc.promptTask(
|
||||
ctx, taskID, sessionID, "queued prompt", "", false, nil, true,
|
||||
launchOriginAutomatic,
|
||||
promptTaskOptions{
|
||||
claimEntryID: queued.ID,
|
||||
expectedSessionIdentity: &identity,
|
||||
resumeAttempt: attempt,
|
||||
},
|
||||
)
|
||||
promptDone <- promptErr
|
||||
}()
|
||||
|
||||
select {
|
||||
case promptErr := <-promptDone:
|
||||
if promptErr == nil {
|
||||
t.Fatal("promptTask unexpectedly succeeded after fallback launch failure")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("promptTask deadlocked while missing-execution recovery reacquired the dispatch guard")
|
||||
}
|
||||
if hasCancelInFlightGuard(svc, sessionID) {
|
||||
t.Fatal("queued dispatch guard remained held after missing-execution recovery")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPromptTaskKeepsQueuedDispatchGuardThroughModelSwitch(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
const taskID, sessionID = "task-prompt-model-switch", "session-prompt-model-switch"
|
||||
repo := setupTestRepo(t)
|
||||
seedTaskAndSession(t, repo, taskID, sessionID, models.TaskSessionStateWaitingForInput)
|
||||
seedExecutorRunning(t, repo, sessionID, taskID, "execution-prompt-model-switch")
|
||||
session, err := repo.GetTaskSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("get session: %v", err)
|
||||
}
|
||||
session.AgentProfileSnapshot = map[string]interface{}{"model": "old-model"}
|
||||
if err := repo.UpdateTaskSession(ctx, session); err != nil {
|
||||
t.Fatalf("set session model: %v", err)
|
||||
}
|
||||
|
||||
agentMgr := &modelSwitchGateAgentManager{
|
||||
mockAgentManager: &mockAgentManager{
|
||||
isAgentRunning: true,
|
||||
repoForExecutionLookup: repo,
|
||||
},
|
||||
switchEntered: make(chan struct{}),
|
||||
allowSwitch: make(chan struct{}),
|
||||
}
|
||||
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
|
||||
svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{})
|
||||
svc.messageQueue = newAuthoritativeMemoryQueue(repo, testLogger())
|
||||
t.Cleanup(func() {
|
||||
select {
|
||||
case <-agentMgr.allowSwitch:
|
||||
default:
|
||||
close(agentMgr.allowSwitch)
|
||||
}
|
||||
svc.clearAcceptedQueuedDispatch(sessionID)
|
||||
svc.stopSendNowWorkers()
|
||||
})
|
||||
identity, err := svc.messageQueue.ResolveSessionIdentity(ctx, taskID, sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve session identity: %v", err)
|
||||
}
|
||||
if err := svc.messageQueue.SetAutoRun(ctx, sessionID, true); err != nil {
|
||||
t.Fatalf("enable auto-run: %v", err)
|
||||
}
|
||||
if _, err := svc.messageQueue.QueueMessageWithMetadata(
|
||||
ctx, sessionID, taskID, "queued prompt", "new-model", messagequeue.QueuedByUser, false, nil, nil,
|
||||
); err != nil {
|
||||
t.Fatalf("queue prompt: %v", err)
|
||||
}
|
||||
queued, ok, _, err := svc.messageQueue.ReserveQueuedWithAutoRunForSession(ctx, identity)
|
||||
if err != nil || !ok || queued == nil {
|
||||
t.Fatalf("reserve queued prompt: queued=%+v ok=%v err=%v", queued, ok, err)
|
||||
}
|
||||
reservation := svc.markQueuedDispatchInFlightWithIdentityLocked(identity, queued.ID, queued)
|
||||
if reservation == nil {
|
||||
t.Fatal("mark queued dispatch in flight returned nil")
|
||||
}
|
||||
|
||||
promptDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, promptErr := svc.promptTask(
|
||||
ctx, taskID, sessionID, "queued prompt", "new-model", false, nil, true,
|
||||
launchOriginAutomatic,
|
||||
promptTaskOptions{
|
||||
claimEntryID: queued.ID,
|
||||
expectedSessionIdentity: &identity,
|
||||
},
|
||||
)
|
||||
promptDone <- promptErr
|
||||
}()
|
||||
select {
|
||||
case <-agentMgr.switchEntered:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("timed out waiting for model switch")
|
||||
}
|
||||
if !hasCancelInFlightGuard(svc, sessionID) {
|
||||
t.Fatal("queued dispatch guard was not held during model switch")
|
||||
}
|
||||
close(agentMgr.allowSwitch)
|
||||
select {
|
||||
case promptErr := <-promptDone:
|
||||
if promptErr != nil {
|
||||
t.Fatalf("promptTask after model switch: %v", promptErr)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("promptTask did not return after model switch")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -349,9 +349,6 @@ func (s *Service) claimAndDispatchSendNow(ctx context.Context, identity *message
|
||||
} else {
|
||||
reservation = s.markQueuedDispatchInFlightWithSourceLocked(sessionID, claim.Dispatch.ID, nil)
|
||||
}
|
||||
if reservation != nil {
|
||||
reservation.liveEligible.Store(true)
|
||||
}
|
||||
if !s.launchSendNowClaim(claim, reservation) {
|
||||
if restoreErr := s.restoreSendNowClaimWithRetry(context.Background(), claim); restoreErr != nil {
|
||||
s.logger.Error("failed to restore send-now claim after service shutdown",
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/orchestrator/executor"
|
||||
"github.com/kandev/kandev/internal/orchestrator/messagequeue"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
// preDispatchGateAgentManager pauses FIFO A before the provider call and keeps
|
||||
// its completion pending after the acceptance callback. This models a real
|
||||
// provider admission boundary followed by a late predecessor completion.
|
||||
type preDispatchGateAgentManager struct {
|
||||
*mockAgentManager
|
||||
firstDispatchEntered chan struct{}
|
||||
allowFirstDispatch chan struct{}
|
||||
firstAccepted chan struct{}
|
||||
allowFirstReturn chan struct{}
|
||||
firstReturned chan struct{}
|
||||
secondAccepted chan struct{}
|
||||
allowSecondReturn chan struct{}
|
||||
secondReturned chan struct{}
|
||||
promptCount atomic.Int32
|
||||
firstDispatchOnce sync.Once
|
||||
firstAcceptedOnce sync.Once
|
||||
firstReturnedOnce sync.Once
|
||||
secondAcceptedOnce sync.Once
|
||||
secondReturnedOnce sync.Once
|
||||
}
|
||||
|
||||
func (m *preDispatchGateAgentManager) PromptAgentWithDispatchCallback(
|
||||
ctx context.Context,
|
||||
executionID, prompt string,
|
||||
attachments []v1.MessageAttachment,
|
||||
dispatchOnly bool,
|
||||
onDispatched func(),
|
||||
) (*executor.PromptResult, error) {
|
||||
call := m.promptCount.Add(1)
|
||||
if call == 1 {
|
||||
m.firstDispatchOnce.Do(func() { close(m.firstDispatchEntered) })
|
||||
<-m.allowFirstDispatch
|
||||
}
|
||||
result, err := m.PromptAgent(ctx, executionID, prompt, attachments, dispatchOnly)
|
||||
if err != nil || onDispatched == nil {
|
||||
return result, err
|
||||
}
|
||||
onDispatched()
|
||||
switch call {
|
||||
case 1:
|
||||
m.firstAcceptedOnce.Do(func() { close(m.firstAccepted) })
|
||||
<-m.allowFirstReturn
|
||||
m.firstReturnedOnce.Do(func() { close(m.firstReturned) })
|
||||
case 2:
|
||||
m.secondAcceptedOnce.Do(func() { close(m.secondAccepted) })
|
||||
<-m.allowSecondReturn
|
||||
m.secondReturnedOnce.Do(func() { close(m.secondReturned) })
|
||||
default:
|
||||
panic(fmt.Sprintf("preDispatchGateAgentManager: unexpected prompt call %d", call))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *preDispatchGateAgentManager) releaseFirstDispatch() {
|
||||
select {
|
||||
case <-m.allowFirstDispatch:
|
||||
default:
|
||||
close(m.allowFirstDispatch)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *preDispatchGateAgentManager) releaseFirstReturn() {
|
||||
select {
|
||||
case <-m.allowFirstReturn:
|
||||
default:
|
||||
close(m.allowFirstReturn)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *preDispatchGateAgentManager) releaseSecondReturn() {
|
||||
select {
|
||||
case <-m.allowSecondReturn:
|
||||
default:
|
||||
close(m.allowSecondReturn)
|
||||
}
|
||||
}
|
||||
|
||||
type armedTurnCaptureService struct {
|
||||
*repoTurnService
|
||||
armed atomic.Bool
|
||||
captured chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (s *armedTurnCaptureService) arm() {
|
||||
s.armed.Store(true)
|
||||
}
|
||||
|
||||
func (s *armedTurnCaptureService) GetActiveTurn(ctx context.Context, sessionID string) (*models.Turn, error) {
|
||||
if s.armed.Load() {
|
||||
s.once.Do(func() { close(s.captured) })
|
||||
}
|
||||
return s.repoTurnService.GetActiveTurn(ctx, sessionID)
|
||||
}
|
||||
|
||||
func hasCancelInFlightGuard(s *Service, sessionID string) bool {
|
||||
s.cancelInFlightMu.Lock()
|
||||
defer s.cancelInFlightMu.Unlock()
|
||||
_, ok := s.cancelInFlight[sessionID]
|
||||
return ok
|
||||
}
|
||||
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.9
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.10
|
||||
func TestSendQueuedNowSerializesFIFOPredispatchAdmission(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "task-1", "session-1", "step-1")
|
||||
seedExecutorRunning(t, repo, "session-1", "task-1", "exec-1")
|
||||
session, err := repo.GetTaskSession(ctx, "session-1")
|
||||
if err != nil {
|
||||
t.Fatalf("get session: %v", err)
|
||||
}
|
||||
session.State = models.TaskSessionStateWaitingForInput
|
||||
if err := repo.UpdateTaskSession(ctx, session); err != nil {
|
||||
t.Fatalf("set session waiting: %v", err)
|
||||
}
|
||||
|
||||
agentMgr := &preDispatchGateAgentManager{
|
||||
mockAgentManager: &mockAgentManager{isAgentRunning: true, repoForExecutionLookup: repo},
|
||||
firstDispatchEntered: make(chan struct{}),
|
||||
allowFirstDispatch: make(chan struct{}),
|
||||
firstAccepted: make(chan struct{}),
|
||||
allowFirstReturn: make(chan struct{}),
|
||||
firstReturned: make(chan struct{}),
|
||||
secondAccepted: make(chan struct{}),
|
||||
allowSecondReturn: make(chan struct{}),
|
||||
secondReturned: make(chan struct{}),
|
||||
}
|
||||
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
|
||||
svc.messageQueue.SetAutoMergeEnabled(false)
|
||||
svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{})
|
||||
svc.messageCreator = &mockMessageCreator{}
|
||||
turns := &armedTurnCaptureService{
|
||||
repoTurnService: &repoTurnService{repo: repo},
|
||||
captured: make(chan struct{}),
|
||||
}
|
||||
svc.turnService = turns
|
||||
t.Cleanup(func() {
|
||||
agentMgr.releaseFirstDispatch()
|
||||
agentMgr.releaseFirstReturn()
|
||||
agentMgr.releaseSecondReturn()
|
||||
svc.stopSendNowWorkers()
|
||||
})
|
||||
|
||||
if _, err := svc.messageQueue.QueueMessageWithMetadata(
|
||||
ctx, "session-1", "task-1", "running A", "", messagequeue.QueuedByUser, false, nil, nil,
|
||||
); err != nil {
|
||||
t.Fatalf("queue FIFO A: %v", err)
|
||||
}
|
||||
if !svc.drainQueuedMessageForPromptableSession(ctx, "session-1") {
|
||||
t.Fatal("ordinary FIFO drain did not start A")
|
||||
}
|
||||
select {
|
||||
case <-agentMgr.firstDispatchEntered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out before FIFO A provider admission")
|
||||
}
|
||||
if !hasCancelInFlightGuard(svc, "session-1") {
|
||||
t.Fatal("FIFO A released cancellation admission before provider acceptance")
|
||||
}
|
||||
|
||||
b, err := svc.messageQueue.QueueMessageWithMetadata(
|
||||
ctx, "session-1", "task-1", "urgent B", "", messagequeue.QueuedByUser, false, nil, nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("queue Send Now B: %v", err)
|
||||
}
|
||||
if _, err := svc.messageQueue.QueueMessageWithMetadata(
|
||||
ctx, "session-1", "task-1", "later C", "", messagequeue.QueuedByUser, false, nil, nil,
|
||||
); err != nil {
|
||||
t.Fatalf("queue FIFO C: %v", err)
|
||||
}
|
||||
|
||||
turns.arm()
|
||||
sendNowDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, sendErr := svc.SendQueuedNow(ctx, "session-1", QueueSendNowScopeEntry, b.ID)
|
||||
sendNowDone <- sendErr
|
||||
}()
|
||||
select {
|
||||
case <-turns.captured:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for Send Now turn capture")
|
||||
}
|
||||
|
||||
agentMgr.releaseFirstDispatch()
|
||||
select {
|
||||
case <-agentMgr.firstAccepted:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for FIFO A provider acceptance")
|
||||
}
|
||||
select {
|
||||
case err := <-sendNowDone:
|
||||
if err != nil {
|
||||
t.Fatalf("Send Now B: %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for Send Now B request")
|
||||
}
|
||||
select {
|
||||
case <-agentMgr.secondAccepted:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for replacement B provider acceptance")
|
||||
}
|
||||
if got := agentMgr.promptCount.Load(); got != 2 {
|
||||
t.Fatalf("provider prompt count after B acceptance = %d, want exactly A and B", got)
|
||||
}
|
||||
agentMgr.mu.Lock()
|
||||
prompts := append([]string(nil), agentMgr.capturedPrompts...)
|
||||
agentMgr.mu.Unlock()
|
||||
if len(prompts) != 2 || prompts[1] != "urgent B" {
|
||||
t.Fatalf("provider prompts after B acceptance = %#v, want A and one B", prompts)
|
||||
}
|
||||
|
||||
if got := agentMgr.cancelAgentCalls.Load(); got != 1 {
|
||||
t.Fatalf("cancel calls before late A completion = %d, want 1", got)
|
||||
}
|
||||
status := svc.messageQueue.GetStatus(ctx, "session-1")
|
||||
if status.Count != 1 || status.Entries[0].Content != "later C" {
|
||||
t.Fatalf("queue after B acceptance = %#v, want C only", status.Entries)
|
||||
}
|
||||
activeBefore, err := turns.GetActiveTurn(ctx, "session-1")
|
||||
if err != nil || activeBefore == nil {
|
||||
t.Fatalf("active replacement turn before late A completion = %#v, err=%v", activeBefore, err)
|
||||
}
|
||||
replacement := svc.acceptedQueuedDispatchForSession("session-1")
|
||||
if replacement == nil || replacement.currentPhase() != queuedDispatchLive {
|
||||
t.Fatalf("replacement reservation before late A completion = %#v, want live", replacement)
|
||||
}
|
||||
attemptBefore, ok := svc.promptAttemptForSession("session-1")
|
||||
if !ok || attemptBefore == nil {
|
||||
t.Fatal("replacement prompt attempt was not recorded")
|
||||
}
|
||||
|
||||
agentMgr.releaseFirstReturn()
|
||||
select {
|
||||
case <-agentMgr.firstReturned:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for late FIFO A completion")
|
||||
}
|
||||
activeAfter, err := turns.GetActiveTurn(ctx, "session-1")
|
||||
if err != nil || activeAfter == nil || activeAfter.ID != activeBefore.ID {
|
||||
t.Fatalf("late FIFO A completion changed active replacement: before=%#v after=%#v err=%v", activeBefore, activeAfter, err)
|
||||
}
|
||||
if got := svc.acceptedQueuedDispatchForSession("session-1"); got != replacement {
|
||||
t.Fatal("late FIFO A completion cleared or replaced B ownership")
|
||||
}
|
||||
attemptAfter, ok := svc.promptAttemptForSession("session-1")
|
||||
if !ok || attemptAfter != attemptBefore {
|
||||
t.Fatal("late FIFO A completion cleared or replaced B prompt-attempt ownership")
|
||||
}
|
||||
|
||||
agentMgr.releaseSecondReturn()
|
||||
select {
|
||||
case <-agentMgr.secondReturned:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for replacement B completion")
|
||||
}
|
||||
}
|
||||
|
||||
var _ executor.AgentManagerClient = (*preDispatchGateAgentManager)(nil)
|
||||
@@ -274,7 +274,6 @@ func TestExecuteSendNowClaimRejectsRecreatedSessionBeforePrompt(t *testing.T) {
|
||||
t.Fatalf("claim old prompt: %v", err)
|
||||
}
|
||||
reservation := svc.markQueuedDispatchInFlightWithIdentityLocked(identity, claim.Dispatch.ID, nil)
|
||||
reservation.liveEligible.Store(true)
|
||||
|
||||
if _, err := repo.DB().ExecContext(
|
||||
ctx,
|
||||
@@ -587,6 +586,206 @@ func TestSendQueuedNowSupersedesPendingFIFOHandoff(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// callbackAfterPromptEntryAgentManager models a provider that accepts a prompt
|
||||
// after entering its turn and before the turn finishes. The callback must be
|
||||
// able to release admission while the provider call remains in progress.
|
||||
type callbackAfterPromptEntryAgentManager struct {
|
||||
*mockAgentManager
|
||||
promptEntries []<-chan struct{}
|
||||
promptCalls atomic.Int32
|
||||
}
|
||||
|
||||
func (m *callbackAfterPromptEntryAgentManager) PromptAgentWithDispatchCallback(
|
||||
ctx context.Context,
|
||||
executionID, prompt string,
|
||||
attachments []v1.MessageAttachment,
|
||||
dispatchOnly bool,
|
||||
onDispatched func(),
|
||||
) (*executor.PromptResult, error) {
|
||||
type promptResult struct {
|
||||
result *executor.PromptResult
|
||||
err error
|
||||
}
|
||||
resultCh := make(chan promptResult, 1)
|
||||
go func() {
|
||||
result, err := m.PromptAgent(ctx, executionID, prompt, attachments, dispatchOnly)
|
||||
resultCh <- promptResult{result: result, err: err}
|
||||
}()
|
||||
|
||||
call := int(m.promptCalls.Add(1)) - 1
|
||||
if call < len(m.promptEntries) {
|
||||
select {
|
||||
case <-m.promptEntries[call]:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
if onDispatched != nil {
|
||||
onDispatched()
|
||||
}
|
||||
result := <-resultCh
|
||||
return result.result, result.err
|
||||
}
|
||||
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.2
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.7
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.9
|
||||
func TestSendQueuedNowCancelsLiveFIFOTurn(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
scope string
|
||||
entryID string
|
||||
logicalProfileID string
|
||||
executionProfileID string
|
||||
wantSentCount int
|
||||
wantPrompt string
|
||||
wantRemaining string
|
||||
}{
|
||||
{
|
||||
name: "entry with fixed profile",
|
||||
scope: QueueSendNowScopeEntry,
|
||||
logicalProfileID: "fixed-profile",
|
||||
executionProfileID: "fixed-profile",
|
||||
wantSentCount: 1,
|
||||
wantPrompt: "urgent B",
|
||||
wantRemaining: "later C",
|
||||
},
|
||||
{
|
||||
name: "all with dynamic Cursor execution",
|
||||
scope: QueueSendNowScopeAll,
|
||||
logicalProfileID: "dynamic-profile",
|
||||
executionProfileID: "cursor-profile",
|
||||
wantSentCount: 2,
|
||||
wantPrompt: "urgent B\n\nlater C",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "task-1", "session-1", "step-1")
|
||||
seedExecutorRunning(t, repo, "session-1", "task-1", "exec-cursor")
|
||||
session, err := repo.GetTaskSession(ctx, "session-1")
|
||||
if err != nil {
|
||||
t.Fatalf("get session: %v", err)
|
||||
}
|
||||
session.State = models.TaskSessionStateWaitingForInput
|
||||
session.AgentProfileID = tc.logicalProfileID
|
||||
session.ExecutionProfileID = tc.executionProfileID
|
||||
if err := repo.UpdateTaskSession(ctx, session); err != nil {
|
||||
t.Fatalf("set session ready with execution attribution: %v", err)
|
||||
}
|
||||
|
||||
firstPromptEntered := make(chan struct{})
|
||||
allowFirstPrompt := make(chan struct{})
|
||||
secondPromptEntered := make(chan struct{})
|
||||
allowSecondPrompt := make(chan struct{})
|
||||
var releaseFirstPrompt, releaseSecondPrompt sync.Once
|
||||
var promptCount atomic.Int32
|
||||
baseAgentMgr := &mockAgentManager{
|
||||
isAgentRunning: true,
|
||||
repoForExecutionLookup: repo,
|
||||
promptAgentFunc: func(context.Context, string, string, []v1.MessageAttachment, bool) (*executor.PromptResult, error) {
|
||||
switch promptCount.Add(1) {
|
||||
case 1:
|
||||
close(firstPromptEntered)
|
||||
<-allowFirstPrompt
|
||||
case 2:
|
||||
close(secondPromptEntered)
|
||||
<-allowSecondPrompt
|
||||
default:
|
||||
t.Errorf("FIFO/Send Now dispatched more than two prompts")
|
||||
}
|
||||
return &executor.PromptResult{}, nil
|
||||
},
|
||||
}
|
||||
agentMgr := &callbackAfterPromptEntryAgentManager{
|
||||
mockAgentManager: baseAgentMgr,
|
||||
promptEntries: []<-chan struct{}{firstPromptEntered, secondPromptEntered},
|
||||
}
|
||||
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
|
||||
svc.messageQueue.SetAutoMergeEnabled(false)
|
||||
svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{})
|
||||
svc.messageCreator = &mockMessageCreator{}
|
||||
t.Cleanup(func() {
|
||||
releaseFirstPrompt.Do(func() { close(allowFirstPrompt) })
|
||||
releaseSecondPrompt.Do(func() { close(allowSecondPrompt) })
|
||||
svc.stopSendNowWorkers()
|
||||
})
|
||||
|
||||
if _, err := svc.messageQueue.QueueMessageWithMetadata(
|
||||
ctx, "session-1", "task-1", "running A", "", messagequeue.QueuedByUser, false, nil, nil,
|
||||
); err != nil {
|
||||
t.Fatalf("queue FIFO message A: %v", err)
|
||||
}
|
||||
if !svc.drainQueuedMessageForPromptableSession(ctx, "session-1") {
|
||||
t.Fatal("ordinary FIFO drain did not start A")
|
||||
}
|
||||
select {
|
||||
case <-firstPromptEntered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for FIFO prompt A")
|
||||
}
|
||||
|
||||
if _, err := svc.messageQueue.QueueMessageWithMetadata(
|
||||
ctx, "session-1", "task-1", "urgent B", "", messagequeue.QueuedByUser, false, nil, nil,
|
||||
); err != nil {
|
||||
t.Fatalf("queue Send Now message B: %v", err)
|
||||
}
|
||||
if _, err := svc.messageQueue.QueueMessageWithMetadata(
|
||||
ctx, "session-1", "task-1", "later C", "", messagequeue.QueuedByUser, false, nil, nil,
|
||||
); err != nil {
|
||||
t.Fatalf("queue FIFO remainder C: %v", err)
|
||||
}
|
||||
status := svc.messageQueue.GetStatus(ctx, "session-1")
|
||||
if len(status.Entries) != 2 {
|
||||
t.Fatalf("queued remainder before Send Now = %#v, want B and C", status.Entries)
|
||||
}
|
||||
if tc.scope == QueueSendNowScopeEntry {
|
||||
tc.entryID = status.Entries[0].ID
|
||||
}
|
||||
|
||||
sent, err := svc.SendQueuedNow(ctx, "session-1", tc.scope, tc.entryID)
|
||||
if err != nil {
|
||||
t.Fatalf("Send Now error = %v, want successful replacement", err)
|
||||
}
|
||||
if sent != tc.wantSentCount {
|
||||
t.Fatalf("Send Now sent count = %d, want %d", sent, tc.wantSentCount)
|
||||
}
|
||||
if got := agentMgr.cancelAgentCalls.Load(); got == 0 {
|
||||
t.Fatal("Send Now did not cancel the live FIFO turn A")
|
||||
}
|
||||
|
||||
status = svc.messageQueue.GetStatus(ctx, "session-1")
|
||||
if tc.wantRemaining == "" {
|
||||
if status.Count != 0 {
|
||||
t.Fatalf("queue while replacement B is held = %#v, want empty", status.Entries)
|
||||
}
|
||||
} else if status.Count != 1 || status.Entries[0].Content != tc.wantRemaining {
|
||||
t.Fatalf("queue while replacement B is held = %#v, want %q", status.Entries, tc.wantRemaining)
|
||||
}
|
||||
|
||||
releaseFirstPrompt.Do(func() { close(allowFirstPrompt) })
|
||||
select {
|
||||
case <-secondPromptEntered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for Send Now replacement prompt")
|
||||
}
|
||||
|
||||
agentMgr.mu.Lock()
|
||||
prompts := append([]string(nil), agentMgr.capturedPrompts...)
|
||||
agentMgr.mu.Unlock()
|
||||
if len(prompts) != 2 {
|
||||
t.Fatalf("captured prompt count = %d, want FIFO A and replacement", len(prompts))
|
||||
}
|
||||
if prompts[1] != tc.wantPrompt {
|
||||
t.Fatalf("replacement prompt = %q, want %q", prompts[1], tc.wantPrompt)
|
||||
}
|
||||
|
||||
releaseSecondPrompt.Do(func() { close(allowSecondPrompt) })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendQueuedNowConflictsAfterFIFOHandoffAccepted(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
@@ -601,21 +800,31 @@ func TestSendQueuedNowConflictsAfterFIFOHandoffAccepted(t *testing.T) {
|
||||
t.Fatalf("set session waiting: %v", err)
|
||||
}
|
||||
|
||||
promptEntered := make(chan struct{})
|
||||
allowPrompt := make(chan struct{})
|
||||
preClaimEntered := make(chan struct{})
|
||||
releasePreClaim := make(chan struct{})
|
||||
var releasePreClaimOnce sync.Once
|
||||
var executionLookupCalls atomic.Int32
|
||||
promptDone := make(chan struct{})
|
||||
agentMgr := &mockAgentManager{
|
||||
isAgentRunning: true,
|
||||
repoForExecutionLookup: repo,
|
||||
promptAgentFunc: func(context.Context, string, string, []v1.MessageAttachment, bool) (*executor.PromptResult, error) {
|
||||
close(promptEntered)
|
||||
<-allowPrompt
|
||||
return &executor.PromptResult{}, nil
|
||||
promptDone: promptDone,
|
||||
getExecutionIDForSessionFunc: func(context.Context, string) (string, error) {
|
||||
if executionLookupCalls.Add(1) == 1 {
|
||||
close(preClaimEntered)
|
||||
<-releasePreClaim
|
||||
}
|
||||
return "exec-1", nil
|
||||
},
|
||||
}
|
||||
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
|
||||
svc.messageQueue.SetAutoMergeEnabled(false)
|
||||
svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{})
|
||||
svc.messageCreator = &mockMessageCreator{}
|
||||
t.Cleanup(func() {
|
||||
releasePreClaimOnce.Do(func() { close(releasePreClaim) })
|
||||
svc.stopSendNowWorkers()
|
||||
})
|
||||
|
||||
for _, content := range []string{"first queued", "second queued"} {
|
||||
if _, err := svc.messageQueue.QueueMessageWithMetadata(
|
||||
@@ -627,7 +836,15 @@ func TestSendQueuedNowConflictsAfterFIFOHandoffAccepted(t *testing.T) {
|
||||
if !svc.drainQueuedMessageForPromptableSession(ctx, "session-1") {
|
||||
t.Fatal("normal FIFO drain did not start")
|
||||
}
|
||||
<-promptEntered
|
||||
select {
|
||||
case <-preClaimEntered:
|
||||
// GetExecutionIDForSession fires before claimSessionRunningForPrompt
|
||||
// acquires the cancelInFlight guard. Blocking here lets Send Now detect
|
||||
// the accepted FIFO reservation without waiting on the guard held through
|
||||
// provider acceptance.
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for FIFO prompt claim barrier")
|
||||
}
|
||||
|
||||
if _, err := svc.SendQueuedNow(ctx, "session-1", QueueSendNowScopeAll, ""); !errors.Is(err, ErrSendNowConflict) {
|
||||
t.Fatalf("send now error = %v, want %v", err, ErrSendNowConflict)
|
||||
@@ -640,7 +857,12 @@ func TestSendQueuedNowConflictsAfterFIFOHandoffAccepted(t *testing.T) {
|
||||
t.Fatalf("remaining queue = %#v, want second queued only", status.Entries)
|
||||
}
|
||||
|
||||
close(allowPrompt)
|
||||
releasePreClaimOnce.Do(func() { close(releasePreClaim) })
|
||||
select {
|
||||
case <-promptDone:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for FIFO prompt")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamCompletePreservesAcceptedSendNowDispatch(t *testing.T) {
|
||||
@@ -748,7 +970,7 @@ func TestSendQueuedNowCancelsLiveReplacementTurn(t *testing.T) {
|
||||
}
|
||||
})
|
||||
var promptCount atomic.Int32
|
||||
agentMgr := &mockAgentManager{
|
||||
baseAgentMgr := &mockAgentManager{
|
||||
isAgentRunning: true,
|
||||
repoForExecutionLookup: repo,
|
||||
promptAgentFunc: func(context.Context, string, string, []v1.MessageAttachment, bool) (*executor.PromptResult, error) {
|
||||
@@ -763,6 +985,10 @@ func TestSendQueuedNowCancelsLiveReplacementTurn(t *testing.T) {
|
||||
return &executor.PromptResult{}, nil
|
||||
},
|
||||
}
|
||||
agentMgr := &callbackAfterPromptEntryAgentManager{
|
||||
mockAgentManager: baseAgentMgr,
|
||||
promptEntries: []<-chan struct{}{firstPromptEntered, secondPromptEntered},
|
||||
}
|
||||
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
|
||||
svc.messageQueue.SetAutoMergeEnabled(false)
|
||||
svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{})
|
||||
@@ -915,7 +1141,8 @@ func TestStreamCompleteSettlesCurrentSendNowSuccessor(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamCompletePreservesSuccessorForStalePromptGeneration(t *testing.T) {
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.10
|
||||
func TestStreamCompletePreservesLiveFIFOSuccessorForStalePromptGeneration(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "task1", "session1", "step1")
|
||||
@@ -927,6 +1154,7 @@ func TestStreamCompletePreservesSuccessorForStalePromptGeneration(t *testing.T)
|
||||
if tracked, err := svc.claimQueuedDispatchForExecution("session1", "dispatch-1", reservation); err != nil || !tracked {
|
||||
t.Fatalf("claim accepted dispatch: tracked=%v err=%v", tracked, err)
|
||||
}
|
||||
svc.markAcceptedDispatchLive("session1", reservation)
|
||||
successor, err := svc.turnService.StartTurn(ctx, "session1")
|
||||
if err != nil {
|
||||
t.Fatalf("start successor turn: %v", err)
|
||||
@@ -948,10 +1176,10 @@ func TestStreamCompletePreservesSuccessorForStalePromptGeneration(t *testing.T)
|
||||
t.Fatalf("get active successor turn: %v", err)
|
||||
}
|
||||
if active == nil || active.ID != successor.ID {
|
||||
t.Fatalf("stale predecessor complete changed active turn to %#v, want %s", active, successor.ID)
|
||||
t.Fatalf("stale FIFO predecessor complete changed active turn to %#v, want %s", active, successor.ID)
|
||||
}
|
||||
if !svc.acceptedDispatchInFlight("session1") {
|
||||
t.Fatal("stale predecessor complete cleared accepted successor dispatch")
|
||||
t.Fatal("stale FIFO predecessor complete cleared live successor dispatch")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,11 +26,6 @@ type queuedDispatchReservation struct {
|
||||
identity messagequeue.QueueSessionIdentity
|
||||
source *messagequeue.QueuedMessage
|
||||
phase atomic.Uint32
|
||||
// liveEligible is set only for Send Now reservations. It allows the
|
||||
// prompt-claim path to move that reservation to live while it still owns
|
||||
// the session guard; ordinary FIFO handoffs remain in accepted until their
|
||||
// turn settles.
|
||||
liveEligible atomic.Bool
|
||||
// successorTurn is the replacement turn this dispatch opened. A late
|
||||
// complete of the cancelled predecessor must not close that turn or
|
||||
// drop this reservation; only the successor's own ready-path settlement
|
||||
@@ -280,7 +275,7 @@ func (s *Service) isQueuedDispatchAccepted(sessionID string) bool {
|
||||
return accepted != nil && accepted.currentPhase() == queuedDispatchAccepted
|
||||
}
|
||||
|
||||
// markAcceptedDispatchLive moves a Send Now successor out of the handoff
|
||||
// markAcceptedDispatchLive moves a queued successor out of the handoff
|
||||
// conflict window once it owns execution. Stream-complete still protects the
|
||||
// bound successor turn; a later Send Now may cancel that live turn.
|
||||
func (s *Service) markAcceptedDispatchLive(sessionID string, reservation *queuedDispatchReservation) {
|
||||
@@ -294,7 +289,7 @@ func (s *Service) markAcceptedDispatchLive(sessionID string, reservation *queued
|
||||
s.markAcceptedDispatchLiveLocked(sessionID, reservation)
|
||||
}
|
||||
|
||||
// markAcceptedDispatchLiveLocked moves a Send Now successor out of the
|
||||
// markAcceptedDispatchLiveLocked moves a queued successor out of the
|
||||
// handoff conflict window while the caller owns sessionID's cancellation
|
||||
// guard. This keeps the phase transition serialized with prompt ownership.
|
||||
func (s *Service) markAcceptedDispatchLiveLocked(sessionID string, reservation *queuedDispatchReservation) {
|
||||
|
||||
@@ -143,7 +143,7 @@ func TestRouteActionClaimBlocksPromptAdmission(t *testing.T) {
|
||||
t.Fatal("route action handler did not start")
|
||||
}
|
||||
|
||||
_, _, _, _, _, err := svc.claimSessionRunningForPrompt(
|
||||
_, _, _, _, _, _, err := svc.claimSessionRunningForPrompt(
|
||||
ctx, "task1", sessionID, "", false, nil, nil, "", false,
|
||||
)
|
||||
close(releaseHandler)
|
||||
|
||||
@@ -1154,9 +1154,10 @@ type Service struct {
|
||||
// dispatchingQueued tracks the pre-acceptance reservation for the exact
|
||||
// queued message handed to an async worker. acceptedQueuedDispatch keeps
|
||||
// the same ownership visible after the worker claims RUNNING until its turn
|
||||
// settles, so Send Now cannot cancel or duplicate a successor that FIFO has
|
||||
// already accepted. The two maps are managed by queued_dispatch.go and are
|
||||
// arbitrated through cancelInFlight.
|
||||
// settles, so late predecessor events cannot cancel or duplicate the FIFO
|
||||
// successor. The live phase still allows Send Now to replace that successor
|
||||
// after provider acceptance. The two maps are managed by
|
||||
// queued_dispatch.go and are arbitrated through cancelInFlight.
|
||||
dispatchingQueued sync.Map
|
||||
acceptedQueuedDispatch sync.Map
|
||||
// queuedDispatchDrainPending records a boot-ready event that arrived while
|
||||
|
||||
@@ -5396,10 +5396,11 @@ func (promptTaskOptions) failureContext(ctx context.Context) (context.Context, c
|
||||
// *and* the mark through the same per-session guard used for every other
|
||||
// cancel/take-and-dispatch decision (see the Service.cancelInFlight field
|
||||
// doc comment) makes "exactly one dispatch wins" a property of mutual
|
||||
// exclusion instead of a racy read. Ordinary prompts release the guard after
|
||||
// this fast, DB-only step. Lifecycle prompts hold the same guard until agentctl
|
||||
// accepts the prompt, so a context reset cannot cancel the claimed turn in the
|
||||
// gap before provider dispatch.
|
||||
// exclusion instead of a racy read. Direct prompts release the guard after
|
||||
// this fast, DB-only step. Queued prompts transfer the guard to promptTask and
|
||||
// release it at provider acceptance, while lifecycle prompts hold the same
|
||||
// guard until agentctl accepts the prompt. Neither path lets cancellation
|
||||
// supersede a claimed queued turn in the gap before provider dispatch.
|
||||
//
|
||||
// Every return path *before* this step (invalid session, not promptable,
|
||||
// ensureSessionRunning failure, a model switch) is covered by
|
||||
@@ -5443,6 +5444,26 @@ func (s *Service) promptTask(ctx context.Context, taskID, sessionID string, prom
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A queued prompt may restart the provider as part of model switching
|
||||
// before the normal claim helper runs. Keep the same session guard across
|
||||
// that I/O and transfer it into the claim so Send Now cannot admit a
|
||||
// replacement between the restart and provider acceptance. Resume-owned
|
||||
// switches already hold this boundary through modelSwitchGuard below.
|
||||
var queuedDispatchGuard *lockedCancelInFlightGuard
|
||||
if options.claimEntryID != "" && !options.lifecyclePrompt && options.resumeAttempt == nil {
|
||||
queuedDispatchGuard = s.lockCancelInFlightGuard(sessionID)
|
||||
defer func() {
|
||||
if queuedDispatchGuard != nil {
|
||||
queuedDispatchGuard.release()
|
||||
}
|
||||
}()
|
||||
if err := s.waitForCancellationWithGuard(
|
||||
resumePromptCtx, sessionID, queuedDispatchGuard.unlock, queuedDispatchGuard.relock,
|
||||
); err != nil {
|
||||
s.rollbackForegroundDispatchOnFailure(resumePromptCtx, taskID, sessionID, foregroundDispatch)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
runBeforeDispatch := runBeforeDispatchOnce(options.beforeDispatch)
|
||||
|
||||
// Cache the replay identity and acquire the model-switch guard before switching.
|
||||
@@ -5471,6 +5492,7 @@ func (s *Service) promptTask(ctx context.Context, taskID, sessionID string, prom
|
||||
|
||||
session, rollback, releaseDispatchGuard, err := s.claimAndGuardDispatch(
|
||||
resumePromptCtx, taskID, sessionID, foregroundClaim, options, foregroundDispatch, resumeAttempt,
|
||||
queuedDispatchGuard,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -5508,7 +5530,7 @@ func (s *Service) runPromptTurn(
|
||||
) (*PromptResult, error) {
|
||||
promptCtx, session, earlyResult, err := s.validateAndRunDispatchBoundary(
|
||||
ctx, taskID, sessionID, prompt, planMode, resumedForPrompt, attachments,
|
||||
session, rollback, options, foregroundDispatch, runBeforeDispatch,
|
||||
session, rollback, options, foregroundDispatch, runBeforeDispatch, releaseDispatchGuard,
|
||||
)
|
||||
if err != nil || earlyResult != nil {
|
||||
return earlyResult, err
|
||||
@@ -5832,12 +5854,19 @@ func (s *Service) validateAndRunDispatchBoundary(
|
||||
ctx context.Context, taskID, sessionID, prompt string, planMode, resumedForPrompt bool,
|
||||
attachments []v1.MessageAttachment, session *models.TaskSession, rollback promptClaimRollback,
|
||||
options promptTaskOptions, foregroundDispatch *foregroundDispatch, runBeforeDispatch func() error,
|
||||
releaseDispatchGuard func(),
|
||||
) (promptCtx context.Context, resolvedSession *models.TaskSession, earlyResult *PromptResult, err error) {
|
||||
promptCtx = options.executorContext(ctx)
|
||||
session, identityValidationErr := s.validateQueuedPromptDispatch(
|
||||
promptCtx, rollback.sessionIdentity, taskID, sessionID, session,
|
||||
)
|
||||
if identityValidationErr != nil {
|
||||
// Missing-execution recovery reacquires the session cancellation guard.
|
||||
// Release the transferred queued-dispatch guard before entering that
|
||||
// recovery path, while retaining it through successful provider admission.
|
||||
if releaseDispatchGuard != nil {
|
||||
releaseDispatchGuard()
|
||||
}
|
||||
result, err := s.finishPromptDispatchFailure(
|
||||
ctx, taskID, sessionID, prompt, planMode, resumedForPrompt, attachments,
|
||||
rollback, options, identityValidationErr, foregroundDispatch, false, nil,
|
||||
@@ -5845,6 +5874,9 @@ func (s *Service) validateAndRunDispatchBoundary(
|
||||
return promptCtx, nil, result, err
|
||||
}
|
||||
if boundaryErr := runBeforeDispatch(); boundaryErr != nil {
|
||||
if releaseDispatchGuard != nil {
|
||||
releaseDispatchGuard()
|
||||
}
|
||||
failureCtx, cancel := options.failureContext(ctx)
|
||||
defer cancel()
|
||||
s.rollbackForegroundDispatchOnFailure(failureCtx, taskID, sessionID, foregroundDispatch)
|
||||
@@ -6071,9 +6103,10 @@ func (s *Service) claimAndGuardDispatch(
|
||||
options promptTaskOptions,
|
||||
foregroundDispatch *foregroundDispatch,
|
||||
resumeAttempt *resumeAttempt,
|
||||
admissionGuard *lockedCancelInFlightGuard,
|
||||
) (session *models.TaskSession, rollback promptClaimRollback, releaseDispatchGuard func(), err error) {
|
||||
session, rollback, releaseDispatchGuard, err = s.claimDispatchAndAcquireGuard(
|
||||
ctx, taskID, sessionID, foregroundClaim, options, foregroundDispatch, resumeAttempt,
|
||||
ctx, taskID, sessionID, foregroundClaim, options, foregroundDispatch, resumeAttempt, admissionGuard,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, promptClaimRollback{}, nil, err
|
||||
@@ -6102,12 +6135,13 @@ func (s *Service) claimAndGuardDispatch(
|
||||
func (s *Service) claimDispatchAndAcquireGuard(
|
||||
ctx context.Context, taskID, sessionID string, foregroundClaim *foregroundClaim,
|
||||
options promptTaskOptions, foregroundDispatch *foregroundDispatch, resumeAttempt *resumeAttempt,
|
||||
admissionGuard *lockedCancelInFlightGuard,
|
||||
) (*models.TaskSession, promptClaimRollback, func(), error) {
|
||||
session, rollback, err := s.claimPromptDispatchWithResumeAttempt(
|
||||
ctx, taskID, sessionID, options.claimEntryID, options.lifecyclePrompt,
|
||||
options.reserveTurnUntilDispatch, options.promptDispatchRecovery,
|
||||
options.afterClaim, foregroundClaim, options.expectedCurrentTurnID,
|
||||
options.requireNonterminalSession, resumeAttempt, options.expectedSessionIdentity,
|
||||
options.requireNonterminalSession, resumeAttempt, admissionGuard, options.expectedSessionIdentity,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrResumeAttemptCancelled) {
|
||||
@@ -6391,7 +6425,7 @@ func (s *Service) claimPromptDispatch(
|
||||
return s.claimPromptDispatchWithResumeAttempt(
|
||||
ctx, taskID, sessionID, claimEntryID, lifecyclePrompt,
|
||||
reserveTurnUntilDispatch, promptDispatchRecovery, afterClaim, foregroundClaim,
|
||||
expectedCurrentTurnID, requireNonterminalSession, nil, expectedIdentities...,
|
||||
expectedCurrentTurnID, requireNonterminalSession, nil, nil, expectedIdentities...,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6406,6 +6440,7 @@ func (s *Service) claimPromptDispatchWithResumeAttempt(
|
||||
expectedCurrentTurnID string,
|
||||
requireNonterminalSession bool,
|
||||
resumeAttempt *resumeAttempt,
|
||||
admissionGuard *lockedCancelInFlightGuard,
|
||||
expectedIdentities ...*messagequeue.QueueSessionIdentity,
|
||||
) (*models.TaskSession, promptClaimRollback, error) {
|
||||
claimCtx := ctx
|
||||
@@ -6422,10 +6457,13 @@ func (s *Service) claimPromptDispatchWithResumeAttempt(
|
||||
)
|
||||
}
|
||||
claimArgs := []interface{}{expectedIdentity, afterClaim}
|
||||
if admissionGuard != nil {
|
||||
claimArgs = append(claimArgs, admissionGuard)
|
||||
}
|
||||
if resumeAttempt != nil {
|
||||
claimArgs = append(claimArgs, resumeAttempt)
|
||||
}
|
||||
claimed, previousState, turnID, createdTurn, reservedTurn, err := s.claimSessionRunningForPrompt(
|
||||
claimed, previousState, turnID, createdTurn, reservedTurn, dispatchGuardRelease, err := s.claimSessionRunningForPrompt(
|
||||
claimCtx, taskID, sessionID, claimEntryID, reserveTurnUntilDispatch,
|
||||
promptDispatchRecovery, foregroundClaim, expectedCurrentTurnID, requireNonterminalSession,
|
||||
claimArgs...,
|
||||
@@ -6445,6 +6483,7 @@ func (s *Service) claimPromptDispatchWithResumeAttempt(
|
||||
if expectedIdentity != nil {
|
||||
rollback.sessionIdentity = *expectedIdentity
|
||||
}
|
||||
rollback.dispatchGuardRelease = dispatchGuardRelease
|
||||
return claimed, rollback, nil
|
||||
}
|
||||
|
||||
@@ -6805,11 +6844,12 @@ func (s *Service) claimSessionRunningForPrompt(
|
||||
expectedCurrentTurnID string,
|
||||
requireNonterminalSession bool,
|
||||
optionalClaimArgs ...interface{},
|
||||
) (*models.TaskSession, models.TaskSessionState, string, bool, *models.Turn, error) {
|
||||
) (*models.TaskSession, models.TaskSessionState, string, bool, *models.Turn, func(), error) {
|
||||
var (
|
||||
afterClaim func() error
|
||||
expectedIdentity *messagequeue.QueueSessionIdentity
|
||||
startupAttempt *resumeAttempt
|
||||
admissionGuard *lockedCancelInFlightGuard
|
||||
)
|
||||
for _, arg := range optionalClaimArgs {
|
||||
switch value := arg.(type) {
|
||||
@@ -6819,40 +6859,48 @@ func (s *Service) claimSessionRunningForPrompt(
|
||||
expectedIdentity = value
|
||||
case *resumeAttempt:
|
||||
startupAttempt = value
|
||||
case *lockedCancelInFlightGuard:
|
||||
admissionGuard = value
|
||||
}
|
||||
}
|
||||
lock, release := s.acquireCancelInFlightGuard(sessionID)
|
||||
defer release()
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
if admissionGuard == nil {
|
||||
admissionGuard = s.lockCancelInFlightGuard(sessionID)
|
||||
}
|
||||
keepDispatchGuard := false
|
||||
defer func() {
|
||||
if !keepDispatchGuard {
|
||||
admissionGuard.release()
|
||||
}
|
||||
}()
|
||||
lock := admissionGuard.mutex
|
||||
// A reset-owned cancellation must not make prompt admission wait for the
|
||||
// reset that already forbids it. Keep the second check below for a reset
|
||||
// that starts while this prompt is waiting on an unrelated cancellation.
|
||||
if s.isSessionResetInProgress(sessionID) {
|
||||
return nil, "", "", false, nil, ErrSessionResetInProgress
|
||||
return nil, "", "", false, nil, nil, ErrSessionResetInProgress
|
||||
}
|
||||
if err := s.waitForCancellationWithGuard(ctx, sessionID, lock.Unlock, lock.Lock); err != nil {
|
||||
return nil, "", "", false, nil, err
|
||||
return nil, "", "", false, nil, nil, err
|
||||
}
|
||||
if s.isSessionResetInProgress(sessionID) {
|
||||
return nil, "", "", false, nil, ErrSessionResetInProgress
|
||||
return nil, "", "", false, nil, nil, ErrSessionResetInProgress
|
||||
}
|
||||
if err := s.validateResumeAttempt(startupAttempt); err != nil {
|
||||
return nil, "", "", false, nil, err
|
||||
return nil, "", "", false, nil, nil, err
|
||||
}
|
||||
if s.isRouteActionInFlight(sessionID) {
|
||||
return nil, "", "", false, nil, fmt.Errorf("%w, route action is in progress", ErrAgentPromptInProgress)
|
||||
return nil, "", "", false, nil, nil, fmt.Errorf("%w, route action is in progress", ErrAgentPromptInProgress)
|
||||
}
|
||||
if expectedCurrentTurnID != "" {
|
||||
if s.turnService == nil {
|
||||
return nil, "", "", false, nil, errors.New("cannot verify expected prompt turn without turn service")
|
||||
return nil, "", "", false, nil, nil, errors.New("cannot verify expected prompt turn without turn service")
|
||||
}
|
||||
activeTurn, err := s.turnService.GetActiveTurn(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, "", "", false, nil, fmt.Errorf("verify expected prompt turn: %w", err)
|
||||
return nil, "", "", false, nil, nil, fmt.Errorf("verify expected prompt turn: %w", err)
|
||||
}
|
||||
if activeTurn == nil || activeTurn.ID != expectedCurrentTurnID {
|
||||
return nil, "", "", false, nil, fmt.Errorf(
|
||||
return nil, "", "", false, nil, nil, fmt.Errorf(
|
||||
"clarification turn %s is no longer current",
|
||||
expectedCurrentTurnID,
|
||||
)
|
||||
@@ -6860,14 +6908,14 @@ func (s *Service) claimSessionRunningForPrompt(
|
||||
}
|
||||
|
||||
if claimEntryID != "" && !s.isCurrentQueuedDispatch(sessionID, claimEntryID) {
|
||||
return nil, "", "", false, nil, errQueuedDispatchSuperseded
|
||||
return nil, "", "", false, nil, nil, errQueuedDispatchSuperseded
|
||||
}
|
||||
freshSession, sessErr := s.repo.GetTaskSession(ctx, sessionID)
|
||||
if sessErr != nil {
|
||||
return nil, "", "", false, nil, fmt.Errorf("reload session before claiming queued dispatch: %w", sessErr)
|
||||
return nil, "", "", false, nil, nil, fmt.Errorf("reload session before claiming queued dispatch: %w", sessErr)
|
||||
}
|
||||
if freshSession == nil {
|
||||
return nil, "", "", false, nil, errQueuedDispatchSuperseded
|
||||
return nil, "", "", false, nil, nil, errQueuedDispatchSuperseded
|
||||
}
|
||||
reservation := s.queuedDispatchReservationForEntry(sessionID, claimEntryID)
|
||||
if !reservation.matchesSessionIdentity(
|
||||
@@ -6875,31 +6923,31 @@ func (s *Service) claimSessionRunningForPrompt(
|
||||
freshSession.ID,
|
||||
freshSession.QueueIncarnationID,
|
||||
) {
|
||||
return nil, "", "", false, nil, messagequeue.ErrSessionIdentityMismatch
|
||||
return nil, "", "", false, nil, nil, messagequeue.ErrSessionIdentityMismatch
|
||||
}
|
||||
if expectedIdentity != nil &&
|
||||
(freshSession.TaskID != expectedIdentity.TaskID ||
|
||||
freshSession.ID != expectedIdentity.SessionID ||
|
||||
freshSession.QueueIncarnationID != expectedIdentity.SessionIncarnationID) {
|
||||
return nil, "", "", false, nil, messagequeue.ErrSessionIdentityMismatch
|
||||
return nil, "", "", false, nil, nil, messagequeue.ErrSessionIdentityMismatch
|
||||
}
|
||||
if requireNonterminalSession && isTerminalSessionState(freshSession.State) {
|
||||
return nil, "", "", false, nil, newWorkflowAutoStartSessionTerminalizedError(freshSession)
|
||||
return nil, "", "", false, nil, nil, newWorkflowAutoStartSessionTerminalizedError(freshSession)
|
||||
}
|
||||
if promptErr := s.recheckPromptableWithForegroundClaim(
|
||||
taskID, sessionID, freshSession.State, foregroundClaim,
|
||||
); promptErr != nil {
|
||||
return nil, "", "", false, nil, promptErr
|
||||
return nil, "", "", false, nil, nil, promptErr
|
||||
}
|
||||
previousState := freshSession.State
|
||||
switch {
|
||||
case reservation != nil && reservation.identity.SessionIncarnationID != "":
|
||||
if err := s.setQueuedSessionRunningForIdentity(ctx, reservation.identity, freshSession); err != nil {
|
||||
return nil, "", "", false, nil, err
|
||||
return nil, "", "", false, nil, nil, err
|
||||
}
|
||||
case expectedIdentity != nil:
|
||||
if err := s.setQueuedSessionRunningForIdentity(ctx, *expectedIdentity, freshSession); err != nil {
|
||||
return nil, "", "", false, nil, err
|
||||
return nil, "", "", false, nil, nil, err
|
||||
}
|
||||
default:
|
||||
s.setSessionRunning(ctx, taskID, sessionID, freshSession)
|
||||
@@ -6907,10 +6955,10 @@ func (s *Service) claimSessionRunningForPrompt(
|
||||
// The guarded state transition refreshes freshSession in place, so a
|
||||
// competing terminal transition remains visible before turn creation.
|
||||
if requireNonterminalSession && isTerminalSessionState(freshSession.State) {
|
||||
return nil, "", "", false, nil, newWorkflowAutoStartSessionTerminalizedError(freshSession)
|
||||
return nil, "", "", false, nil, nil, newWorkflowAutoStartSessionTerminalizedError(freshSession)
|
||||
}
|
||||
if isTerminalSessionState(freshSession.State) && freshSession.State != models.TaskSessionStateCompleted {
|
||||
return nil, "", "", false, nil, &executor.SessionStateSupersededError{
|
||||
return nil, "", "", false, nil, nil, &executor.SessionStateSupersededError{
|
||||
SessionID: freshSession.ID,
|
||||
State: freshSession.State,
|
||||
}
|
||||
@@ -6927,7 +6975,7 @@ func (s *Service) claimSessionRunningForPrompt(
|
||||
rollback.sessionIdentity = *expectedIdentity
|
||||
}
|
||||
s.rollbackPromptClaimAfterAdmissionFailure(ctx, taskID, sessionID, rollback)
|
||||
return nil, "", "", false, nil, fmt.Errorf("persist prompt turn: %w", err)
|
||||
return nil, "", "", false, nil, nil, fmt.Errorf("persist prompt turn: %w", err)
|
||||
}
|
||||
if reservedTurn != nil && s.turnService != nil {
|
||||
if err := s.turnService.MarkReservedTurnDispatchAttempted(ctx, reservedTurn); err != nil {
|
||||
@@ -6944,7 +6992,7 @@ func (s *Service) claimSessionRunningForPrompt(
|
||||
rollback.sessionIdentity = *expectedIdentity
|
||||
}
|
||||
s.rollbackPromptClaimAfterAdmissionFailure(ctx, taskID, sessionID, rollback)
|
||||
return nil, "", "", false, nil, fmt.Errorf("persist prompt dispatch attempt: %w", err)
|
||||
return nil, "", "", false, nil, nil, fmt.Errorf("persist prompt dispatch attempt: %w", err)
|
||||
}
|
||||
}
|
||||
reservation = s.queuedDispatchReservationForEntry(sessionID, claimEntryID)
|
||||
@@ -6961,20 +7009,28 @@ func (s *Service) claimSessionRunningForPrompt(
|
||||
rollback.sessionIdentity = *expectedIdentity
|
||||
}
|
||||
if err := s.acknowledgePromptClaim(ctx, taskID, sessionID, afterClaim, rollback); err != nil {
|
||||
return nil, "", "", false, nil, err
|
||||
return nil, "", "", false, nil, nil, err
|
||||
}
|
||||
// A Send Now reservation becomes replaceable only after the guarded session
|
||||
// A queued reservation becomes replaceable only after the guarded session
|
||||
// claim and its identity-bound visible side effects have succeeded.
|
||||
if reservation != nil && reservation.liveEligible.Load() {
|
||||
if reservation != nil {
|
||||
s.markAcceptedDispatchLiveLocked(sessionID, reservation)
|
||||
}
|
||||
// Remove only the pre-acceptance marker here. The accepted ownership record
|
||||
// remains until the turn settles, so Send Now cannot cancel or duplicate
|
||||
// this successor while the executor call is still in progress.
|
||||
// Remove only the pre-acceptance marker here. Transfer the guard to
|
||||
// promptTask for queued dispatches so cancellation cannot supersede this
|
||||
// reservation between live promotion and provider acceptance.
|
||||
var dispatchGuardRelease func()
|
||||
if claimEntryID != "" {
|
||||
var releaseOnce sync.Once
|
||||
dispatchGuardRelease = func() {
|
||||
releaseOnce.Do(admissionGuard.release)
|
||||
}
|
||||
keepDispatchGuard = true
|
||||
}
|
||||
if claimEntryID != "" {
|
||||
s.releaseQueuedDispatchPendingIfCurrent(sessionID, reservation)
|
||||
}
|
||||
return freshSession, previousState, turnID, createdTurn, reservedTurn, nil
|
||||
return freshSession, previousState, turnID, createdTurn, reservedTurn, dispatchGuardRelease, nil
|
||||
}
|
||||
|
||||
func (s *Service) validateQueuedPromptDispatch(
|
||||
|
||||
@@ -3434,7 +3434,7 @@ func TestClarificationRecovery_ReleasesGuardAfterRetryDispatch(t *testing.T) {
|
||||
promptAccepted := make(chan promptCall, 2)
|
||||
turnComplete := make(chan struct{})
|
||||
var retryAcceptedOnce sync.Once
|
||||
agentMgr := &mockAgentManager{
|
||||
baseAgentMgr := &mockAgentManager{
|
||||
isAgentRunning: true,
|
||||
repoForExecutionLookup: repo,
|
||||
promptAgentFunc: func(_ context.Context, executionID string, prompt string, _ []v1.MessageAttachment, dispatchOnly bool) (*executor.PromptResult, error) {
|
||||
@@ -3448,6 +3448,15 @@ func TestClarificationRecovery_ReleasesGuardAfterRetryDispatch(t *testing.T) {
|
||||
return &executor.PromptResult{}, nil
|
||||
},
|
||||
}
|
||||
// Keep the provider call blocked after it has entered the turn, but fire
|
||||
// the dispatch callback at that acceptance boundary. The base mock invokes
|
||||
// its callback only after promptAgentFunc returns, which would hold the
|
||||
// admission guard until turnComplete and make this test exercise the mock's
|
||||
// ordering rather than the provider contract.
|
||||
agentMgr := &callbackAfterPromptEntryAgentManager{
|
||||
mockAgentManager: baseAgentMgr,
|
||||
promptEntries: []<-chan struct{}{retryAccepted},
|
||||
}
|
||||
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
|
||||
svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{})
|
||||
|
||||
|
||||
@@ -2941,6 +2941,18 @@ export class ApiClient {
|
||||
});
|
||||
}
|
||||
|
||||
async setQueueAutoMerge(
|
||||
identity: QueueSessionIdentityInput,
|
||||
enabled: boolean,
|
||||
): Promise<{ session_id: string; auto_merge_enabled: boolean }> {
|
||||
return this.wsRequest("message.queue.auto_merge.set", {
|
||||
task_id: identity.taskId,
|
||||
session_id: identity.sessionId,
|
||||
session_incarnation_id: identity.sessionIncarnationId,
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
// --- Integration config seeding (real API, not mock) ---
|
||||
|
||||
async setJiraConfig(payload: {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import type { SeedData } from "../../fixtures/test-base";
|
||||
import type { ApiClient } from "../../helpers/api-client";
|
||||
import { waitForSessionState } from "../../helpers/session";
|
||||
import type { WsWatcher } from "../../helpers/causal-waits";
|
||||
import { waitForAgentMessage, waitForSessionState } from "../../helpers/session";
|
||||
import { waitForComposerQueueMode } from "../../helpers/type-while-busy";
|
||||
import { SessionPage } from "../../pages/session-page";
|
||||
import { SidebarFilterPopoverPage } from "../../pages/sidebar-filter-popover";
|
||||
|
||||
@@ -107,3 +109,142 @@ export async function expectSendNowWorkflowRunning(
|
||||
await expect.poll(async () => (await api.getTask(task.id)).state).toBe("REVIEW");
|
||||
await expect(session.cancelAgentButton()).toBeHidden();
|
||||
}
|
||||
|
||||
function activeQueuedMessage(
|
||||
marker: string,
|
||||
holdMs = 15_000,
|
||||
completionMarker = `${marker} finished`,
|
||||
): string {
|
||||
return [
|
||||
`e2e:message("${marker}")`,
|
||||
'e2e:tool_use("Check", {})',
|
||||
'e2e:tool_result("checked")',
|
||||
`e2e:delay(${holdMs})`,
|
||||
`e2e:message("${completionMarker}")`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.1
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.2
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.9
|
||||
// @covers AC-UI-MESSAGE-QUEUE-SEND-NOW-001.11
|
||||
export async function expectSendNowInterruptsRunningFIFOTurn(
|
||||
page: Page,
|
||||
api: ApiClient,
|
||||
seed: SeedData,
|
||||
mobile: boolean,
|
||||
gateway: WsWatcher,
|
||||
): Promise<void> {
|
||||
const task = await api.createTaskWithAgent(
|
||||
seed.workspaceId,
|
||||
mobile ? "Mobile FIFO Send Now" : "Desktop FIFO Send Now",
|
||||
seed.agentProfileId,
|
||||
{
|
||||
description: "/e2e:simple-message",
|
||||
workflow_id: seed.workflowId,
|
||||
workflow_step_id: seed.startStepId,
|
||||
repository_ids: [seed.repositoryId],
|
||||
},
|
||||
);
|
||||
if (!task.session_id) throw new Error("Task did not return a session ID");
|
||||
const sessionId = task.session_id;
|
||||
const identity = await api.getQueueSessionIdentity(task.id, sessionId);
|
||||
await api.setQueueAutoMerge(identity, false);
|
||||
await api.setQueueAutoRun(identity, true);
|
||||
|
||||
await page.goto(`/t/${task.id}`);
|
||||
const session = new SessionPage(page);
|
||||
await session.waitForLoad();
|
||||
await session.waitForChatIdle({ timeout: 30_000 });
|
||||
await waitForSessionState(api, {
|
||||
taskId: task.id,
|
||||
sessionId,
|
||||
expectedState: "WAITING_FOR_INPUT",
|
||||
message: "FIFO Send Now fixture should start idle",
|
||||
});
|
||||
|
||||
// The initial turn only opens a busy window. A is delivered later by the
|
||||
// ordinary Auto-run path, which is the behavior under test.
|
||||
if (mobile) {
|
||||
await session.sendMessageViaButton("/slow 3s");
|
||||
} else {
|
||||
await session.sendMessage("/slow 3s");
|
||||
}
|
||||
await expect(session.agentStatus()).toBeVisible({ timeout: 15_000 });
|
||||
await waitForComposerQueueMode(page);
|
||||
const markerA = "fifo A response";
|
||||
const markerB = "fifo B response";
|
||||
const markerC = "fifo C response";
|
||||
const completionA = "fifo A finished";
|
||||
const completionB = "fifo B finished";
|
||||
const completionC = "fifo C finished";
|
||||
await api.queueMessage(identity, activeQueuedMessage(markerA, 15_000, completionA));
|
||||
await waitForAgentMessage(api, sessionId, markerA, 60_000);
|
||||
await waitForSessionState(api, {
|
||||
taskId: task.id,
|
||||
sessionId,
|
||||
expectedState: "RUNNING",
|
||||
message: "FIFO A should own the running turn before B is queued",
|
||||
});
|
||||
const workflowStepBefore = (await api.getTask(task.id)).workflow_step_id;
|
||||
|
||||
await api.queueMessage(identity, activeQueuedMessage(markerB, 10_000, completionB));
|
||||
await api.queueMessage(identity, activeQueuedMessage(markerC, 250, completionC));
|
||||
|
||||
const chat = session.activeChat();
|
||||
const chip = chat.getByTestId("queue-chip");
|
||||
if (mobile) await chip.tap();
|
||||
else await chip.click();
|
||||
const panel = chat.getByTestId("queued-ghost-list");
|
||||
await expect(panel).toBeVisible();
|
||||
await expect(panel.getByTestId("queue-entry-text")).toHaveCount(2);
|
||||
const target = panel.getByTestId("queue-entry").filter({ hasText: markerB });
|
||||
await expect(target).toBeVisible();
|
||||
if (!mobile) await target.hover();
|
||||
const sendNow = target.getByTestId("queue-entry-send-now");
|
||||
await expect(sendNow).toBeVisible();
|
||||
await expect(sendNow).toBeEnabled();
|
||||
if (mobile) {
|
||||
const box = await sendNow.boundingBox();
|
||||
expect(box).not.toBeNull();
|
||||
expect(box!.width).toBeGreaterThanOrEqual(44);
|
||||
expect(box!.height).toBeGreaterThanOrEqual(44);
|
||||
}
|
||||
|
||||
const sendNowResponse = gateway.waitForResponse("message.queue.send_now");
|
||||
if (mobile) await sendNow.tap();
|
||||
else await sendNow.click();
|
||||
await sendNowResponse;
|
||||
|
||||
await expect(panel.getByTestId("queue-entry-text")).toHaveCount(1);
|
||||
await expect(panel.getByTestId("queue-entry-text")).toContainText(markerC);
|
||||
await expect(panel.getByTestId("queue-auto-run")).toHaveAttribute("data-state", "checked");
|
||||
await expect(chat.getByTestId("user-message-bubble").filter({ hasText: markerB })).toHaveCount(1);
|
||||
await waitForAgentMessage(api, sessionId, markerB, 30_000);
|
||||
await waitForSessionState(api, {
|
||||
taskId: task.id,
|
||||
sessionId,
|
||||
expectedState: "RUNNING",
|
||||
message: "Send Now replacement B should remain active while C is pending",
|
||||
});
|
||||
expect((await api.getTask(task.id)).workflow_step_id).toBe(workflowStepBefore);
|
||||
await expect(panel.getByTestId("queue-entry-text")).toHaveCount(1);
|
||||
await expect(panel.getByTestId("queue-entry-text")).toContainText(markerC);
|
||||
|
||||
await waitForAgentMessage(api, sessionId, markerC, 60_000);
|
||||
await waitForSessionState(api, {
|
||||
taskId: task.id,
|
||||
sessionId,
|
||||
expectedState: "WAITING_FOR_INPUT",
|
||||
message: "FIFO C should settle after replacement B",
|
||||
});
|
||||
await expect.poll(async () => (await api.getQueueStatus(identity)).count).toBe(0);
|
||||
const agentBodies = chat.locator("[data-agent-message-body][data-message-id]");
|
||||
await expect(agentBodies.filter({ hasText: markerA })).toHaveCount(1);
|
||||
await expect(agentBodies.filter({ hasText: markerB })).toHaveCount(1);
|
||||
await expect(agentBodies.filter({ hasText: markerC })).toHaveCount(1);
|
||||
await expect(agentBodies.filter({ hasText: completionA })).toHaveCount(0);
|
||||
await expect(agentBodies.filter({ hasText: completionB })).toHaveCount(1);
|
||||
await expect(agentBodies.filter({ hasText: completionC })).toHaveCount(1);
|
||||
await expect(chat).not.toContainText("Turn cancelled by user");
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ import { seedRunningGeneratingSession } from "../../helpers/generating-session";
|
||||
import { waitForAgentMessage, waitForSessionDone } from "../../helpers/session";
|
||||
import { expectFullQueueScrolls, seedFullQueueTask } from "./message-queue-scroll-helpers";
|
||||
import { waitForQuickChatComposerReady } from "./quick-chat-helpers";
|
||||
import { expectSendNowWorkflowRunning } from "./message-queue-workflow-helpers";
|
||||
import {
|
||||
expectSendNowInterruptsRunningFIFOTurn,
|
||||
expectSendNowWorkflowRunning,
|
||||
} from "./message-queue-workflow-helpers";
|
||||
import {
|
||||
registerSeparateQueueRows,
|
||||
requestMessageQueueSettings,
|
||||
@@ -21,6 +24,12 @@ test("Send Now keeps a workflow transition running", async ({ testPage, apiClien
|
||||
await expectSendNowWorkflowRunning(testPage, apiClient, seedData, false);
|
||||
});
|
||||
|
||||
test("Send Now interrupts a running FIFO turn", async ({ testPage, apiClient, seedData }) => {
|
||||
test.setTimeout(150_000);
|
||||
const gateway = watchWs(testPage);
|
||||
await expectSendNowInterruptsRunningFIFOTurn(testPage, apiClient, seedData, false, gateway);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Quick Chat queue tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -9,7 +9,11 @@ import { expectFullQueueScrolls, seedFullQueueTask } from "./message-queue-scrol
|
||||
import { registerSeparateQueueRows } from "../../helpers/message-queue-settings";
|
||||
import { assertNoDocumentHorizontalOverflow } from "../../helpers/layout-assertions";
|
||||
import { waitForActiveSessionForegroundActivity } from "../../helpers/session-store";
|
||||
import { expectSendNowWorkflowRunning } from "./message-queue-workflow-helpers";
|
||||
import { watchWs } from "../../helpers/causal-waits";
|
||||
import {
|
||||
expectSendNowInterruptsRunningFIFOTurn,
|
||||
expectSendNowWorkflowRunning,
|
||||
} from "./message-queue-workflow-helpers";
|
||||
|
||||
registerSeparateQueueRows(test);
|
||||
|
||||
@@ -21,6 +25,17 @@ test("mobile Send Now keeps a workflow transition running", async ({
|
||||
await expectSendNowWorkflowRunning(testPage, apiClient, seedData, true);
|
||||
});
|
||||
|
||||
test("mobile Send Now interrupts a running FIFO turn", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
const gateway = watchWs(testPage);
|
||||
await expectSendNowInterruptsRunningFIFOTurn(testPage, apiClient, seedData, true, gateway);
|
||||
await assertNoDocumentHorizontalOverflow(testPage);
|
||||
});
|
||||
|
||||
async function expectTouchTarget(locator: Locator): Promise<void> {
|
||||
await expect(locator).toBeVisible();
|
||||
const box = await locator.boundingBox();
|
||||
|
||||
@@ -510,10 +510,12 @@ describe("sendQueuedNow", () => {
|
||||
});
|
||||
|
||||
it("maps send-now conflict codes to a typed error", async () => {
|
||||
const request = vi.fn().mockRejectedValue({
|
||||
code: "send_now_conflict",
|
||||
message: "Another cancellation is in progress",
|
||||
});
|
||||
const conflict = new WebSocketRequestError(
|
||||
"Another cancellation is in progress",
|
||||
"send_now_conflict",
|
||||
{ session_id: SESSION_ID },
|
||||
);
|
||||
const request = vi.fn().mockRejectedValue(conflict);
|
||||
getWebSocketClientMock.mockReturnValue({ request });
|
||||
|
||||
await expect(
|
||||
|
||||
@@ -6,6 +6,13 @@ status: implemented
|
||||
|
||||
# Implementation Plan: Send Queued Messages Now
|
||||
|
||||
## Follow-up contract change
|
||||
|
||||
The [live FIFO interruption package](../queue-send-now-live-fifo/plan.md)
|
||||
amends the accepted-handoff exclusion in the current requirement. This plan
|
||||
and its completed work orders remain historical implementation evidence;
|
||||
the follow-up owns new race tests, desktop/phone scenarios, and final results.
|
||||
|
||||
## Overview
|
||||
|
||||
Add one explicit WebSocket operation that asks the orchestrator to replace the
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
---
|
||||
created: 2026-09-15
|
||||
status: complete
|
||||
requirements:
|
||||
- REQ-UI-MESSAGE-QUEUE-SEND-NOW-001
|
||||
system_design:
|
||||
- ../../specs/ui/system-design/message-queue-send-now.md
|
||||
legacy_specs: []
|
||||
---
|
||||
|
||||
# Implementation Plan: Interrupt running FIFO turns with Send Now
|
||||
|
||||
## Overview
|
||||
|
||||
Allow a new Send Now request to replace an ordinary FIFO-delivered turn after
|
||||
its prompt handoff completes. First implement the shared ownership transition
|
||||
with deterministic backend regressions. Then verify the desktop/phone path,
|
||||
real transport errors, and public guidance. Implementation is complete.
|
||||
|
||||
The user accepted this contract change on 2026-09-15. It amends
|
||||
AC-UI-MESSAGE-QUEUE-SEND-NOW-001.8 and adds .9-.11. The existing
|
||||
[replacement-turn ADR](../../decisions/2026-08-05-queue-send-now-replaces-turn.md)
|
||||
remains authoritative for cancellation and workflow behavior.
|
||||
|
||||
## Evidence and reproduction
|
||||
|
||||
The reporter's Darwin build, commit `18d38c11a`, launched Cursor ACP. An earlier
|
||||
queued input was dispatched at 10:32:15 +0100. A second input was queued at
|
||||
10:35:06. Five Send Now attempts from 10:35:11 through 10:35:38 returned
|
||||
`Another cancellation or Send Now operation is in progress`. Cursor continued
|
||||
producing output. No dynamic-profile selection failure was observed.
|
||||
|
||||
The source retained ordinary FIFO reservations in `queuedDispatchAccepted`
|
||||
until settlement because the live transition was gated to Send Now. The
|
||||
accepted phase triggered `ErrSendNowConflict`. This implemented the former
|
||||
whole-turn exclusion in criterion .8; the repair now applies the same guarded
|
||||
accepted-to-live transition to ordinary FIFO.
|
||||
|
||||
Existing `TestSendQueuedNowConflictsAfterFIFOHandoffAccepted` passes and proves
|
||||
the provider-independent rejection through a real service FIFO drain. It does
|
||||
not replay the reporter's entire Cursor process. The bundle does not identify
|
||||
which conflict predicate fired, so incident attribution is strongly supported
|
||||
rather than a directly logged guard branch.
|
||||
|
||||
## Scope
|
||||
|
||||
### In scope
|
||||
|
||||
- Shared accepted-to-live transition for FIFO and Send Now reservations.
|
||||
- Handoff, cancellation, successor, and late-completion regression coverage.
|
||||
- Fixed and persisted dynamic-to-Cursor session attribution in service tests.
|
||||
- Desktop and phone reproduction through the existing queue panel.
|
||||
- Real `WebSocketRequestError` regression for Send Now conflict feedback.
|
||||
- Clarify queue steering in the existing public how-to sections.
|
||||
|
||||
### Out of scope
|
||||
|
||||
- Provider adapters, dynamic routing policy, schema or protocol changes.
|
||||
- Queue UI redesign, new copy, bulk header controls, or retry automation.
|
||||
- Changes to explicit Cancel, queue editing, merging, or persistence policy.
|
||||
|
||||
## Technical approach
|
||||
|
||||
Follow the [paired design](../../specs/ui/system-design/message-queue-send-now.md).
|
||||
Keep the accepted ownership record while promoting its phase at the existing
|
||||
successful guarded prompt-claim boundary. Remove the Send Now-only eligibility
|
||||
condition. Do not clear ownership to make the conflict disappear.
|
||||
|
||||
Rewrite the old whole-turn conflict test as two distinct cases: conflict before
|
||||
handoff completion and successful interruption after claim ownership. Preserve
|
||||
existing pending-FIFO supersession and live Send Now successor tests.
|
||||
|
||||
Current `queue-api.ts` already handles `WebSocketRequestError`. Verify this with
|
||||
a Send Now-specific test; do not backport the reporter's old client code or
|
||||
add redundant production mapping.
|
||||
|
||||
## ASCII UI preview
|
||||
|
||||
UI-01: Existing expanded queue while FIFO input A is running.
|
||||
Shared composition; this package changes the action result, not layout.
|
||||
|
||||
```text
|
||||
[Agent is working on A]
|
||||
Queue [Auto-run: ON] [Auto-merge: OFF] [Clear all]
|
||||
B: urgent correction [Send Now] [row actions]
|
||||
C: later work [Send Now] [row actions]
|
||||
[Composer]
|
||||
|
||||
After Send Now on B:
|
||||
[Cancel pending] -> [Agent is working on B]
|
||||
Queue [Auto-run: ON] [Auto-merge: OFF] [Clear all]
|
||||
C: later work [Send Now] [row actions]
|
||||
[Composer]
|
||||
```
|
||||
|
||||
Desktop exposes row actions on hover/focus. Phone exposes touch actions
|
||||
without hover, with at least 44px targets. Reuse the shipped
|
||||
`mobile-message-queue-management.spec.ts` inline panel: one queue scroll owner,
|
||||
visible composer, no horizontal overflow. A genuine handoff conflict shows the
|
||||
existing localized conflict toast, preserves pending rows, and permits retry
|
||||
after completion. Labels above are illustrative; existing translations and
|
||||
control order remain authoritative. Maps to .1, .2, .9, .11.
|
||||
|
||||
## Tests
|
||||
|
||||
- .2/.7/.9: `TestSendQueuedNowCancelsLiveFIFOTurn`, table-driven for entry/all
|
||||
scope and fixed/dynamic attribution, in `queue_send_now_test.go`.
|
||||
- .8: `TestSendQueuedNowConflictsAfterFIFOHandoffAccepted`, a barrier before successful
|
||||
guarded claim completion, in the same file.
|
||||
- .10: `TestStreamCompletePreservesLiveFIFOSuccessorForStalePromptGeneration`
|
||||
plus the claim-to-provider-I/O half of `TestSendQueuedNowCancelsLiveFIFOTurn`
|
||||
in the same file; retain existing captured-turn, duplicate-cancel, workflow,
|
||||
and restoration cases.
|
||||
- .9/.10: `TestSendQueuedNowSerializesFIFOPredispatchAdmission` holds ordinary
|
||||
FIFO A after guarded claim completion and before provider admission, races
|
||||
Send Now B, and verifies that B waits for A's bounded admission, replaces it
|
||||
exactly once, preserves C, and survives late A completion without stale turn,
|
||||
ownership, or prompt-attempt mutation.
|
||||
- Dispatch recovery: `TestPromptTaskReleasesDispatchGuardBeforeMissingExecutionRecovery`
|
||||
drives queued identity validation to `ErrExecutionNotFound` and verifies that
|
||||
fresh-launch recovery can reacquire the per-session guard without deadlock.
|
||||
- Model switching: `TestPromptTaskKeepsQueuedDispatchGuardThroughModelSwitch`
|
||||
pauses provider model selection before prompt claim and verifies that the
|
||||
queued dispatch guard remains held across that I/O.
|
||||
- .11: real-class conflict test in `queue-api.test.ts`.
|
||||
|
||||
Task 01 records the backend RED and GREEN results in its work order. Task 02
|
||||
records the client, browser, and public-doc results after the backend change.
|
||||
|
||||
## E2E tests
|
||||
|
||||
- `message-queue.spec.ts`, chromium: ordinary FIFO starts A; wait for its
|
||||
distinct output, queue B/C, click B's Send Now, verify B once and C afterward.
|
||||
- `mobile-message-queue-management.spec.ts`, mobile-chrome: the same scenario
|
||||
using tap, with visible touch controls and no horizontal overflow.
|
||||
- Use `watchWs` before navigation/actions and API/agent-output evidence for
|
||||
lifecycle boundaries. Do not use elapsed sleeps to infer handoff completion.
|
||||
- Mock provider scripts make the scenario deterministic. Real Cursor credentials
|
||||
are not required; service tests cover dynamic concrete-execution identity.
|
||||
|
||||
## Companion packages
|
||||
|
||||
The implemented [original package](../message-queue-send-now/plan.md) remains
|
||||
historical delivery evidence. Its whole-turn exclusion is replaced by this
|
||||
package and amended criterion .8. Existing queue-run and automation behavior is
|
||||
unchanged. Do not relabel historical checks as proof of the new contract.
|
||||
|
||||
## Work orders
|
||||
|
||||
- [x] [Task 01: Make live FIFO turns interruptible](task-01-live-fifo.md)
|
||||
- [x] [Task 02: Verify queue steering across clients](task-02-client-verification.md)
|
||||
|
||||
## Verification results
|
||||
|
||||
Diagnosis completed before implementation:
|
||||
|
||||
```bash
|
||||
(cd apps/backend && go test -tags fts5 ./internal/orchestrator -run '^TestSendQueuedNowConflictsAfterFIFOHandoffAccepted$' -count=1)
|
||||
```
|
||||
|
||||
PASS. This asserts the old rejection behavior, not the proposed fix.
|
||||
Package validation passed:
|
||||
|
||||
- `python3 scripts/list-docs.py validate`: 272 decisions and 935 specifications.
|
||||
- `python3 scripts/lint-spec-files.test.py`: 36 tests passed.
|
||||
- `python3 scripts/lint-spec-files.py --all`: passed.
|
||||
- Package Markdown links and acceptance IDs resolve to existing artifacts.
|
||||
- `git diff --check`: passed.
|
||||
|
||||
Task 01 implementation results:
|
||||
|
||||
- `TestSendQueuedNowCancelsLiveFIFOTurn`: PASS for entry/all scope, fixed and
|
||||
dynamic-to-Cursor execution attribution.
|
||||
- `TestSendQueuedNowConflictsAfterFIFOHandoffAccepted`: PASS with a prompt-claim
|
||||
barrier; the accepted handoff still fails closed.
|
||||
- `TestStreamCompletePreservesLiveFIFOSuccessorForStalePromptGeneration`: PASS;
|
||||
a stale predecessor cannot settle the live FIFO successor.
|
||||
- `TestSendQueuedNowSerializesFIFOPredispatchAdmission`: PASS; the ordinary
|
||||
FIFO cancellation guard remains held from live promotion through provider
|
||||
acceptance, then B replaces A exactly once, C remains queued, and a late A
|
||||
completion cannot mutate B's turn, ownership, or prompt-attempt record.
|
||||
- `TestPromptTaskReleasesDispatchGuardBeforeMissingExecutionRecovery`: PASS;
|
||||
queued identity validation can enter missing-execution recovery only after
|
||||
releasing the transferred dispatch guard.
|
||||
- `TestPromptTaskKeepsQueuedDispatchGuardThroughModelSwitch`: PASS; queued
|
||||
provider model selection remains inside the dispatch admission guard.
|
||||
- `go test -tags fts5 -race ./internal/orchestrator -run
|
||||
'Test.*(SendNow|SendQueuedNow|QueuedDispatch|FIFOHandoff)' -count=1`: PASS.
|
||||
- `git diff --check`: PASS.
|
||||
|
||||
Task 02 implementation results:
|
||||
|
||||
- `pnpm exec vitest run lib/api/domains/queue-api.test.ts`: 30 tests passed.
|
||||
- Web typecheck, Prettier, and targeted ESLint passed.
|
||||
- Chromium Send Now subset: 3 tests passed, including the FIFO interruption
|
||||
scenario.
|
||||
- Mobile Chrome Send Now subset: 3 tests passed, including the FIFO
|
||||
interruption scenario and overflow check.
|
||||
- Public-doc tests: 62 passed; public-doc validation covered 46 pages.
|
||||
- Specification catalog validation covered 272 decisions and 935
|
||||
specifications; specification lint passed.
|
||||
- `git diff --check`: passed.
|
||||
|
||||
## Risks
|
||||
|
||||
- Removing accepted ownership rather than changing phase can admit duplicate
|
||||
drains or let a late completion clear the replacement.
|
||||
- The claim-to-provider-I/O window must remain serialized against cancellation.
|
||||
- Existing tests intentionally assert the old contract and need a real handoff
|
||||
barrier; simply deleting their assertions would remove race protection.
|
||||
- The reporter ran an older build. The generic-toast mapping is already repaired
|
||||
on this branch and needs a regression test, not another production fix.
|
||||
@@ -0,0 +1,172 @@
|
||||
---
|
||||
id: "01-live-fifo"
|
||||
title: "Make live FIFO turns interruptible"
|
||||
status: complete
|
||||
wave: 1
|
||||
depends_on: []
|
||||
plan: "plan.md"
|
||||
requirements:
|
||||
- REQ-UI-MESSAGE-QUEUE-SEND-NOW-001
|
||||
acceptance_criteria:
|
||||
- AC-UI-MESSAGE-QUEUE-SEND-NOW-001.2
|
||||
- AC-UI-MESSAGE-QUEUE-SEND-NOW-001.7
|
||||
- AC-UI-MESSAGE-QUEUE-SEND-NOW-001.8
|
||||
- AC-UI-MESSAGE-QUEUE-SEND-NOW-001.9
|
||||
- AC-UI-MESSAGE-QUEUE-SEND-NOW-001.10
|
||||
system_design:
|
||||
- ../../specs/ui/system-design/message-queue-send-now.md
|
||||
---
|
||||
|
||||
# Task 01: Make live FIFO turns interruptible
|
||||
|
||||
## Summary
|
||||
|
||||
Promote ordinary FIFO reservations at the successful guarded prompt-claim
|
||||
boundary already used by Send Now. Keep settlement ownership and all captured
|
||||
turn, session incarnation, and cancellation protections.
|
||||
|
||||
## In scope
|
||||
|
||||
- In `queue_send_now_test.go`, add `TestSendQueuedNowCancelsLiveFIFOTurn` before
|
||||
production changes. Use real queue drain and service dispatch with a blocking
|
||||
mock executor; synchronize on prompt entry. Assert Send Now succeeds, cancels
|
||||
A, sends selected B once, and leaves C queued while B is held open.
|
||||
- Cover entry/all scope, fixed profile, and a session whose logical dynamic
|
||||
profile differs from its persisted concrete Cursor profile. Seed existing
|
||||
execution attribution using repository test helpers. Assert cancellation uses
|
||||
that execution and introduces no queue-specific profile lookup or selection.
|
||||
- Preserve a real accepted-handoff conflict test by placing a barrier before
|
||||
guarded claim completion. Keep pending-FIFO supersession coverage. Do not
|
||||
reinterpret blocked long-running `PromptAgent` I/O as an incomplete handoff.
|
||||
- Add late-predecessor completion and claim-to-provider-I/O cancellation cases.
|
||||
Use channels and cleanup releases, not sleeps. Prove a superseded worker
|
||||
cannot dispatch after replacement, restore accepted A, clear B's reservation,
|
||||
or drain C while B is active.
|
||||
- Add a deterministic predispatch race regression that pauses ordinary FIFO A
|
||||
after guarded claim completion and before provider admission. Keep the
|
||||
cancellation guard through the bounded acceptance callback, then prove Send
|
||||
Now B replaces A exactly once, C remains pending, and late A completion
|
||||
cannot mutate B's turn, ownership, or prompt-attempt record.
|
||||
- Release a transferred dispatch guard before identity validation routes a
|
||||
missing execution into fresh-launch recovery, which reacquires the same
|
||||
per-session guard.
|
||||
- Keep the queued dispatch guard through model-switch provider I/O before the
|
||||
normal prompt claim takes ownership.
|
||||
- Remove the origin-specific `liveEligible` gate, field, and setter if redundant;
|
||||
promote only the exact current reservation after successful claim effects.
|
||||
Keep accepted-record cleanup, turn binding, and identity fencing intact.
|
||||
- Retain silent cancellation and workflow behavior. Update source comments
|
||||
that incorrectly describe accepted ownership as whole-turn exclusion.
|
||||
|
||||
## Out of scope
|
||||
|
||||
Provider adapters, routing policy, persistence changes, UI changes, and any
|
||||
removal of cancellation or generation checks.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. The new live-FIFO test fails with `ErrSendNowConflict` before the fix and
|
||||
passes after it for both scopes and profile cases, with exact delivery/order.
|
||||
2. Incomplete handoff and real overlapping cancellation still fail closed;
|
||||
late events and predispatch cancellation cannot affect a newer owner.
|
||||
3. Existing Send Now workflow, restoration, successor, and pending-FIFO tests
|
||||
pass. Accepted A is never returned to pending storage by interruption.
|
||||
|
||||
## Verification
|
||||
|
||||
From the repository root:
|
||||
|
||||
```bash
|
||||
(cd apps/backend && go test -tags fts5 ./internal/orchestrator -run '^TestSendQueuedNowCancelsLiveFIFOTurn$' -count=1)
|
||||
(cd apps/backend && go test -tags fts5 -race ./internal/orchestrator -run 'Test.*(SendNow|SendQueuedNow|QueuedDispatch|FIFOHandoff)' -count=1)
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Record the first command's RED result before editing production code, then its
|
||||
GREEN result. If new shared helpers require additional tests, add their exact
|
||||
suite to this work order before marking it done.
|
||||
|
||||
## Files likely touched
|
||||
|
||||
- `apps/backend/internal/orchestrator/queued_dispatch.go`
|
||||
- `apps/backend/internal/orchestrator/task_operations.go`
|
||||
- `apps/backend/internal/orchestrator/queue_send_now.go`
|
||||
- `apps/backend/internal/orchestrator/queue_send_now_test.go`
|
||||
- `apps/backend/internal/orchestrator/queue_send_now_workflow_state_test.go`
|
||||
- `apps/backend/internal/orchestrator/prompt_dispatch_identity_test.go`
|
||||
|
||||
## Dependencies
|
||||
|
||||
None.
|
||||
|
||||
## Risks
|
||||
|
||||
The most important boundary is guarded claim completion versus the return of a
|
||||
long-running provider call. Tests must distinguish both without deleting the
|
||||
accepted ownership record. Review the exact identity and cancellation guard
|
||||
held at each test barrier to avoid a test-only deadlock.
|
||||
|
||||
## Parallelism
|
||||
|
||||
`sequential`
|
||||
|
||||
## Inputs
|
||||
|
||||
- [Requirement](../../specs/ui/requirements/message-queue-send-now.md), .2/.7-.10.
|
||||
- [Design](../../specs/ui/system-design/message-queue-send-now.md), transition
|
||||
to live and interruption/recovery sections.
|
||||
- Existing `TestSendQueuedNowConflictsAfterFIFOHandoffAccepted`,
|
||||
`TestSendQueuedNowCancelsLiveReplacementTurn`, and
|
||||
`TestSendQueuedNowConflictsBeforeReplacementClaimsPrompt` patterns.
|
||||
|
||||
## Results
|
||||
|
||||
RED recorded before production changes:
|
||||
|
||||
```text
|
||||
(cd apps/backend && go test -tags fts5 ./internal/orchestrator -run '^TestSendQueuedNowCancelsLiveFIFOTurn$' -count=1)
|
||||
FAIL: both table cases returned send-now operation is already in progress.
|
||||
```
|
||||
|
||||
GREEN and focused race verification after production changes:
|
||||
|
||||
```text
|
||||
(cd apps/backend && go test -tags fts5 ./internal/orchestrator -run '^TestSendQueuedNowCancelsLiveFIFOTurn$' -count=1)
|
||||
PASS
|
||||
|
||||
(cd apps/backend && go test -tags fts5 -race ./internal/orchestrator -run 'Test.*(SendNow|SendQueuedNow|QueuedDispatch|FIFOHandoff)' -count=1)
|
||||
PASS
|
||||
|
||||
(cd apps/backend && go test -tags fts5 ./internal/orchestrator -run '^(TestPromptTaskReleasesDispatchGuardBeforeMissingExecutionRecovery|TestPromptTaskExpectedIdentityRejectsReplacementAfterClaim|TestSendQueuedNowSerializesFIFOPredispatchAdmission)$' -count=1)
|
||||
PASS
|
||||
|
||||
(cd apps/backend && go test -tags fts5 ./internal/orchestrator -run '^TestPromptTaskKeepsQueuedDispatchGuardThroughModelSwitch$' -count=1)
|
||||
PASS
|
||||
|
||||
TestStreamCompletePreservesLiveFIFOSuccessorForStalePromptGeneration
|
||||
PASS
|
||||
|
||||
TestSendQueuedNowSerializesFIFOPredispatchAdmission
|
||||
PASS
|
||||
The test asserts exactly one B with C preserved and that late A completion
|
||||
cannot change B's active turn, ownership, or prompt-attempt record.
|
||||
|
||||
git diff --check
|
||||
PASS
|
||||
```
|
||||
|
||||
The table-driven GREEN cases cover entry/all scope, fixed profile attribution,
|
||||
and a logical dynamic profile with persisted concrete Cursor execution. The
|
||||
accepted handoff remains a conflict until guarded claim completion, while the
|
||||
live FIFO reservation can be cancelled during the provider call. A stale
|
||||
predecessor completion leaves the live successor reservation intact. The
|
||||
predispatch regression covers the separate claim-to-provider-admission fence:
|
||||
ordinary FIFO A keeps the per-session cancellation guard until provider
|
||||
acceptance, so a concurrent Send Now cannot supersede A before its dispatch
|
||||
side effects are durable. It also checks that the provider receives exactly one
|
||||
B and that the replacement prompt-attempt record remains after late A return.
|
||||
The identity-recovery regression drives a queued resume through
|
||||
`ErrExecutionNotFound` during identity validation and verifies that fresh-launch
|
||||
recovery returns after the transferred dispatch guard is released.
|
||||
The model-switch regression pauses provider model selection before prompt claim
|
||||
and verifies that the queued dispatch guard remains held across that I/O.
|
||||
@@ -0,0 +1,148 @@
|
||||
---
|
||||
id: "02-client-verification"
|
||||
title: "Verify queue steering across clients"
|
||||
status: complete
|
||||
wave: 2
|
||||
depends_on:
|
||||
- "01-live-fifo"
|
||||
plan: "plan.md"
|
||||
requirements:
|
||||
- REQ-UI-MESSAGE-QUEUE-SEND-NOW-001
|
||||
acceptance_criteria:
|
||||
- AC-UI-MESSAGE-QUEUE-SEND-NOW-001.1
|
||||
- AC-UI-MESSAGE-QUEUE-SEND-NOW-001.2
|
||||
- AC-UI-MESSAGE-QUEUE-SEND-NOW-001.9
|
||||
- AC-UI-MESSAGE-QUEUE-SEND-NOW-001.11
|
||||
system_design:
|
||||
- ../../specs/ui/system-design/message-queue-send-now.md
|
||||
---
|
||||
|
||||
# Task 02: Verify queue steering across clients
|
||||
|
||||
## Summary
|
||||
|
||||
Prove the reported FIFO sequence through desktop and phone queue controls.
|
||||
Verify the existing transport error mapping and document the refined behavior.
|
||||
|
||||
## In scope
|
||||
|
||||
- Add a shared scenario in `message-queue-workflow-helpers.ts` with distinct
|
||||
markers for FIFO A, selected B, and remainder C. Disable auto-merge for the
|
||||
disposable session so the entries remain distinct.
|
||||
- Start A through ordinary Auto-run/FIFO, not through Send Now or a direct
|
||||
composer prompt. Wait for its output and authoritative running state, then
|
||||
enqueue B/C and invoke B's row Send Now. Hold B active while asserting C
|
||||
remains pending; after B finishes, assert C executes once and A does not
|
||||
restart. Assert the workflow step does not advance from silent cancellation.
|
||||
- Add desktop `Send Now interrupts a running FIFO turn` and phone
|
||||
`mobile Send Now interrupts a running FIFO turn` tests in the existing suites.
|
||||
Use click/hover on desktop and tap on phone. Scope selectors to active chat.
|
||||
Arm `watchWs` before navigation and causal response waits before mutations.
|
||||
Use existing mock scripts to keep a turn active; never infer readiness from
|
||||
elapsed sleep. Clean up disposable tasks and modified settings on failure.
|
||||
- Add a `sendQueuedNow` API regression whose rejection is an actual
|
||||
`WebSocketRequestError` with `send_now_conflict`, asserting `QueueSendNowError`.
|
||||
Current production mapping is expected to pass. Do not change production
|
||||
mapping unless this focused regression exposes a separate failure.
|
||||
- Clarify in the existing public queue how-to sections that a running
|
||||
FIFO-delivered turn can be redirected after handoff. Retain brief genuine
|
||||
conflict/retry guidance and existing explicit Cancel distinctions.
|
||||
|
||||
## Out of scope
|
||||
|
||||
New UI controls, localization keys, real provider credentials, generic transport
|
||||
refactors, and changes to global defaults or dynamic routing policy.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Desktop and phone each cancel running FIFO A, deliver B once, and retain C
|
||||
for later Auto-run without a workflow transition or page reload.
|
||||
2. Real transport conflict errors reach the existing localized conflict path.
|
||||
Existing genuine conflict behavior and queue reconciliation remain intact.
|
||||
3. Phone controls are visible without hover, touch-sized, and contained; public
|
||||
how-to guidance matches the new behavior and all required checks pass.
|
||||
|
||||
## ASCII UI preview
|
||||
|
||||
UI-01, same existing inline composition as the [plan](plan.md#ascii-ui-preview):
|
||||
|
||||
```text
|
||||
A running -> [B: Send Now] -> Cancel pending -> B running
|
||||
Queue: B, C Queue: C
|
||||
Composer remains visible Auto-run remains ON
|
||||
```
|
||||
|
||||
Desktop uses hover/focus row actions; phone exposes a visible 44px touch target.
|
||||
One queue scroll region, no new navigation or overlay. Verify the current
|
||||
mobile queue exemplar rather than adding responsive CSS. Maps to .1/.2/.9/.11.
|
||||
|
||||
## Verification
|
||||
|
||||
From the repository root; bootstrap dependencies once if this worktree has not
|
||||
been installed:
|
||||
|
||||
```bash
|
||||
(cd apps && pnpm install --frozen-lockfile)
|
||||
(cd apps/web && pnpm exec vitest run lib/api/domains/queue-api.test.ts)
|
||||
(cd apps/web && pnpm e2e:run --project chromium tests/chat/message-queue.spec.ts -- --grep 'Send Now')
|
||||
(cd apps/web && pnpm e2e:run --project mobile-chrome tests/chat/mobile-message-queue-management.spec.ts -- --grep 'Send Now')
|
||||
node --test scripts/validate-public-docs.test.mjs
|
||||
node scripts/validate-public-docs.mjs
|
||||
python3 scripts/list-docs.py validate
|
||||
python3 scripts/lint-spec-files.py --all
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Managed E2E commands rebuild artifacts. Run them sequentially with the runner's
|
||||
worker limits. Backend RED is owned by Task 01; these E2E tests verify the
|
||||
integrated change after that fix, not a claimed pre-fix browser reproduction.
|
||||
|
||||
## Files likely touched
|
||||
|
||||
- `apps/web/e2e/helpers/api-client.ts`
|
||||
- `apps/web/e2e/tests/chat/message-queue-workflow-helpers.ts`
|
||||
- `apps/web/e2e/tests/chat/message-queue.spec.ts`
|
||||
- `apps/web/e2e/tests/chat/mobile-message-queue-management.spec.ts`
|
||||
- `apps/web/lib/api/domains/queue-api.test.ts`
|
||||
- `docs/public/sessions-and-review.md`
|
||||
- `docs/public/coordination.md`
|
||||
|
||||
## Dependencies
|
||||
|
||||
Task 01.
|
||||
|
||||
## Risks
|
||||
|
||||
A directly prompted A would miss the FIFO-only defect. An API-level accepted
|
||||
request alone does not prove B ran: assert agent output and ordering. Restore
|
||||
any shared settings; prefer per-session overrides on disposable records.
|
||||
|
||||
## Parallelism
|
||||
|
||||
`sequential`
|
||||
|
||||
## Inputs
|
||||
|
||||
- [Requirement](../../specs/ui/requirements/message-queue-send-now.md), .1/.2/.9/.11.
|
||||
- [Design](../../specs/ui/system-design/message-queue-send-now.md), presentation
|
||||
and compatibility sections.
|
||||
- `expectSendNowWorkflowRunning` and the existing mobile targeted-order test.
|
||||
- `queue-api.ts` current `asWSError`, `knownQueueError`, and existing API tests.
|
||||
|
||||
## Results
|
||||
|
||||
- `pnpm exec vitest run lib/api/domains/queue-api.test.ts`: 30 tests passed,
|
||||
including an actual `WebSocketRequestError` with `send_now_conflict`.
|
||||
- Web typecheck, Prettier, and targeted ESLint passed.
|
||||
- `cd apps/web && pnpm run typecheck`
|
||||
- `cd apps/web && pnpm exec prettier --check e2e/tests/chat/message-queue-workflow-helpers.ts lib/api/domains/queue-api.test.ts`
|
||||
- `cd apps/web && pnpm exec eslint e2e/tests/chat/message-queue-workflow-helpers.ts lib/api/domains/queue-api.test.ts`
|
||||
- Chromium Send Now subset: 3 tests passed.
|
||||
- Mobile Chrome Send Now subset: 3 tests passed, including the touch-sized
|
||||
visible action and overflow assertion.
|
||||
- `node --test scripts/validate-public-docs.test.mjs`: 62 tests passed.
|
||||
- `node scripts/validate-public-docs.mjs`: 46 published docs pages validated.
|
||||
- `python3 scripts/list-docs.py validate`: 272 decisions and 935
|
||||
specifications validated.
|
||||
- `python3 scripts/lint-spec-files.py --all`: passed.
|
||||
- `git diff --check`: passed.
|
||||
@@ -151,7 +151,7 @@ Use the queue controls according to the outcome you want:
|
||||
|
||||
- **Auto-run** is ON by default. ON runs eligible messages one at a time in FIFO order. OFF lets the current response finish, then holds every later message. The per-session setting survives an empty queue, reload, and backend restart. Turning it ON starts the head immediately when the session is promptable; clarification, workflow transitions, cancellation, and other lifecycle guards can defer delivery without changing the displayed ON state.
|
||||
- **Auto-merge** shows the effective automatic-fold policy for this session. Changing it creates a permanent session override; untouched sessions continue to inherit the install-wide setting.
|
||||
- Every row's **Send Now** targets that message. It sends directly when the session is promptable; when an agent turn is active, it waits for backend cancellation acknowledgement and replaces that captured turn. A successful Send Now turns Auto-run ON, runs the selected row first, then continues the preserved remainder as separate FIFO turns. It does not record ordinary Cancel side effects, complete the cancelled workflow step, or move the task to review.
|
||||
- Every row's **Send Now** targets that message. It sends directly when the session is promptable; when an agent turn is active, it waits for backend cancellation acknowledgement and replaces that captured turn. This includes a turn that Auto-run delivered from the FIFO queue after its prompt handoff completes. The handoff remains protected while it is completing, so a concurrent Send Now conflict keeps the rows pending for retry. A successful Send Now turns Auto-run ON, runs the selected row first, then continues the preserved remainder as separate FIFO turns. It does not record ordinary Cancel side effects, complete the cancelled workflow step, or move the task to review.
|
||||
- **Clear all** removes every visible pending row without sending a prompt.
|
||||
- **Cancel** in the chat toolbar stops the active turn immediately as a user cancellation. It may record the cancellation, complete an eligible workflow step, and move the task to review. It does not send queued content; when pending rows remain, Auto-run becomes OFF so they stay parked.
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ When you queue a prompt, Kandev records a submission identity before it reports
|
||||
|
||||
A full queue, invalid content or attachment, identity conflict, or unavailable session shows a **Message not sent** error and keeps the draft and attachments. If delivery remains uncertain, Kandev shows **Message send status unknown** and keeps them for inspection. A confirmed admission clears only the submitted draft; a failed queue refresh does not turn an accepted admission into a failure.
|
||||
|
||||
Every row has **Send Now** for targeted priority. It sends that row directly when the session is promptable or replaces the captured active turn after backend cancellation acknowledgement. A successful Send Now turns Auto-run ON, runs the selected row first, then continues the remaining rows as separate FIFO turns without ordinary Cancel side effects. **Clear all** discards the visible queue. The chat toolbar's **Cancel** immediately stops the active turn, sends no queued prompt, parks any pending backlog by turning Auto-run OFF, and can complete the workflow step or move the task to review.
|
||||
Every row has **Send Now** for targeted priority. It sends that row directly when the session is promptable or replaces the captured active turn after backend cancellation acknowledgement. This includes a turn that Auto-run delivered from the FIFO queue after its prompt handoff completes. The handoff remains protected while it is completing, so a concurrent Send Now conflict keeps the rows pending for retry. A successful Send Now turns Auto-run ON, runs the selected row first, then continues the remaining rows as separate FIFO turns without ordinary Cancel side effects. **Clear all** discards the visible queue. The chat toolbar's **Cancel** immediately stops the active turn, sends no queued prompt, parks any pending backlog by turning Auto-run OFF, and can complete the workflow step or move the task to review.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -26,7 +26,16 @@ When an agent is in a long-running turn, an urgent correction can sit in the que
|
||||
- **AC-UI-MESSAGE-QUEUE-SEND-NOW-001.5:** The bulk turn uses the oldest selected entry's model and plan-mode snapshot. Its transcript envelope uses that entry's sender attribution while retaining source entry identities and provenance in metadata for restoration and diagnostics.
|
||||
- **AC-UI-MESSAGE-QUEUE-SEND-NOW-001.6:** If the aggregate would exceed the existing per-message attachment count, attachment byte, or entity-reference limits, the request is rejected before cancellation. No content is truncated and the queue is unchanged.
|
||||
- **AC-UI-MESSAGE-QUEUE-SEND-NOW-001.7:** A promptable session dispatches immediately without cancellation. A busy session uses the existing backend-owned cancellation progress, cancels only the turn observed when the action began, and starts the replacement turn after cancellation settles.
|
||||
- **AC-UI-MESSAGE-QUEUE-SEND-NOW-001.8:** If ordinary FIFO delivery has reserved a queued entry but has not yet accepted its prompt, Send Now wins that same-session handoff. The reserved source is restored before the requested selection is claimed, so an all-scope replacement can include it in one aggregate prompt. Once FIFO has accepted its prompt, Send Now fails closed with `send_now_conflict`; it does not duplicate or cancel that successor turn.
|
||||
- **AC-UI-MESSAGE-QUEUE-SEND-NOW-001.8:** If ordinary FIFO delivery has reserved a queued entry but has not yet accepted its prompt, Send Now wins that same-session handoff. The reserved source is restored before the requested selection is claimed, so an all-scope replacement can include it in one aggregate prompt. During the accepted prompt handoff, Send Now fails closed with `send_now_conflict`. Once the successor owns the running turn, a new Send Now request can interrupt it under the same captured-turn checks as any other active turn.
|
||||
|
||||
- **AC-UI-MESSAGE-QUEUE-SEND-NOW-001.9:** A running turn started by ordinary FIFO delivery shall be interruptible by a new Send Now request after its prompt handoff completes. This applies to fixed and dynamic profiles, including Cursor. The selected pending entry runs once; the interrupted input is not restored or repeated, and other pending entries retain FIFO order.
|
||||
- **AC-UI-MESSAGE-QUEUE-SEND-NOW-001.10:** A request that observes an older turn shall not cancel a newer successor. Overlapping cancellation requests remain conflicts. Late completion from an interrupted turn shall not settle the replacement or release its pending queue work.
|
||||
- **AC-UI-MESSAGE-QUEUE-SEND-NOW-001.11:** Desktop and phone Send Now actions shall show the existing localized conflict feedback for a genuine handoff conflict and refresh the authoritative queue. They shall allow a later request after handoff without a page reload.
|
||||
|
||||
## Design and delivery
|
||||
|
||||
- [System design](../system-design/message-queue-send-now.md)
|
||||
- [FIFO interruption repair package](../../../plans/queue-send-now-live-fifo/plan.md)
|
||||
|
||||
## Migrated source detail
|
||||
|
||||
@@ -79,8 +88,9 @@ follow-up, without completing or advancing the task's workflow step.
|
||||
accepted its prompt, Send Now wins that same-session handoff. The reserved
|
||||
source is restored before the requested selection is claimed, so an
|
||||
all-scope replacement can include it in one aggregate prompt. Once FIFO has
|
||||
accepted its prompt, Send Now fails closed with `send_now_conflict`; it does
|
||||
not duplicate or cancel that successor turn.
|
||||
accepted its prompt but has not completed the handoff, Send Now fails closed
|
||||
with `send_now_conflict`. A later request can interrupt the running successor
|
||||
when it is the turn captured by that request.
|
||||
- Send Now is a replacement/steering cancellation. It does not create the
|
||||
ordinary **Turn cancelled** message, move the task to review, evaluate
|
||||
`cancel_triggers_turn_complete`, or run the cancelled turn's
|
||||
@@ -174,8 +184,11 @@ queue-take serialization point. An ordinary FIFO handoff has an explicit
|
||||
pre-acceptance phase: Send Now may supersede that reservation while the worker
|
||||
has not claimed prompt ownership, but the worker must claim ownership before
|
||||
creating a visible user message, running turn-start workflow effects, or
|
||||
accepting the agent prompt. After that claim, the handoff is terminal for Send
|
||||
Now and the existing conflict response applies.
|
||||
accepting the agent prompt. The accepted handoff remains protected until the
|
||||
successor owns the running turn. A later Send Now request can replace that turn;
|
||||
an older request cannot cancel a successor that appeared after its capture.
|
||||
The [Send Now system design](../system-design/message-queue-send-now.md) defines
|
||||
the ownership boundary and settlement rules.
|
||||
|
||||
When Send Now supersedes a pre-acceptance FIFO reservation, the backend
|
||||
restores that exact source (including clearing a durable lifecycle
|
||||
@@ -216,8 +229,9 @@ not undo that explicit resume instruction.
|
||||
- **FIFO handoff race:** if normal FIFO delivery reserved the head but has not
|
||||
accepted its prompt, Send Now restores/reclaims that reservation and
|
||||
dispatches the requested exact selection. If FIFO already accepted the
|
||||
prompt, Send Now returns `send_now_conflict`; it leaves that successor and
|
||||
the remaining queue authoritative rather than creating a duplicate turn.
|
||||
prompt but has not completed the handoff, Send Now returns
|
||||
`send_now_conflict`. After handoff, a new request may replace that running
|
||||
successor without restoring or duplicating its already accepted input.
|
||||
- **Prompt admission fails after claim:** the backend restores the original
|
||||
entries and their FIFO positions before publishing status. Auto-run stays ON
|
||||
because the operation was already accepted as a resume. Existing ordinary
|
||||
@@ -274,10 +288,13 @@ not undo that explicit resume instruction.
|
||||
a protocol client requests `scope: "all"`, **THEN** the FIFO reservation is
|
||||
restored, both messages are claimed in FIFO order, and exactly one
|
||||
replacement prompt contains both bodies.
|
||||
- **GIVEN** normal FIFO delivery has already accepted its successor prompt,
|
||||
**WHEN** the user clicks Send Now, **THEN** the action fails closed without a
|
||||
duplicate user message, duplicate prompt, or cancellation of that successor,
|
||||
and the authoritative remaining queue is preserved.
|
||||
- **GIVEN** normal FIFO delivery is in its accepted prompt handoff, **WHEN**
|
||||
the user clicks Send Now, **THEN** the action fails closed without a duplicate
|
||||
message, prompt, or cancellation, and the remaining queue is preserved.
|
||||
- **GIVEN** normal FIFO delivery has completed the handoff and its turn is
|
||||
running, **WHEN** the user sends another pending entry now, **THEN** the
|
||||
captured running turn is interrupted and the exact selected entry starts once.
|
||||
The interrupted input is not returned to the queue.
|
||||
- **GIVEN** the workflow step enables `cancel_triggers_turn_complete`, **WHEN**
|
||||
the user sends a queued message now, **THEN** the task stays on the same step
|
||||
and only the replacement turn's ordinary lifecycle hooks may change it.
|
||||
@@ -298,7 +315,8 @@ not undo that explicit resume instruction.
|
||||
- Sending an arbitrary user-selected subset other than one entry or all visible
|
||||
pending entries.
|
||||
- Changing **Remove**, **Clear all**, edit, or merge semantics. FIFO participates
|
||||
in Send Now handoff arbitration only until its prompt is accepted. Normal
|
||||
in Send Now reservation arbitration before prompt acceptance and in ordinary
|
||||
captured-turn interruption after the handoff completes. Normal
|
||||
FIFO policy and first-party queue controls are governed by
|
||||
[Control Pending Message Auto-run](message-queue-run.md).
|
||||
- Making ordinary queued-message dispatch crash-durable after its existing
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
---
|
||||
status: current
|
||||
system: ui
|
||||
created: 2026-09-15
|
||||
requirements:
|
||||
- REQ-UI-MESSAGE-QUEUE-SEND-NOW-001
|
||||
owners:
|
||||
- kandev
|
||||
---
|
||||
|
||||
# Send Now and queued turn ownership
|
||||
|
||||
## Boundary
|
||||
|
||||
This design accompanies the existing [Send Now requirement](../requirements/message-queue-send-now.md).
|
||||
It retains that capability's current specification owner during migration.
|
||||
The task orchestrator owns runtime arbitration; agent profile selection remains
|
||||
with the agent runtime. No second requirement is introduced in either system.
|
||||
|
||||
The [replacement-turn decision](../../../decisions/2026-08-05-queue-send-now-replaces-turn.md)
|
||||
and the [queue automation design](message-queue-automation-controls.md) remain
|
||||
applicable. Session identity, policy transactions, restoration generations, and
|
||||
explicit Cancel semantics are unchanged.
|
||||
|
||||
## Components and phases
|
||||
|
||||
`internal/orchestrator/queued_dispatch.go` owns `queuedDispatchReservation`.
|
||||
`queue_send_now.go` captures the active turn, arbitrates cancellation, claims
|
||||
an exact queue selection, and starts the replacement worker.
|
||||
`task_operations.go` owns the guarded prompt claim and its visible side effects.
|
||||
|
||||
| Phase | Send Now arbitration | Settlement ownership |
|
||||
| --- | --- | --- |
|
||||
| `queuedDispatchPending` | May restore and supersede the unaccepted FIFO source | Exact reservation |
|
||||
| `queuedDispatchAccepted` | Conflict while the prompt handoff is incomplete | Exact reservation |
|
||||
| `queuedDispatchLive` | A new request may cancel its captured active turn | Exact reservation and bound successor turn |
|
||||
| Superseded or settled | Cannot dispatch, restore, or clear a newer owner | Existing identity and generation checks |
|
||||
|
||||
The accepted record has two responsibilities: short handoff exclusion and
|
||||
longer settlement ownership. Keep the record after it becomes live. Deleting
|
||||
it to enable interruption would also discard protection against late events.
|
||||
|
||||
## Transition to live
|
||||
|
||||
Use the existing guarded boundary at the end of `claimSessionRunningForPrompt`:
|
||||
revalidate the session incarnation and promptability, claim the session and
|
||||
turn, perform `acknowledgePromptClaim`, then promote the exact current accepted
|
||||
reservation through `markAcceptedDispatchLiveLocked`. Release the pending
|
||||
marker only after these operations succeed.
|
||||
|
||||
Apply that transition to ordinary FIFO and Send Now reservations. The former
|
||||
`liveEligible` distinction restricted the live phase to Send Now reservations;
|
||||
the implementation removes that origin-specific gate and its redundant
|
||||
field/setter. Do not promote on a timer, the browser's RUNNING projection, an
|
||||
unrelated stream event, or a provider name.
|
||||
|
||||
Here, live means ownership of the guarded prompt claim, including its visible
|
||||
side effects. It does not mean the long-running executor call has returned.
|
||||
Keep the existing dispatch/cancellation serialization around provider admission.
|
||||
A cancellation between claim and provider I/O must not let a superseded worker
|
||||
send after its replacement. Exercise that ordering in a channel-controlled test.
|
||||
|
||||
The transition must compare reservation identity. A late worker cannot promote
|
||||
or release a newer reservation. Continue binding successor turns through the
|
||||
existing prompt ownership and acceptance paths. An unavailable or changed
|
||||
session/turn identity fails closed through existing validation.
|
||||
|
||||
## Interruption and recovery
|
||||
|
||||
`sendQueuedNowAfterCapture` still rejects an active cancellation or an accepted
|
||||
handoff. A live FIFO reservation proceeds to captured-turn validation and
|
||||
`dispatchSendNowSelection`, just as a live Send Now reservation does today.
|
||||
|
||||
Cancellation uses `cancellationKindQueueSendNow`. The exact selected pending
|
||||
entry, or all-scope snapshot, is claimed only after cancellation settles.
|
||||
An already accepted input is never restored merely because its turn was
|
||||
interrupted. Ordinary and durable entries retain their existing admission,
|
||||
acknowledgement, generation, and retry rules.
|
||||
|
||||
Keep `acceptedDispatchInFlight`, successor-turn binding, and exact-reservation
|
||||
cleanup effective for live FIFO turns. Completion from an interrupted
|
||||
predecessor cannot clear the replacement, start a competing FIFO drain, or
|
||||
complete the workflow step. A request captured before a successor appeared
|
||||
fails with the existing conflict or turn-changed response, as appropriate to
|
||||
its arbitration point.
|
||||
|
||||
No schema, wire payload, feature toggle, provider selection, or new cancellation
|
||||
path is required. A dynamic session uses its existing concrete execution for
|
||||
cancellation and follows the existing runtime contract for the replacement.
|
||||
|
||||
## Presentation and compatibility
|
||||
|
||||
The queue hook, existing row control, cancellation projection, and queue refetch
|
||||
remain shared across desktop and phone. Reuse the inline queue panel and its
|
||||
single scroll region. Desktop retains hover/focus actions; coarse pointers
|
||||
retain visible touch targets. No new control or layout is needed.
|
||||
|
||||
`queue-api.ts` already maps a real `WebSocketRequestError` into a typed queue
|
||||
error on the current branch. Add a Send Now-specific regression using that
|
||||
class, rather than reproducing the reporter's older `instanceof Error` bypass.
|
||||
The existing `chat:sendNowConflict` translation remains the feedback for a real
|
||||
handoff conflict. No new localized copy is planned.
|
||||
|
||||
Clients that previously received a conflict for the entire FIFO turn can now
|
||||
successfully interrupt it after the guarded claim. The response shape, genuine
|
||||
conflict handling, Auto-run policy, and queue ordering remain compatible.
|
||||
|
||||
## Rationale
|
||||
|
||||
Protecting the whole FIFO turn prevents users from steering long-running work
|
||||
solely because its input came from the queue. Removing all exclusion would
|
||||
risk duplicate admission during handoff. The shared accepted-to-live boundary
|
||||
supports interruption while preserving the existing ownership controls.
|
||||
This refines the existing replacement-turn decision; no independent ADR is
|
||||
needed because this design records the narrow alternatives and constraint.
|
||||
|
||||
## Verification mapping
|
||||
|
||||
| Acceptance criteria | Evidence |
|
||||
| --- | --- |
|
||||
| .2, .7, .9 | Real-service FIFO drain followed by exact-entry/all-scope Send Now; cancellation and exactly one replacement |
|
||||
| .8, .10 | Barriers during accepted handoff; stale capture, stale completion, overlapping cancel, and superseded-worker tests |
|
||||
| .9 | Fixed-profile and persisted dynamic-to-Cursor identity cases; no profile re-selection added by queue code |
|
||||
| .1, .11 | Desktop click and phone tap through the existing queue panel, plus real WebSocket error mapping |
|
||||
|
||||
Implementation and exact commands live in the
|
||||
[repair package](../../../plans/queue-send-now-live-fifo/plan.md).
|
||||
Reference in New Issue
Block a user