diff --git a/.github/i18n/README.ar.md b/.github/i18n/README.ar.md index 3fce449c..e6efaf03 100644 --- a/.github/i18n/README.ar.md +++ b/.github/i18n/README.ar.md @@ -561,7 +561,9 @@ memory({ mode: "import", inputPath: "./memories.json" }); اختياريًا ثبّت متغير استدلال للنموذج بـ `"opencodeVariant": "xhigh"` (مثلًا لـ grok-4.7). يُطبَّق على استدعاءات LLM الداخلية للمكون الإضافي (ملخصات الالتقاط التلقائي، تعلّم الملف، تنظيف الملف)، بما في ذلك عندما يكون `opencodeModel` هو `"inherit"`، حتى يمكن للعمل الخلفي استخدام مستوى استدلال مختلف عن الجلسة التفاعلية. -نماذج الاستدلال البطيئة (أو مطالبات الملف الكبيرة جدًا) يمكن أن تتجاوز ميزانية المخرجات المنظمة الافتراضية البالغة 90 ثانية. عيّن `"opencodeTimeoutMs"` (بالمللي ثانية) لتمديدها لاستدعاءات المخرجات المنظمة الداخلية (ملخصات الالتقاط التلقائي، تعلّم الملف) — مثلًا `"opencodeTimeoutMs": 180000` لمدة 3 دقائق. تُقيَّد القيم إلى 10000..600000؛ يبقى الافتراضي 90000. تُحوَّل السلاسل الرقمية. يستخدم تنظيف الملف مهلة منفصلة أطول. +نماذج الاستدلال البطيئة (أو مطالبات الملف الكبيرة جدًا) يمكن أن تتجاوز ميزانية المخرجات المنظمة الافتراضية البالغة 90 ثانية. عيّن `"opencodeTimeoutMs"` (بالمللي ثانية) لتمديدها لاستدعاءات المخرجات المنظمة الداخلية (ملخصات الالتقاط التلقائي، تعلّم الملف) — مثلًا `"opencodeTimeoutMs": 180000` لمدة 3 دقائق. تُقيَّد القيم إلى 10000..600000؛ يبقى الافتراضي 90000. تُحوَّل السلاسل الرقمية. + +مهل تنظيف الملف منفصلة: تنظيف API الخارجي/اليدوي افتراضيًا 60 ثانية عبر `"userProfileCleanupTimeoutMs"` (نفس التقييد 10000..600000؛ مثلًا `"userProfileCleanupTimeoutMs": 180000`). يحتفظ تنظيف جلسة OpenCode بميزانية ثابتة 300 ثانية. تُشتق مهلة خمول HTTP في Node كـ `max(userProfileCleanupTimeoutMs, 300000) + 30000`، ويسمح جلب واجهة الويب لـ `/ai-cleanup` حتى 630 ثانية حتى لا تقطع أي طبقة الموعد النهائي الخارجي المرفوع. المزودون المدعومون: أي مزود يدرجه `opencode providers list` (مثل `anthropic`، `openai`، `github-copilot`، `openrouter`، ...). diff --git a/.github/i18n/README.de.md b/.github/i18n/README.de.md index aaff76a7..6575474d 100644 --- a/.github/i18n/README.de.md +++ b/.github/i18n/README.de.md @@ -563,7 +563,9 @@ Das Plugin stellt strukturierte Output-Requests an die Session-API von opencode, Optional eine Reasoning-Variante des Modells mit `"opencodeVariant": "xhigh"` pinnen (z. B. für grok-4.7). Sie gilt für die internen LLM-Aufrufe des Plugins (Auto-Capture-Zusammenfassungen, Profil-Lernen, Profil-Cleanup), auch wenn `opencodeModel` `"inherit"` ist, sodass Hintergrundarbeit ein anderes Reasoning-Level als die interaktive Sitzung nutzen kann. -Langsame Reasoning-Modelle (oder sehr große Profil-Prompts) können das Standard-Budget von 90 s für strukturierte Ausgabe überschreiten. `"opencodeTimeoutMs"` (Millisekunden) setzen, um es für interne Structured-Output-Aufrufe (Auto-Capture-Zusammenfassungen, Profil-Lernen) zu verlängern — z. B. `"opencodeTimeoutMs": 180000` für 3 Minuten. Werte werden auf 10000..600000 geklemmt; der Standard bleibt 90000. Numerische Strings werden coerced. Profil-Cleanup nutzt ein separates, längeres Timeout. +Langsame Reasoning-Modelle (oder sehr große Profil-Prompts) können das Standard-Budget von 90 s für strukturierte Ausgabe überschreiten. `"opencodeTimeoutMs"` (Millisekunden) setzen, um es für interne Structured-Output-Aufrufe (Auto-Capture-Zusammenfassungen, Profil-Lernen) zu verlängern — z. B. `"opencodeTimeoutMs": 180000` für 3 Minuten. Werte werden auf 10000..600000 geklemmt; der Standard bleibt 90000. Numerische Strings werden coerced. + +Profil-Cleanup-Timeouts sind separat: externes/manuelles API-Cleanup defaultet auf 60 s über `"userProfileCleanupTimeoutMs"` (gleiche Klemme 10000..600000; z. B. `"userProfileCleanupTimeoutMs": 180000`). OpenCode-Session-Cleanup behält ein festes 300-s-Budget. Das Node-HTTP-Idle-Timeout wird als `max(userProfileCleanupTimeoutMs, 300000) + 30000` abgeleitet, und der Web-UI-Fetch für `/ai-cleanup` erlaubt bis 630 s, damit keine Schicht ein erhöhtes externes Deadline unterbietet. Unterstützte Provider: jeder von `opencode providers list` gelistete Provider (z. B. `anthropic`, `openai`, `github-copilot`, `openrouter`, ...). diff --git a/.github/i18n/README.fr.md b/.github/i18n/README.fr.md index f77a12c7..bdf84aa1 100644 --- a/.github/i18n/README.fr.md +++ b/.github/i18n/README.fr.md @@ -496,7 +496,9 @@ Le plugin émet des requêtes à sortie structurée vers l'API de session d'open Optionnellement, épinglez une variante de raisonnement du modèle avec `"opencodeVariant": "xhigh"` (p. ex. pour grok-4.7). Elle s'applique aux appels LLM internes du plugin (résumés d'auto-capture, apprentissage du profil, nettoyage du profil), y compris quand `opencodeModel` vaut `"inherit"`, pour que le travail d'arrière-plan puisse utiliser un niveau de raisonnement différent de la session interactive. -Les modèles de raisonnement lents (ou les très gros prompts de profil) peuvent dépasser le budget de sortie structurée par défaut de 90 s. Définissez `"opencodeTimeoutMs"` (millisecondes) pour l'étendre pour les appels internes à sortie structurée (résumés d'auto-capture, apprentissage du profil) — p. ex. `"opencodeTimeoutMs": 180000` pour 3 minutes. Les valeurs sont bornées à 10000..600000 ; le défaut reste 90000. Les chaînes numériques sont converties. Le nettoyage du profil utilise un timeout séparé, plus long. +Les modèles de raisonnement lents (ou les très gros prompts de profil) peuvent dépasser le budget de sortie structurée par défaut de 90 s. Définissez `"opencodeTimeoutMs"` (millisecondes) pour l'étendre pour les appels internes à sortie structurée (résumés d'auto-capture, apprentissage du profil) — p. ex. `"opencodeTimeoutMs": 180000` pour 3 minutes. Les valeurs sont bornées à 10000..600000 ; le défaut reste 90000. Les chaînes numériques sont converties. + +Les timeouts de nettoyage du profil sont séparés : le nettoyage API externe/manuel vaut 60 s par défaut via `"userProfileCleanupTimeoutMs"` (même borne 10000..600000 ; p. ex. `"userProfileCleanupTimeoutMs": 180000`). Le nettoyage via session OpenCode garde un budget fixe de 300 s. Le timeout d'inactivité HTTP Node est dérivé comme `max(userProfileCleanupTimeoutMs, 300000) + 30000`, et le fetch Web UI de `/ai-cleanup` autorise jusqu'à 630 s pour qu'aucune couche ne sous-coupe une échéance externe relevée. Fournisseurs pris en charge : tout fournisseur listé par `opencode providers list` (p. ex. `anthropic`, `openai`, `github-copilot`, `openrouter`, ...). diff --git a/.github/i18n/README.nl.md b/.github/i18n/README.nl.md index 2be9b829..07bb13f6 100644 --- a/.github/i18n/README.nl.md +++ b/.github/i18n/README.nl.md @@ -567,7 +567,9 @@ De plugin stuurt structured-output-verzoeken naar de session-API van opencode in Optioneel kun je een model-reasoningvariant vastzetten met `"opencodeVariant": "xhigh"` (bijv. voor grok-4.7). Die wordt toegepast op de interne LLM-calls van de plugin (auto-capture-samenvattingen, profiel-leren, profielopschoning), ook wanneer `opencodeModel` `"inherit"` is, zodat achtergrondwerk een ander reasoningniveau kan gebruiken dan de interactieve sessie. -Trage reasoningmodellen (of zeer grote profielprompts) kunnen het standaard 90 s structured-output-budget overschrijden. Stel `"opencodeTimeoutMs"` (milliseconden) in om het te verlengen voor interne structured-output-calls (auto-capture-samenvattingen, profiel-leren) — bijv. `"opencodeTimeoutMs": 180000` voor 3 minuten. Waarden worden geclampt tot 10000..600000; de standaard blijft 90000. Numerieke strings worden gecoeerd. Profielopschoning gebruikt een aparte, langere timeout. +Trage reasoningmodellen (of zeer grote profielprompts) kunnen het standaard 90 s structured-output-budget overschrijden. Stel `"opencodeTimeoutMs"` (milliseconden) in om het te verlengen voor interne structured-output-calls (auto-capture-samenvattingen, profiel-leren) — bijv. `"opencodeTimeoutMs": 180000` voor 3 minuten. Waarden worden geclampt tot 10000..600000; de standaard blijft 90000. Numerieke strings worden gecoeerd. + +Profielopschonings-timeouts zijn apart: externe/handmatige API-opschoning default naar 60 s via `"userProfileCleanupTimeoutMs"` (zelfde clamp 10000..600000; bijv. `"userProfileCleanupTimeoutMs": 180000`). OpenCode-sessie-opschoning houdt een vast 300 s-budget. De Node HTTP-idle-timeout wordt afgeleid als `max(userProfileCleanupTimeoutMs, 300000) + 30000`, en de Web UI-fetch voor `/ai-cleanup` staat tot 630 s toe zodat geen laag een verhoogde externe deadline ondermijnt. Ondersteunde providers: elke provider uit `opencode providers list` (bijv. `anthropic`, `openai`, `github-copilot`, `openrouter`, ...). diff --git a/.github/i18n/README.tr.md b/.github/i18n/README.tr.md index 02e553a8..ccd42e05 100644 --- a/.github/i18n/README.tr.md +++ b/.github/i18n/README.tr.md @@ -565,7 +565,9 @@ Eklenti, sağlayıcı uç noktalarını doğrudan çağırmak yerine yapılandı İsteğe bağlı olarak `"opencodeVariant": "xhigh"` ile bir model muhakeme varyantını sabitleyin (örn. grok-4.7 için). Eklentinin dahili LLM çağrılarına uygulanır (otomatik yakalama özetleri, profil öğrenme, profil temizleme); `opencodeModel` `"inherit"` olsa bile, böylece arka plan çalışması etkileşimli oturumdan farklı bir muhakeme düzeyi kullanabilir. -Yavaş muhakeme modelleri (veya çok büyük profil prompt’ları) varsayılan 90 sn yapılandırılmış çıktı bütçesini aşabilir. Dahili yapılandırılmış çıktı çağrıları (otomatik yakalama özetleri, profil öğrenme) için uzatmak üzere `"opencodeTimeoutMs"` (milisaniye) ayarlayın — örn. 3 dakika için `"opencodeTimeoutMs": 180000`. Değerler 10000..600000’e sıkıştırılır; varsayılan 90000 kalır. Sayısal dizgeler zorlanır. Profil temizleme ayrı, daha uzun bir zaman aşımı kullanır. +Yavaş muhakeme modelleri (veya çok büyük profil prompt’ları) varsayılan 90 sn yapılandırılmış çıktı bütçesini aşabilir. Dahili yapılandırılmış çıktı çağrıları (otomatik yakalama özetleri, profil öğrenme) için uzatmak üzere `"opencodeTimeoutMs"` (milisaniye) ayarlayın — örn. 3 dakika için `"opencodeTimeoutMs": 180000`. Değerler 10000..600000’e sıkıştırılır; varsayılan 90000 kalır. Sayısal dizgeler zorlanır. + +Profil temizleme zaman aşımları ayrıdır: harici/manuel API temizleme `"userProfileCleanupTimeoutMs"` ile varsayılan 60 sn’dir (aynı 10000..600000 sıkıştırma; örn. `"userProfileCleanupTimeoutMs": 180000`). OpenCode oturum temizliği sabit 300 sn bütçesini korur. Node HTTP boşta kalma zaman aşımı `max(userProfileCleanupTimeoutMs, 300000) + 30000` olarak türetilir ve Web UI `/ai-cleanup` fetch’i 630 sn’ye kadar izin verir; böylece hiçbir katman yükseltilmiş harici son tarihi altından kesmez. Desteklenen sağlayıcılar: `opencode providers list` tarafından listelenen herhangi bir sağlayıcı (örn. `anthropic`, `openai`, `github-copilot`, `openrouter`, ...). diff --git a/.github/i18n/README.zh.md b/.github/i18n/README.zh.md index d20bca46..06b456ce 100644 --- a/.github/i18n/README.zh.md +++ b/.github/i18n/README.zh.md @@ -536,7 +536,9 @@ memory({ mode: "import", inputPath: "./memories.json" }); 可选地用 `"opencodeVariant": "xhigh"` 固定模型推理变体(例如用于 grok-4.7)。它会应用于插件的内部 LLM 调用(自动捕获摘要、画像学习、画像清理),包括当 `opencodeModel` 为 `"inherit"` 时,以便后台工作可以使用与交互式会话不同的推理级别。 -慢速推理模型(或非常大的画像提示)可能超过默认的 90 秒结构化输出预算。设置 `"opencodeTimeoutMs"`(毫秒)可为内部结构化输出调用(自动捕获摘要、画像学习)延长 — 例如 `"opencodeTimeoutMs": 180000` 表示 3 分钟。值钳制在 10000..600000;默认保持 90000。数字字符串会被强制转换。画像清理使用单独的、更长的超时。 +慢速推理模型(或非常大的画像提示)可能超过默认的 90 秒结构化输出预算。设置 `"opencodeTimeoutMs"`(毫秒)可为内部结构化输出调用(自动捕获摘要、画像学习)延长 — 例如 `"opencodeTimeoutMs": 180000` 表示 3 分钟。值钳制在 10000..600000;默认保持 90000。数字字符串会被强制转换。 + +画像清理超时是单独的:外部/手动 API 清理默认 60 秒,通过 `"userProfileCleanupTimeoutMs"`(同样钳制在 10000..600000;例如 `"userProfileCleanupTimeoutMs": 180000`)。OpenCode 会话清理保持固定的 300 秒预算。Node HTTP 空闲超时按 `max(userProfileCleanupTimeoutMs, 300000) + 30000` 推导,Web UI 对 `/ai-cleanup` 的 fetch 最多允许 630 秒,这样任一层都不会低于提高后的外部截止时间。 支持的提供商:`opencode providers list` 列出的任何提供商(例如 `anthropic`、`openai`、`github-copilot`、`openrouter` 等)。 diff --git a/README.md b/README.md index 89f4291b..d25e70dd 100644 --- a/README.md +++ b/README.md @@ -624,7 +624,9 @@ The plugin issues structured-output requests to opencode's session API instead o Optionally pin a model reasoning variant with `"opencodeVariant": "xhigh"` (e.g. for grok-4.7). It is applied to the plugin's internal LLM calls (auto-capture summaries, profile learning, profile cleanup), including when `opencodeModel` is `"inherit"`, so background work can use a different reasoning level than the interactive session. -Slow reasoning models (or very large profile prompts) can exceed the default 90 s structured-output budget. Set `"opencodeTimeoutMs"` (milliseconds) to extend it for internal structured-output calls (auto-capture summaries, profile learning) — e.g. `"opencodeTimeoutMs": 180000` for 3 minutes. Values are clamped to 10000..600000; the default stays 90000. Numeric strings are coerced. Profile cleanup uses a separate, longer timeout. +Slow reasoning models (or very large profile prompts) can exceed the default 90 s structured-output budget. Set `"opencodeTimeoutMs"` (milliseconds) to extend it for internal structured-output calls (auto-capture summaries, profile learning) — e.g. `"opencodeTimeoutMs": 180000` for 3 minutes. Values are clamped to 10000..600000; the default stays 90000. Numeric strings are coerced. + +Profile cleanup timeouts are separate: external/manual-API cleanup defaults to 60 s via `"userProfileCleanupTimeoutMs"` (same 10000..600000 clamp; e.g. `"userProfileCleanupTimeoutMs": 180000`). OpenCode-session cleanup keeps a fixed 300 s budget. The Node HTTP idle timeout is derived as `max(userProfileCleanupTimeoutMs, 300000) + 30000`, and the Web UI `/ai-cleanup` fetch allows up to 630 s so neither layer undercuts a raised external deadline. Supported providers: any provider listed by `opencode providers list` (e.g. `anthropic`, `openai`, `github-copilot`, `openrouter`, ...). diff --git a/opencode-mem.example.jsonc b/opencode-mem.example.jsonc index 4ce12dc7..f87c5269 100644 --- a/opencode-mem.example.jsonc +++ b/opencode-mem.example.jsonc @@ -482,6 +482,10 @@ "userProfileAutoCleanupEnabled": true, // Number of analyzed user prompts between automatic AI cleanup runs "userProfileAutoCleanupInterval": 100, + // Abort deadline (ms) for external/manual-API profile cleanup (default 60000, clamped to 10000..600000). + // OpenCode-session cleanup keeps a separate longer timeout (300000). Node HTTP idle timeout + // is derived as max(this, opencode cleanup) + 30000 so the server never undercuts the provider call. + // "userProfileCleanupTimeoutMs": 180000, // Enable LLM validation of existing preferences against recent behavior. // When enabled, each analysis round checks if top-5 preferences still match recent prompts. diff --git a/src/config.ts b/src/config.ts index c63db442..d0996081 100644 --- a/src/config.ts +++ b/src/config.ts @@ -142,9 +142,10 @@ interface OpenCodeMemConfig { /** * Timeout in milliseconds for the plugin's internal structured-output LLM * calls (auto-capture summaries, profile learning). Profile cleanup keeps - * its own longer timeout. Clamped to 10000..600000; non-number/non-finite - * values (and non-numeric strings) fall back to the 90000 default. Numeric - * strings like "180000" are coerced. + * its own longer timeout (see `userProfileCleanupTimeoutMs` for the external + * path). Clamped to 10000..600000; non-number/non-finite values (and + * non-numeric strings) fall back to the 90000 default. Numeric strings like + * "180000" are coerced. */ opencodeTimeoutMs?: number; aiSessionRetentionDays?: number; @@ -188,6 +189,12 @@ interface OpenCodeMemConfig { userProfileMinEvidenceForRetention?: number; userProfileAutoCleanupEnabled?: boolean; userProfileAutoCleanupInterval?: number; + /** + * Abort deadline (ms) for external/manual-API profile cleanup. Default 60000, + * clamped to 10000..600000. OpenCode-session cleanup keeps its own longer + * timeout. The Node HTTP idle timeout is derived above this value. + */ + userProfileCleanupTimeoutMs?: number; userProfileValidationEnabled?: boolean; showAutoCaptureToasts?: boolean; showUserProfileToasts?: boolean; @@ -405,6 +412,7 @@ const DEFAULTS: Required< userProfileMinEvidenceForRetention: 3, userProfileAutoCleanupEnabled: true, userProfileAutoCleanupInterval: 100, + userProfileCleanupTimeoutMs: 60_000, userProfileValidationEnabled: false, showAutoCaptureToasts: true, showUserProfileToasts: true, @@ -916,6 +924,10 @@ const CONFIG_TEMPLATE = `{ "userProfileAutoCleanupEnabled": true, // Number of analyzed user prompts between automatic AI cleanup runs "userProfileAutoCleanupInterval": 100, + // Abort deadline (ms) for external/manual-API profile cleanup (default 60000, clamped to 10000..600000). + // OpenCode-session cleanup keeps a separate longer timeout (300000). Node HTTP idle timeout + // is derived as max(this, opencode cleanup) + 30000 so the server never undercuts the provider call. + // "userProfileCleanupTimeoutMs": 180000, // Enable LLM validation of existing preferences against recent behavior. // When enabled, each analysis round checks if top-5 preferences still match recent prompts. @@ -1184,16 +1196,44 @@ export const OPENCODE_TIMEOUT_MS_DEFAULT = 90_000; * clamped to [OPENCODE_TIMEOUT_MS_MIN, OPENCODE_TIMEOUT_MS_MAX]. */ export function normalizeOpencodeTimeoutMs(value: unknown): number { + return normalizeClampedTimeoutMs(value, { + min: OPENCODE_TIMEOUT_MS_MIN, + max: OPENCODE_TIMEOUT_MS_MAX, + fallback: OPENCODE_TIMEOUT_MS_DEFAULT, + }); +} + +export const USER_PROFILE_CLEANUP_TIMEOUT_MS_MIN = 10_000; +export const USER_PROFILE_CLEANUP_TIMEOUT_MS_MAX = 600_000; +export const USER_PROFILE_CLEANUP_TIMEOUT_MS_DEFAULT = 60_000; + +/** + * External profile-cleanup abort deadline: non-number/non-finite values fall + * back to the default (numeric strings are coerced first), otherwise clamped + * to [USER_PROFILE_CLEANUP_TIMEOUT_MS_MIN, USER_PROFILE_CLEANUP_TIMEOUT_MS_MAX]. + */ +export function normalizeUserProfileCleanupTimeoutMs(value: unknown): number { + return normalizeClampedTimeoutMs(value, { + min: USER_PROFILE_CLEANUP_TIMEOUT_MS_MIN, + max: USER_PROFILE_CLEANUP_TIMEOUT_MS_MAX, + fallback: USER_PROFILE_CLEANUP_TIMEOUT_MS_DEFAULT, + }); +} + +function normalizeClampedTimeoutMs( + value: unknown, + opts: { min: number; max: number; fallback: number } +): number { let numeric = value; if (typeof value === "string") { const trimmed = value.trim(); - if (trimmed.length === 0) return OPENCODE_TIMEOUT_MS_DEFAULT; + if (trimmed.length === 0) return opts.fallback; numeric = Number(trimmed); } if (typeof numeric !== "number" || !Number.isFinite(numeric)) { - return OPENCODE_TIMEOUT_MS_DEFAULT; + return opts.fallback; } - return Math.min(OPENCODE_TIMEOUT_MS_MAX, Math.max(OPENCODE_TIMEOUT_MS_MIN, numeric)); + return Math.min(opts.max, Math.max(opts.min, numeric)); } /** @@ -1512,6 +1552,9 @@ function buildConfig(fileConfig: OpenCodeMemConfig) { userProfileAutoCleanupEnabled: fileConfig.userProfileAutoCleanupEnabled ?? DEFAULTS.userProfileAutoCleanupEnabled, userProfileAutoCleanupInterval, + userProfileCleanupTimeoutMs: normalizeUserProfileCleanupTimeoutMs( + fileConfig.userProfileCleanupTimeoutMs + ), userProfileValidationEnabled: fileConfig.userProfileValidationEnabled ?? DEFAULTS.userProfileValidationEnabled, userProfileStaleDays: fileConfig.userProfileStaleDays ?? DEFAULTS.userProfileStaleDays, diff --git a/src/services/request-timeouts.ts b/src/services/request-timeouts.ts index 35e0a2c0..36cfd054 100644 --- a/src/services/request-timeouts.ts +++ b/src/services/request-timeouts.ts @@ -1,8 +1,33 @@ +/** Default abort deadline for external (manual API) profile cleanup. */ export const EXTERNAL_PROFILE_CLEANUP_TIMEOUT_MS = 60_000; + +/** Abort deadline for OpenCode-session profile cleanup. */ export const OPENCODE_PROFILE_CLEANUP_TIMEOUT_MS = 300_000; const HTTP_TIMEOUT_GRACE_MS = 30_000; -export const NODE_HTTP_IDLE_TIMEOUT_MS = - Math.max(EXTERNAL_PROFILE_CLEANUP_TIMEOUT_MS, OPENCODE_PROFILE_CLEANUP_TIMEOUT_MS) + - HTTP_TIMEOUT_GRACE_MS; +/** + * Max clamp for `userProfileCleanupTimeoutMs` (and the Web UI fetch budget for + * `/ai-cleanup`). Keep the browser timeout at least this high so a raised + * backend deadline is never undercut by the frontend. + */ +export const USER_PROFILE_CLEANUP_TIMEOUT_MS_MAX = 600_000; + +/** Web UI fetch timeout for POST `/ai-cleanup` (covers max backend + grace). */ +export const WEB_AI_CLEANUP_FETCH_TIMEOUT_MS = + USER_PROFILE_CLEANUP_TIMEOUT_MS_MAX + HTTP_TIMEOUT_GRACE_MS; + +/** + * Node `server.timeout` must sit above every cleanup deadline so the HTTP idle + * timer does not abort a still-running provider call. + */ +export function resolveNodeHttpIdleTimeoutMs( + externalCleanupTimeoutMs: number = EXTERNAL_PROFILE_CLEANUP_TIMEOUT_MS +): number { + return ( + Math.max(externalCleanupTimeoutMs, OPENCODE_PROFILE_CLEANUP_TIMEOUT_MS) + HTTP_TIMEOUT_GRACE_MS + ); +} + +/** Default idle timeout when no config is loaded yet. */ +export const NODE_HTTP_IDLE_TIMEOUT_MS = resolveNodeHttpIdleTimeoutMs(); diff --git a/src/services/user-profile/ai-cleanup.ts b/src/services/user-profile/ai-cleanup.ts index 0904da7b..1299e347 100644 --- a/src/services/user-profile/ai-cleanup.ts +++ b/src/services/user-profile/ai-cleanup.ts @@ -2,10 +2,7 @@ import type { UserProfileData } from "./types.js"; import { CONFIG } from "../../config.js"; import { log } from "../logger.js"; import { loadOpencodeProvider } from "../ai/opencode-provider-loader.js"; -import { - EXTERNAL_PROFILE_CLEANUP_TIMEOUT_MS, - OPENCODE_PROFILE_CLEANUP_TIMEOUT_MS, -} from "../request-timeouts.js"; +import { OPENCODE_PROFILE_CLEANUP_TIMEOUT_MS } from "../request-timeouts.js"; import { applySafeExtraParams } from "../ai/providers/base-provider.js"; export interface AICleanupResult { @@ -265,7 +262,7 @@ async function callViaExternalAPI( Authorization: `Bearer ${CONFIG.memoryApiKey}`, }, body: JSON.stringify(requestBody), - signal: AbortSignal.timeout(EXTERNAL_PROFILE_CLEANUP_TIMEOUT_MS), + signal: AbortSignal.timeout(CONFIG.userProfileCleanupTimeoutMs), }); log("AI cleanup: external API http done", { httpMs: Date.now() - t0, status: response.status }); diff --git a/src/services/web-server.ts b/src/services/web-server.ts index 9b6bfb66..bcf74898 100644 --- a/src/services/web-server.ts +++ b/src/services/web-server.ts @@ -8,7 +8,8 @@ import { corsPreflightResponse, disallowedCorsResponse, isAllowedBrowserOrigin } import { assertWebServerNetworkAuth, authorizeApiRequest } from "./web-api-auth.js"; import { getOrCreateAuthToken, isAuthorizedApiRequest } from "./auth-token.js"; import { WebAuth } from "./web-auth.js"; -import { NODE_HTTP_IDLE_TIMEOUT_MS } from "./request-timeouts.js"; +import { CONFIG } from "../config.js"; +import { resolveNodeHttpIdleTimeoutMs } from "./request-timeouts.js"; import { handleListTags, handleListMemories, @@ -185,7 +186,7 @@ function serveFetch(opts: { // rebind after a crashed predecessor left orphaned sockets behind. server.listen({ port: opts.port, host: opts.hostname, reuseAddr: true, exclusive: false }); server.unref(); - server.timeout = NODE_HTTP_IDLE_TIMEOUT_MS; + server.timeout = resolveNodeHttpIdleTimeoutMs(CONFIG.userProfileCleanupTimeoutMs); server.keepAliveTimeout = 10000; server.headersTimeout = 11000; diff --git a/tests/ai-cleanup.test.ts b/tests/ai-cleanup.test.ts index f8318650..e23e637b 100644 --- a/tests/ai-cleanup.test.ts +++ b/tests/ai-cleanup.test.ts @@ -123,6 +123,7 @@ mock.module(${JSON.stringify(configUrl)}, () => ({ memoryModel: ${withExternalApi ? '"gpt-ext"' : "undefined"}, memoryApiUrl: ${withExternalApi ? '"http://example.test/v1"' : "undefined"}, memoryApiKey: "test-key", + userProfileCleanupTimeoutMs: 60_000, memoryExtraParams: { enable_thinking: false, top_p: 0.7, diff --git a/tests/config-resolution.test.ts b/tests/config-resolution.test.ts index cdfe94ca..b5d7c439 100644 --- a/tests/config-resolution.test.ts +++ b/tests/config-resolution.test.ts @@ -285,6 +285,39 @@ describe("project-scoped config resolution", () => { expect(CONFIG.opencodeTimeoutMs).toBe(90000); }); + it("parses userProfileCleanupTimeoutMs with clamping and default fallback", () => { + existsSpy = spyOn(fs, "existsSync").mockImplementation((p) => + normalizePath(p).includes(".config/opencode/opencode-mem") + ); + readSpy = spyOn(fs, "readFileSync"); + + readSpy.mockReturnValue(JSON.stringify({ userProfileCleanupTimeoutMs: 180000 }) as any); + initConfig("/some/project"); + expect(CONFIG.userProfileCleanupTimeoutMs).toBe(180000); + + readSpy.mockReturnValue(JSON.stringify({ userProfileCleanupTimeoutMs: 500 }) as any); + initConfig("/some/project"); + expect(CONFIG.userProfileCleanupTimeoutMs).toBe(10000); + + readSpy.mockReturnValue(JSON.stringify({ userProfileCleanupTimeoutMs: 9_999_999 }) as any); + initConfig("/some/project"); + expect(CONFIG.userProfileCleanupTimeoutMs).toBe(600000); + + readSpy.mockReturnValue( + JSON.stringify({ userProfileCleanupTimeoutMs: Number.POSITIVE_INFINITY }) as any + ); + initConfig("/some/project"); + expect(CONFIG.userProfileCleanupTimeoutMs).toBe(60000); + + readSpy.mockReturnValue(JSON.stringify({ userProfileCleanupTimeoutMs: "180000" }) as any); + initConfig("/some/project"); + expect(CONFIG.userProfileCleanupTimeoutMs).toBe(180000); + + readSpy.mockReturnValue(JSON.stringify({}) as any); + initConfig("/some/project"); + expect(CONFIG.userProfileCleanupTimeoutMs).toBe(60000); + }); + it("parses autoCaptureProviderOrder with default fallback", () => { existsSpy = spyOn(fs, "existsSync").mockImplementation((p) => normalizePath(p).includes(".config/opencode/opencode-mem") diff --git a/tests/config.test.ts b/tests/config.test.ts index 4ea67fda..aeb89cff 100644 --- a/tests/config.test.ts +++ b/tests/config.test.ts @@ -171,6 +171,7 @@ describe("config", () => { expect(CONFIG.userProfileMinEvidenceForRetention).toBe(3); expect(CONFIG.userProfileAutoCleanupEnabled).toBe(true); expect(CONFIG.userProfileAutoCleanupInterval).toBe(100); + expect(CONFIG.userProfileCleanupTimeoutMs).toBe(60000); }); it("should have toast settings as booleans", () => { diff --git a/tests/web-server-request-lifecycle.test.ts b/tests/web-server-request-lifecycle.test.ts index 68689cec..a44bcb85 100644 --- a/tests/web-server-request-lifecycle.test.ts +++ b/tests/web-server-request-lifecycle.test.ts @@ -5,6 +5,8 @@ import { EXTERNAL_PROFILE_CLEANUP_TIMEOUT_MS, NODE_HTTP_IDLE_TIMEOUT_MS, OPENCODE_PROFILE_CLEANUP_TIMEOUT_MS, + USER_PROFILE_CLEANUP_TIMEOUT_MS_MAX, + resolveNodeHttpIdleTimeoutMs, } from "../src/services/request-timeouts.js"; class RequestStub extends EventEmitter { @@ -66,5 +68,9 @@ describe("Node web request lifecycle", () => { it("keeps the HTTP timeout above every cleanup deadline", () => { expect(NODE_HTTP_IDLE_TIMEOUT_MS).toBeGreaterThan(EXTERNAL_PROFILE_CLEANUP_TIMEOUT_MS); expect(NODE_HTTP_IDLE_TIMEOUT_MS).toBeGreaterThan(OPENCODE_PROFILE_CLEANUP_TIMEOUT_MS); + + const raised = resolveNodeHttpIdleTimeoutMs(USER_PROFILE_CLEANUP_TIMEOUT_MS_MAX); + expect(raised).toBeGreaterThan(USER_PROFILE_CLEANUP_TIMEOUT_MS_MAX); + expect(raised).toBeGreaterThan(OPENCODE_PROFILE_CLEANUP_TIMEOUT_MS); }); }); diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 01e5fa37..0e56c49e 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -40,9 +40,10 @@ export async function fetchAPI( ): Promise> { try { const controller = new AbortController(); + // /ai-cleanup must outlive userProfileCleanupTimeoutMs (max 600s) + server grace. const timeoutMs = options.timeout || - (options.method === "POST" && endpoint.includes("/ai-cleanup") ? 180000 : 60000); + (options.method === "POST" && endpoint.includes("/ai-cleanup") ? 630000 : 60000); const { timeout: _timeout, headers: extraHeaders, ...fetchOptions } = options; const timeoutId = setTimeout(() => controller.abort(), timeoutMs); const response = await fetch(endpoint, { diff --git a/web/src/lib/components/explorer/AiCleanupDialog.svelte b/web/src/lib/components/explorer/AiCleanupDialog.svelte index 9ef641d1..21afff8f 100644 --- a/web/src/lib/components/explorer/AiCleanupDialog.svelte +++ b/web/src/lib/components/explorer/AiCleanupDialog.svelte @@ -157,7 +157,8 @@ const result = await fetchAPI("/api/user-profile/ai-cleanup", { method: "POST", body: JSON.stringify({ includeIds: ids, profileVersion: profile?.version }), - timeout: 180000, + // Covers max userProfileCleanupTimeoutMs (600s) + HTTP idle grace (30s). + timeout: 630000, }); if ( !(await toastApiResult(result, { failKey: "toast-ai-cleanup-failed", translate: i18n.t })) ||