Commit Graph

59 Commits

Author SHA1 Message Date
matevip
9fd5843dda fix(llm): pin OpenAI-compatible HTTP client to HTTP/1.1 (#89) 2026-05-11 11:22:23 +08:00
matevip
00098fe5f1 feat(agent,channel): scrub fake generated-file URLs + paste-body hint for public-account articles 2026-05-10 19:15:44 +08:00
matevip
c2aecf18ef feat(agent,llm): multimodal sidecar routing for unsupported attachments (#87) 2026-05-09 16:41:26 +08:00
matevip
80cb3c84eb fix(agent): decouple framework recursion limit from per-agent max_iterations 2026-05-05 13:06:40 +08:00
matevip
be1fc86836 feat(agents): pixelart icons, per-role colors, runtime identity merge, locale templates 2026-05-04 15:26:02 +08:00
matevip
42d406ffc8 fix(agent): drop brittle output policing, add evidence-grounded long-task safeguards 2026-05-04 11:55:44 +08:00
matevip
3d50b9c132 feat(skill): catalog sort + usage stats 2026-05-04 11:55:35 +08:00
matevip
66f09a968a feat(chat-stream): streaming UX overhaul + multi-agent stability layer 2026-05-03 17:15:02 +08:00
matevip
bc417d00ef chore: neutralize internal references in code comments and migrations 2026-05-02 15:42:10 +08:00
matevip
55f4ba1195 feat(llm): per-Model HTTP read-timeout override 2026-05-02 15:40:59 +08:00
matevip
92bd8e9b6e feat(agent): re-enable per-Agent model override 2026-05-02 15:40:24 +08:00
matevip
eaacb3a78f fix(agent): include tools schema in context-window budget 2026-05-02 15:40:03 +08:00
matevip
7ca568c69b fix(skill): knowledge wrappers + provider routing + feature gates 2026-05-01 09:49:37 +08:00
matevip
d927521d51 feat(skill): install/uninstall split + Requirements API + provider router 2026-05-01 09:48:59 +08:00
matevip
688b37b652 feat(skill): features matrix + effective-tool expansion 2026-05-01 09:48:39 +08:00
matevip
47bdb97a3a fix(agent): per-model multimodal capability resolution (issue #44) 2026-04-30 17:25:51 +08:00
matevip
101aa3209e fix(skill): stop the LLM from calling skill names as tools (issue #46)
When a user-installed skill (e.g. RedisOps) was bound to an agent, the
model frequently called the skill name directly as a tool, hit
"Tool not found: RedisOps", and either gave up or fell back to shell
guessing. Two compounding causes:

1. The system prompt block injected by SkillRuntimeService listed each
   skill as `- **RedisOps** — desc`, which is the same format used for
   tool catalogs and primed the model to call the names directly. The
   "how to use" instructions referenced `read_skill_file` /
   `run_skill_script` — names that don't exist in the tool registry,
   so even a compliant LLM couldn't follow them.

2. ToolExecutionExecutor's `callback == null` branches returned a bare
   "Tool not found: <name>" string. The model had no recovery signal
   and no hint that the name it called was actually a skill.

Fix is two-layered:

- Prompt rewrite (SkillRuntimeService.buildSkillPromptEnhancement): lead
  with an explicit warning that skills are NOT directly callable, use the
  correct camelCase tool names (readSkillFile / runSkillScript), include
  a concrete worked example anchored to the first enabled skill, and
  render the listing as a markdown table so it stops looking like a
  callable tool list. listAvailableSkills tool description and output
  follow the same pattern.

- Runtime safety net (ToolExecutionExecutor): when toolCallbackMap.get
  misses, check if the requested name (case-insensitive) matches an
  active skill. If so, return a precise hint telling the LLM the right
  invocation pattern instead of the bare error. Wired through both the
  main execute path and the pre-approved replay path. SkillRuntimeService
  is attached via a setter from AgentGraphBuilder so the executor's many
  legacy constructors stay untouched, and it's nullable so isolated
  tests still work.

Adds 5 unit tests covering: skill match -> hint, case-insensitive match,
no-match -> bare error, no SkillRuntimeService wired -> bare error,
pre-approved replay path -> hint.

Reported and reproduced by @pipima9950-glitch in issue #46.
2026-04-30 16:36:30 +08:00
matevip
6390abdecc fix(llm): apply read timeout to streaming chat WebClient (openai-compat + anthropic) 2026-04-30 08:54:46 +08:00
matevip
1864801c90 fix(tool): browser_use Windows compat + stop LLM treating it as web search 2026-04-30 08:54:15 +08:00
matevip
e759ad4a1b sync: settings UI polish, channel reliability fixes, DeepSeek cross-turn fix
- Settings → Models: inline API key, frosted drawer, dark-mode polish, provider icons, i18n sweep
- WeChat Work channel: rebuild HttpClient on reconnect, dedup failure signals, route auth_succeed errcode!=0 through failure handler
- Channel framework: per-adapter error isolation, QR auth SPI, health indicators
- Agent: patch cross-turn assistants for DeepSeek thinking-mode
- GitHub: bilingual issue templates with required fields
2026-04-29 11:22:47 +08:00
matevip
b4697f2806 fix(cron): post-deploy bug bundle — flakiness, scheduler, channel UI
User-reported field issues + a deeper code audit revealed multiple
overlapping bugs in the prior cron-channel delivery change. This fixes
all six.

#1 — Concurrency race on ToolExecutionExecutor (root cause of 'sometimes
   succeeds, sometimes fails' tool calls). The volatile instance fields
   currentRequesterId / currentWorkspaceBasePath / currentChatOrigin
   were shared by every conversation routed through the same per-agent
   executor; one user mid-build-loop while another's execute()
   overwrote the field would cross-contaminate the captured values into
   PreparedToolCall. Fix: kill the instance fields, thread
   origin/requester/workspace as method params straight into
   PreparedToolCall snapshot. Comment pins the rule so it cannot regress.

#2 — CHAT_ORIGIN missing from KeyStrategyFactory (latent timebomb,
   masked by spring-ai-alibaba-graph-core's non-filtering builder path).
   Without an addStrategy registration, multi-node state merges in long
   ReAct / Plan-Execute loops drop the key, ActionNode reads
   ChatOrigin.EMPTY, and the cron persists with channel_id=NULL. Also
   caught 4 more keys that were latently unregistered:
   WORKSPACE_BASE_PATH, STOP_REQUESTED, RETURN_DIRECT_TRIGGERED,
   DIRECT_TOOL_OUTPUTS. All five now registered in both ReAct and
   Plan-Execute factories.

#3 — CronJobs UI didn't surface channel binding. CronJobDTO carried
   channelId / deliveryConfig but the list page never rendered them.
   Added: (a) 'channel' column on list page, (b) channel + targetId
   rows in the detail modal, (c) backend batch-loads channel names via
   ChannelMapper.selectBatchIds so the column shows the human-readable
   name, (d) i18n keys (zh + en), (e) channelName field on TS CronJob
   type.

#4a — DingTalk targetId expiry. ChannelChatOriginFactory.resolveTargetId
   used to prefer ChannelMessage.replyToken which for DingTalk encodes
   a sessionWebhook URL that expires ~90 minutes after the inbound
   message. Cron persisted with that webhook then dies with 401/403 and
   marks NOT_DELIVERED forever. Fix: prefer the stable chatId, fall
   back to senderId — both work indefinitely via DingTalk's Robot API.

#4b — Scheduler pool exhaustion under long LLM. CronJobService's
   ThreadPoolTaskScheduler ran with poolSize=4 AND the LLM call lived
   on the scheduler thread. Four concurrent crons saturated the pool
   and the 5th silently missed its tick. Fix: keep scheduler tiny (it
   just fires triggers) and offload runAgent to a dedicated
   virtual-thread executor (cron-execute-* threads). LLM workload is
   I/O-bound — virtual threads scale to thousands at trivial cost.

#5 — Minor latent bugs:
   - AbstractCronResultDelivery.claimRun used .in(... 'NONE','PENDING',null),
     but SQL IN never matches NULL. Rewrote as IS NULL OR IN
     (NONE,PENDING) so legacy pre-V57 rows can still claim.
   - CronDeliveryListener.onCompletedRaw was an empty @EventListener
     with a wrong-headed comment about test fallbackExecution. Removed.
   - CronJobTool.resolveAgentId silently returned 1L when origin
     lacked an agentId — would silently bind to whatever agent #1
     happens to be. Replaced with explicit error so wiring bugs surface
     immediately instead of producing scheduled-but-never-runs crons.

State-key registration guard. New StateKeyRegistrationCoverageTest
scans MateClawStateKeys via reflection and parses
AgentGraphBuilder.java to extract every
.addStrategy(MateClawStateKeys.X, ...). Asserts every non-_NODE
constant appears in at least one factory. Caught the 4 unregistered
keys above on first run; will catch any future 'forgot to register'
regression.

Tests: 33 unit/arch tests + 27 regression in touched areas — all green.
Vue typecheck clean.

Refs: #25, #16
2026-04-28 21:45:07 +08:00
matevip
69f065e212 fix(llm): support Volcano Ark base URLs and surface friendly errors
- Generalize the OpenAI-compatible chat/models path resolver so any
  baseUrl ending in /v{N} (Ark /v3, Zhipu /v4, ...) drops the duplicate
  /v1 prefix. Volcano Engine test-connection and chat were posting to
  /api/v3/v1/chat/completions and getting 404.
- Replace the six pre-seeded Doubao alias rows (doubao-1.5-*) with five
  valid Ark direct-call ids (doubao-seed-1-8-251228 etc.) and flip
  support_model_discovery=TRUE so users can refresh their account's
  actual catalog. Aliases were marketing names, not API names, so every
  call hit InvalidEndpointOrModel.NotFound.
- Translate Ark business errors into actionable Chinese hints: include
  the response body in the error chain, match ModelNotOpen and
  InvalidEndpointOrModel codes, extract the offending model id, and
  classify them as MODEL_NOT_FOUND so failover skips retries.
2026-04-28 19:26:58 +08:00
matevip
c0c642380a feat(llm): provider liveness model + honor requireApiKey on chat path
Phase 1 of the model-module refactor: combine pool / cooldown / probe-
completion signals into a single Liveness state surfaced through the
provider DTO, so the dropdown stops listing providers that are provably
unreachable. Zero schema change; one PR backend + frontend.

Backend
- Liveness enum with five mutually-exclusive states: LIVE, COOLDOWN,
  REMOVED, UNPROBED, UNCONFIGURED. Computed in ModelProviderService
  from AvailableProviderPool / ProviderHealthTracker / ProviderInitProbe
  snapshots batched once per listProviders() call.
- ProviderInitProbe.hasBeenProbed exposes a monotonic Set so the UI
  can distinguish 'still booting' from 'probed and removed' — without
  it the startup window flashes false REMOVED states.
- ProviderInfoDTO gains liveness + unavailableReason +
  cooldownRemainingMs + lastProbedAtMs. The legacy 'available' boolean
  stays but is now derived from liveness == LIVE so the chat fallback
  walker and the dropdown agree about what's usable.
- ProviderInitProbe injected into ModelProviderService via
  ObjectProvider to break the startup cycle (probe already depends on
  the service).

Frontend
- ProviderInfo type extended with liveness + the three detail fields.
- ModelSelector filters UNCONFIGURED + REMOVED out of the dropdown,
  shows COOLDOWN / UNPROBED with a status dot and dimmed rows that the
  user can still click to override.
- ProviderCard renders a five-state badge driven by liveness instead
  of the old configured + pool-entry combo. Reprobe button now keys
  off liveness in {REMOVED, COOLDOWN}.
- useProviders drops loadProviderPool / providerPool — pool data ships
  inline on each ProviderInfo, saves a round trip per page load and
  keeps a single source of truth.
- i18n: 8 new keys across zh-CN and en-US for liveness labels and the
  cooldown countdown tooltips.

Bonus fix (discovered during verification): AgentGraphBuilder.buildOpenAiApi
hard-required a usable API key on every OpenAI-compat provider, ignoring
the per-provider requireApiKey flag. That bug stranded keyless local
runtimes (LM Studio / MLX / llama.cpp) the moment a user actually
launched them; Ollama only worked by accident because its seed row
carries a placeholder string in api_key. keyRequired now honors
requireApiKey, and Spring AI's NoopApiKey is used when no key is needed
so the Authorization header is omitted entirely.

Test
- ModelProviderServiceLivenessTest covers all five Liveness states +
  the probe-bean-absent fallback branch.
- vip.mate.llm.** suite (118 tests) green; vue-tsc clean.
- End-to-end browser sanity: 27 raw providers reduce to 6 LIVE groups
  in the chat dropdown; LM Studio / MLX / llama.cpp render REMOVED red
  badges with reprobe buttons; cloud providers without keys show
  UNCONFIGURED.
2026-04-28 14:59:11 +08:00
matevip
4898b79d49 fix(agent): strip tool_choice="auto" so strict OpenAI-compatible servers accept the request
Some self-hosted OpenAI-compatible serving frameworks return a 400 Bad Request
with a generic Pydantic "body=None / Field required" error when the outbound
request carries tool_choice="auto" but the server was launched without an
auto-tool-choice opt-in flag. The error message hides the real cause: the
request is rejected at validation time before the body is parsed, so the
upstream client sees only the generic body-missing error.

Per the OpenAI spec, omitting tool_choice when tools is non-empty is
functionally equivalent to "auto" — the server defaults to auto-pick.
Adding a stripAutoToolChoice patcher to the buildOpenAiApi chain:

- changes nothing on compliant servers (OpenAI / DashScope / DeepSeek / Kimi
  default to auto when tools are present)
- unblocks strict OpenAI-compatible self-hosted endpoints

Explicit values other than "auto" ({"none", "required", or a function
descriptor}) are passed through unchanged.

Run on both chatCompletionEntity and chatCompletionStream paths so both
buffered and streaming calls benefit.
2026-04-27 20:35:24 +08:00
matevip
cc3c9a8618 fix(ux): preserve in-flight turn on tab switch + raise max_iterations cap to 100
Three small but high-impact fixes that all surfaced together while
verifying the long-form generation flow.

1. ChatConsole onBeforeUnmount no longer kills the backend turn.
   Previously, switching tabs / route navigation / any cause that
   unmounted the chat view called stopChatGeneration(), which POSTs
   /chat/{cid}/stop and aborts the in-flight LLM call. The user
   reported a turn dying mid-generation just from switching pages.
   Replaced with resetForNewConversation() — front-end SSE disconnect
   only, no /stop. Backend keeps running; pollActivity / status probe
   reconnects on return. Aligns with the existing comment in
   selectConversation: "let A's backend agent run continue running."

2. Agent max_iterations raised 25 → 100 with a hard ceiling.
   The previous 25-step ceiling caused LimitExceededNode to fire on
   substantive multi-tool tasks (document generation + image conversion
   + retry loops). 100 matches QwenPaw's _MAX_MAX_ITERATIONS upper
   bound. New plumbing:
   - BaseAgent.MAX_ITERATIONS_HARD_CEILING = 100 public constant
   - BaseAgent default field 25 → 100 (Java-side fallback)
   - AgentGraphBuilder clamps any per-agent DB override to the
     ceiling at runtime; if the row holds 200, runtime sees 100 and
     a WARN is logged with the original value.
   - V47 migration (h2 + mysql) idempotently bumps the three default
     seeded agents (1000000001, 1000000002, 1000000003) only if they
     still hold the old defaults (25 / 20). User-customized values
     are not touched.
   - data-en/zh/-mysql-en/-mysql-zh seed files updated to 100 for
     fresh installs.

3. DocxRenderTool tells the LLM not to prepend a host to the URL.
   DeepSeek and Claude have both been observed wrapping the
   /api/v1/files/generated/{id} relative path returned by renderDocx
   into an absolute URL with a hallucinated domain (e.g.
   https://ai-tools-system.com/...), breaking the download link in
   the rendered chat bubble. The tool's return string now appends an
   explicit "must use the relative path verbatim, do not add any
   https:// or http:// prefix" instruction, which Claude and
   DeepSeek both honor.
2026-04-27 08:17:17 +08:00
matevip
fcdb3fc15e fix(agent): break self-replicating 400, narration, args truncation, queue drop
A series of cross-cutting stability fixes that surfaced together
during a long debugging session.

reasoning_content / Claude prefill self-replicating 400:

- ChatController persists typed errors (content starts with '[错误] ')
  with status='error', so the failure text stops being re-sent as
  multi-turn context — DeepSeek thinking 400 ('reasoning_content
  must be passed back') and Claude 400 ('does not support assistant
  message prefill') used to recursively re-create themselves every
  retry by polluting history.
- BaseAgent.sanitizeForLlm filters status='error' / '[错误] ' prefix
  assistant messages from history before LLM dispatch.
- BaseAgent.fetchHistoryMessages defensively drops trailing
  AssistantMessages — Claude rejects assistant-tail prompts.
- NodeStreamingChatHelper.dropTrailingAssistant runs the same
  defense at every doStreamCall pre-egress, so the in-turn
  summarizing→reasoning transition (which leaves an assistant
  scaffold at the tail) doesn't trip Claude either.
- AgentGraphBuilder.FallbackPolicy.DEEPSEEK switched (null,true,true)
  → (' ',false,true), aligning with KIMI/OPENAI's tolerant ' '
  fallback. The previous 'force explicit 400' design was the
  self-replicating loop's prime mover.

narration + tool args truncation:

- ReasoningNode.DEFAULT_MAX_OUTPUT_TOKENS 4096 → 16384. The 4k cap
  was decapitating renderDocx tool_call args mid-stream when the
  model emitted a long content field on top of thinking content;
  the resulting 'invalid JSON' aborted execution silently.
- ReasoningNode appends a hermes-style TOOL_USE_ENFORCEMENT clause
  to every system prompt: 'when you say you will perform an action,
  call the tool now in the same response — narration is a protocol
  violation'. Treats 'now I will generate the docx' (and never
  actually calling renderDocx) as a forbidden pattern.
- ToolExecutionExecutor.normalizeToolExecutionError reframes the
  JSON-truncated error as actionable instructions: 're-call the
  same tool now with shorter content or split into multiple
  sequential calls; do NOT describe the result as text'.

side fixes from the same evening:

- ChatController doOnComplete skips completionPublisher.publish
  when isError=true, keeping memory extraction off the garbage path.
- ChatController doOnComplete queued-message guard simplified to
  'cr.queuedInput() != null', matching the other 4 sites in the
  controller. The previous 'isInterruptFollowup || !wasStopped'
  guard silently dropped queued messages when the user did
  Stop-then-Enqueue (wasStopped=true && interruptType=null), losing
  the freshly-typed follow-up message.
- prompts/graph/summarize-system.txt now distinguishes 'single
  task' (default; output one cohesive summary) from 'multiple
  independent sub-tasks' (use the子任务 N format). Stops the
  summarizer from inventing '子任务 1: PRO-027' decomposition for
  unitary requests like 'write me a project proposal'.
2026-04-27 07:51:01 +08:00
matevip
1d5bb58e9b fix(anthropic): allow ANTHROPIC_CLAUDE_CODE in StateGraph whitelist 2026-04-26 08:34:09 +08:00
matevip
84370566de test(agent): cover patchReasoningContent consumer 2026-04-24 18:16:12 +08:00
matevip
155bab1739 fix(llm): skip unconfigured provider when resolving default model 2026-04-20 21:50:01 +08:00
matevip
af8f712986 fix(failover): source fallback chain from the pool, not is_default flags
Two related changes that align buildFallbackChain with how users actually
think about failover.

1) Source = configured providers (was: only providers with fallback_priority > 0)
   Earlier the chain was strictly "providers the user explicitly opted in via
   fallback_priority > 0". A healthy in-pool provider with priority=0 was
   silently excluded — surprising since the pool was supposed to be the source
   of truth for "what is usable". After this change:
     - Candidates  = every configured provider
     - Pool gating = same as before (in-pool members only at build time;
                     runtime walker re-checks)
     - Order       = agent prefs (PR-3) → fallback_priority asc (>0) →
                     priority==0 alphabetical
   So fallback_priority is now purely an ordering hint, never an exclusion.

2) Per-provider model picker = default OR first-enabled (was: default only)
   Previously a provider was skipped if no chat model on it had is_default=true.
   That is admin friction with no benefit — every provider had to be visited in
   Settings just to mark a default before it could appear in failover. New
   pickFallbackModel():
     - first try getDefaultModelByProvider — user explicit pick wins
     - otherwise take the first enabled chat model on the provider
     - skip only if neither exists

User-visible effect on the deployment that surfaced this:
  - kimi-code primary fails (401 — real auth issue, separate from this bug)
  - Pool short-circuits primary → walker fires
  - Walker now sees dashscope (in-pool) AND ollama (in-pool) as candidates,
    even though neither has fallback_priority set
  - dashscope first enabled qwen model is picked → request succeeds via
    dashscope without anyone touching Settings

45 failover-related tests still green (unit-level chain-build behavior is
backward-compatible; only the candidate set and model-selection lookups
changed, both broadening the chain rather than narrowing it).
2026-04-19 20:34:58 +08:00
matevip
6c15622b59 refactor(llm): RFC-009 PR-0b — migrate DashScope + Anthropic helpers out of AgentGraphBuilder
PR-0 only installed the strategy seam; the actual ~600 LOC of provider-
specific construction stayed in AgentGraphBuilder as transitional public
helpers. PR-0b moves the DashScope + Anthropic halves into their builders
proper. (OpenAI larger refactor — 5 sub-helpers including Kimi/o-series
special cases — is left for a follow-up PR-0c.)

AgentDashScopeChatModelBuilder now owns:
  - buildDashScopeApi (with provider/env/reflection key+url fallback chain)
  - buildDashScopeOptions (model/temp/max-tokens/topP + built-in search)
  - normalizeDashScopeBaseUrl (strip /compatible-mode/, return null for SDK default)
  - readApiKeyFromDefaultChatModel + readBaseUrlFromDefaultChatModel +
    readDashScopeApiFromDefaultChatModel (reflection-based final fallback)
  - isBuiltinSearchEnabled (renamed from isDashScopeSearchEnabled, called
    by AgentGraphBuilder.build via the now-injected dashScopeBuilder ref)

AgentAnthropicChatModelBuilder now owns:
  - buildAnthropicApi (key validation, applyHttpTimeouts duplicated locally)
  - buildAnthropicOptions (extended-thinking budget mapping low/medium/high/max
    → 4k/8k/16k/32k, temperature=1 enforcement, RFC-014 prompt cache options)

AgentGraphBuilder dropped:
  - DashScope: ~120 LOC (api + options + 4 helpers + isDashScopeSearchEnabled)
  - Anthropic: ~75 LOC (api + options)
  - DashScopeChatModel + DashScopeConnectionProperties fields (unused after move)
  - Deprecated single-fallback buildFallbackModel (no callers, superseded
    by buildFallbackChain since RFC-009 PR-1)
  - 5 imports for moved DashScope/Anthropic types

Net: -154 LOC in AgentGraphBuilder (1721 → 1567), +372 across the two new
builders. Strategy seam is now real for 3 of 4 protocols (ChatGPT was
already standalone, OpenAI is PR-0c). 220/220 tests still green — no
behavior change.
2026-04-19 19:22:57 +08:00
matevip
3d213eb281 chore: sync multiple commits from private dev
Covers 15 upstream commits (private mirror → public):

Multi-provider failover (RFC-009):
- PR-0: extract ChatModelBuilder strategy seam
- PR-1a: AvailableProviderPool data structure
- PR-1b: startup provider liveness probe + 4 protocol strategies
- PR-1c: wire AvailableProviderPool into runtime chat-model selection
- PR-1d: provider pool REST endpoint + UI badges
- PR-1e: manual reprobe trigger + auto-reprobe on provider config change
- PR-3: per-agent provider preferences (agents can override the
  org-wide fallback chain)

Wiki subsystem (RFC-029~033):
- Relation model, resilient background jobs, light-weight processing
  path, retrieval enhancement, frontend redesign (single landing commit)
- Follow-up fixes: null guards + stats query + i18n polish, move
  WikiProcessingJobMapper to repository/ for @MapperScan, align
  implementation with RFC-029~031 spec
- Copy pass: replace "富化 / enrich" wording with clearer "链接 / link"
- Style: switch enrich/repair buttons to @element-plus/icons-vue
2026-04-19 18:37:44 +08:00
matevip
3b11a3def6 fix(failover): AUTH_ERROR triggers fallback chain + UI splits provider 401 from session expiry
Two related issues from the Kimi-401 user report:

1. Backend (NodeStreamingChatHelper): a primary AUTH_ERROR (e.g. Kimi 401
   with an invalid API key) returned immediately without trying the
   fallback chain — a fallback provider with a different, valid key
   never got a chance. Even with DashScope correctly configured as the
   fallback, the user chat dead-ended on a 401.

   The original assumption ("auth never self-heals so do not retry")
   holds for the primary same-model retry loop but is wrong for the
   fallback chain — different providers have different keys. Apply the
   same break-into-fallback policy that BILLING and MODEL_NOT_FOUND
   already use. recordPrimary(false) is preserved so the cooldown
   counter still accumulates.

2. Frontend (chatError.ts + i18n): the error-text matching for
   /认证|auth|unauthorized|401/i was so broad it matched the substring
   "auth" inside URLs like https://api.kimi.com/.../auth, classifying
   any model 401 as user "session expired" and rendering the misleading
   "页面将自动跳转到登录页" copy. (The redirect itself only fires from
   /api/v1/auth/* axios paths and SSE-connection 401s, not from this
   payload-text path — but the copy alone is the worst kind of false
   alarm.)

   Add a new ChatErrorCategory provider_auth_error and split the
   pattern matching: narrow auth_expired (HTTP 401 / 登录已过期 /
   session expired / 凭证失效) is matched FIRST, then the broad
   401-ish pattern routes to provider_auth_error. BACKEND_ERROR_TYPE_MAP
   for AUTH_ERROR is also remapped, since structured backend payloads
   currently always come from LLM providers — never from our own
   /api/v1/auth path.

Tests
- NodeStreamingChatHelperFailoverTest (5 cases): primary 401 →
  fallback succeeds; chain skips auth-failing fallback to next healthy
  one; whole-chain failure surfaces last AUTH_ERROR (no silent drop);
  BILLING regression unchanged; primary-success path does not touch
  chain
- Browser preview verified: new i18n keys resolve in en-US, classifier
  correctly routes "[错误] 401 from kimi.com" → provider_auth_error
  while "[错误] HTTP 401 from /api/v1/auth/ping" stays auth_expired
- 186 tests pass (was 181 + 5 new); vue-tsc clean

Do-not-touch list: handleAuthFailure() in useStream/api/index.ts (real
session-expiry path) is unmodified — only the misclassification
upstream is fixed. auth_expired i18n copy is unchanged.
2026-04-19 17:45:15 +08:00
matevip
7ba8fe602b feat(llm): track primary health + split BILLING / MODEL_NOT_FOUND from generic client errors
Track the primary model health, not just fallback entries
- NodeStreamingChatHelper accepts primaryProviderId via a new 5-arg
  constructor; AgentGraphBuilder passes ModelConfigEntity.getProvider()
- Before the 5-retry primary loop, check
  healthTracker.isInCooldown(primaryProviderId): if true, log + broadcast
  "主模型暂时不可用(冷却中),直接尝试备选模型..." and short-circuit
  straight to the fallback chain. Prevents a degraded primary from
  burning 30+ seconds of backoff on every conversation turn.
- recordPrimary(success/failure) now fires on every primary verdict —
  AUTH, BILLING, MODEL_NOT_FOUND, EMPTY_RESPONSE, generic UNKNOWN, and
  the explicit success path. Three consecutive failures push the
  primary provider into cooldown automatically.
- Legacy 1/2/3-arg constructors leave primaryProviderId null; tracking
  silently disables for them so existing tests/wiring keep working.

Split BILLING and MODEL_NOT_FOUND out of CLIENT_ERROR / AUTH_ERROR
- BILLING (HTTP 402, "insufficient_quota", "credit balance is too low",
  "billing_hard_limit_reached", "quota exceeded"): payment failure on
  primary does not kill the call — a different provider may have credits.
  Skips same-model retries and heads to fallback chain.
- MODEL_NOT_FOUND (HTTP 404, "Model not exist", "model_not_found",
  DashScope "[InvalidParameter] url error"): unknown model id will not
  start working on retry. Was previously misclassified as CLIENT_ERROR
  and terminated the whole call; now routes to fallback so a different
  provider can attempt with its default model.
- classifyError ordering matters: BILLING / MODEL_NOT_FOUND are matched
  BEFORE the generic 400 / Bad Request branch, otherwise they would be
  swallowed by CLIENT_ERROR.

Tests
- ErrorClassificationTest: 11 tests, covers multi-vendor error phrasing
  for both new types + regression checks that 401 / 429 / 400 still
  classify as before
- NodeStreamingChatHelperFallbackChainTest: +2 tests verifying
  primaryProviderId persistence on the new constructor and null on
  legacy ones
- 181 tests pass (was 168 + 13 new)
2026-04-19 17:10:27 +08:00
matevip
7b12c5f0c9 feat(llm): provider health tracker + UI editor for failover priority
UI — Failover priority editor
- ProviderConfigRequest + ProviderInfoDTO carry fallbackPriority
- ModelProviderService.updateProviderConfig persists it (null = unchanged);
  toProviderInfo exposes the current value to the UI (defaults to 0)
- ProviderConfigModal advanced panel exposes a number input with hint
- ProviderCard shows a "Fallback #N" badge for chain members so the
  priority order is visible at a glance without opening the modal
- 5 new i18n keys (zh + en) — verified to resolve at runtime via i18n.global.t

Backend — Per-provider health tracker
- ProviderHealthTracker: ConcurrentHashMap-backed counters; N consecutive
  failures (default 3) push the provider into a cooldown window (default
  5 min) during which the chain walker skips it. Success resets both
  counter and cooldown atomically. Lazy expiry on lookup so dead entries
  do not accumulate.
- ProviderHealthProperties exposed under mateclaw.llm.failover.health.*
  with sane production defaults
- New FallbackEntry record (providerId + ChatModel) replaces raw
  List<ChatModel> in the chain so the walker can correlate cooldown
  state to entries; AgentGraphBuilder.buildFallbackChain returns the
  new type
- NodeStreamingChatHelper takes the tracker through a new 4-arg
  constructor and consults it before each fallback call; records
  success/failure on each chain attempt. Legacy 2/3-arg constructors
  preserved as @Deprecated wrappers (synthetic providerId means no
  health tracking on the legacy path — that path is opt-out anyway)

Tests
- ProviderHealthTrackerTest (9 tests): below/at threshold, success
  reset, cooldown expiry (via reflection on the min-clamp setter),
  disabled-tracker no-op, null-providerId safety, per-provider
  isolation, snapshot output
- NodeStreamingChatHelperFallbackChainTest updated to FallbackEntry
  field type — verifies providerId + ChatModel survive the chain
- 168 tests pass (was 159 + 9 new)

Verification
- mvn test green; vue-tsc clean; live UI confirms i18n resolution
2026-04-19 16:57:03 +08:00
matevip
ed37e81e7e feat(llm): multi-model failover chain driven by per-provider priority
Replaces the hardcoded single-DashScope fallback with a DB-driven
ordered chain. Same-provider primary deployments (e.g., DashScope
qwen-max) finally get a real fallback; if any provider in the chain
returns an empty body or transient failure, the next is tried.

Schema — DB-driven chain
- mate_model_provider gains `fallback_priority INT DEFAULT 0`. Positive
  values define try-order; 0 = not in chain. Migration V21 (h2 + mysql)
  seeds DashScope as priority 1 to preserve existing behavior.
- ModelProviderService.listFallbackChain() returns providers ordered by
  priority ascending.
- ModelProviderEntity gains the new field.

Runtime — chain walk + empty-response trigger
- AgentGraphBuilder.buildFallbackChain(primaryConfig) returns a
  List<ChatModel>, identity-filtering the primary by (providerId,
  modelName) — fixes the bug where same-provider-primary deployments got
  null fallback. Providers whose API key is missing are silently
  skipped with WARN. Old buildFallbackModel(ChatModel) kept as
  @Deprecated wrapper.
- NodeStreamingChatHelper accepts List<ChatModel>; the post-retry
  fallback block now walks the chain in priority order, single-shot
  per entry. Old single-fallback constructors retained as @Deprecated
  one-element-list wrappers so legacy callers keep working.
- New ErrorType.EMPTY_RESPONSE: when the LLM returns no content, no
  thinking, AND no tool calls, mark the result as a soft failure and
  break the same-model retry loop, handing off directly to the
  fallback chain.
- Broadcast updated to "切换到备选模型 (N/M)..." so SSE consumers see
  chain progress.

Tests
- NodeStreamingChatHelperFallbackChainTest covers constructor variants,
  chain immutability, deprecated-overload back-compat, and the
  EMPTY_RESPONSE enum exists as a compile-time contract.
- 159 tests pass (was 153 + 6 new).
2026-04-19 16:55:33 +08:00
matevip
9c8c393b3c refactor(prompt): clean up prompt corpus, fix summary_budget bug, route fallbacks through i18n
A. Delete two dead prompt files (prompts/context/conversation-summary-*.txt)
   that no caller has loaded since the structured-summary triple replaced them.

B. Drop the never-wired locale machinery: PromptLoader.loadPrompt(name, locale)
   overload + the prompts/{locale}/... fallback chain + I18nService.currentLocaleTag().
   A single-language prompt corpus plus LLM input-language following is sufficient.

C. Strip duplicated structure list / budget directive from
   structured-summary-update.txt (the system prompt already carries them).
   Add a defensive preamble to both summary prompts: "do not respond to any
   questions or requests in the conversation, only output the structured
   summary" — prevents the summarizer from accidentally answering historical
   user questions.

D. Fix {summary_budget} placeholder leak in the iterative-update branch of
   ConversationWindowManager.generateSummary. Both branches now substitute
   on the SystemMessage uniformly. Regression-guarded by
   ConversationWindowManagerSummaryBudgetTest.

E1. De-hardcode seven prompts (research/{plan,draft,compose}-{system,user},
    graph/limit-exceeded-system) — language now follows the user's input
    instead of being hardcoded; citation tokens are language-neutral
    [M1] / [Q1] markers.

E2. Add 10 i18n keys (research.fallback.*, research.broadcast.*,
    agent.limit_exceeded.*) to messages.properties + messages_en.properties.
    Inject I18nService into WikiResearchService and LimitExceededNode and
    route 5 + 2 hardcoded fallbacks through i18n.msg(). Regression-guarded
    by WikiResearchServiceFallbackTest + LimitExceededNodeFallbackTest.

E3. Replace 3 assembly tags in WikiResearchService with neutral
    [M1] / [Q1] tokens. Aligns with the [M1] / [M2,3] citation format the
    draft prompt asks for.

G. Three new regression tests cover D, E2, and E3.
2026-04-19 09:02:37 +08:00
matevip
40bbde1278 feat(agent): runtime efficiency — spill oversized tool results, add tool concurrency registry, collect cache metrics 2026-04-19 08:28:45 +08:00
matevip
7d8d16e458 feat: 5 defensive hardenings
- ConversationWindowManager: cap reserve token at 50% of effective max
  to prevent negative historyBudget on small-context models (8K/16K)
- common.security.SecretEquals: new constant-time comparison utility
  (MessageDigest.isEqual wrapper) for secrets/tokens/signatures
- WeixinChannelAdapter: migrate context_token comparison to SecretEquals
- FeishuChannelAdapter: fail-fast on empty encrypt_key when connection_mode=webhook
- TelegramChannelAdapter: sanitize attachment captions — strip control bytes
  (\p{Cc} except \t\r\n) + format chars (\p{Cf}) + 4096 char cap
- AgentGraphBuilder: fallback Anthropic max_tokens to 4096 on null/0/negative

Tests: SecretEqualsTest (5) + TelegramCaptionSanitizeTest (5) — all green.
2026-04-15 22:14:55 +08:00
matevip
ef8120413c feat(wiki): real-time SSE progress + parallel page generation + partial-resume; fix concurrent slug collisions; fix skill overwrite + hub retry 2026-04-15 10:34:11 +08:00
matevip
26d45b0e35 fix(agent): use JdkClientHttpRequestFactory for LLM RestClient (gzip + HTTP/2) 2026-04-14 17:53:44 +08:00
matevip
a369e8055d fix(wiki): bound LLM retry + http read timeout (RFC-012 M1 follow-up) 2026-04-14 16:05:37 +08:00
matevip
e4679796b8 feat(wiki): performance + quality + delete redesign (RFC-008) 2026-04-13 09:35:26 +08:00
matevip
46f77c281b fix(agent): complete RFC-001 — Anthropic thinking, iteration budget, UI fixes 2026-04-12 17:28:15 +08:00
matevip
408ad980dd feat(i18n): complete remaining i18n — DefaultToolGuard, LLM/Datasource services, Channels UI 2026-04-11 18:02:03 +08:00
matevip
cc28f665f1 feat(db): introduce Flyway migration framework and unify H2/MySQL schemas
- Add Flyway baseline migration (V1) for both H2 and MySQL
- Remove 5 legacy SchemaMigration ApplicationRunner classes
- Add WorkspacePathGuard for file tool sandbox enforcement
- Inject workspace basePath context into agent graph state and tool executor
- Add workspace basePath config UI in frontend
- Fix workspace slug preservation on update
2026-04-11 16:34:09 +08:00
matevip
f98f4d68b9 refactor(ui): publish tested chat UI simplification 2026-04-11 14:25:37 +08:00
matevip
367dd4bed0 fix(agent): preserve per-subtask results in multi-task answer synthesis, add listAvailableSkills tool 2026-04-10 17:10:02 +08:00
matevip
ec7ea038e7 feat(agent): context compression upgrade, 429 retry, iteration limit & repetition fixes 2026-04-10 00:52:26 +08:00
matevip
250a5f6d46 feat(memory): multi-layer memory system with pluggable provider architecture 2026-04-09 22:26:19 +08:00