Commit Graph

3388 Commits (b14bcbcd541fc0fdd67eef518828a28302358e18)

Author SHA1 Message Date
诉说晚秋 b14bcbcd54
fix(notion): 保留正文抓取失败时的同步游标 (#3693) 2026-10-09 10:43:59 +08:00
icearia0219 005627b180 fix(agent): compare tool enum values without string coercion
Fixes Tencent/WeKnora#3946
2026-10-08 21:07:11 +08:00
clumsypsc 2a02807a61 fix(chunker): respect Markdown fences during heading detection 2026-10-08 21:06:59 +08:00
wizardchen 676a59307e fix(settings): improve modal sizing and integration page layout 2026-10-08 20:36:36 +08:00
lyingbug 0c5d28abb7
feat: index and recall images with multimodal embedding models (#3683)
* feat(models): expose embedding input modalities

Whether an embedding model maps images into the same space as text is
what will decide if a knowledge base can store image vectors. The
catalog already had the field, but most multimodal embedding models
were missing it and embedding rows never reported it.

- Catalog: declare input modalities for the Doubao and Tongyi vision
  embeddings, the Aliyun multimodal / qwen-vl embedding families and
  jina-embeddings-v4, as listed in each vendor's documentation. The
  migration baseline changes for exactly these nine entries.
- Model responses resolve capabilities for embedding rows too, so
  capabilities.input reflects the catalog merged with spec.input.
- Model editor: an "Image input" switch for embedding models. It follows
  the catalog and writes spec.input only when the row differs from it;
  picking another catalog model or switching vendor drops the
  declaration. Model cards show the image badge for such models.

* feat(embedding): embed images with multimodal embedding models

Adds the image side of an embedder, for models that map images into the
same space as their text vectors so a text query can find an image.

- api: EmbedImage (bytes + MIME type, sent inline as base64 because the
  object store is usually unreachable from the vendor) and an
  ImageEmbedder implemented by all four protocols, each in the image
  shape its reference documents: Ark image_url, DashScope contents[].image,
  Gemini inlineData parts, and on the OpenAI shape an object keyed by the
  vendor's image_field (Jina: "image"). A plain OpenAI-compatible
  endpoint names no image field and takes no images.
- Settings: image_field, max_image_batch_size (default one per request),
  max_image_bytes and image_mime_types, filled from vendor docs for the
  DashScope multimodal models, gemini-embedding-2 and Jina.
- embedding: an optional ImageEmbedder interface reached through
  AsImageEmbedder, so existing Embedder implementations and fakes are
  untouched. An embedder takes images only when the catalog (or the
  row's spec.input) lists image AND the endpoint can carry one. Images
  are checked against the documented limits before any request, then
  split at the documented images per request. The concurrency, debug
  and Langfuse decorators forward it; logs and traces carry the MIME
  type and size, never the bytes.

The migration baseline changes only for the entries whose resolved
embedding settings now carry image limits.

* feat(knowledge): index images by their own vector and recall them

When the knowledge base's embedding model embeds images, each image now
gets a vector of its own next to its caption and OCR chunks, so a query
can find an image by what it shows even where the caption left it out.

Ingestion
- After the caption/OCR chunks are indexed, the multimodal task embeds
  the image (embedding.PrepareImage converts and shrinks it to the
  vendor's documented limits) and stores it as a new image_vector chunk:
  Content is the caption (OCR text when there is none) for reranking and
  the answer context; its index row carries the image's vector with
  SourceType ImageSourceType. Scanned PDF pages are skipped, their OCR
  text serves better. A failure here is logged and never fails the task.
- The image vector gets its own chunk rather than a second index row on
  the caption chunk: OpenSearch and Weaviate key documents by ChunkID,
  so a second row would overwrite the caption's text vector, and copy,
  move and enable/disable all follow chunk IDs.
- CompositeRetrieveEngine.BatchIndexVectors writes precomputed vectors
  through each engine's normal BatchIndex, keeping row order (the
  composite's de-duplication does not).
- Paths that rebuild vectors from text leave image_vector alone:
  syncChunkIndex only syncs its enabled flag, updateChunkVector skips
  it, and a caption edit updates its Content only.
- The multimodal task's caption/OCR index rows now set IsEnabled; only
  backends with a column default were storing them as enabled.

Retrieval
- A text query scores lower against an image than against text, so when
  the model embeds images the document vector search is widened by half
  (capped at 500) and run at min(VectorThreshold, 0.1); each store
  group's hits are then held to their own threshold before score
  normalization: text at VectorThreshold, images at min(VectorThreshold,
  0.1). Keyword hits on image rows are dropped, their Content being the
  already-indexed caption.
- image_vector hits are searchable and merge like caption hits: parent
  context is attached, and the caption is not repeated from ImageInfo.

Adds golang.org/x/image for scaling and WebP/BMP decoding.

* fix(models): report no thinking levels for embedding, rerank and ASR models

Embedding rows now carry capabilities, and the end-to-end run showed them
listing off/auto/minimal/low/medium/high: these references resolve no chat
protocol, and an empty level map reads as "every level supported". A model
without a chat protocol does not think, so its capabilities say so.

* fix(compaction): never read a cancelled turn's stream as a summary

streamSummary selects on the turn's context and the provider stream at
once. When the turn is already cancelled both are ready (providers close
the stream once their context ends), and select picks at random, so a
stopped turn could come back as a completed, partial summary with a nil
error. TestSummarizationIsNotRetriedOnceTheTurnIsCancelled caught it
intermittently in CI and reproduces under -race with several -cpu values.

Check the context before each receive and again when the stream closes.

* feat(knowledge): put image vectors behind a knowledge-base switch, off by default

Image vector indexing and recall used to turn on whenever the knowledge
base's embedding model declared image input. A model that takes images is
often chosen for text alone, so an upgrade would have added an embedding
call per image, widened vector recall 1.5x and lowered the image threshold
to 0.1 for those knowledge bases without anyone asking.

ImageProcessingConfig gains image_vector_enabled (default false; stored
JSON without the key reads as off, so existing knowledge bases stay off
with no migration). Both sides now need the switch and the model:

- indexImageVector returns before touching the model unless the KB opted
  in (KnowledgeBase.IsImageVectorEnabled, which also needs vector indexing).
- applyImageRecall resolves the embedding model only when some KB in the
  search opted in, and records the opted-in KBs per store group
  (storeGroup.ImageKBIDs). Only those groups widen the pool and lower the
  threshold; image hits of any other KB, including ones indexed before the
  switch was turned off, are dropped.

The KB editor shows the switch in the image processing section, with a
warning when the selected embedding model does not declare image input;
docs describe the switch, its cost and what turning it off does.

* fix(knowledge): leave image vectors behind when cloning into a KB that is off

CloneChunk copied every chunk of the source document and then CopyIndices
for all of them, so copying a document from a knowledge base with image
vectors on into one with the switch off (same model and store) still
created image_vector chunks and their index rows, bypassing the switch
that indexImageVector honours.

Image vector chunks are now dropped from the copy when the target has not
opted in. Every engine's CopyIndices copies only the rows of chunks in the
mapping, so their index rows stay behind too.

* fix(search): refill the vector pool past stale image vectors

Image hits of a knowledge base whose switch is off were dropped only after
the engine had ranked and cut its results at TopK. Image vectors indexed
before the switch was turned off could fill that pool and push out valid
text hits: with MatchCount 5 the pool is 50, and 50 stale image rows
ranked above the text left the search empty.

No engine can filter rows by source type (Postgres and SQLite do not even
take ExcludeChunkIDs), so the exclusion cannot move into the query. When
the document vector pool comes back full and holds stale image rows, that
search alone runs again on a pool twice as large, until it holds TopK rows
that are not stale, the index runs out, or the pool reaches
maxRetrievalPoolSize (at most four extra calls from a pool of 50). The pool
is then cut back to TopK such rows, matching an engine-side exclusion
unless more than maxRetrievalPoolSize-TopK stale rows rank above the text.

* feat(i18n): translate the image vector switch and image input keys into zh-TW

The zh-TW locale arrived from main after this branch added five keys: the
knowledge base's image vector switch (label, description, unsupported-model
warning) and the embedding model's image input flag (label, description).

* fix(knowledge): leave image vectors behind when moving into a KB that is off

A reuse_vectors move relocates a document's chunks and index rows in place:
MoveKnowledgeIndices rebinds the rows by document ID and
MoveChunksByKnowledgeID rebinds the chunks. Moving a document from a
knowledge base with image vectors on into one with the switch off therefore
carried its image_vector chunks and their vectors along, the same bypass the
clone path had.

When the target has not opted in, the image_vector chunks are now deleted
during the move, their index rows first and then the chunks, so a retry
finds the chunks again rather than leaving orphaned rows. A target that
opted in still receives them unchanged.

* fix(retriever): keep image vectors out of keyword-only engines

BatchIndexVectors handed image rows to every engine of the composite,
including one that serves keyword retrieval alone (Elasticsearch v7 next to
a vector store). There the row holds nothing but the image's caption, which
the caption's own chunk already indexes, and retrieval discards every
keyword hit on it.

Image rows now go only to engines that serve vector retrieval. An engine
that serves both keeps one row for both kinds, so its keyword search still
meets them; the search side handles that.

* fix(search): refill the keyword pool past image rows

Every engine that serves both kinds of retrieval stores one row per index
entry and runs its keyword search over that row's content, so an image
vector row, whose content is its caption, is a keyword hit wherever the
caption's own chunk is. filterImageHits drops all of them, but only after
the engine has cut its ranking at TopK, so they crowded out text and caption
hits; a keyword ranking that put the image rows first came back empty.

The keyword pool is now refilled the way the vector pool is refilled past
stale image vectors: when it came back full and held image rows, the
keyword search runs again on a pool twice as large, up to
maxRetrievalPoolSize, and is cut back to TopK hits that are kept.

Leaving the rows out of the keyword index instead would mean writing them
without searchable content (Milvus and Tencent VectorDB derive a BM25
sparse vector from it, and how they take an empty one is unverified) or a
source-type filter in every engine's keyword query (ten engines, and
filterable fields that existing collections lack).

* revert: let image vectors move with the document into a KB that is off

This reverts commit e259977fe915f7d0bc30c4b02bc7af04da1c8dd4.

Deleting the image vector index rows by chunk ID before the move is not
reliable: the Weaviate and Elasticsearch v8 delete wrappers ignore partial
failures, and OpenSearch rejects more than 1000 IDs with ErrBatchTooLarge.
A partial delete followed by the chunk delete leaves index rows whose chunks
are gone, which nothing ever cleans up.

Without it, the image_vector chunks and their index rows move together
with the document. While the target's switch is off they are filtered at
query time (the pool refill keeps them from crowding out text), they are
removed with the document on delete, reparse or knowledge base delete, both
chunks and index rows by knowledge ID, and they become active again if the
target turns the switch on. The clone path keeps dropping them, since there
the rows are copied rather than moved.

* fix(search): keep the image row refill from losing hits it already had

refillPool replaced a pool with the answer to each larger search. A refill
that answered only in part (RetrieveResult.Error, swallowed into a warning
by retainPartialResults, as when some collections of the store did not
answer) could hold fewer text rows than the complete smaller pool, or none:
40 stale image rows above 10 text came back from a partial refill as the
40 image rows alone, and the search lost all 10 text hits. A refill that
failed outright failed the whole store group, discarding a first round that
had succeeded.

A refill is now best effort. A failed or incomplete refill search stops
the refill and leaves the last complete pool in place, cut back to TopK
kept rows as before, so a refill can no longer leave a search worse off
than it was without it. Merging the partial answer into the pool was not
done: its rows would need deduplicating and its ranking is cut at a
different TopK over a different set of collections, while keeping the
previous pool is exact.

* docs(knowledge): say what happens to image vectors in a KB that is off and what the refill costs

The image vector section now says that with the switch off, image vectors
that were indexed before it was turned off, or that came along when the
document was moved in from a KB that has it on, are kept but filtered at
query time, are removed when the document is deleted or reparsed or the
KB is deleted, and are recalled again once the switch is turned on; a copy
into such a KB leaves them behind.

It also states the cost of keeping dropped image rows from crowding text
out of the pools: the vector and keyword pools are searched again with
TopK doubled up to the 500 candidate cap, which adds queries for store
groups that hold such rows, and text can still be missed when more than
about 500 candidates are image rows. A failed or partial refill keeps the
previous complete pool.

* fix(search): log unexpected refill result sets, and describe the refill stop condition precisely
2026-10-08 18:19:53 +08:00
lyingbug b7f3181066
docs: count 29 built-in model vendors and list Hugging Face TEI and Pinecone (#4048)
#3956 (Hugging Face TEI) and #3957 (Pinecone) added two rerank-only
vendors, but the READMEs, the models page, the extension-points page and
the homepage still said 27, and the vendor table had no rows for them.
The v0.8.2 release notes keep their historical 27.
2026-10-08 18:03:07 +08:00
ZW. 5a25e26142
feat(rerank): support Pinecone Inference protocol (#3957)
* feat(rerank): support Pinecone Inference protocol

* test(rerank): align Pinecone catalog baseline and lint

* test(models): expect 29 built-in vendors with Pinecone and TEI

---------

Co-authored-by: bigdu332 <bigdu332@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 17:54:15 +08:00
LuckVd ea7cf8d5d7
fix(models): emit explicit empty content for assistant tool-call turns (#3605)
Assistant history messages that carry tool_calls but empty text previously
omitted the content field entirely on the wire. Strict local OpenAI-compatible
engines (vLLM / Xinference serving Qwen-family Jinja chat templates) treat the
missing field as undefined/null and crash while rendering the next turn,
surfacing as "I'm sorry, I was unable to generate a response".

Always serialize "content": "" for assistant tool-call turns. The empty
string is accepted by every standard OpenAI-compatible endpoint.

Fixes #1487

Co-authored-by: LuckVd <LuckVd@users.noreply.github.com>
2026-10-08 17:43:05 +08:00
wizardchen a729d1fc8c docs(models): state which rerank limits split requests and which fail the call
The rerank limits row said every limit splits the request automatically.
Only max_documents and max_request_chars do; an over-long query or
document (max_query_chars / max_document_chars, or a single document
that does not fit the request budget beside the query) fails the call.
Taken from the documentation part of #3757; max_documents keeps
0 = unlimited.

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-08 17:03:41 +08:00
wizardchen 0de62b2f80 fix(chat): restore citation source navigation and soften highlights 2026-10-08 16:59:50 +08:00
wizardchen 1c528d83de fix(i18n): add the zh-TW Seafile strings missing after #3616 and #3916
#3616 (Seafile) and #3916 (zh-TW) were merged one after the other; each
was green on its own, but zh-TW had no translations for the 21 Seafile
keys, so the locale key audit fails on main.
2026-10-08 16:47:53 +08:00
Junhao Ye d2bc0df6a2
feat(i18n): add Traditional Chinese (zh-TW) locale support (#3916)
* i18n(zh-TW): add Traditional Chinese (Taiwan) locale bundle (6,547 keys)

機械產生自 zh-CN.ts:以 zhconv (zh-tw) 為字形基底,詞彙層以 tw-terms.tsv(364 條生效詞條)覆寫,保留 26 條 never 與 47 條保護詞。骨架等價、鍵序列、Node 真實載入、內嵌區塊 四道檢查皆通過(詳見審計目錄)。

* i18n(zh-TW): register locale bundle in i18n infrastructure (5 → 6)

- resolveDefaultLocale.ts: SUPPORTED_LOCALES = ['zh-CN','zh-TW','en-US','ru-RU','ko-KR','ja-JP']
- i18n/index.ts: 載入 zhTW 並掛入 messages['zh-TW']
- localeKeyAudit.ts: 加入 LOCALE_BUNDLES['zh-TW'] 與測試守門(LOCALE_ORDER、emptyBundles)
- localeKeyAudit.test.ts: 把 zh-TW 補進期望清單
- locales/{en-US,ja-JP,ko-KR,ru-RU,zh-CN}.ts: language 區塊補 zhTW 顯示名(讓語言切換器正確顯示繁中選項)

* i18n(zh-TW): fix normalizeEmbedLocale and add zh-TW embed block (514 keys)

原實作 startsWith('zh') 直接命中 zh-TW/zh-HK/zh-Hant 並回傳 zh-CN
→ 繁中使用者將永遠看到簡體字串。修正後:
  - 繁中變體 (zh-tw/zh-hk/zh-mo/zh-hant) 排在通用 zh 之前,優先回傳 zh-TW
  - 內嵌 zh-TW 區塊加入 514 個字串,骨架與 zh-CN 區塊逐字元相同(只換區塊名)

* i18n(zh-TW): wire zh-TW into UI language pickers and TDesign locale

- App.vue: 載入 tdesign-vue-next esm/zh_TW,tdLocaleMap['zh-TW'] = zhTWConfig
- Login.vue: 語言切換器新增 { value: 'zh-TW', label: '繁體中文', shortLabel: '繁中', flag: '繁' }
  (刻意不用旗標 emoji,改以「繁」字標示,語意清楚且無爭議)
- GeneralSettings.vue: 設定頁語言下拉新增 <t-option value='zh-TW' ...>
- AgentEmbedChannelPanel.vue: 代理嵌入頻道語言選單新增繁中
- IMChannelPanel.vue: IM 頻道語言選單新增繁中

* i18n(zh-TW): widen API union types and update tests for zh-TW

- api/agent/index.ts: IMChannel.locale 聯合型別補 'zh-TW'
- api/embed/index.ts: EmbedLocaleTag 聯合型別補 'zh-TW'
- i18n/embedLocale.test.ts: supported-list 期望補上 zh-TW;新增 7 條 normalizeEmbedLocale 斷言(覆蓋 zh-tw / zh-hk / zh-mo / zh-hant / zh-Hant-TW 等變體正確路由到 zh-TW)
- locales/workspaceTerminology.test.ts: workspace 詞彙測試也對 zh-TW 做同樣的禁用詞斷言(與其他 locale 同步)

* i18n(zh-TW): add zh-TW to backend supportedLocales whitelist

- internal/types/locale.go: supportedLocales["zh-TW"] = {}
  (NormalizeSupportedLocale 會靜默丟掉未列出的 tag,導致前端語言選擇器實際寫入空字串——
   此修正保證前端選 zh-TW 時 embed 預設語言與 IM 回覆語言會被後端接受)
- internal/types/locale_test.go: 期望清單補上 zh-TW
- internal/handler/mcp_usage_instructions.go: MCP 工具使用說明對照表新增 zh-TW → 'Traditional Chinese'

* fix(i18n): translate revoke as 撤銷 in zh-TW and allow zh-TW as the runtime default locale

The zh-CN → zh-TW conversion turned every 撤销 into 復原 (restore), so
revoke buttons for OAuth tokens, device pairing, invitations and system
admins read as the opposite action. Only the undo sense (此操作不可撤销)
keeps 復原.

docker-entrypoint.sh whitelists DEFAULT_LOCALE and did not accept zh-TW,
so DEFAULT_LOCALE=zh-TW silently fell back to Simplified Chinese. Also
list zh-TW in the IM locale error and the locale hints.

---------

Co-authored-by: junhao-ye <junhao-ye@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 16:18:17 +08:00
zaqqmm 19542f2a1d
feat(datasource): add Seafile data source connector (#3616)
* fix(datasource): omit last_sync_cursor from the data source list response

The settings page polls GET /datasource every few seconds during a sync,
and connector cursors can grow to megabytes. No list consumer reads the
cursor, so NewDataSourceResponses now blanks it; detail, create and
update responses still return it through NewDataSourceResponse.

* feat(datasource): add Seafile connector with fingerprint-based incremental sync

Sync folders and files from one Seafile library per data source. The
connector walks the selected scope one directory level at a time,
downloads files through the link + fileserver flow without credentials,
and reconciles deletions against a per-file oid/mtime/size fingerprint
cursor that is checkpointed every 50 mutations.

- resource ids are "<repo_id>:<path>"; ancestors collapse, one library
- per-file failures become coded error items and keep the path pending
- directory failures and Retry-After > 60s abort without deletions
- forced full runs keep the old cursor as a deletion baseline
- API token never reaches cursors, metadata, logs or error text
- share the supported import extension set through internal/utils

* feat(datasource): add Seafile frontend connector and docs

Wire the Seafile data source into the editor dialog, channel labels
and the five locales, and document how to connect a Seafile 10.0.1
library.

- connector definition with base_url + API token fields and icon
- picker guard: one library per data source, at least one selection
- "library" resource type and icon in the lazy tree
- channel label in the knowledge base filter, document views and chat
- i18n for labels, guide steps and the eight seafile_* sync error codes
- website-docs integration guide, data source and extension point doc
  updates, and Seafile in the README data source lists

---------

Co-authored-by: zaqqmm <q-zhang10@qq.com>
2026-10-08 16:18:09 +08:00
linus-liu-web bcbd65a459
fix(datasource/dingtalk): Validate 不再因为某个工作区读不到就整库判失败 (#3782)
* fix(datasource/dingtalk): 多工作区租户里一个工作区读不到就整库判失败

Validate 原来在第一个读不到的工作区或文档上直接 return err。租户的
listWorkspaces 会返回组织内的全部工作区,而 operator 通常只被授权其中
一部分,于是"知识库里混了多个工作区、其中一个没权限"会被判成"凭据
错误",整库都建不起来,哪怕另一个工作区完全可读。

改为在循环里累计 lastErr / workspaceFail / sawDocument:某个工作区列不出
节点、或某个文档读不到,都只记录原因并 continue,不再中断;循环结束后
只有"一个能读的都没有"才报错。一个文档都没暴露的租户仍然放行——没有
可读之物就无法证伪凭据,只有"存在却读不到"才算问题。

文档探测抽成 verifyDocument,后续接入上传文件、表格时在这里加分支。

验证:
- 容器内 go build ./internal/...(仅第三方 sqlite-vec cgo 因环境缺
  sqlite3.h 失败)+ go test ./internal/datasource/... 全部通过
- 反向验证:把 Validate 还原成"第一个失败即返回"后,
  TestValidateSkipsWorkspacesTheOperatorCannotRead 与
  TestValidateSurvivesWorkspaceListingFailure 立即失败

* test(datasource/dingtalk): 钉住 Validate 收紧路径并修正 verifyDocument 注释

Validate 改成继续遍历所有工作区后,多出一条比改动前更严的失败路径:
"工作区 1 只有文件夹(可读)+ 工作区 2 有一个本 operator 读不到的文档"
这种配置,改动前在第一个工作区末尾就 return nil,现在会报错。这条路径是
有意的——存在却读不到的文档意味着数据源同步不出任何东西,不是无关工作区
的权限噪音——但之前没有任何测试。

新增 TestValidateRejectsTenantWhoseOnlyDocumentIsUnreadable 固定该行为与
意图;并给既有的"全部文档都读不到"用例补上"错误必须带工作区名/文档名"的
断言(原先只 Contains("no permission"))。

顺带把 verifyDocument 的注释从"上传文件与表格目前不可摄取、永远到不了
这个函数"改成描述不变量:只有 isDocument 接受的原生类型才会进入该函数,
一个类型获得摄取路径时同时成为 document、获得同步读路径并在该函数获得
探测,上传文件与表格随各自的摄取路径一起接入。原措辞在表格/上传 PR 合并
后即失效。

验证:
- go test ./internal/datasource/connector/dingtalk/... -count=1 通过
- 反向验证:把 Validate 换回改动前的实现(首个工作区无文档即 return nil)
  后,新用例失败并报 "Validate must fail";恢复后通过

* fix(datasource/dingtalk): Validate 每个工作区只探 1 个文档,并给探测总数加上限

应用缺少文档读权限时每次探测都会失败,原先会把每个工作区根目录下的每个文档
都串行探一遍,大租户里一次校验就是几百次调用。改为探测失败后直接跳到下一个
工作区,并且最多探测 maxValidateProbes(5) 个文档后返回最后一个错误。

* fix(datasource/dingtalk): Validate 进入文件夹找文档,根目录只有文件夹的工作区不再被误判

根目录只有文件夹、文件夹里有可读文档的工作区,原先会被另一个读不到的工作区拖累,
整体判失败(main 上这种情况是通过的)。Validate 现在按 scanWorkspace 的走法对
每个工作区做广度优先查找,取第一个文档探测;子文件夹列举共用 20 次额度,额度用尽
仍有文件夹没看完时视为无法证伪,直接通过。

* fix(datasource/dingtalk): Validate 子文件夹列举失败不再当空目录,并按页限额、防环

- 非根文件夹列举失败时把本次校验记为无法确定(放行),不再当成空目录导致
  另一个工作区的不可读文档把整库判死;取消/超时错误直接返回,不再被当成
  凭据有效,也不会被之前记下的 inconclusive 吞掉。
- BFS 加 visited 集合,子节点 ID 等于祖先或工作区根时不再无限列举。
- 新增 listNodesPage 单页列举,Validate 的列举额度按实际 HTTP 分页计数:
  节点列举请求最多 len(workspaces) + maxValidateListings 次(另加客户端重试)。

* fix(datasource/dingtalk): Validate 先翻完同层分页再进子文件夹,重复 nextToken 时停下

子文件夹排在父目录下一页之前时,根目录第一页全是文件夹、文档在第二页的
工作区会把列举额度花在子文件夹上,第二页的文档永远探不到。现在每个文件夹
先翻完自己的分页再下钻,和 listNodes 给 scanWorkspace 的顺序一致;同一
文件夹重复返回 nextToken 时停下并按无法确定处理。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: 🏠 <linus@192.168.10.6>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 15:20:27 +08:00
wizardchen ae90546262 fix(frontend): avoid false unsaved changes warnings 2026-10-08 14:57:40 +08:00
LuckVd b5c8d90cc2
fix(chat_pipeline): treat non-JSON model refusals as skipped graph extraction (#3606)
* fix(chat_pipeline): treat non-JSON model refusals as skipped graph extraction

When a chunk carries nothing extractable (e.g. a table-of-contents page),
the LLM correctly answers with a prose refusal such as "抱歉…". parseOutput
then fed that prose to json.Unmarshal, failing with a confusing
"invalid character 'æ'" (the first byte of a CJK character), marking the
chunk task GRAPH_EXTRACT_FAILED and letting asynq replay the identical
doomed LLM call up to the retry limit.

Classify responses that contain no JSON structure at all (no '{' or '[')
as errModelDeclined and complete the extraction with an empty graph so the
task succeeds as an explicit skip. Malformed or truncated JSON (structure
present) still fails and retries as before.

Fixes #3600

* fix(chat_pipeline): keep empty model responses retriable in graph extraction

An empty response is usually transient (gateway returning 200 with no
content, a reasoning model spending its whole budget on reasoning,
content filtering), and a retry often succeeds. Only non-empty prose
with no JSON structure is treated as a declined extraction.

* fix(graph): skip prose refusals only in the async chunk task, keep truncation retriable

ParseGraph no longer turns a prose answer into an empty graph. It returns
an error wrapping ErrModelDeclined, and ChunkExtractService.Handle is the
only caller that treats it as a skip (span output skipped=model_declined).
The /initialization "try extract" endpoint and query-side entity extraction
report the refusal as a failure again, so the graph settings form no longer
gets its few-shot examples replaced with an empty result.

Extractor.Extract drops the ErrModelDeclined marker when finish_reason is
"length": prose with no JSON because the output budget ran out is
truncation, and asynq should retry it.

* fix(graph): retry every truncation spelling, not only finish_reason=length

Extract kept a prose answer retriable only when FinishReason was exactly
"length". max_tokens / max_output_tokens (and case/space variants that
IsLengthFinishReason already accepts), a stream that broke before the stop
event ("incomplete") and an adapter that reports no reason were still read
as a refusal, so the async chunk task skipped the chunk for good.

Only a reason that proves the model stopped on its own now counts as a
refusal. Ollama's non-streaming Chat also forwards done_reason, so a
num_predict cut-off is reported as "length" instead of an empty string.

* fix(graph): only treat a response with no JSON anywhere as a refusal

The refusal check looked at the first extracted fence, so a prose fence
followed by a JSON fence was skipped as a refusal instead of failing as a
retriable parse error.

---------

Co-authored-by: LuckVd <LuckVd@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 14:57:11 +08:00
5quan 3fb6b9d631
fix(kb): let the update API set vlm_config (#3704)
* fix(kb): let update API set vlm_config

UpdateKnowledgeBaseRequest only carried name/description/config, so the
PUT /knowledge-bases/:id endpoint could never change a knowledge base's
multimodal (VLM) config, even though CreateKnowledgeBase accepts a
top-level vlm_config. Thread an optional vlm_config through the handler
and service so the update path mirrors create (nil = no change).

Fixes #1723

* test(kb): pass the vlm_config argument in tests added on main

* fix(kb): accept only model-managed vlm_config fields on update

The update API copied the request's VLMConfig wholesale, so a caller
could set the legacy ModelName/BaseURL/APIKey/InterfaceType fields and
have the VLM client call BaseURL directly, outside model management and
its SSRF checks. Only Enabled/ModelID/DescriptionLanguage/
CustomInstructions are taken now; legacy fields keep their stored value.
A referenced model must exist and be a VLLM model (400 otherwise), and
disabling clears ModelID, matching the initialization config endpoint.

* fix(kb): validate and gate vlm_config on the update API

- Enforce the 4000-character custom_instructions cap
  (types.ValidateKnowledgeBasePromptInstructions), as create and
  /initialization/config already do.
- vlm_config is a KB setting: require kbSettingsAccess (owner workspace
  or admin share) like /initialization/config, so share editors get 403.
- Stored legacy model_name/base_url keep IsEnabled() true on their own,
  so disabling returned 200 but left VLM on, and managed -> disabled fell
  back to the old endpoint. Clear them when the request enables a managed
  model_id, or disables VLM without echoing back the stored
  model_name+base_url (GET-then-PUT keeps legacy on). Request legacy
  fields are only compared, never written. Enabling without model_id on a
  non-legacy KB is now a 400 instead of a silent no-op.
- Document the vlm_config semantics in the KB API reference.

* fix(kb): keep the legacy VLM endpoint only for pure legacy knowledge bases

CreateKnowledgeBase stores vlm_config as sent, so a managed model_id can
sit next to legacy model_name/base_url; resolveVLM then uses the managed
model. The update's keep-legacy paths (disable echoing the stored legacy
fields, enabled=true without model_id) cleared model_id but kept the
legacy fields, so IsEnabled() stayed true and image calls moved to the
stored base_url.

Those paths now apply only when no model_id is stored. On a mixed config
a disable clears everything, and enabled=true without model_id is a 400,
the same as on any managed knowledge base.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 14:37:23 +08:00
LingYi bea0d7b689
fix(docreader): preserve PPTX fallback image associations (#3973)
* fix(docreader): preserve PPTX fallback image associations

* fix(docreader): visit PPTX shapes in MarkItDown's position order

MarkItDown emits pictures sorted by (top, left) per slide and per group, not
in z-order, so two same-named pictures on one slide could swap images. Sort
the same way when collecting placeholder sources.

* fix(docreader): skip unresolvable PPTX picture relationships instead of failing the document

A picture with no a:blip, an r:embed that is dangling or points at an
external relationship, or a media part python-pptx dropped at load time
made _picture_sources raise, so the whole PPTX (slide text included)
failed to parse. Record None for that picture to keep the queue position
and leave its placeholder untouched; other pictures still attach.

* fix(docreader): also skip PPTX pictures whose blipFill is missing

python-pptx raises InvalidXmlError (a PythonPptxError, not a ValueError)
when a p:pic has no p:blipFill; catch it so the picture is skipped
instead of failing the whole document.

---------

Co-authored-by: LingYi-Liang <270316896+LingYi-Liang@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 14:37:07 +08:00
诉说晚秋 d84cdabac4
fix(rss): refresh titles and source links when article text is unchanged (#3824)
* fix(rss): 修复正文未变时标题和来源链接不同步

* fix(datasource/rss): 旧 h: 游标只升级不重建,原文抓取失败时保留旧游标

升级后第一次增量原先会把 feed 里每一条仍在的旧条目删掉重建(Wiki、手工标签、
知识 ID 都会丢),原文接口临时失败时还会把库里的全文降级成 feed 摘要。

现在对旧 h: 游标的条目:重新解析出的正文哈希与 h: 相同时,只把游标升级为 i:
指纹、不输出;原文抓取失败时沿用 h: 游标、不输出,留到下次重试;只有正文真的
变了才输出。

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 14:02:56 +08:00
ZW. 99b4c3a9b0
feat(rerank): support Hugging Face TEI protocol (#3956)
* feat(rerank): support Hugging Face TEI protocol

* style(rerank): satisfy TEI lint checks

* fix(rerank): cap Hugging Face TEI batches at 32 documents

TEI rejects requests above --max-client-batch-size, which defaults to 32.
Without a declared ceiling the shared batching layer sends the whole
candidate set in one request, so a default TEI deployment fails rerank
whenever hybrid retrieval returns more than 32 candidates.

* fix(rerank): send truncate and merge extra_body in the TEI client

TEI before 1.9 starts with --auto-truncate=false and rejects the whole
/rerank call when one passage is longer than the model's input limit, so
retrieval silently falls back to the original order. Ask for truncation
explicitly, as the NIM client does with truncate=END.

The TEI client also ignored compat extra_body, unlike the Cohere, NIM and
DashScope clients. Merge it the same way: query, texts and raw_scores stay
owned by the client, truncate is a default that extra_body may override.

---------

Co-authored-by: bigdu332 <bigdu332@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 14:02:49 +08:00
linus-liu-web 1826f46b12
fix(docparser): 云解析超时改为跟随既有配置,不再硬编码 (#3891)
* fix(docparser): 云解析轮询上限接入配置,去掉两处硬编码超时

PaddleOCR-VL Cloud 与 WeKnoraCloud 两个 reader 的整批轮询上限仍是写死的:
paddleocr_vl_cloud_converter.go 的 paddleOCRVLCloudTimeout(600s)直接决定了
pollJob 的 deadline,reader 结构体没有任何 timeout 字段;weknoracloud_http_reader.go
的 pollTimeout 固定 20 分钟。

同族的另外两个 reader 早就可以配置:MinerU Cloud 走
WEKNORA_MINERU_CLOUD_TIMEOUT(mineru_cloud_converter.go),自建 PaddleOCR-VL 走
WEKNORA_PADDLEOCR_VL_TIMEOUT(paddleocr_vl_converter.go)。后果是运维把
WEKNORA_DOCREADER_CALL_TIMEOUT(默认 30m)调大也无效:WeKnoraCloud 的 20 分钟
比它还短,硬编码上限先触发,大体积扫描件固定在第 10/20 分钟失败。

改动:
- PaddleOCRVLCloudReader 增加 timeout / pollInterval 字段(与 MinerUCloudReader
  同形),构造函数用 requestTimeoutFromEnv 读 WEKNORA_PADDLEOCR_VL_CLOUD_TIMEOUT
  (默认仍是 600s),pollJob 用 c.timeout / c.pollInterval;超时文案对齐 MinerU
  的 "task timed out after %s (%d polls)"(旧的 "after %d polls" 是 27b0c84b 已经
  替 MinerU 换掉的写法)。
- WeKnoraCloudSignedDocumentReader 的 pollTimeout 改读
  WEKNORA_WEKNORACLOUD_TIMEOUT(默认仍是 20m)。
- .env.example 补两条说明,位置紧跟 WEKNORA_MINERU_CLOUD_TIMEOUT。

新增用例:两个 reader 的 env→超时值映射(含空/非法/0/负数回退默认)、超时真的会
结束一个厂商持续报 running 的任务(假服务器与假 Transport,带看门狗,回归时 5 秒
内失败而不是轮询 600 秒)。只回退接线(保留字段)时四条用例在 10 秒内全部变红:
PaddleOCR-VL Cloud 的 200ms 配置被忽略、WeKnoraCloud 读回 20m 而非配置值;
把两个源文件整体回退则用例引用的新配置面不存在,包测试无法编译。

* docs(docparser): document PaddleOCR-VL Cloud / WeKnoraCloud poll timeouts

Add the two new env vars to both website-docs timeout tables and pass them
through docker-compose.yml next to WEKNORA_MINERU_CLOUD_TIMEOUT.

* fix(docparser): WeKnoraCloud 轮询上限在调用方已有 deadline 时也生效

入库和临时文档调用 pollTaskResult 时 ctx 都带有 DocReader 调用超时,
原先的 !ok 条件让 WEKNORA_WEKNORACLOUD_TIMEOUT 在生产路径上被跳过。
改为始终叠加 WithTimeout,context 自动取内外较早的 deadline;
回归测试补上父 ctx 带更长 deadline 的场景。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 14:02:42 +08:00
Jang Dong Ik b5fd79edf2
fix(model): treat 400 as reachable in chat connection test again (#3929)
* fix(model): treat 400 as reachable in chat connection test again

checkChatModelConnection probes with max_tokens=1 and is meant to treat a
400 as "endpoint reachable, auth OK". It detected that by matching the
go-openai wording "status code: 400". Since #3470 the error comes from
api.HTTPError ("API request failed with status 400: ..."), so the branch
never matched and the probe reported a failure.

This shows up with reasoning models behind LiteLLM: the 1-token budget
cannot finish a message, the gateway answers 400, and Test Connection
fails although the saved model chats fine.

Match the status code via errors.As on *api.HTTPError instead of the
message text.

* test(handler): drop unused request parameter in fake chat gateway

* fix(model): report a 400 that carries an auth error as auth failure

Gemini's native API answers an invalid key with 400 INVALID_ARGUMENT /
API_KEY_INVALID. Since the connection check now treats any typed 400 as
reachable, that showed "连接正常,模型可用" for a bad key. Keep the 400 pass
only when the body does not describe a credential problem, and let
classifyConnectionError recognise those bodies so the message says
认证失败 instead of a bare 连接失败.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 14:02:35 +08:00
yetuge a75e8e9ac0
fix(datasource): 语雀/Notion/IMA/飞书连接器 API 响应体补体积上限 (#3985)
* fix(datasource): 语雀/Notion/IMA/飞书 API 响应体补体积上限

#3887 给 GitLab 客户端补了 readCapped 上限;语雀、Notion、IMA、飞书四个
连接器的 API 读取仍是裸 io.ReadAll,破损或恶意端点可让同步进程缓冲无界
响应体。各连接器比照 GitLab 同步同一上限(16 MiB)与显式超限报错,limit
做成字段以便测试下调。飞书 429/5xx 错误路径的 best-effort 读取刻意不动。

* fix(datasource): 响应体上限为零值时回退到默认 16 MiB

测试里直接用字面量构造的 Client 不经过 NewClient,jsonLimit 为 0,
readCapped 会拒绝任何响应,导致 feishu/core 11 个现有测试失败。
readCapped 遇到非正数 limit 时改用 maxJSONResponseBytes。

* fix(datasource): 响应体超限不再重试;补齐飞书 token 与下载错误分支的读取上限

- yuque/ima/feishu/notion 的 readCapped 改用哨兵错误 errResponseTooLarge,
  文案不变;yuque doRequest、ima callAPIAt、feishu DoRequest 遇到超限直接返回,
  不再按退避重试 3 次(同一请求必然再次超限,只会白耗限流额度)。
- 飞书 GetTenantAccessToken 改为 readCapped + json.Unmarshal,和其他 API 响应同一上限。
- 飞书 downloadRawBytes 的 429/5xx/非 200 错误预览只读 4 KiB,
  download failed 错误不再携带完整响应体。

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 14:02:29 +08:00
rill 9a2cd20063
fix(frontend): keep target="_blank" on sanitized markdown links (#3818)
* md预览链接 a 增加target

* fix(security): keep target on links in document preview sanitizer

documentPreviewDomPurifyConfig spread the base config and then replaced
ADD_ATTR with the image attributes only, dropping the 'target' entry
this PR adds, so links in document previews still lost target="_blank".
Extend the base ADD_ATTR instead, and lock both configs with tests.

* fix(security): drop author-supplied target before sanitizing links

ADD_ATTR now allows target globally so the hook-added target="_blank"
survives, but that also kept author values on elements the hook never
rewrites (SVG <a>, <area>, protocol-relative / uppercase / leading-space
hrefs in sanitizeHTML and document preview), e.g. target="_blank"
rel="opener" or target="_top". Strip target in beforeSanitizeElements
so only the hook's _blank, always paired with rel="noopener noreferrer",
can appear.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 14:02:22 +08:00
澍 11aa00f85f
fix(agent): preserve untouched numeric tool arguments during casting (#3936)
* fix(agent): preserve untouched numeric tool arguments during casting

Fixes Tencent/WeKnora#3934

* test(agent): wrap long schema literal to satisfy lll

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:14:18 +08:00
Jin cbfd66fd92
fix(knowledge): delete written chunks when the storage quota check fails (#3656)
* fix(knowledge): delete written chunks when the storage quota check fails

processChunks writes the chunks before the storage quota check. When the
check fails, or the tenant cannot be re-read for it, the knowledge is marked
failed and the function returned without removing those chunks, so they
stayed active (deleted_at IS NULL, is_enabled = true) under a failed,
disabled knowledge. The BatchIndex failure path already deletes them; do the
same in both quota branches. Nothing has been indexed at that point, so only
the chunk rows need removing.

Fixes #3648

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style(knowledge): keep the processChunks doc comment on processChunks

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:14:10 +08:00
Wen.Vale de2dfd3034
fix(multimodal): bound remote image downloads by the file size limit (#3906)
* fix(multimodal): bound remote image downloads by the file size limit

* style(utils): wrap over-long lines in the DownloadBytes test

---------

Co-authored-by: Wen.Vale <224270013+SEVEN-us@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:14:04 +08:00
SIRIUS 49e262147c
fix(cli): preserve directory structure in doc upload --recursive (#3753)
* fix(cli): preserve directory structure in doc upload --recursive

`doc upload --recursive` passed an empty customFileName to
CreateKnowledgeFromFile, so every file landed in the knowledge base root
and the directory tree it was asked to walk was lost. The web UI's folder
upload does not have this problem -- it passes the browser-supplied
relative path, which the server splits into folder_path + file_name via
types.SplitKnowledgeRelativePath.

Pass the path relative to the walked directory instead. Files directly
under that directory still send "" so the request stays byte-identical to
the previous behaviour for the common flat-directory case; only nested
files gain a folder prefix.

- knowledgeRelativePath() converts to forward slashes (the server splits on
  "/", so Windows backslashes would not separate) and returns "" for paths
  outside the walked root rather than leaking a "../" chain into the folder
  tree.
- The test double previously discarded customFileName with `_,` -- which is
  why this could regress with the suite green. It now records the value and
  two tests cover the nested and flat cases.

* fix(cli): reject only the parent component in knowledgeRelativePath

Review feedback on the recursive-upload folder path:

- `strings.HasPrefix(rel, "..")` also rejected children whose name merely
  starts with dots, e.g. `..drafts/report.pdf`. Replaced with a
  component-wise check (`rel == ".."` or `".."+separator` prefix).
- Root-level files must send ""; the guard now returns "" for
  `filepath.Dir(rel) == "."` explicitly rather than relying on the
  accidental prefix match to encode that rule.

Covered by a `..drafts/report.pdf` case in
TestUploadRecursive_PreservesFolderStructure.

* test(cli): expect an empty name for root files in knowledgeRelativePath

knowledgeRelativePath returns "" for files directly under the walked
root, so the test must expect that. Also wrap an over-long line.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:13:57 +08:00
LingYi e6ecb9adcc
fix(dataset): allow selecting the QA answer model (#3944)
* fix(dataset): allow selecting the QA answer model

* test(dataset): expect gpt-5.6-sol as the default QA model

The default moved from gpt-4o-2024-05-13 to gpt-5.6-sol on main (#3965).

---------

Co-authored-by: LingYi-Liang <270316896+LingYi-Liang@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:04:49 +08:00
linus-liu-web 4eb23a8560
fix(qdrant): CopyIndices 用服务端返回的 next_page_offset 翻页,不再按页尾 id 回填 (#3882)
* fix(qdrant): 复制索引改用服务端返回的游标,重复游标报错并给分页加跳数上限

CopyIndices 用"上一页最后一个点的 id"当游标(repository.go:987)。Qdrant 的
scroll offset 是**包含**语义 —— proto 里写的是 "Start with this ID",实测下一页
正是从该 id 本身开始返回,所以每翻一页都会把上一页的最后一个点再读一次、再写一份
到目标库。服务端本来就把下一页该用的游标放在 ScrollResponse.next_page_offset
("Use this offset for the next query")里,而客户端只在 ScrollAndOffset() 中返回它,
本函数调用的 Scroll() 恰好把它丢掉了;终止条件也只能退化成"这一页比 64 短"。

在真实 Qdrant 1.19.1 上实测:150 个源 chunk 复制出 152 个目标点,chunk-63 与
chunk-126 各被复制两次(每个页边界一个),totalCopied 同步虚高。源库只要超过一页
(>64 个 chunk)就会命中,不需要服务端有任何异常行为。

本次修改:

- 改用 q.client.ScrollAndOffset,游标直接取服务端返回的 next_page_offset;终止
  条件改为"服务端没有下一页"(next_page_offset == nil),不再用短页推断读完。
- 记录用过的游标,重复即返回 "copy indices made no progress at cursor ...",
  检测点在整页处理之前,重复的那一页不会再多写一份。
- 分页跳数上限 maxCopyPaginationHops(10000 页);触顶打印 Warn 并返回错误,
  而不是把这一轮复制当成成功。
- 修复后同一份数据在真实 Qdrant 上测得 150 个目标点、0 重复。

回归用例用假 gRPC 服务端(拦截 unary RPC,对齐 repository_test.go 的
newInterceptedQdrantClient)复刻真实服务端的游标语义:150 个源 chunk 必须各复制
一次(修复前 152 个点、2 个重复);游标恒定不动的源端必须报 no progress
(修复前 5 秒写入 3127040 个点仍未返回);一直推进但永不结束的源端在第 10000 页
被拦下。

* fix(qdrant): drop the CopyIndices page cap

10000 pages of 64 points capped a copy at 640k points and failed the
whole clone beyond that. The scroll walks every point of the source
knowledge base (a single-knowledge clone included), so a cap derived from
the chunk map would cut off small clones out of large bases too.
next_page_offset only moves forward, so the repeated-cursor check already
stops a walk that cannot finish, and the task context bounds the rest.

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:04:43 +08:00
MLYoshi 4dd19b5356
fix(frontend): render single tilde literally instead of GFM strikethrough (#3963)
* fix(markdown): 单个波浪号不再被解析成删除线

GFM 会把区间标记(如 2020~2035)里的单个 `~` 误解析成删除线。
覆盖 marked 的 del tokenizer:`~~...~~` 仍走默认删除线规则,
单个 `~` 则按字面保留;并新增单测覆盖时间/区间场景。

* fix(markdown): register the literal single-tilde tokenizer once

doc-content.vue and WikiBrowser.vue called marked.use() for the del
tokenizer override inside <script setup>, so every mount wrapped the
global marked tokenizer one more time. Move the extension into
utils/markedLiteralTilde.ts and register it on the global marked behind
a once-only guard; the preview Marked instance reuses the same
extension object. Add a test that repeated registration does not
re-wrap tokenizer.del.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:04:36 +08:00
Perfecto 336f84c3be
fix(data-analysis): skip style-only worksheets before DuckDB loading (#3660)
* fix(data-analysis): skip style-only worksheets before DuckDB loading

* chore: retrigger CI for XLSX sheet fix

* fix(data-analysis): keep all sheets when the worksheet preflight fails

The style-only sheet preflight is best-effort: if it cannot read the
workbook parts, log a warning and load the sheets DuckDB enumerated
instead of failing the whole workbook. Context cancellation still
aborts the load.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:04:29 +08:00
Lukas e7aaf8ae02
fix(docreader): keep the space held by a whitespace-only inline element (#3978)
markdownify renders an emphasis, code or link element whose text is only
whitespace as "", and the whitespace goes with it. HTML and MHTML
uploads therefore lost word boundaries: `further<strong> </strong>
reference` became `furtherreference`, and `<b>First</b><b> </b><b>Last</b>`
became `**First****Last**`. Editors produce that markup whenever a single
space between two words carries different formatting.

Before conversion, unwrap such elements so their whitespace stays as plain
text. Only elements with no child elements are touched, innermost first,
so a linked image keeps its link and nested wrappers come off completely.
2026-10-08 01:31:48 +08:00
linus-liu-web dabbdaf156
fix(notion): 分页循环补重复游标防护与跳数上限 (#3890)
paginatePages 与 GetBlockChildrenFlat 都只以 has_more / 空 next_cursor 为终止
条件:既不记录用过的游标,也没有页数上限。Notion(或中间网关)只要回
has_more=true 且 next_cursor 不前进——包括"空 results + has_more=true"这种厂商
形状——循环就永远退不出来,同一页被反复抓取:SearchPages(资源发现)与
QueryDatabaseAll(数据库记录)都汇入 paginatePages,客户端自带 3 req/s 限流,
所以表现为以 3 rps 稳定空转到任务 deadline,同步任务永不进终态;若伴随非空
results,allPages 还会无界增长。

同文件的 getBlockChildrenRecursive 已有 maxBlocksPerPage 兜底,Confluence
(seen + maxPaginationHops)、DingTalk(seenTokens + maxPages)也有同族守卫,
这两条循环漏了。

改动:
- 抽一条 advancePaginationCursor:每页取回 next_cursor 后调用,重复游标立即报
  错,页数达到 maxPaginationHops(10000,对齐 Confluence)时 Warn 并报错。触顶
  必须留日志:从外部看这种失败和"还在正常同步"一模一样。
- paginatePages 与 GetBlockChildrenFlat 一并接入(同文件同型缺陷,发现阶段扫子
  页面走的正是后者)。

新增用例:重复游标(第 2 次请求即报错,含"空页 + has_more=true"形态)、跳数上限
(正好 10000 次请求后报错且日志含 "pagination exceeded 10000 pages")、真实多页
仍正常合并。测试把 3 rps 限流换成不限速,否则回归场景要跑 55 分钟。去掉本次改动
后三条用例全部失败(重复游标场景实测跑到 10006 次请求才被假服务器的预算拦下)。

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 01:29:20 +08:00
linus-liu-web 5077f35800
fix(notion): 超过 block 上限截断时补 Warn,避免内容与子页面静默缺失 (#3771)
* fix(notion): 超过 block 上限截断时补 Warn,避免内容与子页面静默缺失

单个页面/块超过 maxBlocksPerPage(1000) 时客户端会静默停止分页:第 1000
个 block 之后的正文不会进入 markdown,其后的 child_page/child_database
也不会被 fetchPage 递归同步。又因为游标记录的是 last_edited_time,页面
未变更时同步会直接跳过该页,截断因此长期存在且无任何提示。飞书同类上限
(feishu/core/blocks.go 的 maxDocumentBlocks)已有 Warn,这里对齐其措辞
补齐可观测性。

- cap 触发且 API 仍有下一页时打一条 Warn,含块/页面 ID 与上限数字,说明
  剩余 block 不会被同步;是否真为截断由纯函数 blocksTruncated 判定,恰好
  1000 个 block 的页面不会误报;
- 不改 cap 数值、page_size、递归逻辑与游标语义。

测试 truncation_test.go:伪造返回 1001 个 block 的 children 接口,断言
Warn 内容且第 11 次请求未发出;另覆盖恰好 1000 的边界与 blocksTruncated
真值表。

* fix(notion): has_more 但 cursor 为空时不再静默丢内容

blocksTruncated 的第三个条件 nextCursor != "" 在 Notion 契约下与 has_more
冗余:has_more=false 时 next_cursor 必为 null。于是"has_more=true 但
next_cursor 为空"这种异常响应仍会静默截断——未命中 cap 时循环本就因空游标
break,命中 cap 时又因该条件跳过 Warn,两种情况都不留痕迹。

- 谓词收敛为 currentCount >= maxBlocksPerPage && hasMore,不再要求游标非空:
  cap 命中且 has_more=true 即视为截断;
- has_more=true 而 next_cursor 为空时单独打一条 Warn,带上块 ID 与已取块数,
  说明无法继续翻页、剩余内容不会被同步(无论是否命中 cap 都打);
- 不改 cap 数值、break 条件、page_size、递归深度与游标语义。

测试:真值表去掉游标列,并删掉把"cap 命中 + 空游标 = 不告警"固化成期望的
用例;新增 TestBlockCapWarnsWhenHasMoreHasNoCursor(cap 命中 + has_more=true
+ 空游标须同时出现 cap Warn 与游标 Warn,且不发出第 11 次请求)与
TestHasMoreWithoutCursorWarnsBelowTheCap(cap 以下同样要告警);原有正常翻页
用例补断言:格式正确的分页不得出现游标异常 Warn。反向验证:谓词还原为原样
后两个新用例均失败。

* test(notion): rename block-cap log helper to avoid clashing with #3845

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 01:29:12 +08:00
ordinary being 6057a81017
fix(middleware): stop buffering whole request bodies in the access log (#3927)
Logger() runs ahead of Auth and of every route handler, and read the entire
request body with io.ReadAll before any per-route http.MaxBytesReader was
installed. Bound the read to the log budget and hand the unread remainder back
to the handler through io.MultiReader.
2026-10-08 01:29:05 +08:00
kevin 20038cbda6
fix(asynqdl): truncate dead-letter errors on a rune boundary (#3964) 2026-10-08 01:28:59 +08:00
Fei.Chen dad81cb8c1
fix(sandbox): reclassify exec races with the idle sweep as NotFound so rebinding heals (#3980)
An exec that collided with the idle sweeper's delete (#3942 mechanism A)
surfaced as a non-zero exit with an empty stderr, which the filesystem op
wrappers classified as InvalidRequest — outside CanReplaceRemoteBinding's
NotFound/Terminal allow-list, so the rebinding self-heal never ran and the
failure reached the user (empty answer, zero steps). The op wrappers now
re-inspect on failure and reclassify as NotFound when the Engine confirms
the container is gone, making the sweeper's 'deleting needs no coordination
with the binding store' premise hold for the mid-flight window too. Only a
confirmed 404 reclassifies; transport errors keep the original kind.

The shared message now carries the exit code — with an empty stderr it was
the one missing clue during the original diagnosis (#3942).

Co-authored-by: vicfei <vicfei@users.noreply.github.com>
2026-10-08 01:28:53 +08:00
Fei.Chen b8d83eab1c
fix(skills): skip vendored dep trees in install verification script enumeration (#3943)
* fix(skills): skip vendored dep trees in install verification script enumeration

sortedScriptPaths fed every .py/.js/.sh in the bundle into one shell 'for
f in ...' command. A skill that vendors a scientific venv (pandas/scipy/
matplotlib etc.) carries thousands of .py files under .venv/, and the
generated command exceeds the exec single-argument limit (MAX_ARG_STRLEN,
128KiB): /bin/sh fails with 'argument list too long' (exit 255) before
any check runs, so no dependency-heavy skill can ever install.

Vendored trees are installed dependencies, not scripts the model can
name; their health is already covered by the dependency verification
passes. Skip .venv/ and node_modules/ prefixes in sortedScriptPaths,
which fixes the tree check, the per-language parse passes and the
runtime prerequisite pass at once.

Verified by installing a 4862-file / 105MB quant skill (pandas+numpy+
scipy+statsmodels+matplotlib venv, real interpreter binary instead of
symlinks since zips cannot carry them): install failed before the fix,
reaches ready after it.

* fix(skills): skip vendored trees at any depth, not only at the bundle root

Bundles are author-zipped, so tools/.venv/ or sub/package/node_modules/
are as legal as root-level trees and enumerated just the same. The
filter now matches vendored trees under any prefix; nested placements
are covered by a regression test.

---------

Co-authored-by: vicfei <vicfei@users.noreply.github.com>
2026-10-08 01:28:45 +08:00
fhgffy 562127c654
fix(client): accept optional spaces in SSE event fields (#3975) 2026-10-08 01:28:38 +08:00
LeonSGP b413023d28
fix(cli): classify wrapped SDK HTTP errors correctly (#3992) 2026-10-08 01:28:31 +08:00
LeonSGP ff33184433
fix(cli): preserve integer precision in jq output (#3991) 2026-10-08 01:28:25 +08:00
LeonSGP cefd5920f8
fix(cli): apply list limits after filtering and sorting (#3990) 2026-10-08 01:28:19 +08:00
LeonSGP 7d75ce3a6f
fix(client): make multipart uploads replayable (#3989) 2026-10-08 01:28:12 +08:00
dvd233 4a0c7fa91f
fix(cli): render paginated API results in text mode (#3984) 2026-10-08 01:28:05 +08:00
dvd233 4ea94afcb9
fix(cli): propagate paginated response read errors (#3983) 2026-10-08 01:27:58 +08:00
xxxxx 9d4cc233c6
feat(ui): add search to Skills and MCP toolbox lists (#3731) 2026-10-08 01:27:51 +08:00
VictorMaznyuk 3206e15e83
fix(docs): make `make docs` reproduce the committed Swagger again (#3751)
Running `make docs` on main no longer reproduces the committed docs/*:
every definition loses its package-qualified name (types.* instead of
github_com_Tencent_WeKnora_internal_types.*), enums disappear, ErrorCode
becomes a plain integer, and docs/swagger_contract_test.go fails
(TestModelDeleteUsageContract).

Cause: internal/localsandbox is not a dependency of cmd/server (its
importers are behind the `desktop` build tag), but swag's directory walk
reaches it. Its `const X = core.X` aliases make swag load
internal/localsandbox/core again through go/loader, and that second load
re-registers every already-deduplicated type under its short name without
enum values. Excluding the directory removes the second load.

That load was also hiding a second problem: skill_handler.go references
errors.AppError in @Failure without importing internal/errors, so with the
exclude swag stops with "cannot find type definition: errors.AppError".
A blank import lets swag resolve it.

Co-authored-by: Victor Maznyuk <victor@maznyuk.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 01:26:08 +08:00
dependabot[bot] 11bfacad97
chore(deps): bump the cli-deps group in /cli with 2 updates (#3920)
Bumps the cli-deps group in /cli with 2 updates: [github.com/mattn/go-runewidth](https://github.com/mattn/go-runewidth) and [github.com/modelcontextprotocol/go-sdk](https://github.com/modelcontextprotocol/go-sdk).


Updates `github.com/mattn/go-runewidth` from 0.0.28 to 0.0.30
- [Commits](https://github.com/mattn/go-runewidth/compare/v0.0.28...v0.0.30)

Updates `github.com/modelcontextprotocol/go-sdk` from 1.7.0 to 1.8.0
- [Release notes](https://github.com/modelcontextprotocol/go-sdk/releases)
- [Commits](https://github.com/modelcontextprotocol/go-sdk/compare/v1.7.0...v1.8.0)

---
updated-dependencies:
- dependency-name: github.com/mattn/go-runewidth
  dependency-version: 0.0.30
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: cli-deps
- dependency-name: github.com/modelcontextprotocol/go-sdk
  dependency-version: 1.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: cli-deps
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-08 01:26:00 +08:00
linus-liu-web 626185a120
fix(wiki): 重建链接逐页写失败不再静默,半成品不再回 200 (#3884)
RebuildLinks 的保存循环把每页 UpdateMeta 的失败降级成一条 Warn,函数最后
无条件 return nil,于是 handler 里既有的 err != nil 分支永远进不去:任意
一页写失败(行锁等待、死锁、连接中断、超时)时调用方仍拿到
200 "Links rebuilt successfully",而这些页面的 in_links/out_links 保持旧
值,反向链接与图谱继续显示过期关系,且没有任何途径知道"只重建了一部分"。

保持尽力而为的语义不变(一页失败不影响其余页面继续写入),但把失败页聚合
起来在结尾返回,沿用同仓库 knowledge_delete.go / wiki_ingest.go 的
errors.Join 写法,以及同文件 MovePage 对同一个 UpdateMeta 调用的报错写法。
handler 无需改动:其既有 500 分支会如实返回 "N of M pages failed" 与失败页
slug。

回归用例用 SQLite 触发器让指定页的 UPDATE 真的报错(不是 mock),走真实仓库
与真实 handler:
- 部分失败:RebuildLinks 返回聚合错误,可写页仍被刷新,失败页保持旧值;
- 全部失败:错误里含 3 of 3 与全部 slug;
- HTTP 层:部分失败回 500 且错误体含失败页与底层原因,全部成功才回 200。

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-08 01:25:53 +08:00