feat(dingtalk): add reasoning mode and support evidence

This commit is contained in:
姚章浩
2026-09-10 16:24:56 +08:00
parent 0798a2dac7
commit bfa1b1b25f
45 changed files with 2713 additions and 102 deletions
+80
View File
@@ -0,0 +1,80 @@
package reasoningmode
import (
"fmt"
"strings"
"unicode"
)
func ResolveGuideLocale(locale, query string) string {
locale = strings.TrimSpace(locale)
if locale != "" && locale != "auto" {
return locale
}
hasLatin := false
for _, value := range query {
if unicode.In(value, unicode.Han, unicode.Hiragana, unicode.Katakana, unicode.Hangul) {
return "zh-CN"
}
if unicode.In(value, unicode.Latin) {
hasLatin = true
}
}
if hasLatin {
return "en"
}
return "zh-CN"
}
func DecorateAnswer(answer string, execution ExecutionMode, expired bool, completion Completion) string {
return DecorateAnswerForLocale(answer, execution, expired, completion, "zh-CN")
}
func DecorateAnswerForLocale(answer string, execution ExecutionMode, expired bool, completion Completion, locale string) string {
content := strings.TrimSpace(answer)
prefixes := make([]string, 0, 2)
if expired {
prefixes = append(prefixes, "💡 智能推理模式已因10分钟无操作自动关闭,当前已切回【快速问答模式】。")
}
if execution == ExecutionReasoning || execution == ExecutionReasoningSingle {
prefixes = append(prefixes, "【智能推理模式】")
}
if len(prefixes) > 0 {
content = strings.Join(prefixes, "\n\n") + "\n\n" + content
}
suffixes := make([]string, 0, 3)
if completion.ShowHint {
suffixes = append(suffixes, "💡 推理模式还剩2轮,到期将自动关闭,如需继续可发送 /think on 重置轮次")
}
if completion.AutoClosed {
suffixes = append(suffixes, fmt.Sprintf(
"💡 持续推理模式已满%d轮,已自动切回【快速问答模式】\n如需继续深度推理,可再次发送 /think on 开启",
completion.RoundNumber,
))
}
if completion.ShowOnboarding {
suffixes = append(suffixes, firstUseGuide(locale))
}
if len(suffixes) > 0 {
content += "\n\n" + strings.Join(suffixes, "\n\n")
}
return content
}
func firstUseGuide(locale string) string {
if strings.EqualFold(strings.TrimSpace(locale), "en") {
return "💡 First-time Guide\n" +
"✅ Default: Fast Q&A Mode — knowledge-based, fast and cost-effective\n" +
"🔹 For deep reasoning & analysis:\n" +
"Continuous use: /think on to enable, auto-off after 10 rounds\n" +
"Single use: /think + your question, auto switch back after reply\n" +
"💬 /help for all commands · /setting for language & preferences"
}
return "💡 首次使用指南\n" +
"✅ 当前默认使用快速问答模式,基于知识库快速作答,成本更低\n" +
"🔹 需深度推理分析时:\n" +
"连续使用:发送 /think on 开启持续模式,10轮对话后自动关闭\n" +
"单次使用:发送 /think + 你的问题,用完自动切回省钱模式\n" +
"💬 /help 查看全部指令・/setting 配置语言与偏好"
}
+50
View File
@@ -0,0 +1,50 @@
package reasoningmode
import (
"strings"
"testing"
)
func TestDecorateAnswerMarksReasoningAndRemainingRounds(t *testing.T) {
answer := DecorateAnswer("分析结果", ExecutionReasoning, false, Completion{RoundNumber: 8, ShowHint: true})
if !strings.HasPrefix(answer, "【智能推理模式】\n\n分析结果") {
t.Fatalf("answer=%q", answer)
}
if !strings.Contains(answer, "推理模式还剩2轮") || !strings.Contains(answer, "/think on") {
t.Fatalf("answer=%q", answer)
}
}
func TestDecorateAnswerMarksSingleReasoningWithoutRoundHint(t *testing.T) {
answer := DecorateAnswer("单次结果", ExecutionReasoningSingle, false, Completion{})
if answer != "【智能推理模式】\n\n单次结果" {
t.Fatalf("answer=%q", answer)
}
}
func TestDecorateAnswerAppendsAutomaticClose(t *testing.T) {
answer := DecorateAnswer("最终结果", ExecutionReasoning, false, Completion{RoundNumber: 10, AutoClosed: true})
if !strings.Contains(answer, "持续推理模式已满10轮") || !strings.Contains(answer, "已自动切回【快速问答模式】") {
t.Fatalf("answer=%q", answer)
}
}
func TestDecorateAnswerExplainsIdleExpiryOnNextQuickAnswer(t *testing.T) {
answer := DecorateAnswer("快速结果", ExecutionQuick, true, Completion{})
if !strings.HasPrefix(answer, "💡 智能推理模式已因10分钟无操作自动关闭") || !strings.HasSuffix(answer, "快速结果") {
t.Fatalf("answer=%q", answer)
}
}
func TestDecorateAnswerAppendsFirstUseGuideOnce(t *testing.T) {
answer := DecorateAnswer("快速结果", ExecutionQuick, false, Completion{ShowOnboarding: true})
for _, required := range []string{"首次使用指南", "默认使用快速问答模式", "/think on", "/think + 你的问题", "/help", "/setting"} {
if !strings.Contains(answer, required) {
t.Fatalf("answer=%q missing %q", answer, required)
}
}
without := DecorateAnswer("快速结果", ExecutionQuick, false, Completion{})
if strings.Contains(without, "首次使用指南") {
t.Fatalf("onboarding repeated: %q", without)
}
}
+15
View File
@@ -0,0 +1,15 @@
package reasoningmode
import "testing"
func TestResolveGuideLocaleUsesQuestionWhenPreferenceIsAuto(t *testing.T) {
if got := ResolveGuideLocale("auto", "How do I configure CRA?"); got != "en" {
t.Fatalf("English auto locale=%q", got)
}
if got := ResolveGuideLocale("auto", "如何配置CRA?"); got != "zh-CN" {
t.Fatalf("Chinese auto locale=%q", got)
}
if got := ResolveGuideLocale("ja", "English text"); got != "ja" {
t.Fatalf("explicit locale changed to %q", got)
}
}
+75
View File
@@ -0,0 +1,75 @@
package reasoningmode
import "strings"
type CommandKind string
const (
CommandEnable CommandKind = "enable"
CommandDisable CommandKind = "disable"
CommandSingle CommandKind = "single"
CommandHelp CommandKind = "help"
CommandInvalid CommandKind = "invalid"
)
type Command struct {
Kind CommandKind
Query string
}
func ParseCommand(raw string) (Command, bool) {
value := strings.TrimSpace(raw)
fields := strings.Fields(value)
if len(fields) == 0 {
return Command{}, false
}
name := strings.ToLower(fields[0])
switch name {
case "/help", "/帮助", "/h":
if len(fields) != 1 {
return Command{Kind: CommandInvalid}, true
}
return Command{Kind: CommandHelp}, true
case "/开启推理":
if len(fields) != 1 {
return Command{Kind: CommandInvalid}, true
}
return Command{Kind: CommandEnable}, true
case "/关闭推理", "/rag":
if len(fields) != 1 {
return Command{Kind: CommandInvalid}, true
}
return Command{Kind: CommandDisable}, true
case "/think":
default:
return Command{}, false
}
if len(fields) == 1 {
return Command{Kind: CommandEnable}, true
}
second := strings.ToLower(fields[1])
switch second {
case "on", "start":
if len(fields) != 2 {
return Command{Kind: CommandInvalid}, true
}
return Command{Kind: CommandEnable}, true
case "off", "end":
if len(fields) != 2 {
return Command{Kind: CommandInvalid}, true
}
return Command{Kind: CommandDisable}, true
default:
query := strings.TrimSpace(value[len(fields[0]):])
if second == "+" {
query = strings.TrimSpace(strings.TrimPrefix(query, "+"))
}
if query == "" {
return Command{Kind: CommandInvalid}, true
}
return Command{Kind: CommandSingle, Query: query}, true
}
}
+100
View File
@@ -0,0 +1,100 @@
package reasoningmode
import "testing"
func TestParseCommandRecognizesPersistentEnableAliases(t *testing.T) {
tests := []string{
"/think",
"/think on",
"/think start",
"/THINK ON",
"/开启推理",
}
for _, input := range tests {
t.Run(input, func(t *testing.T) {
command, ok := ParseCommand(input)
if !ok || command.Kind != CommandEnable || command.Query != "" {
t.Fatalf("ParseCommand(%q)=(%+v,%t), want enable", input, command, ok)
}
})
}
}
func TestParseCommandRecognizesDisableAliases(t *testing.T) {
tests := []string{
"/think off",
"/think end",
"/THINK OFF",
"/关闭推理",
"/rag",
}
for _, input := range tests {
t.Run(input, func(t *testing.T) {
command, ok := ParseCommand(input)
if !ok || command.Kind != CommandDisable || command.Query != "" {
t.Fatalf("ParseCommand(%q)=(%+v,%t), want disable", input, command, ok)
}
})
}
}
func TestParseCommandRecognizesSingleTurnReasoning(t *testing.T) {
command, ok := ParseCommand(" /think 对比 CRA 和 CR 系列 ")
if !ok || command.Kind != CommandSingle || command.Query != "对比 CRA 和 CR 系列" {
t.Fatalf("command=%+v ok=%t", command, ok)
}
}
func TestParseCommandAcceptsDocumentedOptionalPlusSeparator(t *testing.T) {
command, ok := ParseCommand("/think + 分析根因")
if !ok || command.Kind != CommandSingle || command.Query != "分析根因" {
t.Fatalf("command=%+v ok=%t", command, ok)
}
}
func TestParseCommandRecognizesHelpAliases(t *testing.T) {
for _, input := range []string{"/help", "/帮助", "/h", "/H"} {
t.Run(input, func(t *testing.T) {
command, ok := ParseCommand(input)
if !ok || command.Kind != CommandHelp {
t.Fatalf("ParseCommand(%q)=(%+v,%t), want help", input, command, ok)
}
})
}
}
func TestParseCommandRejectsEmbeddedOrSimilarInputs(t *testing.T) {
tests := []string{
"普通问题",
"abc /think on",
"/thinking",
"//think on",
}
for _, input := range tests {
t.Run(input, func(t *testing.T) {
if command, ok := ParseCommand(input); ok {
t.Fatalf("ParseCommand(%q)=(%+v,true), want no command", input, command)
}
})
}
}
func TestParseCommandInterceptsMalformedControlArguments(t *testing.T) {
tests := []string{
"/think on 多余内容",
"/think off 多余内容",
"/think start 多余内容",
"/think end 多余内容",
"/rag 多余内容",
"/开启推理 多余内容",
"/关闭推理 多余内容",
}
for _, input := range tests {
t.Run(input, func(t *testing.T) {
command, ok := ParseCommand(input)
if !ok || command.Kind != CommandInvalid {
t.Fatalf("ParseCommand(%q)=(%+v,%t), want invalid command", input, command, ok)
}
})
}
}
+154
View File
@@ -0,0 +1,154 @@
package reasoningmode
import (
"context"
"errors"
"fmt"
"strings"
"time"
)
const defaultIdleTimeout = 10 * time.Minute
type Scope struct {
TenantKey string
Channel string
ExternalActorID string
}
type TurnCompletion struct {
Scope Scope
TurnID string
Execution ExecutionMode
Answer string
Locale string
Expired bool
At time.Time
Idle time.Duration
}
type Repository interface {
ResolveState(context.Context, Scope, time.Time) (State, bool, error)
Enable(context.Context, Scope, time.Time, time.Duration) (State, error)
Disable(context.Context, Scope, time.Time) (State, bool, error)
SetMaxRounds(context.Context, Scope, int, time.Time) (State, error)
SetHintEnabled(context.Context, Scope, bool, time.Time) (State, error)
CompleteTurn(context.Context, TurnCompletion) (Completion, error)
}
type Decision struct {
Handled bool
Reply string
Query string
AgentID string
Execution ExecutionMode
Expired bool
}
type Service struct {
repo Repository
quickAgentID string
reasoningAgentID string
now func() time.Time
idleTimeout time.Duration
}
func NewService(repo Repository, quickAgentID, reasoningAgentID string) (*Service, error) {
quickAgentID = strings.TrimSpace(quickAgentID)
reasoningAgentID = strings.TrimSpace(reasoningAgentID)
if repo == nil {
return nil, errors.New("reasoning mode repository is required")
}
if quickAgentID == "" || reasoningAgentID == "" {
return nil, errors.New("quick and reasoning agent IDs are required")
}
if quickAgentID == reasoningAgentID {
return nil, errors.New("quick and reasoning agent IDs must differ")
}
return &Service{
repo: repo,
quickAgentID: quickAgentID,
reasoningAgentID: reasoningAgentID,
now: time.Now,
idleTimeout: defaultIdleTimeout,
}, nil
}
func (s *Service) Prepare(ctx context.Context, scope Scope, text string) (Decision, error) {
if err := validateScope(scope); err != nil {
return Decision{}, err
}
query := strings.TrimSpace(text)
if query == "" {
return Decision{}, errors.New("reasoning mode query is required")
}
if command, ok := ParseCommand(query); ok {
switch command.Kind {
case CommandEnable:
state, err := s.repo.Enable(ctx, scope, s.now(), s.idleTimeout)
if err != nil {
return Decision{}, err
}
return Decision{Handled: true, Reply: fmt.Sprintf(
"✅ 已开启【智能推理模式】(计费标准更高)\n持续模式将在%d轮对话后自动关闭,也可随时输入 /think off 手动关闭",
state.MaxRounds,
)}, nil
case CommandDisable:
_, wasReasoning, err := s.repo.Disable(ctx, scope, s.now())
if err != nil {
return Decision{}, err
}
if !wasReasoning {
return Decision{Handled: true, Reply: "当前未开启推理模式,默认是快速问答模式。"}, nil
}
return Decision{Handled: true, Reply: "✅ 已关闭智能推理模式,切回【快速问答模式】"}, nil
case CommandSingle:
return Decision{Query: command.Query, AgentID: s.reasoningAgentID, Execution: ExecutionReasoningSingle}, nil
case CommandHelp:
return Decision{Handled: true, Reply: helpReply()}, nil
default:
return Decision{Handled: true, Reply: "用法:/think <问题>、/think on、/think off。"}, nil
}
}
state, expired, err := s.repo.ResolveState(ctx, scope, s.now())
if err != nil {
return Decision{}, err
}
if state.Mode == ModeReasoning {
return Decision{Query: query, AgentID: s.reasoningAgentID, Execution: ExecutionReasoning}, nil
}
return Decision{Query: query, AgentID: s.quickAgentID, Execution: ExecutionQuick, Expired: expired}, nil
}
func helpReply() string {
return "一、模式说明\n" +
"默认模式:快速问答模式,基于知识库快速准确作答,响应快、成本低,适合信息查询和事实确认。\n" +
"智能推理模式:支持多步思考与工具调用,计费标准更高,适合复杂分析和推导。\n\n" +
"二、模式切换指令\n" +
"/think + 你的问题:仅当前问题使用智能推理\n" +
"/think on:开启持续智能推理模式\n" +
"/think off 或 /rag:关闭并切回快速问答模式\n\n" +
"三、其他常用指令\n" +
"/help:查看本帮助说明\n" +
"/setting 或 /设置:配置语言、自动关闭轮数和提示开关\n\n" +
"只有行首以 / 开头的完整指令会被识别。持续推理模式会在剩余2轮时提醒,到期自动切回快速问答模式。"
}
func (s *Service) Complete(ctx context.Context, input TurnCompletion) (Completion, error) {
if input.At.IsZero() {
input.At = s.now()
}
if input.Idle <= 0 {
input.Idle = s.idleTimeout
}
return s.repo.CompleteTurn(ctx, input)
}
func validateScope(scope Scope) error {
if strings.TrimSpace(scope.TenantKey) == "" || strings.TrimSpace(scope.Channel) == "" || strings.TrimSpace(scope.ExternalActorID) == "" {
return errors.New("tenant, channel and external actor are required")
}
return nil
}
+179
View File
@@ -0,0 +1,179 @@
package reasoningmode
import (
"context"
"strings"
"testing"
"time"
)
type fakeRepository struct {
state State
expired bool
enableCalls int
disableCalls int
completeCalls int
lastCompletion TurnCompletion
}
func (f *fakeRepository) ResolveState(context.Context, Scope, time.Time) (State, bool, error) {
return f.state, f.expired, nil
}
func (f *fakeRepository) Enable(context.Context, Scope, time.Time, time.Duration) (State, error) {
f.enableCalls++
f.state.Mode = ModeReasoning
f.state.RoundsUsed = 0
return f.state, nil
}
func (f *fakeRepository) Disable(context.Context, Scope, time.Time) (State, bool, error) {
f.disableCalls++
wasReasoning := f.state.Mode == ModeReasoning
f.state.Mode = ModeQuick
f.state.RoundsUsed = 0
return f.state, wasReasoning, nil
}
func (f *fakeRepository) SetMaxRounds(context.Context, Scope, int, time.Time) (State, error) {
return f.state, nil
}
func (f *fakeRepository) SetHintEnabled(context.Context, Scope, bool, time.Time) (State, error) {
return f.state, nil
}
func (f *fakeRepository) CompleteTurn(_ context.Context, input TurnCompletion) (Completion, error) {
f.completeCalls++
f.lastCompletion = input
return Completion{Next: f.state}, nil
}
func newTestService(t *testing.T, repo Repository) *Service {
t.Helper()
service, err := NewService(repo, "builtin-quick-answer", "builtin-smart-reasoning")
if err != nil {
t.Fatal(err)
}
service.now = func() time.Time { return time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC) }
return service
}
func testScope() Scope {
return Scope{TenantKey: "tenant", Channel: "dingtalk", ExternalActorID: "staff-1"}
}
func TestPrepareEnablesPersistentReasoningLocally(t *testing.T) {
repo := &fakeRepository{state: DefaultState()}
decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/think on")
if err != nil {
t.Fatal(err)
}
if !decision.Handled || decision.Query != "" || repo.enableCalls != 1 {
t.Fatalf("decision=%+v enableCalls=%d", decision, repo.enableCalls)
}
for _, want := range []string{"已开启【智能推理模式】", "计费标准更高", "10轮", "/think off"} {
if !strings.Contains(decision.Reply, want) {
t.Fatalf("reply=%q missing %q", decision.Reply, want)
}
}
}
func TestPrepareDisablesPersistentReasoningLocally(t *testing.T) {
repo := &fakeRepository{state: State{Mode: ModeReasoning, MaxRounds: 10, HintEnabled: true}}
decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/rag")
if err != nil {
t.Fatal(err)
}
if !decision.Handled || repo.disableCalls != 1 || !strings.Contains(decision.Reply, "已关闭智能推理模式") {
t.Fatalf("decision=%+v disableCalls=%d", decision, repo.disableCalls)
}
}
func TestPrepareFriendlyReplyWhenReasoningAlreadyOff(t *testing.T) {
repo := &fakeRepository{state: DefaultState()}
decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/think off")
if err != nil {
t.Fatal(err)
}
if !decision.Handled || !strings.Contains(decision.Reply, "当前未开启推理模式") {
t.Fatalf("decision=%+v", decision)
}
}
func TestPrepareSingleReasoningDoesNotMutatePersistentState(t *testing.T) {
repo := &fakeRepository{state: DefaultState()}
decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/think 分析根因")
if err != nil {
t.Fatal(err)
}
if decision.Handled || decision.Query != "分析根因" || decision.AgentID != "builtin-smart-reasoning" || decision.Execution != ExecutionReasoningSingle {
t.Fatalf("decision=%+v", decision)
}
if repo.enableCalls != 0 || repo.disableCalls != 0 {
t.Fatalf("unexpected state mutation: %+v", repo)
}
}
func TestPrepareRoutesPersistentAndQuickQuestions(t *testing.T) {
tests := []struct {
name string
state State
agentID string
execution ExecutionMode
}{
{name: "quick", state: DefaultState(), agentID: "builtin-quick-answer", execution: ExecutionQuick},
{name: "reasoning", state: State{Mode: ModeReasoning, MaxRounds: 10, HintEnabled: true}, agentID: "builtin-smart-reasoning", execution: ExecutionReasoning},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
decision, err := newTestService(t, &fakeRepository{state: test.state}).Prepare(context.Background(), testScope(), "普通问题")
if err != nil {
t.Fatal(err)
}
if decision.Handled || decision.Query != "普通问题" || decision.AgentID != test.agentID || decision.Execution != test.execution {
t.Fatalf("decision=%+v", decision)
}
})
}
}
func TestPrepareRoutesExpiredReasoningToQuickWithNotice(t *testing.T) {
repo := &fakeRepository{state: DefaultState(), expired: true}
decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "继续")
if err != nil {
t.Fatal(err)
}
if decision.AgentID != "builtin-quick-answer" || decision.Execution != ExecutionQuick || !decision.Expired {
t.Fatalf("decision=%+v", decision)
}
}
func TestPrepareInterceptsInvalidThinkCommand(t *testing.T) {
decision, err := newTestService(t, &fakeRepository{state: DefaultState()}).Prepare(context.Background(), testScope(), "/think on 多余内容")
if err != nil {
t.Fatal(err)
}
if !decision.Handled || !strings.Contains(decision.Reply, "用法") {
t.Fatalf("decision=%+v", decision)
}
}
func TestPrepareReturnsLocalHelpWithoutStateMutation(t *testing.T) {
repo := &fakeRepository{state: DefaultState()}
decision, err := newTestService(t, repo).Prepare(context.Background(), testScope(), "/help")
if err != nil {
t.Fatal(err)
}
if !decision.Handled {
t.Fatalf("decision=%+v", decision)
}
for _, required := range []string{"快速问答模式", "智能推理模式", "/think + 你的问题", "/think on", "/think off", "/setting"} {
if !strings.Contains(decision.Reply, required) {
t.Fatalf("help=%q missing %q", decision.Reply, required)
}
}
if repo.enableCalls != 0 || repo.disableCalls != 0 {
t.Fatalf("help mutated mode: %+v", repo)
}
}
+105
View File
@@ -0,0 +1,105 @@
package reasoningmode
import (
"errors"
"time"
)
type Mode string
type ExecutionMode string
const (
ModeQuick Mode = "quick"
ModeReasoning Mode = "reasoning"
ExecutionQuick ExecutionMode = "quick"
ExecutionReasoning ExecutionMode = "reasoning"
ExecutionReasoningSingle ExecutionMode = "reasoning_single"
)
var ErrInvalidState = errors.New("invalid reasoning mode state")
type State struct {
Mode Mode
MaxRounds int
RoundsUsed int
HintEnabled bool
LastActivityAt time.Time
ExpiresAt time.Time
OnboardingShown bool
OnboardingShownAt time.Time
}
type Completion struct {
Next State
RoundNumber int
ShowHint bool
AutoClosed bool
ShowOnboarding bool
}
func DefaultState() State {
return State{Mode: ModeQuick, MaxRounds: 10, HintEnabled: true}
}
func EffectiveState(state State, now time.Time) (State, bool) {
if state.Mode != ModeReasoning || state.ExpiresAt.IsZero() || state.ExpiresAt.After(now) {
return state, false
}
state.Mode = ModeQuick
state.RoundsUsed = 0
state.ExpiresAt = time.Time{}
return state, true
}
func ApplySuccessfulTurn(state State, execution ExecutionMode, now time.Time, idleTimeout time.Duration) (Completion, error) {
if err := validateState(state); err != nil {
return Completion{}, err
}
if idleTimeout <= 0 {
return Completion{}, ErrInvalidState
}
if execution != ExecutionQuick && execution != ExecutionReasoning && execution != ExecutionReasoningSingle {
return Completion{}, ErrInvalidState
}
result := Completion{Next: state}
if !state.OnboardingShown {
result.ShowOnboarding = true
result.Next.OnboardingShown = true
result.Next.OnboardingShownAt = now
}
if execution != ExecutionReasoning || state.Mode != ModeReasoning {
return result, nil
}
result.RoundNumber = state.RoundsUsed + 1
result.Next.LastActivityAt = now
if result.RoundNumber >= state.MaxRounds {
result.AutoClosed = true
result.Next.Mode = ModeQuick
result.Next.RoundsUsed = 0
result.Next.ExpiresAt = time.Time{}
return result, nil
}
result.Next.RoundsUsed = result.RoundNumber
result.Next.ExpiresAt = now.Add(idleTimeout)
result.ShowHint = state.HintEnabled && state.MaxRounds-result.RoundNumber == 2
return result, nil
}
func validateState(state State) error {
if state.Mode != ModeQuick && state.Mode != ModeReasoning {
return ErrInvalidState
}
if state.MaxRounds < 1 || state.MaxRounds > 50 {
return ErrInvalidState
}
if state.RoundsUsed < 0 || state.RoundsUsed > state.MaxRounds {
return ErrInvalidState
}
return nil
}
+111
View File
@@ -0,0 +1,111 @@
package reasoningmode
import (
"testing"
"time"
)
func defaultTestState() State {
return State{Mode: ModeQuick, MaxRounds: 10, HintEnabled: true}
}
func TestApplySuccessfulTurnShowsOnboardingOnceInQuickMode(t *testing.T) {
now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC)
result, err := ApplySuccessfulTurn(defaultTestState(), ExecutionQuick, now, 10*time.Minute)
if err != nil {
t.Fatal(err)
}
if !result.ShowOnboarding || result.RoundNumber != 0 || result.AutoClosed || result.ShowHint {
t.Fatalf("result=%+v", result)
}
if !result.Next.OnboardingShown || result.Next.Mode != ModeQuick || result.Next.RoundsUsed != 0 {
t.Fatalf("next=%+v", result.Next)
}
second, err := ApplySuccessfulTurn(result.Next, ExecutionQuick, now.Add(time.Minute), 10*time.Minute)
if err != nil {
t.Fatal(err)
}
if second.ShowOnboarding {
t.Fatal("onboarding must only be shown once")
}
}
func TestApplySuccessfulTurnShowsRemainingTwoHint(t *testing.T) {
now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC)
state := State{Mode: ModeReasoning, MaxRounds: 10, RoundsUsed: 7, HintEnabled: true, OnboardingShown: true}
result, err := ApplySuccessfulTurn(state, ExecutionReasoning, now, 10*time.Minute)
if err != nil {
t.Fatal(err)
}
if result.RoundNumber != 8 || !result.ShowHint || result.AutoClosed {
t.Fatalf("result=%+v", result)
}
if result.Next.Mode != ModeReasoning || result.Next.RoundsUsed != 8 || !result.Next.ExpiresAt.Equal(now.Add(10*time.Minute)) {
t.Fatalf("next=%+v", result.Next)
}
}
func TestApplySuccessfulTurnAutoClosesAtConfiguredLimit(t *testing.T) {
now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC)
state := State{Mode: ModeReasoning, MaxRounds: 10, RoundsUsed: 9, HintEnabled: true, OnboardingShown: true}
result, err := ApplySuccessfulTurn(state, ExecutionReasoning, now, 10*time.Minute)
if err != nil {
t.Fatal(err)
}
if result.RoundNumber != 10 || !result.AutoClosed || result.ShowHint {
t.Fatalf("result=%+v", result)
}
if result.Next.Mode != ModeQuick || result.Next.RoundsUsed != 0 || !result.Next.ExpiresAt.IsZero() {
t.Fatalf("next=%+v", result.Next)
}
}
func TestApplySuccessfulTurnRespectsDisabledHint(t *testing.T) {
state := State{Mode: ModeReasoning, MaxRounds: 10, RoundsUsed: 7, HintEnabled: false, OnboardingShown: true}
result, err := ApplySuccessfulTurn(state, ExecutionReasoning, time.Now(), 10*time.Minute)
if err != nil {
t.Fatal(err)
}
if result.ShowHint {
t.Fatal("disabled hint must remain hidden")
}
}
func TestApplySuccessfulTurnSingleReasoningDoesNotChangePersistentMode(t *testing.T) {
now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC)
state := defaultTestState()
result, err := ApplySuccessfulTurn(state, ExecutionReasoningSingle, now, 10*time.Minute)
if err != nil {
t.Fatal(err)
}
if result.RoundNumber != 0 || result.AutoClosed || result.Next.Mode != ModeQuick || result.Next.RoundsUsed != 0 {
t.Fatalf("result=%+v", result)
}
}
func TestApplySuccessfulTurnDoesNotReenableModeClosedWhileAnswerRan(t *testing.T) {
state := State{Mode: ModeQuick, MaxRounds: 10, HintEnabled: true, OnboardingShown: true}
result, err := ApplySuccessfulTurn(state, ExecutionReasoning, time.Now(), 10*time.Minute)
if err != nil {
t.Fatal(err)
}
if result.RoundNumber != 0 || result.Next.Mode != ModeQuick || result.Next.RoundsUsed != 0 {
t.Fatalf("result=%+v", result)
}
}
func TestEffectiveStateExpiresReasoningWithoutMutatingPreferences(t *testing.T) {
now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC)
state := State{
Mode: ModeReasoning, MaxRounds: 15, RoundsUsed: 4,
HintEnabled: false, OnboardingShown: true, ExpiresAt: now,
}
effective, expired := EffectiveState(state, now)
if !expired || effective.Mode != ModeQuick || effective.RoundsUsed != 0 || !effective.ExpiresAt.IsZero() {
t.Fatalf("effective=%+v expired=%t", effective, expired)
}
if effective.MaxRounds != 15 || effective.HintEnabled || !effective.OnboardingShown {
t.Fatalf("preferences changed on expiry: %+v", effective)
}
}