An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Apply the agent confirmation timeout to question waits
Daniele2b0fba4b6dd
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 8e830ed15d..fb6584e13d 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -823,7 +823,7 @@"agentTimeout": "المهلة","agentTimeoutTip": "إجمالي مهلة جلسة الوكيل، 0 = بلا حد","agentConfirmTimeout": "مهلة التأكيد",- "agentConfirmTimeoutTip": "الرفض التلقائي بعد انتهاء المهلة، 0 = انتظار بلا حد",+ "agentConfirmTimeoutTip": "الرفض التلقائي بعد انتهاء المهلة، وينطبق ذلك أيضًا على مدة انتظار إجابة الأسئلة؛ 0 = انتظار بلا حد","agentMaxRetries": "الحد الأقصى للمحاولات","agentMaxRetriesTip": "الحد الأقصى لمحاولات إعادة طلب API عند الفشل","agentMaxToolCallRounds": "الحد الأقصى لجولات استدعاء الأدوات",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex e86bcc410f..0d45ed9df6 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -823,7 +823,7 @@"agentTimeout": "Timeout","agentTimeoutTip": "Gesamt-Timeout der Agent-Sitzung, 0 = kein Limit","agentConfirmTimeout": "Bestätigungs-Timeout",- "agentConfirmTimeoutTip": "Nach Timeout automatisch ablehnen, 0 = unbegrenzt warten",+ "agentConfirmTimeoutTip": "Nach Timeout automatisch ablehnen; gilt auch für die Wartezeit auf die Antwort des Agenten; 0 = unbegrenzt warten","agentMaxRetries": "Maximale Wiederholungen","agentMaxRetriesTip": "Maximale API-Wiederholungsversuche bei Fehler","agentMaxToolCallRounds": "Max. Werkzeugaufruf-Runden",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 7c23aeed69..f519502bdf 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -823,7 +823,7 @@"agentTimeout": "Timeout","agentTimeoutTip": "0 = no limit","agentConfirmTimeout": "Confirm Timeout",- "agentConfirmTimeoutTip": "Auto reject after timeout, 0 = wait indefinitely",+ "agentConfirmTimeoutTip": "Auto reject after timeout; also applies to how long the agent waits for an answer; 0 = wait indefinitely","agentMaxRetries": "Max Retries","agentMaxRetriesTip": "Max API retry attempts on failure","agentMaxToolCallRounds": "Max Tool Call Rounds",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 6e37f76e1f..670d8f7798 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -823,7 +823,7 @@"agentTimeout": "Tiempo de espera","agentTimeoutTip": "Tiempo de espera total de la sesión del agente, 0 = sin límite","agentConfirmTimeout": "Tiempo de espera de confirmación",- "agentConfirmTimeoutTip": "Rechazo automático tras agotar el tiempo, 0 = esperar sin límite",+ "agentConfirmTimeoutTip": "Rechazo automático tras agotar el tiempo; también se aplica a la espera de la respuesta del agente; 0 = esperar sin límite","agentMaxRetries": "Reintentos máximos","agentMaxRetriesTip": "Reintentos máximos de la API en caso de error","agentMaxToolCallRounds": "Máx. rondas de llamadas a herramientas",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex f72c5d8568..c22d4dddc6 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -823,7 +823,7 @@"agentTimeout": "Délai d'expiration","agentTimeoutTip": "Délai d'expiration total de la session de l'agent, 0 = sans limite","agentConfirmTimeout": "Délai de confirmation",- "agentConfirmTimeoutTip": "Rejet automatique après expiration, 0 = attente illimitée",+ "agentConfirmTimeoutTip": "Rejet automatique après expiration ; s'applique aussi au délai d'attente de la réponse de l'agent ; 0 = attente illimitée","agentMaxRetries": "Nombre max. de tentatives","agentMaxRetriesTip": "Nombre max. de tentatives API en cas d'échec","agentMaxToolCallRounds": "Nombre max. de tours d'appels d'outils",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 9a3b51d7c7..2660a0200e 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -823,7 +823,7 @@"agentTimeout": "זמן קצוב","agentTimeoutTip": "זמן קצוב כולל להפעלת הסוכן, 0 = ללא הגבלה","agentConfirmTimeout": "פג זמן אישור",- "agentConfirmTimeoutTip": "דחייה אוטומטית לאחר פקיעת הזמן, 0 = המתנה ללא הגבלה",+ "agentConfirmTimeoutTip": "דחייה אוטומטית לאחר פקיעת הזמן; חל גם על זמן ההמתנה לתשובת הסוכן; 0 = המתנה ללא הגבלה","agentMaxRetries": "מקסימום ניסיונות חוזרים","agentMaxRetriesTip": "מקסימום ניסיונות חוזרים של API בכשלון","agentMaxToolCallRounds": "מקסימום סיבובי קריאת כלים",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex ebed7bac5b..c8ef515dd1 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -823,7 +823,7 @@"agentTimeout": "समय सीमा","agentTimeoutTip": "एजेंट सत्र की कुल समय सीमा, 0 = कोई सीमा नहीं","agentConfirmTimeout": "पुष्टि समय समाप्ति",- "agentConfirmTimeoutTip": "ऑपरेशन पुष्टिकरण समय समाप्त होने पर स्वचालित रूप से अस्वीकार कर दिया जाएगा, 0 = असीमित प्रतीक्षा",+ "agentConfirmTimeoutTip": "ऑपरेशन पुष्टिकरण समय समाप्त होने पर स्वचालित रूप से अस्वीकार कर दिया जाएगा; यह एजेंट के उत्तर की प्रतीक्षा अवधि पर भी लागू होता है; 0 = असीमित प्रतीक्षा","agentMaxRetries": "अधिकतम पुनः प्रयास","agentMaxRetriesTip": "API अनुरोध विफल होने पर अधिकतम पुनः प्रयास की संख्या","agentMaxToolCallRounds": "अधिकतम टूल कॉल राउंड",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 761b5ca669..232d190ca9 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -823,7 +823,7 @@"agentTimeout": "Batas waktu","agentTimeoutTip": "Batas waktu total sesi agen, 0 = tanpa batas","agentConfirmTimeout": "Batas waktu konfirmasi",- "agentConfirmTimeoutTip": "Tolak otomatis setelah waktu habis, 0 = tunggu tanpa batas",+ "agentConfirmTimeoutTip": "Tolak otomatis setelah waktu habis; juga berlaku untuk waktu tunggu jawaban agen; 0 = tunggu tanpa batas","agentMaxRetries": "Percobaan maksimum","agentMaxRetriesTip": "Percobaan ulang API maksimum saat gagal","agentMaxToolCallRounds": "Maks. putaran panggilan alat",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex a13426109e..082da22ff4 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -823,7 +823,7 @@"agentTimeout": "Timeout","agentTimeoutTip": "Timeout totale della sessione agente, 0 = nessun limite","agentConfirmTimeout": "Timeout conferma",- "agentConfirmTimeoutTip": "Rifiuto automatico dopo la scadenza, 0 = attesa illimitata",+ "agentConfirmTimeoutTip": "Rifiuto automatico dopo la scadenza; vale anche per l'attesa della risposta dell'agente; 0 = attesa illimitata","agentMaxRetries": "Tentativi massimi","agentMaxRetriesTip": "Tentativi massimi API in caso di errore","agentMaxToolCallRounds": "Massimo round di chiamate strumento",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex ceaf7ad96e..2f9115eb96 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -823,7 +823,7 @@"agentTimeout": "タイムアウト","agentTimeoutTip": "エージェント セッション全体のタイムアウト、0 は制限なし","agentConfirmTimeout": "確認タイムアウト",- "agentConfirmTimeoutTip": "タイムアウト後に自動的に拒否、0 は無制限に待機",+ "agentConfirmTimeoutTip": "タイムアウト後に自動的に拒否; エージェントの回答を待つ時間にも適用されます; 0 は無制限に待機","agentMaxRetries": "最大リトライ回数","agentMaxRetriesTip": "API リクエスト失敗時の最大リトライ回数","agentMaxToolCallRounds": "最大ツール呼び出しラウンド数",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 648796c63f..3f9241e4ef 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -823,7 +823,7 @@"agentTimeout": "시간 초과","agentTimeoutTip": "에이전트 세션 전체 시간 초과, 0 은 제한 없음","agentConfirmTimeout": "확인 시간 초과",- "agentConfirmTimeoutTip": "시간 초과 후 자동 거부, 0 은 무제한 대기",+ "agentConfirmTimeoutTip": "시간 초과 후 자동 거부; 에이전트가 답변을 기다리는 시간에도 적용됩니다; 0 은 무제한 대기","agentMaxRetries": "최대 재시도 횟수","agentMaxRetriesTip": "API 요청 실패 시 최대 재시도 횟수","agentMaxToolCallRounds": "최대 도구 호출 라운드",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 7415748f25..ccfe4378b3 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -823,7 +823,7 @@"agentTimeout": "Time-out","agentTimeoutTip": "Totale time-out van de agentsessie, 0 = geen limiet","agentConfirmTimeout": "Bevestigingstime-out",- "agentConfirmTimeoutTip": "Automatisch afwijzen na time-out, 0 = onbeperkt wachten",+ "agentConfirmTimeoutTip": "Automatisch afwijzen na time-out; geldt ook voor hoe lang de agent op een antwoord wacht; 0 = onbeperkt wachten","agentMaxRetries": "Max. pogingen","agentMaxRetriesTip": "Max. API-herhalingspogingen bij fout","agentMaxToolCallRounds": "Max. toolaanroep-rondes",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 4f24868925..8101622615 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -823,7 +823,7 @@"agentTimeout": "Limit czasu","agentTimeoutTip": "Całkowity limit czasu sesji agenta, 0 = bez limitu","agentConfirmTimeout": "Limit czasu potwierdzenia",- "agentConfirmTimeoutTip": "Automatyczne odrzucenie po przekroczeniu czasu, 0 = oczekiwanie bez limitu",+ "agentConfirmTimeoutTip": "Automatyczne odrzucenie po przekroczeniu czasu; dotyczy też czasu oczekiwania agenta na odpowiedź; 0 = oczekiwanie bez limitu","agentMaxRetries": "Maks. liczba ponowień","agentMaxRetriesTip": "Maks. liczba ponownych prób API przy błędzie","agentMaxToolCallRounds": "Maks. liczba rund wywołań narzędzi",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex b02d420bec..9f4eb75c4b 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -823,7 +823,7 @@"agentTimeout": "Tempo limite","agentTimeoutTip": "Tempo limite total da sessão do agente, 0 = sem limite","agentConfirmTimeout": "Tempo limite de confirmação",- "agentConfirmTimeoutTip": "Rejeição automática após expirar o tempo, 0 = aguardar sem limite",+ "agentConfirmTimeoutTip": "Rejeição automática após expirar o tempo; também se aplica ao tempo que o agente espera por uma resposta; 0 = aguardar sem limite","agentMaxRetries": "Tentativas máximas","agentMaxRetriesTip": "Tentativas máximas da API em caso de falha","agentMaxToolCallRounds": "Máx. rodadas de chamadas de ferramentas",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 9242573199..901d6fbe02 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -823,7 +823,7 @@"agentTimeout": "Тайм-аут","agentTimeoutTip": "Общий тайм-аут сессии агента, 0 = без ограничения","agentConfirmTimeout": "Тайм-аут подтверждения",- "agentConfirmTimeoutTip": "Автоматический отказ при истечении времени, 0 = ожидание без ограничения",+ "agentConfirmTimeoutTip": "Автоматический отказ при истечении времени; также применяется ко времени ожидания ответа агентом; 0 = ожидание без ограничения","agentMaxRetries": "Макс. повторов","agentMaxRetriesTip": "Макс. повторных попыток API при сбое","agentMaxToolCallRounds": "Макс. раундов вызова инструментов",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 7b0323f53a..5aa5c829ff 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -823,7 +823,7 @@"agentTimeout": "Časový limit","agentTimeoutTip": "Celkový časový limit relácie agenta, 0 = bez limitu","agentConfirmTimeout": "Časový limit potvrdenia",- "agentConfirmTimeoutTip": "Automatické odmietnutie po uplynutí času, 0 = čakanie bez obmedzenia",+ "agentConfirmTimeoutTip": "Automatické odmietnutie po uplynutí času; platí aj pre čas čakania agenta na odpoveď; 0 = čakanie bez obmedzenia","agentMaxRetries": "Max. počet opakovaní","agentMaxRetriesTip": "Max. počet opakovaných pokusov API pri chybe","agentMaxToolCallRounds": "Max. počet kôl volania nástrojov",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 3e25f9db46..b52cceba80 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -823,7 +823,7 @@"agentTimeout": "หมดเวลา","agentTimeoutTip": "หมดเวลารวมของเซสชันเอเจนต์, 0 = ไม่จำกัด","agentConfirmTimeout": "หมดเวลายืนยัน",- "agentConfirmTimeoutTip": "ปฏิเสธอัตโนมัติเมื่อหมดเวลา, 0 = รอไม่จำกัด",+ "agentConfirmTimeoutTip": "ปฏิเสธอัตโนมัติเมื่อหมดเวลา; ใช้กับระยะเวลาที่เอเจนต์รอคำตอบด้วย; 0 = รอไม่จำกัด","agentMaxRetries": "จำนวนครั้งสูงสุด","agentMaxRetriesTip": "จำนวนครั้งสูงสุดในการลอง API ใหม่เมื่อล้มเหลว","agentMaxToolCallRounds": "รอบการเรียกเครื่องมือสูงสุด",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 0dd7ea45dc..1f6e7deb3b 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -823,7 +823,7 @@"agentTimeout": "Zaman aşımı","agentTimeoutTip": "Agent oturumu toplam zaman aşımı, 0 = sınırsız","agentConfirmTimeout": "Onay zaman aşımı",- "agentConfirmTimeoutTip": "Zaman aşımından sonra otomatik reddet, 0 = sınırsız bekle",+ "agentConfirmTimeoutTip": "Zaman aşımından sonra otomatik reddet; ajanın yanıt bekleme süresi için de geçerlidir; 0 = sınırsız bekle","agentMaxRetries": "Maks. yeniden deneme","agentMaxRetriesTip": "Hata durumunda maks. API yeniden deneme sayısı","agentMaxToolCallRounds": "Maks. araç çağrısı turu",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 4dc784f26c..839de7bacf 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -823,7 +823,7 @@"agentTimeout": "Таймаут","agentTimeoutTip": "Загальний таймаут сесії агента, 0 = без обмежень","agentConfirmTimeout": "Таймаут підтвердження",- "agentConfirmTimeoutTip": "Автоматична відмова після спливу часу, 0 = очікування без обмежень",+ "agentConfirmTimeoutTip": "Автоматична відмова після спливу часу; також застосовується до часу очікування відповіді агентом; 0 = очікування без обмежень","agentMaxRetries": "Макс. повторів","agentMaxRetriesTip": "Макс. повторних спроб API при збої","agentMaxToolCallRounds": "Макс. раундів виклику інструментів",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 7079e71066..8b0dfb29cc 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -823,7 +823,7 @@"agentTimeout": "超时时间","agentTimeoutTip": "智能体会话总超时时间,0 表示不限制","agentConfirmTimeout": "确认超时时间",- "agentConfirmTimeoutTip": "操作确认超时后自动拒绝,0 表示一直等待",+ "agentConfirmTimeoutTip": "操作确认超时后自动拒绝,也作用于智能体提问的等待时间,0 表示一直等待","agentMaxRetries": "最大重试次数","agentMaxRetriesTip": "API 请求失败时的最大重试次数","agentMaxToolCallRounds": "最大工具调用轮数",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 9c90029841..3410e0d85c 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -823,7 +823,7 @@"agentTimeout": "逾時時間","agentTimeoutTip": "智能體會話總超時時間,0 表示不限制","agentConfirmTimeout": "確認超時時間",- "agentConfirmTimeoutTip": "操作確認超時後自動拒絕,0 表示一直等待",+ "agentConfirmTimeoutTip": "操作確認超時後自動拒絕,也作用於智慧體提問的等待時間,0 表示一直等待","agentMaxRetries": "最大重試次數","agentMaxRetriesTip": "API 請求失敗時的最大重試次數","agentMaxToolCallRounds": "最大工具調用輪數",diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex ad9782cb45..c037bb604b 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -163,6 +163,8 @@ const (doomLoopWarnThreshold = 3// doomLoopStopThreshold 是相同签名连续命中时终止 agent 的阈值。doomLoopStopThreshold = 5+ // fallbackQuestionTimeout 是确认超时时间非法(负数)时 question 工具的兜底等待时长。+ fallbackQuestionTimeout = 5 * time.Minute)// toolSignatureKeys 列出各工具里真正"区分一次调用"的关键参数。@@ -1417,7 +1419,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagresultStr = toolInputErr.Error()isErr = true} else if tc.Function.Name == "question" {- resultStr = handleQuestion(ctx, args, roundID, ch, 5*time.Minute)+ resultStr = handleQuestion(ctx, args, roundID, ch, resolveQuestionTimeout(confirmTimeout))} else if registration.isBrowser() {executed := handleBrowserCapability(ctx, tc, registration, args, ch,resolveBrowserCapabilityTimeout(confirmTimeout))@@ -1764,7 +1766,7 @@ func handleQuestion(ctx context.Context, args map[string]any, roundID string, ch} else {return "Question cancelled."}- case <-time.After(timeout):+ case <-optionalAgentDeadline(timeout):if acceptedAnswer, accepted := finishQuestionWait(questionID, ch2); accepted {answer = acceptedAnswer} else {@@ -1830,7 +1832,16 @@ func optionalAgentDeadline(timeout time.Duration) <-chan time.Time {func resolveBrowserCapabilityTimeout(confirmTimeout time.Duration) time.Duration {if confirmTimeout <= 0 {- return 120 * time.Second+ return time.Duration(conf.DefaultAgentConfirmTimeout) * time.Second+ }+ return confirmTimeout+}++// resolveQuestionTimeout 解析 question 工具等待用户作答的时长:确认超时时间为 0 时一直等待,+// 其余情况沿用确认超时时间(调用方已把负数兜底为默认值),因此默认配置下为 600 秒。+func resolveQuestionTimeout(confirmTimeout time.Duration) time.Duration {+ if confirmTimeout <= 0 {+ return fallbackQuestionTimeout}return confirmTimeout}diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.goindex 68e533895a..cb45e01c54 100644--- a/kernel/agent/tools_test.go+++ b/kernel/agent/tools_test.go@@ -24,6 +24,7 @@ import ("time""github.com/sashabaranov/go-openai"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/mcp/tools")@@ -423,11 +424,63 @@ func TestAgentConfirmationDeadlineZeroHasNoLimit(t *testing.T) {if deadline := optionalAgentDeadline(time.Second); deadline == nil {t.Fatal("positive confirmation timeout did not create a deadline")}- if timeout := resolveBrowserCapabilityTimeout(0); timeout != 120*time.Second {+ if timeout := resolveBrowserCapabilityTimeout(0); timeout != time.Duration(conf.DefaultAgentConfirmTimeout)*time.Second {t.Fatalf("zero confirmation timeout disabled the browser capability timeout: %v", timeout)}}+func TestQuestionTimeoutReusesConfirmTimeout(t *testing.T) {+ if timeout := resolveQuestionTimeout(0); timeout != fallbackQuestionTimeout {+ t.Fatalf("zero confirmation timeout did not use the fallback question timeout: %v", timeout)+ }+ if timeout := resolveQuestionTimeout(90 * time.Second); timeout != 90*time.Second {+ t.Fatalf("positive confirmation timeout was not reused by question: %v", timeout)+ }+}++func TestQuestionWithoutDeadlineWaitsForAnswer(t *testing.T) {+ events := make(chan AgentEvent, 1)+ resultCh := make(chan string, 1)+ go func() {+ resultCh <- handleQuestion(context.Background(), map[string]any{"questions": []any{}}, "test-round", events, 0)+ }()++ event := <-events+ if event.Type != "question" || event.QuestionID == "" {+ t.Fatalf("unexpected question event: %#v", event)+ }+ if !AnswerQuestion(event.QuestionID, []string{"no deadline answer"}) {+ t.Fatal("question answer was rejected")+ }+ select {+ case result := <-resultCh:+ if result != "no deadline answer" {+ t.Fatalf("unexpected question result: %q", result)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("question without a deadline did not wait for the answer")+ }+}++func TestQuestionTimeoutReportsTimeout(t *testing.T) {+ events := make(chan AgentEvent, 1)+ resultCh := make(chan string, 1)+ go func() {+ resultCh <- handleQuestion(context.Background(), map[string]any{"questions": []any{}}, "test-round", events, 50*time.Millisecond)+ }()++ event := <-events+ if event.Type != "question" || event.QuestionID == "" {+ t.Fatalf("unexpected question event: %#v", event)+ }+ if result := <-resultCh; result != "No answer received (timed out)." {+ t.Fatalf("unexpected question result: %q", result)+ }+ if AnswerQuestion(event.QuestionID, []string{"late answer"}) {+ t.Fatal("answer was accepted after the question timed out")+ }+}+func TestQuestionAndBrowserCapabilityResultsAreAcceptedOnce(t *testing.T) {const questionID = "test-question"questionCh := make(chan QuestionAnswer, 1)diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex 89c1448571..1e0a9807df 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -208,7 +208,7 @@ func newAgentSessionDeadline(timeoutSeconds int) (*time.Timer, <-chan time.Time)func resolveAgentConfirmTimeout(timeoutSeconds int) time.Duration {if timeoutSeconds < 0 {- return 120 * time.Second+ return conf.DefaultAgentConfirmTimeout * time.Second}return time.Duration(timeoutSeconds) * time.Second}diff --git a/kernel/api/agent_timeout_test.go b/kernel/api/agent_timeout_test.goindex 42f2453621..2cc50e028f 100644--- a/kernel/api/agent_timeout_test.go+++ b/kernel/api/agent_timeout_test.go@@ -11,6 +11,8 @@ package apiimport ("testing""time"++ "github.com/siyuan-note/siyuan/kernel/conf")func TestNewAgentSessionDeadlineZeroHasNoLimit(t *testing.T) {@@ -24,13 +26,16 @@ func TestNewAgentSessionDeadlineZeroHasNoLimit(t *testing.T) {}func TestResolveAgentConfirmTimeout(t *testing.T) {+ if conf.DefaultAgentConfirmTimeout != 600 {+ t.Fatalf("default confirmation timeout changed: %d", conf.DefaultAgentConfirmTimeout)+ }if timeout := resolveAgentConfirmTimeout(0); timeout != 0 {t.Fatalf("zero confirmation timeout was changed: %v", timeout)}if timeout := resolveAgentConfirmTimeout(30); timeout != 30*time.Second {t.Fatalf("positive confirmation timeout was not preserved: %v", timeout)}- if timeout := resolveAgentConfirmTimeout(-1); timeout != 120*time.Second {+ if timeout := resolveAgentConfirmTimeout(-1); timeout != time.Duration(conf.DefaultAgentConfirmTimeout)*time.Second {t.Fatalf("negative confirmation timeout did not use the default: %v", timeout)}}diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex 2b2ed7b67b..1d2c360fba 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -39,6 +39,9 @@ type AI struct {Providers []*Provider `json:"providers"`}+// DefaultAgentConfirmTimeout 是智能体确认超时时间的默认值(秒),也用于智能体提问的等待时长。+const DefaultAgentConfirmTimeout = 600+type Agent struct {ModelID string `json:"modelId"`SessionTimeout int `json:"sessionTimeout"`@@ -181,7 +184,7 @@ func defaultAgent() *Agent {return &Agent{SessionTimeout: 600,StreamIdleTimeout: 120,- ConfirmTimeout: 120,+ ConfirmTimeout: DefaultAgentConfirmTimeout,MaxRetries: 3,Temperature: 1.0,MaxCompletionTokens: 0,