Default missing KB metadata to document tag relation lookup, propagate tag resolution failures instead of returning empty results, and reject ambiguous bare tag_ids when multiple knowledge bases are in scope.
Add a side panel for web and knowledge-base citations with citation-badge
highlighting, refine collapsed RAG pipeline summary layout, and emit
knowledge_base_id from agent knowledge_search results.
Emit search_source metadata from RAG progress events so quick-answer steps,
summaries, and IM labels no longer mislabel web-only results as knowledge base search.
Expose optional API key in settings UI, map longer API snippets into Content
for RAG, align maxResults fallback with other providers, sync Swagger enum,
and add follow-up unit tests.
Add Keenable Search alongside the existing DuckDuckGo / Bing / Google /
Tavily / Ollama / Baidu / SearXNG providers.
- internal/infrastructure/web_search/keenable.go: KeenableProvider
implementing the WebSearchProvider interface, following the Tavily
provider pattern. Keyless by default: with no API key it calls the
public endpoint (/v1/search/public, rate-limited); a key switches to
/v1/search and lifts the cap. Base URL is hardcoded (SSRF-safe), proxy
is honored.
- Registered "keenable" in the container registry.
- Added the keenable provider type + type metadata (RequiresAPIKey=false)
and service validation (no required key, like DuckDuckGo).
- Provider-specific empty-results diagnostic (keyless rate-limit hint).
- Frontend: extend the provider union type with 'keenable'.
- Unit tests: keyless vs keyed endpoint, attribution header, maxResults
trim, result mapping, error status, name.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
API principal HMAC secrets are write-only from the server, so users could
not copy a newly generated or rotated key before the input was cleared.
Retain the plaintext in-session after save, simplify secret field controls,
and add copy guidance across locales.
Introduce unit tests for the tenant API key validation logic, ensuring that scoped keys require capabilities, while full-access keys are validated without them. The tests cover various scenarios, reinforcing the expected behavior of the API key validation function.
Enhance the tenant API key service by introducing asynchronous throttling for the last_used_at updates during API key authentication. This change reduces database write frequency under high request rates, improving performance. Additionally, update tests to validate the throttling behavior, ensuring that last_used_at is only updated once per key within the defined interval. This implementation aligns with the goal of optimizing API key management and maintaining system efficiency.
Eliminate the POST /tenants/{id}/api-key endpoint for resetting tenant API keys, transitioning to a more granular API key management approach. Update related documentation and API specifications to reflect the new structure, including changes to the tenant API key management paths. Adjust frontend code and internationalization files to remove references to the deprecated API key reset functionality, enhancing clarity and consistency across the application.
Change the default role for tenant API keys from 'admin' to 'owner' to align with the new authorization model. Update related tests to reflect this change, ensuring that API keys with the owner role are correctly denied access to management paths and system-admin routes. Introduce new tests to validate that API keys are properly restricted from accessing sensitive endpoints, reinforcing the security measures in place.
Add DenyAPIKeyPrincipal middleware to explicitly block API-key principals from accessing certain routes, ensuring security for endpoints outside the /api/v1 group. Introduce tests to validate that API keys are correctly denied access while allowing JWT sessions to pass through. This enhances the overall authorization model by reinforcing the default-deny approach for API keys.
Redesign tenant API key authorization around one dimension (role) plus a
central default-deny gate, replacing the previous role + KB-scoped flag model.
- Add APIKeyGate as the single authority for API-key authorization: routes
declare one policy (MinRole) via apiKeyGroup/apiKeyRoute helpers; undeclared
routes are denied by default. JWT principals short-circuit the gate and the
JWT-centric RBAC guards short-circuit for API-key principals.
- Roles: viewer/contributor/admin are knowledge-base data-plane only (KB scope
is a pure downstream data filter); owner is a full-access tenant tier that
unlocks tenant-level infrastructure routes and is required for every method.
- Drop the KBScoped policy flag and the KB-restricted-vs-tenant branching.
- Security hardening: never disclose HMAC secret (return presence only), abort
writes on API-key encryption failure, deny KB-restricted keys on /files, and
backfill legacy key hashes at startup instead of O(N) plaintext scans.
- Frontend: two-level create dialog (access type -> permission level), rename
role labels to reflect actual scope, sync en/zh/ko/ru locales.
- Fix startup self-check false-positive on trailing-slash routes and normalize
gin paths before comparison; add regression tests.
Introduce tests to validate that tenant API keys are correctly restricted from accessing management paths. Implemented new test cases for both allowed and forbidden paths, ensuring proper enforcement of API key scopes. Additionally, refactored existing tests to utilize the new rejection logic.
Replace scopes JSON with a viewer/contributor/admin role column, move
unsafe-method authorization from path-prefix middleware to declarative
APIKey* guards on routes, and close remaining KB-scope gaps in handlers.
Use c.Request.Context() in authenticateAPIKeyRequest so scoped keys are
actually restricted, update dto tests for removed tenant.api_key, and add
a regression test for the attach-context contract.
Enforce per-key knowledge base restrictions on batch/search read paths,
centralize scope checks in shared KB access validators, and propagate
TenantAPIKeyScope through logger.CloneContext so async QA cannot bypass it.
Revoke existing keys on reset, unify scope enforcement, default empty
scopes to read-only, map API key scopes to tenant roles, and remove dead
key-generation helpers left over from the tenant api_key column removal.
Deleting or disabling a Feishu channel left its WebSocket long connection
alive: the Lark SDK's Start blocks on a bare select{} and never observes
ctx, and v3.6.1 exposed no public Close(), so the wsCancel() cleanup was a
no-op. The socket stayed open, the SDK kept auto-reconnecting, and Feishu
kept pushing messages — causing cross-environment message duplication when
the same bot was bound elsewhere.
Fix in three layers:
1. Connection teardown
- Upgrade oapi-sdk-go v3.6.1 -> v3.9.7 (adds Client.Close()).
- Add LongConnClient.Close() wrapping wsClient.Close(); factory's cleanup
now calls Close() first, then wsCancel() as a belt-and-braces fallback.
2. Multi-instance coordination
- wsLeaderRetryLoop: after acquiring leadership, re-check the DB before
starting; abort if the channel was deleted/disabled while waiting.
- wsLeaderRenewLoop: on each renewal, re-check the DB; step down if the
channel was deleted/disabled on another instance (HTTP request may have
been served elsewhere), so the leader doesn't keep the connection open
until process restart.
3. Robustness
- DB checks distinguish gorm.ErrRecordNotFound (channel truly gone ->
stop/abort) from transient DB errors (skip this round, retry next tick)
so a DB hiccup can't cause a spurious stop or permanent leader-abort.
- startChannelInternal now stops any existing channelState for the same
ID before overwriting, making it idempotent against concurrent start
paths and preventing adapter/long-connection leaks.
No interface changes; webhook and long-poll modes unaffected.
Co-Authored-By: Claude <noreply@anthropic.com>
A hardening + finalization pass over the agent-first CLI: correctness fixes,
richer machine-readable signals, flag/naming consistency, and a symmetric
config surface. Pre-1.0, so it includes breaking renames.
Correctness:
- agent update: resolve/validate --model/--rerank-model (was storing a bogus
name verbatim, corrupting config.model_id).
- doctor: honor WEKNORA_HOST / WEKNORA_API_KEY (headless path no longer reports
"no host configured").
- session ask / MCP session_ask: text answer was empty on non-TTY — the agent
stream sets Done=true on an intermediate agent_query frame before the answer,
and AgentAccumulator treated the first Done as terminal. Terminate on the
`complete` event (new sdk.AgentResponseTypeComplete), not a per-frame Done.
- batch exit codes: any per-item failure collapses to operation.failed (exit 1),
including `doc upload --recursive` partial failures — a permanent per-file
failure (e.g. a duplicate) no longer surfaces as a retryable exit 7 an agent
would loop on; per-item typed errors stay in the envelope.
Agent-first signals & discovery:
- error.exit_code in the envelope (type + exit_code disambiguate the
input.invalid_argument exit-2-vs-5 split in one JSON read).
- meta.hint on empty content search and on draft doc create; doc wait fails fast
on a never-parsing draft instead of hanging to --timeout.
- retrieval-readiness is visible in the natural flow: kb status / kb check emit
retrieval_ready, and kb create hints the fix when no embedding model is bound
— an unconfigured KB no longer looks silently healthy.
- schema contract completeness: every leaf declares output + >=1 example
(drift-guarded); output strings match the meta actually emitted; chunk list
and search docs now emit meta.total_count (both previously dropped it).
- schema tolerates a quoted multi-word command label; zero-state auth — and
`link` with no profile — point at profile setup / the headless WEKNORA_KB_ID
path instead of looping on `auth login`.
- id-addressed reads tolerate a redundant --kb (doc view/wait, chunk list/view
accept and ignore it, declared in schema) so a carried-over --kb doesn't
exit 2; streaming commands warn that --jq does not apply to an NDJSON stream.
- keep JSON-always as the default; --jq hints spell out the .data path.
Consistency & gating:
- doc create: drop the deprecated --name alias (--title only; pre-1.0 break).
- chunk list --limit aligned to 1..10000; model list --limit/-L with
has_more/total_count; api write-gates -X PUT/PATCH (exit 10); skills install
expands a leading ~.
- docs corrected: search docs / doc list --keyword help is case-insensitive
(server does LOWER LIKE); AGENTS.md risk-action list (no phantom kb.init; add
model.update / kb.config.set) and batch example (failed item carries `error`);
session resume --message id comes from `message list`, not the stream.
- auth/profile ergonomics: env credentials are now first-class — `auth token`
prints the active WEKNORA_API_KEY / WEKNORA_TOKEN, and auth login/logout/refresh
give an env-aware message instead of looping on "run auth login". `auth logout`
clears credentials but keeps the profile registered (host preserved for
re-login); deleting a profile is `profile remove`'s job (clean logout/remove
separation, matching gh / lark).
Config surface (symmetric read/write, in-place model edits):
- kb config now returns a secret-free KBModelConfigView (was {}); `kb config`
reads, new `kb config set` writes; `kb init` removed (misnomer).
- kb create --chat-model: retrieval-ready in one step.
- model update: edit a model in place (id preserved, references survive) —
rotate --api-key-stdin, change base-url / display-name / etc.
- session continue-stream renamed to session resume.
Docs: AGENTS.md is the single wire-contract source; CHANGELOG slimmed; stale
kb-init / continue-stream references removed; skill wire-vocab guard extended.
AGENTS.md / weknora-shared SKILL document retrieval_ready (a KB needs an
embedding model to be searchable), that --jq does not apply to NDJSON
streams, and the env-credential-first auth path; the KB quickstart example
now creates a retrieval-ready KB.
Make document keyword search case-insensitive (LOWER(...) LIKE LOWER(?)) in the
list filter and SearchKnowledge / SearchKnowledgeInScopes paths so a query and
its differently-cased variant return the same results.
Classify not-found consistently as HTTP 404 (not 500) so clients read a
permanent resource.not_found instead of a retryable 5xx: map the document /
chunk not-found sentinels in the KB-access middleware (typed ErrChunkNotFound
via errors.Is), and return 404 for a missing message on the continue-stream and
message-delete endpoints.
Adds the client-library surface the agent-first CLI builds on:
- named server error-code constants + typed *APIError from non-2xx responses,
- MessageSearchMode / AgentMode / KBSelectionMode and model type/source
enumerators so the CLI validates flags against the server vocabulary,
- SetKBModelConfig for binding embedding/chat models to a knowledge base.
Restore onVisibleChange in card menu close handler so moveMenuMode resets correctly, and align list view popup chrome with card view via shared card-more styles.
- Add DocumentActionMenu.vue: shared component for document context menu
items (edit, view-trace, rebuild, cancel-parse, move, batch-manage,
delete) with consistent visibility conditions
- Add DocumentCardView.vue: standalone card/grid view component extracted
from KnowledgeBase.vue inline template, including hover popover, tag
chips, move sub-flow, and status display
- Update DocumentListView.vue: use shared DocumentActionMenu, add
canMutateKnowledge gating for move/batch-manage, add view-trace and
batch-manage menu items, add move sub-flow support (targets/confirm)
- Update KnowledgeBase.vue: use DocumentCardView component, add
handleCardAction bridge, remove unused helpers and imports
Both card and list views now render identical operation menus from a
single source of truth.
Validate parsed WeKnora_settings is a plain object, deep-clone defaults
on reset, and reuse safeSetItem for reconcile write-back. Extracts load
logic into settingsStorage with unit tests for corrupt and non-object JSON.
- Wrap JSON.parse in loadAndReconcileSettings() with try/catch, fall
back to defaultSettings and remove corrupted WeKnora_settings on
parse failure instead of crashing the app
- Add try/catch around localStorage.setItem write-back for quota
exceeded protection
- Register app.config.errorHandler to catch unhandled Vue errors and
prevent silent component tree crashes
Follow up on #1740/#1741 by typing terminal SSE errors in the SDK,
classifying them as server.error in the CLI/MCP, marking Projector done
on error frames, attaching session_id to MCP stream failures, and
migrating the e2e chat step to the bounded JSON envelope.
Reject refresh attempts when the DB token type is not refresh_token,
and add service-layer tests for bearer refresh rejection, logout
revocation, and expired-token logout handling.