Commit Graph

1310 Commits (014f95f1394a7bfd1c7bbbdcdc19057a80dcaca5)

Author SHA1 Message Date
lyingbug 014f95f139
fix(ui): 统一资源图标并调整会话分叉标识 (#3430)
* fix(ui): 统一资源空状态和共享筛选图标

* fix(ui): 将会话分叉标识移至右侧菜单位置
2026-09-19 20:59:12 +08:00
wizardchen e986579731 refactor(ui): 清理资源列表废弃组件和无效样式 2026-09-19 20:40:19 +08:00
wizardchen eec236b27f fix(ui): 优化资源卡片、标签分组与共享空间创建布局 2026-09-19 20:40:19 +08:00
lyingbug a46a3c5996
fix(ui): 优化对话布局、导航与产物和引用展示 (#3427)
* fix(ui): refine chat scrolling, outline, and panel interactions

* fix(ui): include reference styling, composer copy, and title motion
2026-09-19 19:25:52 +08:00
lyingbug 2a6a9c2517
fix(ui): 优化知识库文档交互与对话布局 (#3420)
* fix(knowledge): streamline document browsing and tag editing

* fix(chat): align panel headers and refine composer spacing
2026-09-19 11:58:49 +08:00
lyingbug 03d9d66a1f
feat(agent): size agent history by the window and calibrate token estimates (#3413)
* feat(agent): size agent history by the window and calibrate token estimates

Agent history was capped at history_turns (default 5) because compaction
could not survive a turn. With checkpoints persisted, load history by
tokens instead, and let compaction bound the session.

Budget. The loader drops the oldest turns that do not fit, and what it
drops is lost: neither replayed nor summarized. A budget equal to the
compaction threshold (the earlier attempt, since reverted) let the loader
trim first, so whenever one turn was larger than the system prompt plus
the new question the request never crossed the threshold; nothing was
summarized and the session became a sliding window with no checkpoint.
agent.HistoryTokenBudget is now the whole window: overflow reaches the
first round's compaction, which summarizes it into a new checkpoint.
A turn-by-turn regression test drives the real loader, budget and
compactor and fails as soon as a stored turn after the checkpoint is
missing from the loaded history; restoring the old budget fails it.

Summarizer input. History can now reach the window, so the part being
summarized can outgrow one request. An overflowing request degrades to a
raw archive that is never persisted, so every later turn would fail the
same way. Prepare keeps the newest messages that fit, the prompt states
how many were left out, and file paths still come from all of them.

Calibration. cl100k counts Chinese at about a token a character where
Qwen and DeepSeek spend about 0.6. The estimator now carries a scale
(clamped to 0.5-1.5, text only), learned from consecutive requests in a
turn: they share tools, system prompt and earlier messages, so the
provider's growth between them prices exactly the appended messages,
without mixing in how a provider renders tool schemas. The turn's scale
is stored on its usage (context_token_scale); the next turn's loader
prices history with it and hands it to the engine. Loading, the first
compaction check and compaction itself share one estimator, so they
agree; calibrating only the trigger would let the loader drop turns
again, which the regression test covers.

Also: history is priced as the engine sends it (redacted KB/Wiki results
cost one line); a checkpoint older than the rows read is matched by the
assistant rows' (created_at, id) order; a read ending on a turn's
question keeps that turn; a compaction discarded for freeing under 5%
still persists its checkpoint; a checkpoint write matching no row is an
error; a partial index backs the newest-checkpoint lookup. Agent mode no
longer reads history_turns: the field leaves AgentConfig, the editor
hides it in smart-reasoning mode, and quick-answer keeps its turn cap.

* fix(agent): address review of window-sized history loading

Summarization. The summarizer call had a fixed 60s total timeout. With
history loaded up to the window, a request could carry ~175k tokens and be
cut off while prefilling or writing normally; the degraded result left no
checkpoint, so the next turn reloaded the same history and failed the same
way. Summarization now streams and is cancelled only after no output for the
engine's stall timeout (120s by default, LLMCallTimeout overrides), with the
overall ceiling left to the transport, as for the engine's own rounds and as
in Codex and Pi. A stopped turn is not retried. When the summarizer still
fails, the raw archive is persisted as a checkpoint marked degraded so the
loop is broken, and the next compaction refines it as the previous summary.
The archive is held to the summary budget, newest messages first, so a
degraded compaction always frees room.

Loading. The loader priced turns as sent but returned and held them as
stored, so wiki pages stored in full and sent as one line could pile up in
memory. It now returns the as-sent history and releases each turn's stored
rows once replayed, keeping about a page of rows at a time.

Index. The partial checkpoint index is replaced by a composite
(session_id, created_at DESC, id DESC) index serving the backwards page,
the newest-checkpoint lookup and the recent-messages reads. It is built with
CREATE INDEX CONCURRENTLY so writes to messages are not blocked; the
migration holds that single statement, since a multi-statement query runs as
an implicit transaction. A PostgreSQL integration test, skipped without
WEKNORA_MIGRATION_TEST_POSTGRES_DSN, applies the chain, runs 000106 down and
up through golang-migrate, and checks both queries use the index without a
sort; the SQLite migration test checks the same plans.

Calibration. It no longer waits for a total token count, and a usage with
only a scale is persisted. A turn that measures nothing carries forward the
scale it started from, so the newest turn always has the latest one.
2026-09-18 22:51:31 +08:00
lyingbug db8e7611be
fix(security): close cross-workspace access paths in shared spaces (#3408)
* fix(security): close cross-workspace access paths in shared spaces

A review of how shared-space (organization) members reach each other's
resources found six paths that bypass the org-share permission model:

- presigned-preview signed any resource handle or storage path, turning a
  known resource:// handle into an anonymous /r/ URL that outlives share
  revocation. It now requires the path to belong to the caller's tenant,
  like /files.
- POST /initialization/initialize let a shared-KB editor rewrite the owner
  workspace's models (base URL, API key) in place. Only the KB's own
  workspace may call it, and rewriting a stored model needs the same
  authority as PUT /models/:id.
- KB JSON carried the legacy inline credentials (storage_config
  secret_id/secret_key, which initialization fills with the MinIO env
  keys, and vlm_config api_key) to every share receiver. They are withheld
  from JSON; their DB columns are unchanged.
- A chat without agent_source_tenant_id resolved shares before the
  caller's own agent, so a member sharing a same-ID built-in agent took
  over other workspaces' default agent. Own agents now win, built-in
  agents can no longer be shared (existing such shares no longer resolve),
  and embed channels drop a visitor-supplied source workspace.
- Any org-admin tenant (even a tenant Viewer inside it) could raise another
  workspace's KB share to editor/admin, and the route guard was bypassable
  via an unrelated :id. Share management is now: the sharer from the source
  tenant (Contributor+), source-tenant Admin+, or an org-admin tenant's
  Admin+ that may only remove or lower. share_id must belong to :id.
- Wiki write tools were registered for every wiki KB in the search targets,
  which only need read access, so a viewer share (e.g. via the built-in
  wiki fixer) could edit or delete another workspace's wiki pages. They now
  act only on KBs the caller may edit.

* fix(security): close the KB settings path and owner details for share receivers

Follow-up to the shared-space review:

- PUT /initialization/config shares the route guard that admits share
  editors, so an editor could still rebind the owner's KB models, chunking
  and storage, and storage backends resolved against the caller's workspace
  let it bind the owner's KB to its own backend. Another workspace now needs
  an admin share (the only share level the frontend offers settings to) and
  may not change the storage binding at all.
- GET /initialization/config showed model base URLs and bucket locations to
  any admin of the caller's own workspace, including share receivers. They
  now only see whether credentials are configured.
- Wiki write tools on the caller's own KBs had no role floor, so a tenant
  Viewer (and the IM, embed and MCP endpoint principals that run as Viewer)
  could write through an agent what the HTTP routes deny. Writes now need
  Contributor+, or the ingest capability for a scoped API key, following
  the RBAC rollout switch.
- resolveAgent logs the share lookup error instead of a nil own-agent error
  when a shared selector fails.

* fix(security): close the medium shared-space access findings

Follow-up to the high-risk fixes, from the same review:

- Wiki fixer moved into a shared KB's workspace ran with the caller's own
  config there: an unset MCP mode registered all of the owner's MCP
  services, and an "all" KB scope reached the owner's other KBs. The scoped
  run now uses the built-in config pinned to that one KB, without MCP,
  skills, sandbox or web search, and falls back to the KB's own model.
- An unset MCP mode means "all" at runtime but is shown as none in the share
  scope; shared runs now treat it as none.
- Quick-answer mode used the request's web_search_enabled alone, so a
  receiver could turn on search the agent disables and spend the owner's
  provider quota. It now requires the agent setting too, as agent mode does.
- summary_model_id picked any model of the workspace a run executes in. It
  is ignored for shared agents and the relocated wiki fixer.
- A workspace that left or was removed from an organization kept sharing its
  KBs and agents. Its shares are revoked on departure, and share queries and
  permission checks require the source workspace's membership and a live
  organization, which also covers rows left behind earlier.
- Sharing an agent exposes its KB scope to all members, so a Contributor
  could share colleagues' KBs (or "all") through an agent. The sharer must
  now be able to share each KB directly (creator or Admin+; "all" needs
  Admin+), also when a shared agent's scope is widened later.
- A scoped API key with manage_channels could mint an MCP endpoint token
  wider than itself. Endpoints it creates, updates or rotates must stay
  within its KB allow-list and capabilities.
- A shared agent's run indexed the receiver's Q&A into the owner's chat
  history KB; indexing now uses the session owner's configuration.
- Sharing an agent with skills keeps injecting the owner's skill
  environment values (product decision); the share panel now warns that
  members can read them. Preview of originals through read-only shares is
  kept as designed and documented.
2026-09-18 22:00:02 +08:00
lyingbug 68e6c03dc4
fix(skills): upgrade outdated sandbox skills without rolling back the catalog or taking them offline (#3406)
* fix(skills): keep retries and catalog installs from rewriting the skill definition

Every install path wrote its archive back to the workspace catalog. After a
skill was re-registered as v2, sandboxes still on v1 are pinned to v1's
archive, so retrying one of them (a failed retry, or a ready skill retried
with guidance) reinstalled v1 and also moved the catalog definition back to
v1 and deleted v2's archive.

Installs now carry where their archive came from. Only an upload or a source
pull is a new definition; a retry or a catalog install uses bytes the
workspace already stores and never rewrites the definition. A retry of a
pinned install keeps its pin and replays its own version, and bytes that
neither the definition nor the row holds are refused with a conflict.

The catalog listing also reports each installation's version so the UI can
show what an upgrade moves from and to.

* feat(frontend): upgrade outdated skill installs from the catalog, sandbox drawer and agent editor

An install whose archive differs from the catalog was flagged as outdated,
but nothing could move it to the catalog version: the install drawer hid
ready installs, and the manage drawer only offered a retry, which replays
the sandbox's own archive.

- Skill settings: cards with outdated installs show an upgrade button that
  opens the install drawer with every outdated sandbox preselected. The
  add wizard and install drawer also let outdated ready installs be picked,
  labelled with the version they move from and to.
- Sandbox skill drawer: an outdated skill shows a "new version" row whose
  upgrade button installs the catalog onto that one sandbox.
- Agent editor: skills on the chosen sandbox that are outdated show the
  version change and an upgrade button, both for admins only, matching the
  admin-only catalog install. The install progress entry, which opens a
  drawer backed by admin-only endpoints, is now admin-only too.
- A skill that is being upgraded is no longer pruned from the agent's
  selected skills while it is briefly not ready.

The outdated check is shared in utils/skillUpgrade.ts.

* feat(skills): keep the previous version serving while an upgrade runs or after it fails

An install rewrote the row to the new version and marked it installing as
soon as it started, and the agent is only offered ready rows. So an upgrade
took the skill away from every sandbox for its whole run, and a failed
upgrade kept it away, even though the image pointer only moves on success
and the previous version was in the image the whole time.

The row now records what it described when it was last ready (served:
version, description, instructions, digest, the archive its files come from,
and the snapshot that installed it). The agent's usable set, member env
acceptance and the @-mention list read TenantSkillEntity.ServedView, which
is that version marked ready while the row is installing or failed. A
successful install clears it and releases its archive; a failure or a stop
keeps it.

Keeping that consistent:
- The served archive counts as a reader when a bundle is released or
  replaced by a re-registered catalog, so v1's files stay readable while v2
  installs.
- The reaper and a failed removal put the served version back when the image
  never moved past it, instead of labelling v1's files with the upgrade's
  metadata. A stuck upgrade whose chain cannot be read is left alone, since
  v1 keeps serving meanwhile.
- The env declaration is stored after the pointer moves rather than before
  the snapshot, so an upgrade that fails late cannot drop the admin value of
  a variable the previous version still reads.

Migration 000104 adds tenant_skills.served. The console says "upgrading,
still running 1.1.0" or "upgrade failed, still running 1.1.0", the agent
editor keeps such skills selectable, and the upgrade texts no longer warn
that the skill goes offline.

* fix(skills): offer only the upgrade to installs the catalog has moved past

Review follow-up on the upgrade flow.

- An install that differs from the catalog, ready or failed, is now offered
  the upgrade and not the retries. The retry icon and the retry-with-guidance
  box both replay the archive the install is pinned to, so next to an
  Upgrade button they reinstalled the version the operator came to leave
  behind. A failed first install of v1 whose catalog has since moved to v2
  used to retry v1 from the drawer while the agent editor's Install went to
  v2; every entry now goes to v2, and the agent editor labels it "Upgrade".
  The drawer explains that the failed install is replaced by the catalog
  version.
- A catalog install or a retry reuses the definition that already holds its
  bytes instead of re-running the catalog upsert, which rewrote the row and
  bumped its updated_at every time the skill was installed somewhere. The
  upsert still runs for a definition that does not exist yet or whose object
  was lost.
2026-09-18 20:27:43 +08:00
MercuialC aaec920a9c
feat(audit): 知识库活动记录对 API Key 操作额外显示 Key 名称 (#3405)
* feat(audit): show API key name on knowledge-base activity

API-key operations currently look like the first tenant user or
"system". Snapshot the key id/name into activity details so the
feed can tell which key initiated the change, without restoring
key authorization onto async workers.

Fixes #3402

* fix(frontend): show activity API key on a second line

The 132px actor column truncates "user · API Key · name" into one
ellipsis. Keep the person on the first line and the key name below.

---------

Co-authored-by: MercuialC <MercuialC@users.noreply.github.com>
Co-authored-by: root <root@localhost.localdomain>
2026-09-18 19:39:34 +08:00
lyingbug 2be7bd4063
fix(agent): search bound knowledge bases before answering, and pass suggested-question origins (#3400)
* fix(agent): search bound knowledge bases before answering, and pass suggested-question origins

A user picked the suggested question "为什么在比较图形时需要谨慎处理?"
and the agent answered in round 1 with no tool call, claiming it had
searched the knowledge base and found nothing, then explained misleading
statistical charts. The question had been generated from "Corners Don't
Look Like That: Regarding Screenspace Ambient Occlusion" in a bound base,
where "comparing graphs" means SSAO falloff curves.

Two things let that happen: the grounding prompt said "Stable general
explanations need no lookup", and nothing told the agent where the
question came from - the base in question had no profile, only two
recent titles in the directory, and the click sent the text alone.

Prompt
- With knowledge tools available, search bound bases before answering a
  question about a topic, even one that reads like general knowledge;
  directory profiles and recent titles cannot prove a base lacks it.
- The general-explanation exemption applies only without bound bases.
- Say you searched or found nothing only when a search tool ran.

Question origin
- Suggested questions from FAQ/document chunks also return knowledge_id.
- Picking one on the home or chat page sends question_origin
  {knowledge_base_id, knowledge_id} with that question only.
- The service keeps the origin only when its base is inside the turn's
  resolved scope and the document belongs to that base; it never
  changes the scope (unlike knowledge_base_ids, which narrows it).
- The engine renders it in runtime_context as <question_origin> with the
  base and document handles and a note to search it before answering.

* fix(agent): keep question origins across file/tag scopes and bind them to the send

Review follow-up for the suggested-question origin.

- Scope check: the origin was kept only when its base was in the resolved
  KB list, which is empty for file-only and tag-only scopes even though
  their bases are searched. It is now checked against SearchTargets after
  they are built; the document is kept only when a target for that base
  covers it (unfiltered base, or a document scope listing it).
  resolveQuestionOriginInfo re-checks SearchTargets, looks up the name of
  a base that is not in kbInfos, and the renderer omits an unknown name.
- Frontend: the origin travelled through module-level "pending" state, so
  a send that returned early (agent not ready, upload in progress,
  steering) left it behind and a second pick overwrote it. It now rides
  with the one send: triggerSend(text, options) -> createSession ->
  send-msg -> sendMsg / changeFirstQuery.
- RetrieveKBOnlyWhenMentioned: suggestions are still generated from the
  agent's bases, but picking one retrieved nothing. The origin now
  selects its base, as an @mention would, when the agent may read it.
- API sync: question_origin in docs/api/chat.md and swagger;
  QuestionOrigin on the Go SDK's KnowledgeQARequest/AgentQARequest and
  knowledge_id on SuggestedQuestion.
2026-09-18 17:00:47 +08:00
lyingbug 9d508c1c7a
feat(frontend): show overall progress for knowledge file uploads (#3399)
* feat(frontend): show overall progress for knowledge file uploads

Batch uploads ran one file at a time with no feedback until the whole
batch finished, and nothing followed the asynchronous parse afterwards.
The knowledge base list still carried a progress panel whose event
emitter was removed with the old menu upload flow, so it never showed.

- Run uploads through a global queue (stores/uploadQueue.ts, wired to
  the API in stores/uploadTasks.ts): three concurrent transfers,
  per-file cancel that aborts the request, retry for failed or
  cancelled files, and polling of the created knowledge rows until
  parsing settles. finalizing counts as searchable.
- Add a floating panel (components/upload-tasks/) mounted in the
  platform shell: stage headline with a progress ring, bytes and ETA
  while uploading, a stacked bar for searchable / in progress / failed /
  duplicate, per-file status with hover actions (cancel, retry, open the
  document), an issues filter, grouping by batch, collapse, a confirm
  before closing mid-upload, and auto-dismiss after a clean finish.
- Warn before unloading the page while transfers are still running.
- Refresh an open knowledge base list as files land (throttled), but
  skip mid-batch reloads while the user has scrolled past the first
  page; the batch's final refresh always runs.
- Remove the orphaned list-page panel, the unused useKnowledgeBase
  requestMethod, the per-batch toasts and the i18n keys they leave
  unused.

* fix(frontend): harden the upload queue's wiring into the app

Review of the upload progress panel found the store misbehaving once
connected to real auth and page events:

- The owner watch used one getter returning a fresh array, so every
  setUser() fired it, even for the same person (opening the user menu,
  hovering the workspace submenu), and dismissed running uploads. Watch
  the user id and tenant id as separate sources.
- Starting a new batch after the previous run finished cleared it
  whole, including failed files still waiting for Retry. Only batches
  whose every file is searchable are dropped now.
- The knowledge base list page reloaded everything on each mid-batch
  refresh (about every 2s), closing open card menus. It now waits for
  the batch's final event; the detail page's mid-batch refreshes only
  reload files and folders, and tags and wiki probes wait for the end.
- A row missing from one successful status poll was marked deleted for
  good. It now takes three consecutive misses, reset when it reappears.
- Closing the panel aborted requests whose body was already sent, which
  the server still stores. Those are left to finish and trigger a list
  refresh when they land.
- Two identical files in one batch could both pass the server's hash
  dedup when uploaded in parallel. Same-size files for one knowledge
  base now never run at once, so the second sees the first's row.

Also: detect cancellation from the abort signal instead of the item
state, ignore a cancelled attempt that settles after its retry started,
bind the beforeunload guard to the panel's lifetime, and show the
subfolder next to file names from folder uploads.

The store body moves into uploadTasksCore.ts with the API, events and
identity injected, so the owner watch and enqueue policy are tested
alongside the queue.
2026-09-18 16:43:59 +08:00
Binks Riverton a9c85fd17e fix(frontend): keep pipeline offsets within chart bounds 2026-09-18 16:42:37 +08:00
wizardchen ad5d6a8fc2 fix(agent): make read_document queries keyword-based and bound its pages
read_document's in-document query was matched as one literal string, so a
keyword query such as "sunflower f(n,k)" found nothing in a 708-chunk
document even when both words were there. The zero-match result gave the
model no next step, and the UI rendered it as "0 / 708 chunks loaded",
which reads like a failed load.

Paging mode also had no size bound: the registry truncates
ToolResult.Output, but the model sees the result rendered from Data, so a
limit=100 page reached ~68k characters in the model context.

- A plain query is split on whitespace; a chunk matches when it contains
  every word, in any order. regex=true still matches one expression.
- A zero-match result carries a <hint> suggesting fewer/different words
  or reading a chunk from search_knowledge results.
- A page stops adding chunks at 80% of the output budget (counting
  per-chunk rendering overhead); next_offset resumes at the first chunk
  not returned, and an oversized first chunk is still returned.
- The UI summary shows in-document search results ("no matches" /
  "N matches") and, for offset paging, the chunk range instead of a page
  number that no longer holds.
2026-09-18 15:09:25 +08:00
Lvcy_cd a8aa19f721 fix(frontend): scale upload timeout with payload size
postUpload inherited the axios instance's 30s default, so any upload taking
longer than 30s was aborted client-side no matter what MAX_FILE_SIZE_MB was
set to. On a ~30 Mbps uplink that caps uploads at roughly 100MB even when the
deployment is configured for 200MB — and every layer underneath (reverse proxy,
frontend nginx, Go handler, docreader gRPC) had already accepted the configured
limit. The server only saw the request after the browser had given up, and
logged "failed to upload file to MinIO: context canceled" with a sub-second
latency.

Four of the five postUpload call sites worked around this by passing an explicit
timeout; knowledge-base file upload and chat temporary attachments did not.
Derive the default from the payload so correct behaviour no longer depends on
each caller remembering to opt in — an explicit config.timeout still wins.

The aborted request also surfaced as "network error, please check your
connection": axios timeouts arrive without error.response, so they landed in
the same branch as an unreachable server and sent people chasing a network
problem that did not exist. Report the two separately.
2026-09-18 15:07:27 +08:00
lyingbug 92e7c0ab37
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381)
* refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents

The agent's retrieval surface had grown to five overlapping tools whose
behaviour was scattered across long descriptions, interleaved "tips" in
tool output (most of which modelcontext discarded before the model saw
them), and a grep_chunks implementation that ran an unindexed regex scan
over the chunks table ordered by created_at, so large knowledge bases lost
recall and paid a full-table scan on every call.

Tool surface
- search_knowledge replaces knowledge_search and grep_chunks: one query,
  mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit.
  Keyword mode runs through the retrieval engine's keyword index instead of
  the DB regex scan. Modes unavailable for the scope are refused with a
  reason. Rerank, MMR and de-duplication are kept; already_seen markers,
  retrieval_statistics and the zero-result "CRITICAL" block are gone.
- read_document replaces list_knowledge_chunks, get_document_info and
  wiki_read_source_doc: id accepts a dN or cN handle, always returns the
  document header, pages by exact offset (fixing the old floor-to-page
  bug), finds passages with query (literal by default, regex opt-in) and
  reads neighbours around a chunk with context.
- list_documents pages through one knowledge base, honouring @file/@tag
  scope.
- wiki_search takes a single query plus regex, knowledge_base_ids, limit;
  literal queries are escaped so the model never reasons about JSON
  escaping. Legacy queries / knowledge_base_id are still accepted.
- query_knowledge_graph is registered only when a graph-enabled KB is in
  scope and its description/tips were trimmed.

Compatibility
- Retired names in stored allowlists, presets and API calls are mapped to
  their successors by NormalizeAllowedTools at registration time; no data
  migration. Stored histories with old names still decode, render and
  redact. Calls to retired names return a replacement hint.
- modelcontext gains an "id" key space that decodes against both the chunk
  and document handle tables (decode-only), plus rendering for the
  document header, chunk roles, in-document matches and next_offset.

Prompts and surfaces
- The RAG, wiki researcher and hybrid templates now name the tools and the
  search -> read -> cite order; tool descriptions are short and contain no
  workflow instructions.
- Engine display names, history redaction, grounding prompt, IM rendering,
  the built-in MCP server (search_knowledge gains mode/limit, grep_chunks
  becomes keyword search, read_document gains query, wiki_search gains
  regex), frontend editor/renderers/i18n, presets, website docs and the
  changelog are updated accordingly.

Tests cover name mapping, mode validation and refusal, output shape,
read_document paging/context/query/scope, list_documents, wiki_search
escaping and legacy arguments, modelcontext decoding and rendering, and
registration-time aliasing and graph gating.

* fix(agent): address review findings on read_document, list_documents and model rendering

- read_document: fetch the second page whenever the first page did not
  reach the end of the document, so an unaligned window near the end no
  longer drops the trailing chunks (also fixes context windows around a
  chunk near the end); a query passed together with a cN handle now
  searches the owning document instead of being ignored; query mode stops
  collecting once the output budget is nearly spent and reports truncated;
  the document row is authorized in place instead of being fetched twice;
  the context read takes the total from the window fetch instead of a
  separate count query.
- list_documents: resolve the page's document scope in one batched tag
  lookup instead of one call per row.
- modelcontext: render read_document output once and read next_offset
  through the existing intValue helper.
- search_knowledge: point title/file-name lookups at list_documents.
- Tests for the boundary window, chunk context near the end, cN + query,
  and budget-bound query results.

* fix(agent): close compatibility gaps in the consolidated retrieval tools

- Wiki-only scopes: read_document and list_documents are registered
  whenever a wiki KB is in scope, since every KB stores chunks. Their
  capability requirement includes wiki but is marked auxiliary, so they do
  not widen a RAG agent's derived "all knowledge bases" filter to wiki-only
  bases (Go and frontend derivations both honour it).
- search_knowledge resolves the retrieval mode per knowledge base instead
  of refusing the call: FAQ and vector-only bases answer keyword requests
  semantically, keyword-only bases answer semantic requests by keyword.
  Results carry requested_mode and mode_fallbacks, the empty-result text
  names the fallback, and the call is refused only when no base in scope
  has a chunk index.
- The model rendering uses the mode the search actually ran with (it was
  always labelled semantic) and emits <mode_fallback> per degraded base.
- list_documents applies the @file/@tag scope before paging: tags are
  pushed into the database filter, pinned documents are loaded by ID, and
  total/next_page count only readable documents.
- read_document resolves chunk context by chunk_index through a new
  ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks
  sharing the index sequence no longer shift the neighbourhood; offset is
  documented as a reading-order position, not a chunk index.
- wiki_search (agent and MCP) keeps its regular-expression default and
  only matches literally when the text is not a valid expression;
  regex=false forces a literal match and regex=true rejects invalid input.
- MCP grep_chunks keeps grep semantics: literal terms from the pattern
  fetch candidates from the keyword index (semantic for bases without
  one), and every returned chunk is verified against the pattern.

* docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics

* docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 14:12:22 +08:00
lyingbug 6db8fdd601
feat(artifacts): artifacts library page backed by a message_artifacts table (#3384)
* feat(artifacts): add an artifacts library with its own message_artifacts table

Skill-generated files were only reachable from inside the conversation that
produced them. This adds a sidebar entry and a page that lists them across
every conversation the user can see.

Storage: artifacts move out of the messages.artifacts JSONB column into a new
message_artifacts table (PostgreSQL 000103, SQLite 000023), backfilled on
upgrade. The table is now the only source of truth; the old column is kept and
the down migration writes the table back into it. The message repository
loads artifacts for every message it returns and writes them on create,
update (when non-nil) and fork, so callers still use Message.Artifacts.
mod_time is stored as RFC 3339 text because the collector matches files on
nanosecond mtimes, which PostgreSQL timestamps would truncate.

API: GET /api/v1/artifacts lists the latest version of each file (grouped by
session + source path, with version_count), scoped like the session list,
with keyword / file type filters and paging. Downloads keep using the
per-session endpoint.

Frontend: "产物/Artifacts" sidebar entry (hidden without sandbox support), a
library page with type tabs, search, date groups, infinite loading, preview
drawer, download and jump-to-conversation; strings in all five locales. The
sidebar's top-menu paths are now one shared list.

* fix(artifacts): keep the restore hash guard and count versions by URL

RecordRestoredArtifactMtime again only stamps rows whose content hash matches
the restored content (and ignores empty hashes), and never rewrites the hash,
matching MessageArtifacts.WithRestoredMtime. Without the guard a restore of
v1's content also moved v2's mtime and relabelled v2 with v1's hash.

The library's version_count now counts distinct URLs per (session, source
path). A later answer that references an earlier file stores another row with
the same URL, which COUNT(*) reported as an extra version.

* fix(artifacts): scope the library to web chats and clear the legacy column

The library used the session list's default scope, which counts sessions
without an owner as legacy tenant-level rows. IM sessions are created without
an owner, so every member saw the file names and titles of every IM chat
(downloads then 404 for non-admins). The library now applies the same "web"
bucket predicate as the home sidebar, extracted from QueryPaged so the two
cannot drift: no IM mapping (including cleared ones), no embed marker, no
API-key owner.

Migrations 000103 / SQLite 000023 now clear messages.artifacts after the
backfill. Message loads still SELECT *, so the stale copy was read on every
history load. Only rows that carried artifacts are rewritten; the column stays
for instances on the old binary during a rolling upgrade, and the down
migration still rebuilds it from the table.

* fix(migrations): keep the 000103 backfill alive on malformed artifact JSON

A single file_size that is not an integer ("12.5", "") or a created_at that
does not parse ("garbage", month 13) raised a cast error and failed the whole
migration, blocking startup. Casts now go through pg_temp helpers that return
NULL on bad input, falling back to 0 and the message's created_at; valid rows
are unchanged. SQLite casts never raise; its migration test now covers the
same malformed values.

* docs(artifacts): describe the web-only library scope and the cleared legacy column
2026-09-18 12:10:19 +08:00
lyingbug b4aa5bbe8d
refactor(frontend): style consistency pass — shared shells, tokens, unified confirmations (#3376)
* refactor(frontend): batch 1 of style consistency cleanup

- theme.css: alias --td-font-family-mono to --app-font-family-mono so the
  29 monospace call sites follow the user's code-font setting
- replace 115 hardcoded rgba(7,192,95,x) brand tints with
  color-mix(in srgb, var(--td-brand-color) N%, transparent) so they track
  the dark-mode brand color
- strip 358 dead var(--td-*, fallback) fallbacks (tokens are guaranteed by
  theme.css); keep the 3 undefined tokens untouched
- menu.vue: drop 9 unreferenced style blocks; remove TencentSans font file
  and its global import
- AgentStreamDisplay: drop 6 unused keyframes; move the teleported wiki
  drawer styles into components/css/wiki-graph-drawer.less imported by
  both chat and WikiBrowser so styling no longer depends on load order
- creatChat: remove four !important fixed-width media queries; chat root no
  longer forces font-size: 20px
- list pages: create buttons use native theme="primary" (drops the purple
  gradient on AgentList); header-action-btn no longer needs !important
- add styleGuard.test.mjs ratchet test (brand rgba, legacy blue, token
  fallbacks, z-index !important, raster icons)

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

* refactor(frontend): unify destructive confirmations on useConfirmDelete

- useConfirmDelete now uses the danger dialog theme with a red confirm
  button; it is the single entry point for delete/leave confirmations
- AgentList, KnowledgeBaseList and OrganizationList drop their hand-rolled
  del-*-dialog (span-as-button, circle.png) in favour of useConfirmDelete;
  circle.png asset removed
- FAQ single-entry delete gains a confirmation (it deleted immediately);
  new knowledgeEditor.faq.confirmDelete key in all five locales
- VectorStore/StorageBackend delete dialogs and the generated-question
  popconfirm use the danger theme like the rest of the app
- style guard raster-icon baseline lowered to 10

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

* feat(frontend): shared modal shell with Esc, overlay close and unsaved guard

Add composables/useModalShell and wire it into the four full-screen
settings-style modals (Settings, AgentEditorModal,
OrganizationSettingsModal, KnowledgeBaseEditorModal):

- Esc closes the modal everywhere (previously only Settings); it defers
  to any open TDesign dialog/drawer/popup and to the agent editor's own
  placeholder popups
- overlay click closes everywhere (Settings gains it)
- editors snapshot their form after load/save; closing with unsaved
  changes now asks "有未保存的更改 / 放弃更改 / 继续编辑" instead of
  silently discarding
- new common.unsavedChanges.* keys in all five locales

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

* fix(frontend): mark instant-effect sections in the knowledge base editor

Share, data source and activity sections apply changes immediately, but
the editor footer still showed Cancel / Save, so users either re-saved
or assumed Cancel would undo. Those sections now show an "applies
immediately" note with a single Close button; other sections keep the
Cancel / Save footer. New knowledgeEditor.footer.instantEffect key in all
five locales.

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

* refactor(frontend): consistent success wording and confirm labels (zh-CN)

- toasts use the "已X" form everywhere: 25 zh-CN values such as
  保存成功 / 删除成功 / 智能体创建成功 become 已保存 / 已删除 / 已创建智能体;
  common.copySuccess now reads the same as common.copied
- confirm buttons in dialogs and popconfirms use the bare verb
  (删除 / 重置 / 移除 / 应用 ...) instead of 确认X; dialog titles keep 确认删除
- GeneralSettings no longer pops a bare "成功" toast after theme / font /
  font-size changes, which are self-evident and applied instantly

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

* refactor(frontend): extract SettingsModalShell for the four settings-style modals

Settings, AgentEditorModal, OrganizationSettingsModal and
KnowledgeBaseEditorModal each carried a copy of the same overlay / panel /
sidebar-nav / footer markup and ~20 CSS blocks, already drifting
(1000/1080/1100px widths, three shadows, different nav paddings).

components/SettingsModalShell.vue now owns that chrome: one 1080x780
panel, grouped nav with badges, optional loading overlay, footer with a
note slot and an actions slot. Consumers keep only their content and
wire `@close` to their useModalShell.requestClose. Settings keeps its
sub-menu nav through the `nav` slot; OrganizationSettingsModal keeps its
image icon through the `nav-icon` slot.

Net: -1025 lines across the four modals.

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

* refactor(frontend): shared resource-card mixins and EmptyState for list pages

KnowledgeBaseList, AgentList and OrganizationList each re-declared the
same 136px card (border, radius, shadow, hover, header/title/description/
bottom, more-button reveal, feature badges) with small drifts, plus a
copy of the empty-state block using the upload illustration for every
kind of emptiness.

- components/css/resource-card.less: .resource-card(),
  .resource-card-grid() and .resource-feature-badge() mixins; the pages
  keep only their own variants (type gradients, favourite star,
  decoration). More-buttons stay visible on touch devices.
- components/EmptyState.vue: icon / title / description / actions; the
  11 empty states now use a matching TDesign icon instead of upload.svg
- badge accent colours move from hard-coded old-blue / material orange /
  pink / slate rgba to color-mix over theme tokens (new
  --app-accent-purple in theme.css); style guard legacy-blue baseline
  drops from 40 to 18

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

* refactor(frontend): shared settings-section mixins for header, row, info, control

25 settings/system/integration pages each re-declared .section-header,
.setting-row, .setting-info and .setting-control with five different
header margins (18-32px), three description sizes and assorted paddings.
components/css/settings-section.less now provides
.settings-section-header() / .setting-row() / .setting-info() /
.setting-control() / .setting-save-state(); pages keep only their
deliberate deviations (e.g. Ollama's column control, TenantInfo's fixed
label column). PlatformAPIKeys' style block switches to less so it can
use the mixins. Net -570 lines.

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

* refactor(frontend): provider-card mixins, dark-safe vendor badges, one spin keyframe

- components/css/provider-card.less: .provider-card() /
  -interactive() / -add() / -badge() / -badge-color() / -body() /
  -header() / -title() / -subtitle() / -more() shared by the model,
  vector store, web search, storage, parser and sandbox settings cards;
  MCP and skill cards reuse the 26px badge variant
- vendor badge colours are now `.provider-card-badge-color(#hex)`: the
  foreground is mixed 75/25 with the text colour so it stays readable in
  dark mode, the background is the same colour at 12% alpha
- 18 copies of a rotate-360 keyframe (steer-spin, chat-header-spin,
  sandbox-terminal-spin, ...) collapse into a global `wk-spin` in
  theme.css; 23 files updated, one source test adjusted

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

* refactor(frontend): use TDesign password toggle for API keys; align chat toolbar buttons

- ModelEditorDialog: the API key field is a plain t-input type="password"
  and relies on TDesign's built-in show/hide eye instead of a hand-rolled
  suffix toggle, matching every other secret field in the app
- chat answer toolbar buttons are 28px with 6px radius, the same size as
  the user-message actions and the input control bar

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

* refactor(frontend): app design tokens, tokenized literals, global TDesign overrides

theme.css gains an app-level token set derived from the de-facto scale
already used in the codebase, so values do not change:
  --app-radius-{xs,sm,md,lg,xl,pill} (4/6/8/10/12/999px)
  --app-text-{2xs..4xl}              (10..24px)
  --app-space-{1..10}                (4px grid)
  --app-motion-{instant,fast,base,slow} (120/150/200/300ms)
  --z-{sticky,dropdown,modal,drawer,popover,toast}

A codemod mapped 675 border-radius, 1904 font-size and 551 transition
duration literals in 191 files onto those tokens (value-preserving; five
source-text tests now accept either form).

assets/theme/tdesign-overrides.less holds global-intent TDesign
overrides; its `.wk-popover` skin replaces six per-file copies of the
blurred popover panel (TenantMembers x2, UserProfile,
OrganizationSettingsModal, systemAdminDialog.less,
share-to-space-panel.overlay.less) without !important.

styleGuard ratchets now also cover radius / font-size / motion literals,
`transition: all`, total `!important` and z-index !important.

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

* fix(frontend): keep symmetric side insets for the chat column on narrow viewports

.chat had padding 0 0 20px 20px so the scrollbar could sit on the content
edge, but that also left the message list and input box flush against the
right edge whenever the viewport was narrower than 960px + sidebar. The
inset now lives on .msg_list and .input-container (--chat-content-inset,
20px each side, max-width 960px + insets); the scroll container still
spans the full column so the scrollbar stays on the edge. Wide layouts are
unchanged (960px content, centered).

* chore(frontend): strip trailing whitespace flagged by pre-push

* test(frontend): accept tokenized font-size and shell-rendered loading overlay

Two source-text assertions only ran in CI (Node 24 discovers .test.ts,
local Node 20 does not):
- ChatQuestionMinimap: the 13px preview font is now var(--app-text-md)
- modelUsageDetails: the editors' loading overlay is rendered by
  SettingsModalShell via :loading instead of an inline v-if
Both regexes now accept either form.

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 23:11:08 +08:00
wizardchen 8b1a64004d feat(mcp): show the endpoint token as the drawer's second step
The "endpoint ready, save the token" dialog stacked the token, the URL and
three client snippets into one tall modal on top of the drawer. The drawer
now has two steps like the embed and IM channel drawers: "Configure" and
"Connect". Creating an endpoint advances to the Connect step in place, where
the one-time token, the endpoint URL and the client snippets (in tabs, one
visible at a time) are read; Finish closes the drawer. Rotating a token and
the card's "Connection info" action open the same step, the latter with the
token placeholder. The separate dialog and the "show client configuration"
button are gone.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 22:51:25 +08:00
lyingbug 76a19f14c4
feat(mcp): add built-in MCP server with per-workspace endpoints (#3371)
* feat(mcp): add built-in MCP server with per-workspace endpoints

WeKnora previously exposed itself to MCP clients only through the Python
package under mcp-server/, which binds one process to one API key and
therefore to one workspace, and mirrors the REST API tool-for-tool.

This adds a native MCP server surface to the Go backend:

- New mcp_endpoints table (PostgreSQL 000100, SQLite 000020). A workspace
  can publish any number of endpoints, each with its own bearer token
  (SHA-256 stored, rotatable, shown once), knowledge-base allowlist, tool
  allowlist, default agent and per-minute rate limit.
- Management API under /api/v1/mcp-endpoints (Viewer reads, Admin writes,
  API keys need manage_channels) plus a tool catalog endpoint.
- internal/mcpserver hosts one mcp-go Streamable HTTP server in stateless
  mode at /mcp/:endpoint_id. tools/list is filtered per endpoint and
  tools/call re-checks the allowlist, applies rate limiting and touches
  last_used_at. MCPEndpointAuth resolves the token and injects the
  workspace, an mcp_endpoint principal and an API-key style scope derived
  from the endpoint, so existing knowledge-base and capability checks
  apply unchanged.
- Redesigned tool set (12 tools in four groups): retrieval and reading
  reuse the agent's native tools; ask runs the default or a named agent
  synchronously and returns a cited answer with a session_id for
  follow-ups; wiki tools cover search, read and index; write tools are
  off by default. Knowledge bases accept ids or names.
- Frontend: new "MCP Server" integrations tab (tab id mcpserver, to
  avoid clashing with the existing MCP-client settings section) with
  endpoint cards, a create/edit drawer, a one-time token dialog and
  ready-to-paste snippets for Cursor/VS Code/Claude Desktop, Claude Code
  and mcp-remote. Locales updated in all five languages.
- Deployment capability integrations.mcpserver wired on both sides.
- Docs: website-docs MCP page now leads with the built-in server; the
  Python mcp-server README carries a deprecation notice.

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

* fix(mcp): wire the MCP server into DI/router and tighten authorization

The previous commit lost eight staged files to the repo pre-commit hook,
which resolves ROOT to the main checkout and re-adds the main-checkout
copies of tracked files into the worktree index. This commit restores them
(container providers, RouterParams and route registration, context key,
principal, clone table entry, deployment capability key, SQLite parity
test) and addresses the review findings:

- Knowledge-base scope is authorized, not trusted: endpoint allowlists and
  every tool call resolve each knowledge base through access.ResolveKB for
  the calling principal (ownership or organization share). Foreign IDs are
  rejected on create/update and dropped at call time.
- Write tools mint explicit editor grants via access.KBAccess.WithGrant
  before calling the knowledge service, so add/update/delete go through the
  same RequireKBWrite path as the REST API. add_document also checks the
  grant itself.
- ask no longer accepts agent_id. It runs only the endpoint's configured
  agent; tenant-owned agents and user-facing builtins qualify, internal
  builtins (wiki fixer, skill installer) are refused both on save and at
  call time. Web search is forced off for MCP calls.
- Tool annotations match behaviour: ask is not read-only, add_document is
  a mutation.
- CORS allows MCP-Protocol-Version / Mcp-Session-Id / Last-Event-ID and
  exposes Mcp-Session-Id for browser-based MCP clients.
- Rate limiter runs its local cleanup goroutine; SQLite migration gains the
  deleted_at index for parity with PostgreSQL; non-ASCII endpoint names get
  unique mcpServers keys derived from the endpoint id.
- Swagger annotations on the management handler.
- Tests: KB isolation (service and server), write grants, endpoint-agent
  restriction, tool annotations, and a router test that mounts the public
  /mcp/:endpoint_id surface and checks the deployment capability.

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

* chore(mcp): renumber migrations after rebase onto main

main took 000100 / 000020 for chunks_index_diet, so the mcp_endpoints
migrations move to 000101 (PostgreSQL) and 000021 (SQLite); the SQLite
parity test and docs follow.

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

* fix(mcp): run document tools under the knowledge base owner tenant

Shared knowledge bases resolved through access.ResolveKB were only half
usable: documents of an organization-shared knowledge base are stored under
the owner tenant, so the document-level tools that queried by the calling
tenant found nothing, and add_document would have created rows under the
caller's tenant inside someone else's knowledge base.

- knowledgeInScope loads documents tenant-agnostically and then requires
  the document to belong to an allowed knowledge base and to that base's
  tenant.
- scopedKBContext replaces grantContext: it resolves the grant, switches
  the execution tenant to the knowledge base owner (KBAccess.Context) and
  swaps TenantInfo to the owner so storage/model settings resolve there.
  list_documents, read_document and every write tool run under it.
- Locale text and docs no longer claim clients can pass agent_id.
- Go SDK gains MCP endpoint methods (client/mcp_endpoint.go) with docs, and
  the Swagger artifacts are regenerated.
- Tests: shared knowledge base read/write under the owner tenant, spoofed
  document tenant rejected, viewer share cannot write.

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

* chore(mcp): renumber migrations after rebase onto main

main now carries 000101 / 000021 (knowledge_profiles), so the
mcp_endpoints migrations move to 000102 (PostgreSQL) and 000022 (SQLite);
the SQLite parity test expects version 22 and the docs follow.

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

* fix(mcp): guard last_used touch without a repository and wrap SDK line

The transport tests build the server without a repository; the background
last_used_at write then dereferenced a nil interface and, on the slower CI
runner, took the test binary down. touchLastUsed now returns early when no
repository is wired, and the tests inject a recording repository and assert
the touch instead. Also wraps a 123-column SDK signature for the client
module's lll check.

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 22:40:05 +08:00
lyingbug 5574ebc011
feat(knowledge): derive knowledge base descriptions from document profiles (#3370)
* feat(knowledge): derive knowledge base descriptions from document profiles

Knowledge bases only had a hand-written description, which most users
leave empty, so agents bound to several knowledge bases had nothing to
route on and searched all of them. This adds a generated description
that is derived from per-document data instead of maintained by a model.

Document profile: the summary call now returns JSON with a 2-3 sentence
summary plus a gist, 3-5 topic keywords, a document type and one
typical question (knowledges.profile). Input is capped at 8k chars and
output at 1024 tokens; plain-text replies from custom templates still
work and simply carry no profile. The summary chunk embeds the gist and
short summary.

Knowledge base aggregate: a database-only fold over those rows (counts
per file type, tag, normalized topic and doc type; stratified samples of
titles and questions; a hash of the inputs). Deleting, moving or
re-parsing a document changes nothing but the rows, so the next rebuild
is exact without any model judgement.

Description text: one small model call over the aggregate yields a
gist, merged topics and typical questions (knowledge_bases.
generated_profile). The call is skipped when the aggregate hash is
unchanged; failures keep the previous text and record the error; an
empty knowledge base clears it. The manual description is never
touched, and the agent runtime context renders both so the model can
pass knowledge_base_ids instead of fanning out.

Refreshes are requested from summary task exit, post-process completion,
deletion, cross-KB moves and enabling the option, debounced per
knowledge base in 30 s windows via kb:profile on the summary queue.
POST /knowledge-bases/:id/profile/generate regenerates synchronously.
profile_config (enabled, model_id, custom_instructions) opts a document
knowledge base in; the settings dialog shows the generated card with
regenerate and adopt-as-description actions in five locales. Search
results now log hits per chunk type so the value of indexing summary
chunks can be measured.

Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the
SQLite schema test expects the new version and columns.

* fix(knowledge): keep generated descriptions out of duplicates and refresh clones

DuplicateKnowledgeBase copies the source row through JSON, which carried
generated_profile onto a knowledge base that has no documents yet, so
an empty duplicate advertised the source's topics. The duplicate now
starts without a generated description and keeps profile_config so it
derives its own once documents arrive.

CopyKnowledgeBase builds the target field by field and skipped
profile_config, and the clone task never asked for a description after
copying the documents, so a clone stayed undescribed until its next
upload. The target now carries a copy of profile_config and both clone
paths request a refresh on completion.

* fix(knowledge): refresh the loaded clone target and carry document profiles

ProcessKBClone requested the description refresh with the reservation
stub it builds before CopyKnowledgeBase runs. For the main create path
that stub has neither a type nor profile_config, so the refresh helper
rejected it and nothing was enqueued. The refresh now uses the loaded
target returned by CopyKnowledgeBase.

cloneKnowledge copied the summary text but not the structured profile,
so even a scheduled refresh would have aggregated titles without topics
until every clone was re-summarized. Cloned documents now carry an
independent copy of the profile.
2026-09-17 22:21:55 +08:00
wizardchen 105c177b80 feat(knowledge): make document summary generation optional 2026-09-17 19:39:52 +08:00
wizardchen 559ad532ae refactor(frontend): consolidate knowledge tag filters and remove stale styles 2026-09-17 16:46:27 +08:00
wizardchen d645334d08 refactor(frontend): share citation popover lifecycle 2026-09-17 15:28:31 +08:00
wizardchen 8fbee673e6 fix(browser): soften handoff UI and prevent preview overlay flicker 2026-09-17 14:51:20 +08:00
wizardchen b3d3851ca1 fix(chat): refine fork feedback and user message actions 2026-09-17 14:50:45 +08:00
nullptr-error 42e6163981
feat(session): fork conversations from a historical user message (#3304)
* feat(session): add fork schema and history queries

为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。

* feat(sandbox): add git, fork snapshots, and bootstrap hook

沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。

* feat(session): checkpoint workspace at the end of each turn

每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。

* feat(session): fork conversations and reap orphan snapshots

支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。

* feat(chat): add session fork entry, prefill, and badges

在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。

* style: add missing newline so session_fork_delete_test.go is gofmt-clean

* fix(session): prune later git history when rolling a fork workspace back

reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。

* style(session): clear golangci-lint findings on the session-fork diff

Pre-push lints the whole PR against main; wrap long lines, check c.Error,
and fix gofumpt/revive/staticcheck so the merge can be pushed.

* fix(chat): show the fork button on hover without shifting the thread

Overlay the action so revealing it no longer expands the user bubble and janks the messages below.

* fix(chat): drop the fork landing banners

Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread.

* fix(agent): dedupe artifacts by content hash, not size

Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only.

* feat(session): allow forking from an assistant answer

User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists.

* fix(session): resolve parent attachments from a forked chat

Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss.

* fix(agent): rewrite sandbox refs after a content-hash skip

Fork restores change mtime on unchanged files, so Collect returns empty
and named citations were left as sandbox: paths. Resolve those names
against session artifacts, notify only real uploads, and stamp restored
mtime only on the matching content hash.

* fix(session): drop a dead fork snapshot and retry checkpoint rewrite

Create from a missing template now abandons bootstrap so the next
Resolve uses a normal sandbox. A failed checkpoint rewrite no longer
marks the bootstrap consumed, which previously made nested forks
SANDBOX_REPLACED.

* fix(session): load forked parent attachments into the prompt

ResolveForPrompt used session-scoped lookup, so copied parent attachment
IDs passed Get but never reached the model. Use the same resolveInSession
path as preview.

* fix(chat): keep the user-message fork button visible

The control was hover-only, which hid it on touch. Always show it, and
drop the unused degrade tooltip.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-17 14:20:18 +08:00
serply e80f5dfbc7 feat(web-search): add Serply provider
Serply returns Google results through a keyed JSON API, which fills the
gap between Google Custom Search (needs an engine ID and a restricted
scope) and the scrapers. The adapter follows brave.go: hardcoded
endpoint, redirects refused so the key never leaves the official host,
4MB response cap, and per-call country and freshness filters. country
maps to Google's gl parameter and pd/pw/pm/py map to tbs qdr:d/w/m/y.
Serply has no date-range filter, so that form returns an error instead
of being silently dropped. num is clamped to 10 because the API serves
one results page per call.

Wiring matches the Bocha provider: type constant and metadata, registry
factory, service validation, frontend union, swagger enum entries (edited
by hand; a full swag regen drags in unrelated drift), and the web search
docs table.
2026-09-17 12:25:09 +08:00
wizardchen 84c9871d16 fix(browser): align BrowserSkill 0.3.0 and repair task lifecycle 2026-09-17 11:54:12 +08:00
wizardchen f2606629b3 refactor(frontend): share skill install progress subscriptions 2026-09-16 23:12:14 +08:00
wizardchen 5bcc43d728 refactor(frontend): share skill installer model configuration 2026-09-16 20:58:03 +08:00
wizardchen bfa7f0ed69 refactor(frontend): remove unused components and share tag selection logic 2026-09-16 20:49:16 +08:00
lyingbug d7ccd5ba51
fix: align client sessions and integration request handling (#3305)
* fix: align client sessions and integration request handling

* fix: preserve trusted Doris redirects and prepare browser tests

* fix: align proxy address checks and integration test coverage
2026-09-16 16:20:57 +08:00
wizardchen 2bc1261b87 chore: remove vendored archives and unused Python helpers 2026-09-16 15:49:36 +08:00
ttommybot a7d3545297
feat(knowledge): add batch file downloads (#3300)
* feat(knowledge): add batch file downloads

* fix(knowledge): harden batch file downloads

Skip entries without original files, keep folder paths in the ZIP, map
client cancel to 400, and cap concurrent archives so a full-select
download is usable without 500s or disk pile-up.

* fix(knowledge): format batch-download tests for pre-push lint

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-16 15:40:10 +08:00
jacentsao 01f0700b35
feat(datasource): add Confluence sync (#3287)
* feat(datasource): add Confluence sync

* fix(confluence): resume full sync and list Server pages without CQL

CQL search silently truncates large spaces and can delete pages that
dropped out of the index. Full-sync checkpoints now keep a deletion
baseline so Asynq retries continue instead of restarting.

* fix(confluence): satisfy package lint for pre-push against main

* fix(confluence): parse Server page lists and keep version expand

The default Server/DC edition unmarshaled /content/page as a nested
envelope, so sync imported zero pages. Pagination next links also drop
expand=version,space, which made later pages versionless and hid edits.

* fix(confluence): classify errors and fail closed on empty listings

Raw Confluence error bodies were copied into sync-log UI, and pagination
next links could leave the configured context path via `..`. Empty
listings against a non-empty baseline now abort instead of deleting.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-16 14:38:16 +08:00
lyingbug 6f98ff80c3 Revert "fix(ui): distinguish file types and enlarge chat resource chips"
This reverts commit 42aceb17fb.
2026-09-15 22:54:52 +08:00
wizardchen 42aceb17fb fix(ui): distinguish file types and enlarge chat resource chips 2026-09-15 22:46:39 +08:00
zhao0335 a84f866892 fix(i18n): add missing MCP OAuth locale keys
McpServiceDialog.vue already calls t() for OAuth form labels and toasts,
but those keys were never added to the locale bundles. Non-Chinese UIs
fell back to the hardcoded Chinese defaults (Scopes, Authorization Status,
Unauthorized, Authorize, Re-authorize, Revoke, and related toasts).

Add the missing mcpServiceDialog OAuth keys and OAuth toast messages for
zh-CN, en-US, ja-JP, ko-KR, and ru-RU so the Authentication section
localizes with the rest of the settings UI.

Fixes #3182
2026-09-14 20:50:48 +08:00
nullptr-error 6ccc5cedf1
feat(sandbox): add a graphical desktop to session sandboxes (#3245) 2026-09-14 20:37:37 +08:00
DEMO 5d3114fc9e
feat(datasource): add DingTalk Docs integration with safe sync and localization (#2313)
* feat(datasource): add DingTalk Docs integration

* fix(datasource): harden DingTalk sync and complete translations

* fix(datasource): close DingTalk review gaps in sync and rendering

Prefer millisecond node timestamps, keep full-sync deletion reconciliation, and stop dropping official block payloads so incremental updates and Markdown import stay complete.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-14 19:53:29 +08:00
hujiaxin fc2c12e8ec fix(models): protect auto-tag model references 2026-09-14 19:29:19 +08:00
wizardchen fbad5b3730 fix: improve model editor connection tests and save flow 2026-09-14 19:18:04 +08:00
wizardchen 935b456c3c fix(skills): isolate skill drops from global file uploads 2026-09-14 18:17:43 +08:00
wizardchen 801ae18f91 fix(embed): enforce host origin allowlists on framed pages 2026-09-14 18:03:57 +08:00
wizardchen e42f09d535 fix(datasource): validate replacement credentials before saving 2026-09-14 17:37:53 +08:00
wizardchen 462999ec3f feat(browser): add picture-in-picture task preview 2026-09-12 11:11:36 +08:00
wizardchen a799f23b26 feat(sandbox): stream live shell and install command output
Publish a bounded stdout/stderr tail for pending shell_exec and skill installs without putting partial logs into the model context.
2026-09-12 10:16:39 +08:00
wizardchen eeaaa7f64c fix(preview): repair PptxGenJS slide masters so previews render
vue-office-pptx shows zero slides when generated decks omit unused master declarations; rewrite the preview copy without changing the stored file.
2026-09-12 10:14:43 +08:00
lyingbug 3910cfb117
fix(browser): complete task cancellation, screenshots, and result display (#3206) 2026-09-12 09:32:26 +08:00
wizardchen 081851c6b8 fix(browser): support human handoffs and resume interrupted tasks 2026-09-11 23:56:13 +08:00