Commit Graph

3548 Commits (44d90beea22a08b701fe3e33b650af9816a4f9f4)

Author SHA1 Message Date
linus-liu-web 44d90beea2
feat(docreader): 上传 HTML 只索引正文,与 URL 导入路径对齐(开关,默认关) (#4424) 2026-10-17 23:24:22 +08:00
LuckVd f89a15e61c
fix(frontend): bundle PDF.js wasm decoders (#4382) 2026-10-17 23:19:37 +08:00
LouisHong 75e7ee4d41
test(mcp): cover read_document query and pagination contract (#4426) 2026-10-17 23:17:26 +08:00
linus-liu-web 26ff988823
fix(notion): 递归子块分页补重复游标与跳数上限,兜底不再被空页绕过 (#4411) 2026-10-17 23:17:21 +08:00
linus-liu-web b2e81a9ac4
fix(notion): 附件下载失败中止本轮不再推进游标,附件不再永久缺失 (#4413) 2026-10-17 23:17:16 +08:00
linus-liu-web 4d767d9dc4
fix(yuque): 两处 offset 分页补跳数上限、重复页检测与 meta.total 提前结束 (#4415) 2026-10-17 23:17:11 +08:00
linus-liu-web 073b5ea616
fix(datasource): 数据源类型图标的 alt 用本地化显示名,不再用裸 type (#4420) 2026-10-17 23:17:07 +08:00
linus-liu-web d92728d88c
fix(datasource/dingtalk): Validate 只校验所选范围,不再扫全租户 (#4421) 2026-10-17 23:17:02 +08:00
linus-liu-web e849eaad5c
feat(datasource/dingtalk): 保留来源目录结构(开关控制,默认关) (#4422) 2026-10-17 23:16:57 +08:00
Jay0130-a 0aa1a517c8
fix(helm): make the data-files claim access modes configurable (#4425) 2026-10-17 23:16:52 +08:00
linus-liu-web a9290dcb60
fix(docreader): Excel 百分比被读小 100 倍 —— 加开关(默认关) (#4423) 2026-10-17 23:16:45 +08:00
linus-liu-web a7d915a70a
feat(resource): 相同图片字节复用一个 handle,不再重复写字节与重复注册 (#4419) 2026-10-17 23:16:40 +08:00
AsanoReo 42f91f7aa7
fix(wiki): read scanned-page OCR when the text chunks are only images (#4430) 2026-10-17 23:16:36 +08:00
Lukas da3317039b
fix(docparser): keep every row and cell of a CSV upload in its table (#4435) 2026-10-17 23:16:31 +08:00
Xinliang Zheng 164dafca85
feat(graph): add standalone JSON graph search API (#4395) 2026-10-17 23:00:55 +08:00
davien b373374bf3
fix(feishu): keep nested text in native table cells (#4400) 2026-10-17 23:00:01 +08:00
Jarvis 2fac6381f7
fix(search): preserve chunk types in tool results (#4402) 2026-10-17 22:48:23 +08:00
Jarvis 8ddb245d1b
fix(mcp): clarify read_document query and pagination semantics (#4403) 2026-10-17 22:48:21 +08:00
linus-liu-web 340b72f141
fix(models): 图片解析复用仓储层的 provider scheme 表,对象存储上的图片不再原样交给厂商 (#4405) 2026-10-17 22:48:17 +08:00
linus-liu-web 2b4c0e362f
fix(wiki): 列 wiki 页面的 page_size 补上界,与兄弟路径一致 (#4407) 2026-10-17 22:48:14 +08:00
linus-liu-web 5044ef69f9
fix(chat): 消息历史与搜索的 limit 补上下界,limit=-1 不再取消 SQL LIMIT (#4409) 2026-10-17 22:48:10 +08:00
linus-liu-web e6dc60be32
fix(knowledge): 文件夹树显示递归文档数,不再把有子目录的文件夹显示成 0 (#4428)
* fix(knowledge): show recursive folder counts in the folder tree

Connector-synced knowledge bases now come with multi-level folders, so a
parent folder often holds no documents of its own while its subtree holds
several. The folder tree, the breadcrumb and the empty state all read
document_count (documents directly in the folder), so those parents rendered
0 and the document list stated "this folder has no documents yet" even though
the documents were one level down. The API was already correct: total_count
carries the recursive number.

- KbFolderTree renders the row's totalCount; the existing tooltip still spells
  out the direct/recursive split.
- KnowledgeBase reports the selected folder's recursive total in the
  breadcrumb. Filtering keeps the flat result count, and a tree that is
  missing or stale falls back to the loaded list total.
- The empty state gains a third branch for folders whose documents all live in
  sub-folders, with a new emptyFolderWithSubfolders message in all six locales.
- folderTree.ts exposes folderDocumentCounts() and shares the node lookup with
  childFolders().

Tests render the tree through Vite SSR (a 0/5 parent and the root row) and
cover the breadcrumb/empty-state computed values plus the template wiring.

* fix(knowledge): count sub-folders beside the breadcrumb document count

The breadcrumb reported the selected folder's recursive document total while
the document list only renders that folder's own documents. A folder holding 2
documents and 1 sub-folder therefore claimed "3 documents" next to a list of 2.
Report the two numbers the page can actually account for, the way the DingTalk
original does: "{documents} documents / {folders} folders".

- The breadcrumb renders a new two-part folderContentsCount message in all six
  locales. Browsing counts the loaded list total (the documents on screen) and
  the folder's direct sub-folders; filtering keeps the flat result count and
  adds no folder number, since it searches documents rather than folders.
- The sub-folder number is childFolders().length: the tree's top-level folders
  at the root, the selected node's children in a folder, and 0 when the tree is
  unavailable or the path is stale.
- The recursive total stays where it is useful: the tree row (totalCount) and
  the empty state, whose folderSubfolderDocumentCount is a different quantity
  (documents below the folder) and is left untouched.

* fix(knowledge): list sub-folders in the document views

Render the current folder's direct sub-folders as rows in the list and as
cards in the grid, ahead of the documents, so browsing matches a file manager
and the DingTalk folder view. Folder entries are navigation only: they carry
no batch checkbox and never enter document selection or sorting.

Filtering still searches the subtree and shows documents only. When the folder
tree is unavailable the views receive an empty list instead of crashing.

Also hide the breadcrumb's folder segment when the folder has no sub-folders
(falling back to the document-only message) and pluralize the folder count in
English and Russian.

* fix(knowledge): use t-icon sizes so the style guard stays at its baseline

The folder row/card icons were sized with literal CSS font-size values,
which the style guard counts against a fixed baseline. Use the t-icon size
attribute instead, as the guard's own guidance asks.

* fix(knowledge): preserve folder list icon size after style guard cleanup

---------

Co-authored-by: linus-liu-web <linus-liu-web@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-17 22:37:58 +08:00
Lukas e2a58ea3cb
fix(docparser): keep JSON numbers and <, >, & as written in JSON uploads (#4436)
jsonToMarkdown decoded the upload with json.Unmarshal, which turns every
number into a float64. An id above 2^53 therefore changed digits:
12345678901234567890 came out as 12345678901234567000, and
9007199254740993 as 9007199254740992. 1.50 became 1.5 and 1e5 became
100000. The decoder now uses UseNumber, and each number is written back
exactly as it was in the file.

The chunks were encoded with json.Marshal, which escapes <, > and & for
embedding in HTML, so "a < b && c > d" was indexed as
"a \u003c b \u0026\u0026 c \u003e d". They are now encoded with HTML
escaping off, in the size measurement as well, so a chunk is measured as
it is written.
2026-10-17 22:31:39 +08:00
jack 1fc00cdc08
fix(agent): share one configurable budget for web_fetch (#4432)
web_fetch stopped at 60s inside the page fetch. The tool wrapper, storePage,
and the HTTP and chromedp fetcher each had their own cap, so a page that
needed about 150s never finished.

WEKNORA_WEB_FETCH_TIMEOUT is the single page budget (default 3m). HTTP and
chromedp share it, and the agent wrapper waits 5 seconds longer so the tool
can return its own result. Other tools and the 15s pipeline fetcher keep
their current timeouts.

Fixes #2298

Co-authored-by: Frank-zhu2000 <332350688+Frank-zhu2000@users.noreply.github.com>
2026-10-17 22:28:32 +08:00
Lukas 578ca1b519
fix(docreader): keep a pipe inside an HTML table cell in that cell (#4433)
HTML and MHTML uploads turn tables into GFM through markdownify, which
writes a pipe in a cell's text as is. That pipe ends the cell, so
<td>a|b</td> became two cells and every later cell in the row moved one
column right. Pipes in table cell text are now escaped before the
conversion, as `\|`.

The escape then has to survive MarkdownTableUtil, which normalizes the
converted tables and split rows on every pipe: `| a \| b | c |` came out
as a three-column row with the escape turned into `\ |`. It now splits
on unescaped pipes only; a pipe after an odd run of backslashes is cell
text, as in the Go chunker since #3979.
2026-10-17 22:27:49 +08:00
lyingbug 345855b59c
fix(anydoc): upgrade patched zip dependency to 9 (#4437) 2026-10-17 22:24:54 +08:00
lyingbug 8776a2d92d
feat(assistant): let the assistant find skills and MCP services on the web (#4429)
* feat(assistant): let the assistant find skills and MCP services on the web

Enable web_search/web_fetch for the WeKnora assistant so it can locate a
skill source or MCP endpoint from a description, with prompt guidance on
sources, injected page text, console-only credentials and a missing search
provider. mcp_service.create now always asks the user.

Agent trials no longer stall on prompts nobody can answer: tool approvals
are refused at once and OAuth falls back to the non-interactive notice.

* fix(ci): wrap the unattended approval test constructor

golangci-lint rejects the NewGate call at 127 characters.
2026-10-17 15:25:08 +08:00
lyingbug 0d7516ea0a
feat(assistant): expand management operations and polish interaction UI (#4427)
* fix(assistant): polish interaction cards and stabilize composer context

Localize operation labels across all six UI languages and expose answer copying in the assistant panel. Refine question and page-link cards with a single open/return action, and keep the current-page context row at a stable height.

* feat(assistant): add common data source, chunk and knowledge base operations

* feat(assistant): support parsing configuration and batch FAQ updates

* feat(assistant): add MCP tool directory query and sync operations

* feat(assistant): manage web search providers and data source sync settings

* feat(assistant): add model configuration copy operation

* feat(assistant): add workspace profile members and system information operations

* feat(assistant): add system administrator queries and runtime diagnostics

* fix(frontend): polish assistant and resource card UI

Refine assistant composer layout, context controls and reply actions, including narrow-window alignment. Unify knowledge base, agent and shared-space cards with consistent icons, hover feedback, favorites, menus and compact localized statistics.

* fix(assistant): preserve concurrent settings and exclude upstream error secrets
2026-10-17 14:35:58 +08:00
The one -Niu f5cfa0ff5f
fix(knowledge): leave the root span open while a retry is left (#4357)
* fix(knowledge): leave the root span open while a retry is left

FailSpan closed the attempt root as failed on any main-stage failure, but
asynq retries reuse the payload and record onto the same attempt. Once the
root is terminal FinalizeAttempt returns on its guard, so a retry that
succeeds leaves the root failed while every child span and the document
itself report completed.

Defer the root's terminal status until the runner has no retry left, using
the same counters ProcessDocument already computes isLastRetry from.

* fix(knowledge): distinguish terminal span failures from retryable errors

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-17 00:24:34 +08:00
The one -Niu ad63fc4b8c
fix(frontend): label the parser engine the backend will actually pick (#4354)
pickDefaultEngineName guessed the default from engine availability order,
so it badges anydoc as the PDF default while preferAnydocWhenAvailable
deliberately excludes PDF, and it labels builtin as the default for the
simple formats the Go reader actually handles.

Mirror the three backend routing tables instead of guessing, and pin the
mirror with a per-group assertion table.
2026-10-16 23:50:15 +08:00
Chris Chen 86767d77e9
fix(frontend): cap concurrent status requests in upload polling (#4348)
The upload panel split every file still parsing into chunks of 40 and
sent all chunks at once on each poll. With a few thousand files in
flight that is 100+ parallel /api/v1/knowledge/batch requests every
few seconds, each holding a Postgres connection, which exhausts the
default max_connections=100 (FATAL: sorry, too many clients already).

Keep at most 4 status requests in flight per poll; the remaining chunks
are queried as earlier ones finish.

Claude-Session: https://claude.ai/code/session_014ENAekfB7Um4VUnzUWWAv1
2026-10-16 23:43:26 +08:00
lyingbug 7115cb2a61
feat(assistant): trial runs, session grants, page links, and MCP/model/skill management (#4375)
* feat(assistant): let the assistant check MCP services and retrieval

Add a probe risk for operations that change nothing but do real work
(connecting to a service, running a retrieval). Probes use POST, run
without approval at every access level, and are capped per run.

Open three operations on top of it:
- mcp_service.test: connect with the saved settings and report why not
- mcp_service.list_tools: list what a service offers before binding it
- knowledge_base.search: raw hybrid recall with thresholds, to explain
  why a document is or is not found

x-agent can now name one method when a handler documents several, and
catalog parameters accept numbers.

* feat(assistant): let the assistant try an agent it set up

Add try_agent: the assistant asks an agent one question the way a user
would and gets back its answer, the tools it called and the documents it
cited, so it can check a setup before calling it done.

- The trial runs as the signed-in user in a new agent_trial session kind,
  which ordinary listings already exclude and the API cannot create, and
  the session is removed afterwards. Runs are non-interactive, so tools
  that would ask the user are refused. Long-term memory is untouched: it
  is written only by the HTTP handler.
- The assistant itself, the Wiki fixer and the skill installer cannot be
  tried, nor any agent granted the operation catalog.
- A trial spends model calls and runs the agent's own tools, so it is a
  write for the access level: confirm asks, auto_write runs, read_only
  does not offer it. The confirmation card names the agent and question;
  ConfirmedTool now lets a wrapped tool supply that text.
- At most 3 trials per turn, 4 minutes each; the tool timeout is raised
  above that. Answers, tool errors and references are capped.
- The runner is bound to the session service after the container builds
  it, since the session service depends on the agent service.

* feat(assistant): let the user allow similar changes for the conversation

The confirmation card for a recoverable change now offers "allow this for
the rest of the conversation". Once chosen, later calls of the same kind
in the same session run without asking, so a batch tidy-up no longer
needs a click per item.

- What a grant covers is derived on the server, never taken from the
  model: the same catalog operation on the same knowledge bases (a
  document's knowledge base comes from the target read) or the same
  agent; the same Wiki tool on the run's Wiki knowledge bases; trials of
  the same agent. Deletions and operations without such a scope, such as
  creating a knowledge base, always ask.
- No new storage: the gate looks for an earlier approved prompt in the
  session with the same grant and allow_in_session set, for the same
  tenant and user. Grants therefore survive suspend/resume and replicas,
  and end with the conversation. A failed lookup asks again.
- The response validator accepts allow_in_session only on approval and
  only when the prompt offered a grant, so a client cannot widen it.
- The card shows the scope in the user's language. The model is told
  such calls may run without a card and that deletions always ask.
- describeTarget now returns its target read so the grant reuses it
  instead of reading again.

* feat(assistant): tell the assistant about settings pages and chat answers

Pages now report which page is open and, for the agent editor, which
section. The model and MCP settings name the model or service open for
editing, and chat answers gain an "ask the assistant" button that
attaches that answer. The backend resolves these for the assistant only:
models and MCP services in the caller's tenant without endpoints or
credentials, and messages through the caller's session read access, with
the question, an answer excerpt and cited sources quoted as data.

* feat(assistant): link the user to pages and filled-in forms

The assistant gains open_page, which shows a button to a knowledge base
or document, a Wiki page, an agent's editor at a tab, a model or MCP
service to edit, or a new model or MCP service with its form filled in.
Targets are read through the operation catalog as the user, so a link
never points at something they cannot open. Drafts take no credentials
and only http(s) endpoints without user info; the card shows the
endpoint, and the user enters keys and saves the form themselves.

* feat(assistant): manage MCP services, model names and skills

* fix(assistant): prefill model drafts on initial navigation

* feat(assistant): document tags, model catalog reads, clearer cards, live page refresh

- Operations project lists of objects; knowledge.get/list report tags.
- model.get shows provider, endpoint and capabilities; new
  model.list_providers and model.get_provider read the model catalog,
  including vendors an admin added.
- open_page and ask_user guidance: offer page buttons whenever the next
  step is the user's, word choices for the user.
- Chat cards: redesigned open-page card pinned under the final answer,
  ask-user inputs in the dock style, approval card with aligned fields,
  translated labels and a question built from the operation summary.
- Open pages reload after assistant changes: deletes and moves wait for
  the background task, Wiki edits now report their changes, KB list
  counts, tags and chat model selectors refresh.
- The assistant panel stays open across reloads within the tab.

* fix(ci): format assistant operation code and wrap long lines

* feat(assistant): let the assistant see, fill and open the page beside it

- read_page / fill_page tools answered by the browser over a page_action prompt,
  with refs, redaction, in-place text edits, undo card and a page-access switch
- composer shows the open page, dialog and selection; a selection bubble and an
  editor toolbar entry ask the assistant about the selected text
- edits scroll into view with a highlight and an inline undo bar
- open_page reaches any settings section, toolbox tool and list page, and can
  navigate there itself to read it, keeping the button when edits are unsaved

* feat(assistant): let the assistant open the tab it needs

A visible tab can be selected and re-read, and system settings can open straight to user management, so the next step is no longer blocked on the wrong tab.

* feat(assistant): expose read-only conversation operations

Add session.list, message.list, message.search and
message.chat_history_stats to the operation catalog, restrict the
sessions and messages areas to non-mutating operations, and search
messages with the raw query instead of the log-sanitized one.

* style(chat): restyle open-page and page-edit cards

* fix(ci): comply with assistant card styles and Go line limits
2026-10-16 23:36:01 +08:00
tayadwx 9a7aa48e44
build(docker): mount the Go build cache when building the app image (#4320)
The compile step sits after `COPY . .`, so every source change invalidates
it. Without a build-cache mount each rebuild regenerates the whole Go
compile cache inside that layer (~2.7 GB): it accumulates in the local
builder cache, and since CI exports intermediate layers
(cache-to: type=gha, mode=max) it is uploaded to the GitHub Actions cache
whose per-repository storage limit is a hard 10 GB.

Mounting /root/.cache/go-build keeps the cache outside the layer: repeated
local builds reuse compiled objects instead of recompiling everything, and
the cached/transferred layer shrinks from ~3 GB to ~265 MB (the compiled
binary). Multi-stage output is unchanged - the final stage still copies
only the binaries and assets it names.

Co-authored-by: tayadwx <tayadwx@users.noreply.github.com>
2026-10-16 23:34:13 +08:00
Jay0130-a e07a190219
fix(tools): reject legacy binary .xls with an actionable error (#4374)
* fix(tools): reject legacy binary .xls with an actionable error

DuckDB's excel extension only reads the ZIP-based OOXML container
(.xlsx/.xlsm). A genuine binary BIFF .xls therefore fails deep inside
read_xlsx with "No xl/workbook.xml found in xlsx file", which neither
names the real cause nor says what to do; the multi-sheet .xls in #4239
surfaced exactly this way and left the agent with an empty table.

Sniff the OLE2/CFB signature by content (not by extension, so a renamed
.xlsx keeps working) and fail up front with a message that names the
conversion to perform. The tool description is updated so the model is
told the same thing before it calls the tool.

Refs #4239

* fix(tools): wrap the legacy-xls warning under the line limit

---------

Co-authored-by: Jay0130-a <Jay0130-a@users.noreply.github.com>
2026-10-16 20:32:43 +08:00
ordinary being f0adfac334
fix(models/api): cap non-streaming provider response bodies (#4397)
Endpoint.Do bounds the error body at 1 MiB. Thirty lines below it, roundTrip
read the success body whole, and the four chat protocols each did the same in
their own read: a reply was buffered without limit before anything inspected it.
The older models/chat layer already caps the same replies at 20 MiB.

Cap them through one helper, and return an over-cap body without the
TransportError wrapper. withRetry retries only TransportError, and repeating an
oversized reply would bill the request again for the same bytes - the same
reason its own doc gives for not retrying a reply that arrives whole but does
not decode.

64 MiB clears every payload the catalog can legitimately return: an embeddings
batch is bounded by BATCH_EMBED_SIZE (default 5) times the model dimensions, and
a chat reply by the model's output-token ceiling. Streaming replies are
assembled incrementally and are unaffected.
2026-10-16 20:31:42 +08:00
JSJ189 7705f77be9
fix(embed): send images when an OpenAI-compatible row declares them (#4389)
An embedding row with spec.input image and no image_format or image_field
was treated as text-only on every vendor except generic and Jina. Default
that case to the vLLM messages format. An explicit object format without a
field stays refused.

Fixes #4343
2026-10-16 20:15:32 +08:00
LuckVd 7ba8e2eba9
fix(embed): hide host context in user messages (#4388)
Co-authored-by: root <root@DESKTOP-P1EOH2K.localdomain>
2026-10-16 19:53:10 +08:00
ordinary being 1fe804bd5c
fix(docparser): bound MinerU result packages and their expansion (#4396)
A MinerU result package arrives over the network from a third-party parse API and
was buffered whole before anything about it was validated. The Cloud converter
downloaded it with an unbounded io.ReadAll, even though the V1 client already caps
the same artifact at mineruV1MaxZipBytes - the two implementations of one feature
disagreed about the limit.

Decompression was unbounded on every path. readZipEntry and readZipEntryBytes
called io.ReadAll on a decompressed archive entry, and extractMarkdownZip keeps
every extracted image in memory until the caller hands the slice on, so a package
of many small entries expanded without ever tripping a per-entry check. The
declared UncompressedSize64 is attacker or vendor controlled and may understate
the expansion, so the header is checked and the read is capped as well.

Cap the download at the V1 ceiling, each entry at maxZipEntryBytes, and the
accumulated images at maxZipImagesTotalBytes. The image budget is a parameter on
extractMarkdownZipBounded so a test can exercise it without materialising the
production figure, mirroring the jsonLimit field added in #3985.
2026-10-16 19:37:27 +08:00
诉说晚秋 cf7aabeaca
fix(mcp): 分离SSE连接生命周期与请求超时 (#4140) 2026-10-16 17:56:15 +08:00
Clint 1b2c7af01a
fix(data-analysis): resolve workspace storage backends in quick answers (#4214) 2026-10-16 17:51:13 +08:00
AstonKrss 12e3e49d80
fix(chat): persist failed quick-answer turns so errors survive refresh (#4306)
* fix(chat): persist failed quick-answer turns so errors survive refresh

A KnowledgeQA (fast-answer/RAG) turn that failed left the assistant row
empty and incomplete forever. The pipeline error was already surfaced
live as an SSE error event (bubble text + toast), but nothing ever
completed the turn: no content was saved, is_completed stayed false, and
the SSE stream never published its completion event, so a refresh
rendered a blank bubble and the connection polled until the client hung
up (issue #4145).

Register an EventError handler for the quick-answer mode that completes
the turn through the same path as a streamed answer:

- persist the error text on the assistant message (appending to a
  partial answer instead of replacing it), falling back to a fixed
  explanation when the error carries no message
- mark the row completed, release the turn lease and publish the SSE
  completion so the stream closes cleanly
- skip chat-history indexing, follow-up suggestions and memory writes
  for the failed turn by completing with an empty query

A late error after a fallback already completed the turn is ignored via
the shared completion guard.

* test: wrap over-length fixture error string to satisfy lll
2026-10-16 17:50:14 +08:00
ordinary being 6dd0a6a3d6
fix(embedding): read the pool's first-error guard under its own mutex (#4014)
BatchEmbedWithPool fans a batch out over the ants pool, so with
BATCH_EMBED_SIZE=1 every text becomes its own sub-batch and several workers run
at once. Each worker starts by testing firstErr to see whether an earlier
sub-batch already failed, but that read was unsynchronised while the writes are
under mu. The race detector reports it between the guard and the failure branch.

The guard exists to stop billing a provider for work whose result will be
discarded. A worker that misses the write issues the request anyway, so the race
defeats the protection it was added for.
2026-10-16 17:42:51 +08:00
Guo-Yixin d3d4963989
fix(mcp): avoid replaying tools after ambiguous call failures (#4124)
* fix(mcp): avoid replaying tools after ambiguous call failures

* test(mcp): cover negotiated handshakes and OAuth call failures
2026-10-16 17:17:33 +08:00
ordinary being c44f939211
fix(web-search): bound provider response bodies instead of buffering them whole (#4370)
Every provider read its response with an unbounded io.ReadAll, or handed
resp.Body straight to json.NewDecoder, so a misconfigured or hostile endpoint
decided how much memory a single search allocated. Two providers made it worse
by reading before they looked at the status code and then interpolating the whole
body into both a log line and the error the caller sees - so a failing endpoint
could push an unbounded blob into the error string as well as into memory.

Reuse the cap the datasource connectors already apply to their API bodies
(readCapped + maxJSONResponseBytes + errResponseTooLarge, added for feishu, ima,
notion and yuque in #3985) rather than inventing a second dialect here. Apply it
to the six providers that read a response body, and bound failed-response
previews the way searxng.go already bounded its own and the connectors bound
theirs.

The two providers that decoded straight from resp.Body now buffer through
readCapped first, since a decoder cannot be capped without buffering.
2026-10-16 17:16:39 +08:00
ordinary being 03059997fe
fix(im): cap IM callback bodies before any adapter reads them (#4369)
Every IM platform calls a public, unauthenticated endpoint - the callback URL
cannot carry a bearer token - and each platform's signature is computed over the
request body, so the bytes have to be read before the request can be
authenticated at all. Each adapter read c.Request.Body with an unbounded
io.ReadAll, so a single unauthenticated POST decided how much memory the
process would allocate.

Add LimitWebhookBody to the shared internal/im package, mirroring how
internal/handler caps uploads and JSON bodies on the authenticated routes, and
call it ahead of all fifteen reads across the eight adapters. Nine of those
reads sit in VerifyCallback or HandleURLVerification, ahead of the credential
check; the rest parse the payload afterwards.

The cap is 4 MiB, far above any real callback: chat messages, interactive cards
and block payloads are kilobytes, and attachments travel as URLs the server
fetches separately under maxIMAttachmentBytes.
2026-10-16 17:16:15 +08:00
Greenplumwine 973d9d051f
feat(datasource): deep-adapt Feishu/Lark sync with folder mirror, block parsing and embedded objects (#3497)
* ci(build): add manual docker build workflow

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

* feat(datasource): deep-adapt Feishu/Lark sync with folder mirror, block parsing and embedded objects

- folder mirror: wiki/drive connectors emit path-qualified FileName so
  knowledge lands in KB folders mirroring the Feishu tree; shortcut
  subtrees deduped; sanitized directory names; legacy datasources
  converge via one-shot resync marker (incremental sync upgrades to
  full once, then clears)
- parse mode: replace FEISHU_DOCX_PARSE_MODE env with per-datasource
  settings.parse_mode (blocks default, export escape hatch); frontend
  selector + 5 locales; zero-migration read-time fallback
- block-level GFM: extend docx block coverage (callout/grid/iframe/
  board/mindnote/agenda/synced blocks), rich text elements (links,
  inline code, KaTeX equations, mentions), real ordered-list numbering,
  code language mapping, merged-cell fill, truncation note
- embedded objects: images (gated off multimodal toggle) and boards
  (download_as_image, 403-degraded) stored as knowledge with
  weknora-img://<n> markers resolved in the document-processing
  pipeline via knowledge FilePath; document attachments whitelisted
  (pdf/md/xls(x)/csv/doc(x)/ppt(x)) as standalone knowledge in the
  parent folder with bidirectional parent/child metadata and filename
  list in the body; videos skipped with placeholder + source link
- golden baseline explicitly re-recorded; docs (.env.example,
  docker-compose, docs/*, website-docs) synced

* fix(datasource): address Feishu deep-adaptation smoke-test findings

- folder mapping: drop the space/root-folder name prefix — the selected
  sync root maps to the knowledge-base root, subdirectories stay relative
- docx blocks: render view(33) blocks silently as containers (children
  only), removing the stray '[飞书块: 视图]' placeholder before file lists
- sheet inline tables: fetch merge ranges via sheets/v3 sheets/query and
  fill the top-left value across the merged region (closed-interval
  interpretation, flagged for real-environment verification)
- knowledge list: hide embedded image/board rows (metadata
  embedded_image=true) from the document list and folder-tree counts;
  rows remain for VLM indexing and marker resolution; search untouched
- frontend: hydrate protected images (resource:// etc.) in the document
  preview so embedded Feishu images/boards actually render

* fix(datasource): resolve embedded image markers at ingest time

The weknora-img://<n> markers were only resolved during document
processing, so chunks carried real resource:// URLs while the stored
markdown file and source_content kept raw markers — file preview
showed blank images. Resolve them in ingestItem before
CreateKnowledgeFromFile (children are emitted first, so image rows
with FilePath already exist); markers with missing children are kept
for the ProcessDocument fallback to degrade. Stored file,
source_content and chunks now agree. Existing datasources converge on
the next full re-sync (update=delete+recreate).

* feat(datasource): resolve Feishu mention users to real names at ingest

docx mention_user elements only carry an open_id, so they rendered as
a generic '@成员'. Resolve the display name via
GET /contact/v3/users/:id (user_id_type=open_id) while generating the
markdown during FetchDocxWithBlocks — before storage, per user
decision; the frontend performs no lookups. A per-sync closure caches
positive and negative lookups; permission errors and empty names
silently degrade to '@成员' (debug log only, ingest never blocked).
Requires one of the contact read scopes (e.g.
contact:user.base:readonly) on the Feishu app.

* refactor(datasource): polish round — defect fixes and structural cleanup

- attachment placeholder patching now targets the unique
  '- weknora-att://<token>' marker line rendered per attachment instead of
  matching by display name, so an identical earlier bullet is never
  replaced by mistake (regression-tested)
- markdown link targets with spaces or parens are percent-escaped
  (iframe / mention_doc / inline links), keeping them parseable
- drive folder-tree walking consolidated into core.WalkDriveTree,
  deleting the 174-line copy in drive/paths.go
- parse mode threading made explicit: DocxFetchInput.ParseMode replaces
  the private client field (connector entry resolves via
  ParseFeishuConfig and passes it through ops)
- maxFeishuDownloadBytes restored to a const; the oversize-degrade test
  now declares an over-cap Content-Length and downloadRawBytes rejects
  early on the header

* refactor(datasource): align Feishu image handling with the platform image pipeline

Replace the image-as-separate-knowledge-row channel with the platform's
orthodox flow: the connector downloads image/board bytes at fetch time and
embeds them in the parent markdown as base64 data URIs; the document
processing image resolver (image_resolver.ResolveAndStore, the same stage
used for parsed PDFs/Word) stores them on the tenant file service, swaps in
persistent provider:// URLs and produces OCR/caption child chunks when a VLM
is configured.

Removed with the marker pipeline:
- weknora-img:// ingest resolution in ingestItem
- the ProcessDocument Step-1.9 marker hook
- the document-list/folder-tree filter for embedded_image rows
- the feishu-specific runtime parse_mode backfill; legacy data sources are
  now stamped by migration 000096 (sqlite 000017) which writes the one-shot
  resync_required marker — the generic full-upgrade + clear consumption stays

Attachment (PDF/Word/md) sub-items are unchanged.

* style: gofmt test files

* fix(datasource): resolve Drive sub-selection kind from the root listing

A single-file Drive selection (rootFolderToken:fileToken) was probed with
folder APIs before falling back: folder meta returned 91202 and the folder
list 1061002 on every sync, logging API errors for a working configuration.

listDriveFilesForResource now walks the root subtree first and reads the
selected node's kind off the listing: a file filters straight out of the
already-fetched results (zero error calls), a sub-folder still gets its
dedicated walk, and only a token missing from the listing (partial listing /
permission edge) keeps the legacy probe + fallback.

Also pins sub-folder selection semantics with a dedicated test.

* fix(datasource): address review findings across the Feishu deep-adaptation branch

Four parallel reviewer slices audited the branch; this applies the accepted
findings.

Content fidelity (blocks rendering):
- todo blocks parse style.done — completed items render "- [x]" instead of
  always unchecked
- code fences size past the longest backtick run in the content, so a line
  of ``` inside code can no longer close the fence early
- ordered-list "auto" numbering only resets on a sibling of the last item;
  child blocks rendered flat between items no longer renumber the run

Image pipeline:
- inline base64 images are capped at the document-processing resolver's
  10 MB budget; larger images degrade to a placeholder instead of leaving a
  permanent raw-base64 blob in stored markdown
- image markers carry a per-document nonce so user-typed look-alike text
  can never be patched in place of a real marker
- attachment marker patching anchors on the token's line end, closing the
  token-prefix collision
- SupportedImageExt recovers image/svg+xml (board exports), which the
  platform resolver already stores natively

Sync correctness:
- clearResyncMarker re-reads the row before writing: a long upgraded sync
  no longer risks reverting concurrent user edits with a stale full-row
  update
- wiki EditTime keys on max(obj_edit_time, node_edit_time): pure
  moves/renames re-file the document on the next incremental sync
- file-typed wiki/drive base names are sanitised; a "/" in a title can no
  longer fake an extra folder level

Docs/tests/comments:
- datasources docs rewritten to the v3 image contract (no image rows,
  no image_map, no parse_mode backfill claim)
- DataSourceEditorDialog drops settings.parse_mode when backtracking to a
  non-Feishu connector type
- stale comments corrected (types.go parse-mode transport, repository
  folder-counts, wiki List partial-error branch, test headers); regression
  tests added for todo done, fence sizing, ordered numbering, svg sniff

* fix(datasource): repair markdown conversion defects found in live smoke test

Live re-sync of the all-block-type Feishu test document surfaced three
converter defects:

- Code blocks: the closing fence reused the opening fence string, so a
  tagged block ended with ```java — CommonMark requires a bare closing
  fence, and every renderer left the block unterminated. The closing
  fence is now backticks only.
- Feishu heading7-9 emitted 7-9 hash marks; GFM stops at H6, so those
  lines rendered as literal '#######' text. They now degrade to bold.
- The docx API percent-encodes link targets (http%3A%2F%2F...); escapeURL
  now reverses that encoding before markdown-escaping, so stored links
  point at real URLs instead of percent-encoded strings.

Verified against the live document via a throwaway API probe: the
'i|g|k' table cells questioned during review are the document's own
content (the sheets copy says i|j|k; the two docx tables genuinely
contain 'g'), not a converter bug.

* fix(frontend): render GFM task lists in document preview

Task list items (- [x] / - [ ]) rendered as plain bullets: marked emits
<input type="checkbox"> for them, but the preview DOMPurify config's
ALLOWED_TAGS allowlist has no 'input', so the element was stripped whole.
The preview renderer now overrides checkbox to emit a styled
task-checkbox span (class/attr both allowlisted) and the preview styles
draw the box with a check mark, hiding the list bullet via :has().

Same gap exists in the chat markdown surface; left untouched there.

* fix(datasource): crop blank canvas borders from whiteboard exports

The board download_as_image API renders the WHOLE board canvas, not the
content bounding box — editors routinely leave the canvas far larger than
the drawing, so board/mindnote/diagram exports surfaced with large blank
areas below the content. The API has no crop parameter, so the connector
now trims near-uniform blank borders after download (bottom-right pixel
seeds the background color, 14/255 per-channel tolerance absorbs JPEG
noise, 8px margin kept). PNG and JPEG are re-encoded; anything
undecodable, fully blank, or already tight passes through unchanged, and
oversized images (>64MP) skip the scan to bound memory.

* fix(datasource): require corner majority before trimming board exports

The blank-border trim seeded the background color from the bottom-right
pixel alone. A large solid shape reaching that corner would seed the
background with its own fill color, and fully-filled rows could then be
trimmed as blank — cutting real content. The background color is now the
majority of the four corner pixels (>=3 must agree); on a split vote
content reaches the corners and the image passes through untrimmed.
Content visible against the background is untouched either way: a row or
column survives if even one pixel differs from the background by more
than the 14/255 JPEG-noise tolerance.

* fix(datasource): widen board trim margin and lower JPEG quality to 80

The 8px margin read as a tight crop — a 32px white frame now visually
bounds the content region. JPEG re-encode quality drops 90 -> 80 to keep
the re-encoded size closer to the original export.

* feat(datasource): timeline widget Markdown degradation + table column alignment

Two content-fidelity gaps from the live smoke test:

- 文档小组件 (add_ons, block_type 40) carry their full data inline in
  record; there is no server-side render to download. The timeline
  component (component_type_id blk_6358a421bca0001c...) now degrades to
  a Markdown list (- **time · title**:text), honoring contentShow and
  omitting empty segments; unknown component types and malformed records
  keep the previous placeholder note.
- docx text blocks carry style.align (1 left / 2 center / 3 right,
  absent unless the author set it). Native-table rendering now collects
  per-column alignment from the first explicit cell and emits GFM colon
  separators (:---: / ---:). Embedded sheets/bitable keep the plain
  separator — their value APIs expose no alignment.

* feat(datasource): show document titles for 云文档 mention links

The docx renderer emitted mention_doc references as [url](url) because
the payload carries no title. Feishu doc URLs now emit a
[weknora-docname://token](url) placeholder and FetchDocxWithBlocks
resolves the titles in one drive metadata batch call
(POST /drive/v1/metas/batch_query, docx/doc/sheet/bitable/wiki/...),
patching the link text to [文档名](url). Refs whose metadata cannot be
fetched — no permission (970003), deleted/mismatched (970005), API
absent — degrade to the previous URL-as-text form with a warn log.

This is display-only: referenced docs are not pulled as sub-documents
(deferred design lives in the task PRD).

* docs(datasource): document mention rendering enhancement and drive rename limitation

- Add optional mention scopes (contact:user.base:readonly,
  drive:drive.metadata:readonly, board:whiteboard:node:read) with
  degrade behavior to the Feishu permission tables
- Describe mention_user real-name lookup, mention_doc title backfill
  and timeline widget placeholders in the blocks rendering flow
- Document the Drive known limitation: folder renames / file moves do
  not bump modified_time, so incremental sync keeps the old KB folder
  structure until a full sync; Wiki sources are unaffected
- Clarify the directory-mapping wording in website-docs to distinguish
  Wiki (rename-aware) from Drive (rename-blind) sources

* docs(datasource): add blocks vs export tradeoff summary to website-docs

* docs(datasource): document docx block-type coverage for blocks mode

- Add a full block-type support table (block_type 1-52 grouped) to the
  datasource dev doc: text/heading/list/task/quote structures, code
  fences with language aliases, containers (callout/quote/grid/view),
  native tables with merged-cell splitting (top-left value fill) and
  column alignment, embedded sheet/bitable converted to in-document
  Markdown tables, image/board inline pipeline, attachment whitelist,
  iframe links, timeline add-on degradation and the placeholder set
- Summarize the same coverage in the drive user guide, the wiki
  quick-start doc and website-docs; fix the stale claim that board
  blocks degrade to placeholders (they ride the image pipeline now)

* style: resolve diff-scoped lint findings across feishu packages

- Wrap over-length signatures and calls (lll, max 120)
- Add doc comments to exported Block* payload types (revive)
- Rename unused closure parameters to _ (revive)
- Check w.Write / resp.Body.Close error returns (errcheck)
- Apply De Morgan rewrite in docname token validation (staticcheck)
- gofumpt-format touched files

golangci-lint run --new-from-rev=main ./... now reports 0 issues.

* ci: drop fork-only docker-build workflow

The manual docker-build workflow lives on the fork's main and is not
part of the upstream contribution; it entered the branch through the
fork-main merge.

* fix(migrations): renumber feishu resync migrations to avoid version collision with upstream

Upstream added 000017_dingtalk_stream_only (sqlite) and 000096_dingtalk_stream_only
(versioned) before our merge, colliding with our 000017/000096 feishu resync
migrations. golang-migrate rejects duplicate versions. Renumber to the next free
slots (sqlite 000027, versioned 000108) and update comments + test constant.

* fix(migrations): renumber feishu resync migrations ahead of upstream 000027/000108

Upstream main now also claims sqlite 000027 and versioned 000108
(session_sandbox_config_tenant), colliding with our just-renumbered
resync migrations. Move to 000028 / 000109.

* fix(feishu): address review — deprecated env fallback and upgrade notes

- Keep FEISHU_DOCX_PARSE_MODE as a one-release deprecated fallback when a
  data source has no per-source parse_mode (deprecation warning logged);
  annotate it in .env.example / docker-compose.yml instead of removing.
- Point stale migration-number comments at the final numbers
  (versioned 000110 / sqlite 000030) in datasource_service.go and tests.
- website-docs: add Feishu upgrade notes (env deprecation, default mode
  flip to blocks, one-shot full resync with embedding/VLM recompute);
  refresh 24-feishu-drive.md parse-mode section to the per-source
  setting and new blocks semantics.

* docs(feishu): document necessary and optional connector permissions

Restore the permission matrix lost with the docs/ removal: necessary
scopes (wiki/drive/export/docx) with missing-permission symptoms and
optional enhancement scopes (embedded sheets/bitable, board export,
mention user/doc rendering) with their degrade behavior, in
10-datasource.md's Feishu section; make 24-feishu-drive.md list the
three necessary drive scopes and link to the full table.

* Revert "docs(feishu): document necessary and optional connector permissions"

This reverts commit 3be19cb1b656b3596f2cb6afb2cda8c2a1d12be1.

* docs(feishu): permission matrix by connector, parse mode and necessity

Necessary-scope tables split by connector (feishu/lark wiki vs
feishu_drive/lark_drive) with blocks/export applicability columns and
missing-permission symptoms; optional enhancement scopes with their
degrade behavior; scope names cross-checked against the Feishu open
platform API docs (files/folder list, medias download, export tasks,
metas batch_query). Full matrix lives in 10-datasource.md; the drive
guide mirrors its own table and links back.

* test(feishu): adapt mention_user_test to upstream retryTestServer signature

* feat(feishu): mirror the sync root (wiki space / drive folder) as a top-level KB folder

So a knowledge base linking several feishu sources can tell them apart at a
glance: syncing folder 测试1 yields 测试1/... and syncing wiki space
飞书知识库同步测试 yields 飞书知识库同步测试/.... Root-name resolution
failure falls back to the previous root-less behaviour without failing the
sync; existing sources converge through the one-shot resync marker.

* refactor(feishu): cache wiki space folder prefix per run, refresh stale comments

Review follow-ups for d012e593f: cache the sanitized space prefix per spaceID
for the whole sync run (K selected spaces now cost one ListWikiSpaces paging
pass instead of K), fix the misleading warn wording, and realign the
WalkDriveTree / driveFolderName doc comments with root-mirror semantics.

* docs(feishu): drop stale and duplicated comments from the deep-adaptation

- board.go: trimBoardImage no longer claims a bottom-right seed (the code
  votes the background over the four corners)
- shared.go: rewrite the FetchDocxWithBlocks note (images/boards inline via
  base64 now; removes a stale-marker splice artefact)
- markdown.go: drop an internal task-number leftover
- datasource_service.go: collapse the ProcessSync/processSyncStreaming notes
  duplicated verbatim from resyncRequired's doc comment, keep the call-site
  why (marker cleared only on success)
- datasource_resync_test.go: drop the obsolete 'backfill' wording

* feat(i18n): 添加解析模式及其提示信息到繁體中文語言包

* fix(frontend): use radius token for task checkbox; fix simplified chars in zh-TW parse mode

CI guard fixes: the PR-added task-checkbox style pushed the radius-literal
count to 161 (> baseline 160); the new zh-TW keys missed the locale parity
audit (user's dc6fdcff9) — also normalise the simplified 文档 leftovers.

* fix(feishu): preserve sync scope, nested content, and legacy settings

Cover shortcut selection, ancestor path changes, nested containers and table boards with regression tests. Avoid redundant Drive traversal, repair resync migrations for legacy settings, and preserve inherited parse modes. Bound board image dimensions before decoding.

* docs(feishu): clarify shortcut scope and incremental path tracking

* Fix Feishu sync reconciliation and embedded media regressions

* Bound Feishu table rendering by actual cell data

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-16 16:49:44 +08:00
tayadwx db7046b85e
refactor(image): turn the hard-coded image flow into configurable pipelines (#3746)
* feat(image): configurable image pipelines, rebuilt on current main

Rebuilds the image-pipeline work on top of the current main, carrying
only the pipeline and request-side changes:

- The hard-coded image flow becomes registry-driven pipelines (default /
  smartocr), selectable per knowledge base, with a frontend panel and
  per-action thinking switches addressed as action-level keys
  (caption.thinking / ocr.thinking) declared once and carried into every
  pipeline.
- Request-side support: VLM.PredictWithOptions carries a per-call
  thinking switch through every implementation and decorator, including
  the background concurrency wrapper.
- OCR failure handling follows main's #4132 semantics: invalid output is
  rejected and recorded (ocr_status / ocr_error_code / .ocr subspan)
  without retrying the whole image; caption/observation failures get
  symmetric subspans instead of leaving the image span green.
- Permanent VLM failures skip the asynq retry budget; a run that
  produced nothing fails honestly instead of passing as skipped.
- UI and locale fixes travel with the panel.

Concurrency, rate limiting and circuit breaking are NOT part of this
branch: they stay with the existing system limiter.

* fix(image): address pipeline configuration and execution regressions

* fix(image): align pipeline overrides and validation semantics

* style(image): keep the new pipeline code inside the lll and gofumpt gates

---------

Co-authored-by: tayadwx <tayadwx@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-16 16:18:57 +08:00
lyingbug 2fbfb44715
feat(assistant): let the assistant manage knowledge bases (#4353)
* feat(assistant): let the assistant manage knowledge bases

Create, update, and delete knowledge bases, tags, and manual Markdown,
and show those confirmations as labeled rows with model names.

* fix(assistant): satisfy lint on knowledge base operations

Check new error returns, wrap lines past 120 characters, and document the exported tag request types.

* fix(assistant): enforce knowledge base settings permissions and preserve patch fields
2026-10-15 23:54:14 +08:00
hahahahahayesyeseys aeeb72a61a
fix(assistant): reject restored ordinary sessions (#4356) 2026-10-15 23:47:51 +08:00
lyingbug 4d4acec418
feat(assistant): manage agents and skills, separate history, refresh pages (#4344)
* feat(assistant): let the assistant manage agents

Expose custom agents to the operation catalog (list, get, create, copy,
update, delete) plus read-only model and MCP service lookups, so the
assistant can set up agents end to end.

- Add PATCH /api/v1/agents/:id. PUT replaces the whole config, so a
  one-field change from the assistant would wipe the rest; PATCH only
  overlays the fields it carries and reuses the PUT validation path.
- Add x-agent-detail so long fields such as the system prompt are only
  projected for single-object reads, not lists.
- Add label_param so a create without a target is labelled by its name.
- The approval card lists agent setting changes and resolves model,
  knowledge base and MCP IDs to names.
- Deny sharing, publishing channels, credentials and OAuth routes; model
  and MCP endpoints, headers and secrets are never projected.
- Update the assistant prompt, starters, API docs and Go SDK.

* feat(assistant): list skills and configure agent skill scope

- Expose usable skill names for an agent sandbox without exposing skill
  administration or connection settings to the model.
- Validate PATCH selections against the workspace sandbox usable set so
  invented names and missing sandbox selections cannot be saved.
- Show skill changes in approvals and align the assistant prompt, API
  documentation, and Go SDK with focused refusal and projection tests.

* feat(assistant): isolate conversation history

- Keep assistant conversations out of ordinary session lists, search, artifacts and delete-all cleanup.
- Add private, paginated assistant history with session switching, confirmed deletion and stale-session recovery.
- Backfill session kinds safely on Postgres and SQLite, preserve kinds on forks, and align API docs and SDK coverage.

* feat(assistant): refresh pages after successful data changes

- Carry decoded mutation targets through live tool-result events without
  exposing refresh metadata to the model or persisted chat history.
- Coalesce page and selector refreshes, update document drawers, and warn
  about changed agents while preserving open editor drafts.
- Cover mutation, approval, stream, lifecycle and cache behavior with Go
  and Node tests using the existing frontend runner and component fixtures.

* feat(assistant): add agent page context and resource scope limits

- Attach verified agent context and persist personal scope across turns and approvals.
- Enforce resource boundaries before operation and Wiki approvals, including edited arguments.
- Add scope controls, translations, API and SDK support, and regression coverage.

* refactor(assistant): remove the scope limit

The scope picker confused users and duplicated what RBAC and the access
level already enforce. Keep the agent page context: the agent editor
still publishes agent_id and the backend still verifies it.

* feat(assistant): render operation and product-doc results

Show find/run operations and WeKnora docs as structured cards instead of raw JSON.

* feat(assistant): default new agents to smart-reasoning

Quick-answer cannot call MCP, and agent.update could not change the mode. New agents now start in smart-reasoning, and a patch can switch agent_mode.

* fix: resolve assistant management CI failures
2026-10-15 21:43:20 +08:00