Commit Graph

2271 Commits

Author SHA1 Message Date
wizardchen ca9da8399e feat(dev): support remote infrastructure via .env.local 2026-07-08 15:42:23 +08:00
wizardchen a1b49e2664 fix(faq): guard against division by zero in import timing logs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-08 15:27:51 +08:00
wizardchen d9bb7aa8f2 fix(search): harden tag scope resolution after #1907
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.
2026-07-08 10:55:42 +08:00
wizardchen 0db71bf2f8 fix(agent): polish selector capability status chips 2026-07-08 10:55:02 +08:00
wizardchen d01526b758 fix(chat): close references drawer on session switch 2026-07-08 00:39:35 +08:00
wizardchen 15b81d1581 fix(agent): gate web search controls by provider readiness 2026-07-08 00:26:34 +08:00
wizardchen 3209ed77fd feat(quick-qa): add references drawer and polish retrieval source UI
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.
2026-07-08 00:26:34 +08:00
wizardchen 45eab4a95f fix(quick-qa): distinguish web and knowledge base retrieval in pipeline UI
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.
2026-07-08 00:26:34 +08:00
wizardchen 77cf6a5789 fix(web-search): polish Keenable provider integration after #1946
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.
2026-07-07 17:14:39 +08:00
Ilya Bogin 8cf9f1c882 feat: add Keenable as a configurable web search provider
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>
2026-07-07 16:58:26 +08:00
wizardchen f7b427009d fix(frontend): keep HMAC secret visible for copy after save
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.
2026-07-07 16:39:51 +08:00
wizardchen 974231190c Add API key member and space capabilities 2026-07-07 12:00:13 +08:00
wizardchen d60614475e test(api-keys): add unit tests for tenant API key validation
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.
2026-07-07 12:00:13 +08:00
wizardchen 2c6f082062 Refine scoped API key capabilities 2026-07-07 12:00:13 +08:00
wizardchen b5cc7d2a28 feat(api-keys): implement throttled last_used_at updates for API key authentication
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.
2026-07-07 12:00:13 +08:00
wizardchen 97c36f634a refactor(api-keys): remove API key reset endpoint and update documentation
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.
2026-07-07 12:00:13 +08:00
wizardchen 1d1e1e3d25 refactor(api-keys): update role handling and enhance API key restrictions
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.
2026-07-07 12:00:13 +08:00
wizardchen a6759d61b5 feat(api-keys): implement DenyAPIKeyPrincipal middleware and related tests
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.
2026-07-07 12:00:13 +08:00
wizardchen d2ffc1b973 refactor(api-keys): simplify authorization to a single-role gate
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.
2026-07-07 12:00:13 +08:00
wizardchen fedb6c3f7e test(api-keys): add tests for tenant API key management path rejection
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.
2026-07-07 12:00:13 +08:00
wizardchen 9a76a24ce6 refactor(api-keys): use role field and route-level API key guards
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.
2026-07-07 12:00:13 +08:00
wizardchen 3ace6e657f fix(frontend): polish API key create dialog UX and align i18n
Map API key permissions to tenant roles in the UI, widen the create dialog,
and sync integrations.api locale strings across en-US, ko-KR, and ru-RU.
2026-07-07 12:00:13 +08:00
wizardchen c65ffa3d9c fix(api-keys): enforce scope from request context after attach
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.
2026-07-07 12:00:13 +08:00
wizardchen 94d18ea15a fix(api-keys): close KB scope gaps in handlers and CloneContext
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.
2026-07-07 12:00:13 +08:00
wizardchen 3f516d7f31 fix(api-keys): harden scoped key auth after code review
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.
2026-07-07 12:00:13 +08:00
wizardchen 505bc7ddec feat: add scoped tenant api keys 2026-07-07 12:00:13 +08:00
langcaiye 1708d6895a fix(search): apply tag filters to knowledge search 2026-07-06 23:30:33 +08:00
cao_j b16cb0bb56 fix(agent): treat end_turn as natural stop 2026-07-06 23:16:18 +08:00
养乐多 baada32cb6 fix(im/feishu): actually close WebSocket long connection when channel is stopped
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>
2026-07-06 23:10:45 +08:00
wizardchen 4f2dca0b63 fix(redis): harden TLS tests and surface TLS config at startup
Isolate Redis TLS unit tests from parent-process env vars and log
REDIS_USE_TLS settings at boot so misconfiguration is easier to spot.
2026-07-06 23:04:52 +08:00
qilifan d5b8d2f886 feat(redis): support TLS for Redis connections (#1930)
[Feature]: Support TLS for Redis connections
2026-07-06 23:02:02 +08:00
nullkey d3c03b2f34 feat(cli)!: v0.10 reliability, agent-UX, and command-surface hardening
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.
2026-07-06 22:53:01 +08:00
nullkey 040a734766 docs: CLI operational contract, quickstart, and changelog
AGENTS.md wire contract for AI agents, README install + 5-minute quickstart,
CHANGELOG, and the root README CLI section.
2026-07-06 22:53:01 +08:00
nullkey 6f8b825f5f feat(cli): agent-first WeKnora CLI
The `weknora` command-line client for the WeKnora RAG server. Full command
surface: kb / doc / chunk / session / message / agent / model / search / chat /
auth / profile / link / api / mcp / skills / config / doctor / schema /
exit-codes.

Agent-first wire contract: JSON envelope by default, typed error codes mapped to
stable exit codes, error.retry_argv / retryable / partial-failure status,
global --dry-run preview, the exit-10 confirmation protocol for writes, and
control/ANSI/Bidi input hygiene. Stateless env-credential auth
(WEKNORA_API_KEY / WEKNORA_TOKEN + WEKNORA_HOST) for headless/CI/agent use.
A curated read-only MCP tool surface (`mcp serve`) and embedded Agent Skills
(`skills install`). Extensive unit + contract-golden tests and CI.
2026-07-06 22:53:01 +08:00
nullkey 445a4330fa fix(server): case-insensitive doc keyword search + not-found classification
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.
2026-07-06 22:53:01 +08:00
nullkey 8f36ea2229 feat(sdk): typed errors, enums, and KB model config for the CLI
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.
2026-07-06 22:53:01 +08:00
wizardchen eba9fe7e78 fix(frontend): unify document action menu styles and reset move state on close
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.
2026-07-06 22:52:32 +08:00
Binks Riverton cb46db23f5 refactor(frontend): extract shared document action menu and card view component
- 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.
2026-07-06 22:45:51 +08:00
wizardchen 1b0502e562 fix(feishu): upload card markdown images 2026-07-06 14:52:29 +08:00
wizardchen 699d6bd235 fix(frontend): harden settings localStorage load after #1925
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.
2026-07-06 10:46:34 +08:00
Binks Riverton 85f5cd760b fix(frontend): prevent white screen from corrupted localStorage
- 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
2026-07-06 10:43:43 +08:00
wizardchen 18d7a6b3d3 Fix manual knowledge editor publish flow 2026-07-03 18:38:34 +08:00
wizardchen 1109e85a57 fix(cli): align stream error handling after output-mode merge
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.
2026-07-03 00:30:34 +08:00
coconut-yc 9437e1ac3c feat(cli)!: add agent-first chat and session ask output modes 2026-07-03 00:21:48 +08:00
coconut-yc 238297e2c5 fix(client): harden chat and agent SSE reliability 2026-07-03 00:13:41 +08:00
wizardchen 1661827d6e fix(security): harden model client redirects 2026-07-02 19:15:46 +08:00
wizardchen 663d13eb58 fix(security): harden outbound requests and file previews 2026-07-02 19:15:46 +08:00
wizardchen 7099a7e181 fix(security): redact IM list credentials and harden MinerU SSRF
Stop returning bot credentials from Viewer-accessible IM channel list
endpoints and validate self-hosted MinerU URLs at config save and fetch time.
2026-07-02 17:58:20 +08:00
Krypt0n123 929697618f fix(nginx):embed iframe x-frame-options 2026-07-02 17:17:24 +08:00
wizardchen 235e86b876 fix(security): harden refresh token validation and add auth tests
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.
2026-07-02 17:08:17 +08:00