Refactor history loading tests and context management

- Updated the TestHistoryLoading function to clarify role filtering, ensuring only user and assistant messages are included in the history.
- Adjusted message creation timestamps for consistency in test scenarios.
- Removed deprecated context creation methods to streamline context management and improve code clarity.
- Enhanced logging levels in context management for better traceability and debugging.
This commit is contained in:
Max 2025-12-11 15:32:06 +08:00
parent 4a1c0ec100
commit eebaf27f1d
3 changed files with 17 additions and 77 deletions

View file

@ -414,7 +414,8 @@ func TestHistoryLoading(t *testing.T) {
chatStore.DeleteChat(chatID)
}()
// Add various message types
// Add various message types (only user/assistant roles allowed by DB constraint)
// loadHistory filters by role (user/assistant only) and converts based on type
err = chatStore.SaveMessages(chatID, []*storetypes.Message{
{
MessageID: fmt.Sprintf("filter_1_%s", reqID),
@ -425,7 +426,7 @@ func TestHistoryLoading(t *testing.T) {
Props: map[string]interface{}{"content": "User message"},
Sequence: 1,
AssistantID: ast.ID,
CreatedAt: time.Now().Add(-4 * time.Minute),
CreatedAt: time.Now().Add(-3 * time.Minute),
},
{
MessageID: fmt.Sprintf("filter_2_%s", reqID),
@ -436,7 +437,7 @@ func TestHistoryLoading(t *testing.T) {
Props: map[string]interface{}{"text": "Loading..."},
Sequence: 2,
AssistantID: ast.ID,
CreatedAt: time.Now().Add(-3 * time.Minute),
CreatedAt: time.Now().Add(-2 * time.Minute),
},
{
MessageID: fmt.Sprintf("filter_3_%s", reqID),
@ -447,17 +448,6 @@ func TestHistoryLoading(t *testing.T) {
Props: map[string]interface{}{"text": "Assistant response"},
Sequence: 3,
AssistantID: ast.ID,
CreatedAt: time.Now().Add(-2 * time.Minute),
},
{
MessageID: fmt.Sprintf("filter_4_%s", reqID),
ChatID: chatID,
RequestID: fmt.Sprintf("req_filter_%s", reqID),
Role: "system",
Type: "event",
Props: map[string]interface{}{"event": "stream_end"},
Sequence: 4,
AssistantID: ast.ID,
CreatedAt: time.Now().Add(-1 * time.Minute),
},
})
@ -471,17 +461,19 @@ func TestHistoryLoading(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, result)
// User and assistant roles are included, system is filtered out
// Note: loading type messages with role=assistant are included (role-based filtering)
// Only system role messages are filtered out
// User and assistant roles are included
// loading type messages with role=assistant are included (role-based filtering)
// History contains: 1 user + 2 assistant (loading + text) = 3 messages
// Plus 1 new input = 4 total
assert.GreaterOrEqual(t, len(result.FullMessages), 3) // At least 1 user + 1 assistant from history + 1 new
// Verify no system role messages
// Verify only user and assistant roles
for _, msg := range result.FullMessages {
assert.NotEqual(t, "system", string(msg.Role))
assert.True(t, msg.Role == agentcontext.RoleUser || msg.Role == agentcontext.RoleAssistant,
"Expected user or assistant role, got: %s", msg.Role)
}
t.Log("✓ System role messages filtered out")
t.Log("✓ Only user and assistant roles included in history")
})
t.Run("ContentExtraction", func(t *testing.T) {

View file

@ -6,9 +6,7 @@ import (
"sync"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/yaoapp/gou/plan"
"github.com/yaoapp/kun/log"
"github.com/yaoapp/yao/agent/output/message"
"github.com/yaoapp/yao/config"
"github.com/yaoapp/yao/openapi/oauth/types"
@ -43,46 +41,6 @@ func New(parent context.Context, authorized *types.AuthorizedInfo, chatID string
return ctx
}
// NewWithPayload create a new context and unmarshal from payload
func NewWithPayload(parent context.Context, authorized *types.AuthorizedInfo, chatID, payload string) *Context {
ctx := New(parent, authorized, chatID)
if payload != "" {
err := jsoniter.Unmarshal([]byte(payload), ctx)
if err != nil {
log.Error("%s", err.Error())
}
}
return ctx
}
// NewWithCancel create a new context with cancel
func NewWithCancel(parent context.Context, authorized *types.AuthorizedInfo, chatID string) (*Context, context.CancelFunc) {
ctx := New(parent, authorized, chatID)
return WithCancel(ctx)
}
// NewWithTimeout create a new context with timeout
func NewWithTimeout(parent context.Context, authorized *types.AuthorizedInfo, chatID string, timeout time.Duration) (*Context, context.CancelFunc) {
ctx := New(parent, authorized, chatID)
return WithTimeout(ctx, timeout)
}
// WithCancel create a new context
func WithCancel(parent *Context) (*Context, context.CancelFunc) {
new, cancel := context.WithCancel(parent.Context)
parent.Context = new
return parent, cancel
}
// WithTimeout create a new context
func WithTimeout(parent *Context, timeout time.Duration) (*Context, context.CancelFunc) {
new, cancel := context.WithTimeout(parent.Context, timeout)
parent.Context = new
return parent, cancel
}
// Release the context and clean up all resources including stacks and trace
func (ctx *Context) Release() {
if ctx.Logger != nil {
@ -355,21 +313,6 @@ func (ctx *Context) TraceID() string {
return ""
}
// recordMessageMetadata records metadata for a sent message
// Used to inherit BlockID and ThreadID in subsequent delta operations
func (ctx *Context) recordMessageMetadata(msg *message.Message) {
if msg.MessageID == "" || ctx.messageMetadata == nil {
return
}
ctx.messageMetadata.setMessage(msg.MessageID, &MessageMetadata{
MessageID: msg.MessageID,
BlockID: msg.BlockID,
ThreadID: msg.ThreadID,
Type: msg.Type,
})
}
// getMessageMetadata retrieves metadata for a message by ID
// Returns nil if message metadata is not found
func (ctx *Context) getMessageMetadata(messageID string) *MessageMetadata {

View file

@ -41,10 +41,15 @@ const (
type LogLevel int
const (
// LogLevelTrace represents the most verbose logging level for detailed tracing
LogLevelTrace LogLevel = iota
// LogLevelDebug represents debug level logging for development diagnostics
LogLevelDebug
// LogLevelInfo represents informational messages for normal operation
LogLevelInfo
// LogLevelWarn represents warning messages for potentially harmful situations
LogLevelWarn
// LogLevelError represents error messages for serious problems
LogLevelError
)