Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ require (
github.com/charmbracelet/huh v1.0.0
github.com/charmbracelet/x/ansi v0.11.6
github.com/firebase/genkit/go v1.13.1
github.com/flanksource/clicky v1.21.95-0.20261112060413-ae2c0bb79614
github.com/flanksource/clicky v1.21.95
github.com/flanksource/clicky/aichat v1.21.91
github.com/flanksource/commons v1.64.1
github.com/flanksource/commons-db v0.1.69
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -333,8 +333,8 @@ github.com/fergusstrange/embedded-postgres v1.34.0 h1:c6RKhPKFsLVU+Tdxsx8q0UxCHs
github.com/fergusstrange/embedded-postgres v1.34.0/go.mod h1:w0YvnCgf19o6tskInrOOACtnqfVlOvluz3hlNLY7tRk=
github.com/firebase/genkit/go v1.13.1 h1:6fgQ0ogxG+SIgtYQD/yf8T0+39lacioB5voFdFYk1tI=
github.com/firebase/genkit/go v1.13.1/go.mod h1:nWewix7d2O+oikJ035XPmY4mrO2phXwmk6NekKmaDLU=
github.com/flanksource/clicky v1.21.95-0.20261112060413-ae2c0bb79614 h1:Ls5AwnjPoDSGJH+pzlwlmXNF9u4nqs2wRUUqa8ljxLs=
github.com/flanksource/clicky v1.21.95-0.20261112060413-ae2c0bb79614/go.mod h1:H4HeUqMEzAz14ewqX5CNu/VnlaZHrTK/1otCgs1O1m4=
github.com/flanksource/clicky v1.21.95 h1:cBuTKkvbWHjpDRswJ0iOPJzNT5QYiyqt31qmJOA7rBg=
github.com/flanksource/clicky v1.21.95/go.mod h1:H4HeUqMEzAz14ewqX5CNu/VnlaZHrTK/1otCgs1O1m4=
github.com/flanksource/clicky/aichat v1.21.91 h1:1yHU8qyHlOyOSbC97MP5XK8A/OAF6NvPulI7Y2MEUmw=
github.com/flanksource/clicky/aichat v1.21.91/go.mod h1:tt9CM4VIZSUbBTtgsri6NgtdCzCOgX1jEeC791TdUy4=
github.com/flanksource/clicky/valkey v1.21.82 h1:6R0Uysg4pJfVu1RmUqdXQqHLhtutHqy24tsAESwa5Ns=
Expand Down
11 changes: 7 additions & 4 deletions pkg/ai/approval/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,16 +175,19 @@ func (b *Broker) OnApproval(
// exactly when it mattered. context.WithoutCancel is the point: ending the
// wait is the response to the cancellation, not a victim of it.
defer func() {
if err != nil {
err = b.abandon(ctx, pending.ID, err)
}
err = errors.Join(err, b.release(context.WithoutCancel(ctx)))
}()
if hookErr := b.observe(ctx, run, held); hookErr != nil {
return api.ApprovalDecision{}, b.abandon(ctx, pending.ID, hookErr)
return api.ApprovalDecision{}, hookErr
}
if notifyErr := b.Notify(ctx, api.Event{
Kind: api.EventPermission, Tool: req.Tool, ToolCallID: req.ToolUseID,
ApprovalID: pending.ID.String(), Input: req.Input, Request: &req,
}); notifyErr != nil {
return api.ApprovalDecision{}, b.abandon(ctx, pending.ID, notifyErr)
return api.ApprovalDecision{}, notifyErr
}
return b.wait(ctx, pending.ID)
}
Expand Down Expand Up @@ -308,12 +311,12 @@ func (b *Broker) wait(ctx context.Context, requestID uuid.UUID) (api.ApprovalDec
// credential is the authority the tool would run under.
if request.CredentialID != nil {
if err := b.DB.ValidateCallerToolCredential(ctx, *request.CredentialID); err != nil {
return api.ApprovalDecision{}, b.abandon(ctx, request.ID, err)
return api.ApprovalDecision{}, err
}
}
select {
case <-ctx.Done():
return api.ApprovalDecision{}, b.abandon(ctx, request.ID, ctx.Err())
return api.ApprovalDecision{}, ctx.Err()
case <-ticker.C:
}
}
Expand Down
98 changes: 98 additions & 0 deletions pkg/ai/approval/broker_cancellation_ginkgo_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package approval_test

import (
"context"
"time"

"github.com/flanksource/captain/pkg/api"
"github.com/flanksource/captain/pkg/database"
"github.com/google/uuid"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gstruct"
"gorm.io/gorm"
)

var _ = Describe("Approval broker cancellation", func() {
DescribeTable("cancels the durable row and releases the run",
func(ctx SpecContext, duringRead bool) {
db := openBrokerDB(ctx)
run := newProviderRun(ctx, db)
callCtx, cancel := context.WithCancel(ctx)
DeferCleanup(cancel)
broker := run.broker(time.Minute)
surfaced := false
queries := db.Gorm().Callback().Query()
const callback = "test:cancel_approval_poll"
Expect(queries.Before("gorm:query").Register(callback, func(_ *gorm.DB) {
if duringRead && surfaced {
cancel()
}
})).To(Succeed())
DeferCleanup(func() { Expect(queries.Remove(callback)).To(Succeed()) })
broker.Notify = func(ctx context.Context, event api.Event) error {
if err := run.notify(ctx, event); err != nil {
return err
}
surfaced = true
if !duringRead {
cancel()
}
return nil
}

decision, err := broker.OnApproval(callCtx, api.ApprovalRequest{
Kind: api.ApprovalKindTool, Tool: "Bash",
Input: map[string]any{"command": "git push"}, ToolUseID: "toolu_cancel_poll",
})
Expect(err).To(MatchError(context.Canceled))
Expect(decision).To(BeZero())
event := run.awaitPermission()
cancelled, err := db.GetTurnRequest(ctx, uuid.MustParse(event.ApprovalID))
Expect(err).NotTo(HaveOccurred())
Expect(*cancelled).To(MatchFields(IgnoreExtras, Fields{
"State": Equal(database.TurnRequestStateCancelled),
"Reason": ContainSubstring(context.Canceled.Error()),
"ResolvedAt": Not(BeNil()),
}))
Expect(run.state(ctx)).To(Equal(database.PromptRunStateRunning))
},
Entry("when cancellation precedes the first poll", false),
Entry("when cancellation interrupts a poll's database read", true),
)

DescribeTable("preserves a durable decision when cancellation precedes the poll",
func(ctx SpecContext, approved bool, state database.TurnRequestState) {
db := openBrokerDB(ctx)
run := newProviderRun(ctx, db)
callCtx, cancel := context.WithCancel(ctx)
DeferCleanup(cancel)
broker := run.broker(time.Minute)
var resolved *database.TurnRequest
broker.Notify = func(ctx context.Context, event api.Event) error {
var err error
resolved, err = db.ResolveToolApprovalRequest(ctx, database.ResolveToolApprovalRequestInput{
SessionID: run.session, RequestID: uuid.MustParse(event.ApprovalID),
Approved: approved, ResolvedBy: "spec", Reason: "reviewed",
})
cancel()
return err
}

decision, err := broker.OnApproval(callCtx, api.ApprovalRequest{
Kind: api.ApprovalKindTool, Tool: "Bash",
Input: map[string]any{"command": "git push"}, ToolUseID: "toolu_cancel_resolved",
})
Expect(err).To(MatchError(context.Canceled))
Expect(decision).To(BeZero())
Expect(resolved).NotTo(BeNil())
Expect(resolved.State).To(Equal(state))
stored, err := db.GetTurnRequest(ctx, resolved.ID)
Expect(err).NotTo(HaveOccurred())
Expect(stored).To(Equal(resolved))
Expect(run.state(ctx)).To(Equal(database.PromptRunStateRunning))
},
Entry("for an approved request", true, database.TurnRequestStateApproved),
Entry("for a denied request", false, database.TurnRequestStateDenied),
)
})
Loading