4169 Commits
Author SHA1 Message Date
wangshun cf5306da87 test(file): keep TOS preview assertion within lint line limit 2026-11-23 14:35:27 +08:00
wangshun dedca86ca4 fix: stream TOS files without unsupported seeking
Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
2026-11-23 14:35:27 +08:00
Winoren 62185f03c1 fix(anydoc): update zip to 9.0.5 (#5833) 2026-11-23 11:59:05 +08:00
poisongodv f4859f7fbb fix(docparser): bound PaddleOCR-VL Cloud submit upload with the configured timeout (#5590)
The submit POST carries the whole document in a single multipart body, so
its hardcoded 60s client ceiling failed every scan larger than ~100MB on
the reporter's uplink (#5589 estimates ~1.8MB/s, so 60s ≈ 108MB) — and
the env knobs users reached for (WEKNORA_PADDLEOCR_VL_CLOUD_TIMEOUT,
WEKNORA_DOCREADER_CALL_TIMEOUT) never applied to this stage. Give the
submit client the per-job timeout the polling side already uses, so
WEKNORA_PADDLEOCR_VL_CLOUD_TIMEOUT now bounds the upload and the poll
together (default stays 600s, still capped by WEKNORA_DOCREADER_CALL_TIMEOUT).

Red/green: TestPaddleOCRVLCloudSubmitStopsAtConfiguredTimeout fails
against the hardcoded 60s client (stub responds after the configured
200ms budget; error is expected but got nil) and passes with the fix; a
paired success-path test pins the normal flow.

Out of scope (unchanged): the 30s per-poll request client, the 120s
result-JSONL download and the 60s per-image download in the same file.

Signed-off-by: 李凝炜 <951448078@qq.com>
2026-11-23 11:23:07 +08:00
zhouh fea856ee77 fix(agent): stop materializing knowledge files after cancellation (#5664) 2026-11-23 11:22:30 +08:00
wei 9a762d95a3 fix(stream): clamp negative offsets in GetEvents and GetSteerEvents (#5773) 2026-11-23 11:21:51 +08:00
Winoren 795fc74f81 fix(query-understand): preserve escaped backslashes during JSON recovery (#5823) 2026-11-23 11:21:28 +08:00
Winoren a73c664810 fix(agent): abort context compaction when the turn is canceled (#5818) 2026-11-23 11:20:45 +08:00
NianJiu 7a3ca49905 Merge pull request #5735 from QuantumJumper23/fix/model-api-key-label
fix(frontend): correct API key labels in the model editor
2026-11-21 12:51:49 -06:00
NianJiu 077e9750bd Merge pull request #5740 from shengzhaowei/docs/vendor-count-30
docs: correct built-in vendor count from 29 to 30
2026-11-21 12:49:18 -06:00
NianJiu 82caca267e Merge pull request #5746 from OUAO-FRANK/codex/issue-5745-heartbeat-query-failure
fix(knowledge): defer stalled recovery when heartbeat lookup fails
2026-11-21 12:49:02 -06:00
NianJiu b4d95ec636 Merge pull request #5743 from ydflow/fix/agent-turn-prefix-fallback-budget
fix(agent): bound split-turn compaction fallback
2026-11-21 12:48:46 -06:00
OUAO-FRANK 0b9663d460 fix(knowledge): defer recovery when heartbeat lookup fails 2026-11-22 00:16:03 +08:00
ydflow 9363f33dcb fix(agent): bound split-turn compaction fallback 2026-11-21 22:30:26 +08:00
wei 333734ee52 docs: correct built-in vendor count from 29 to 30 2026-11-21 19:18:16 +08:00
Satyam Raj c920471d23 fix(frontend): correct API key labels in the model editor 2026-11-21 13:04:58 +05:30
NianJiu 1ef55d4a8d Merge pull request #5712 from Crazy-ChenMiLin/feat/issue-5001-bootstrap-system-admin-at-signup
feat(auth): promote bootstrap system admin at sign-up (fixes #5001)
2026-11-20 23:14:34 -06:00
NianJiu 859bca0191 Merge pull request #5718 from tsumon/fix/gitlab-scope-expansion-5717
fix(gitlab): import newly selected paths when commit is unchanged
2026-11-20 23:14:15 -06:00
tsumonandNianJiu 5d8bc9ff5b fix(gitlab): import newly selected paths across unchanged and moved commits (#5717)
Record each project's selected paths in the GitLab sync cursor so incremental
syncs (both FetchIncremental and FetchStream) detect directory-selection
expansions instead of skipping untouched existing files in newly added roots.

- When a project's commit is unchanged, walk and import only newly uncovered
  roots (keeping unchanged selections incremental).
- When a project's commit also moved (previous != head), emit diff changes
  and deletions from compareChanges while skipping new/modified paths already
  covered by the newly added roots, then walk the added roots so existing
  files are imported once without duplicates and deletions are preserved.
- Reuse gitLabCursor in FetchIncremental and wrap lines to satisfy lll (120).
- Add regression tests covering simultaneous commit advance + scope expansion
  and widening to whole-repository selection across incremental and stream modes.

Co-authored-by: NianJiu <180004567+NianJiuZst@users.noreply.github.com>
2026-11-21 12:39:50 +08:00
chenzaiqiangandNianJiu 4374bf340f feat(auth): promote bootstrap system admin at sign-up (fixes #5001)
Evaluate WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL during userService.Register so a
matching email is promoted to system admin immediately at sign-up when no
system administrator exists yet, eliminating the restart required on fresh
deployments while retaining cmd/server startup promotion for pre-existing users.

- Share BootstrapSystemAdminEmailEnv between service and cmd/server/bootstrap.go.
- Log promotion only after CreateUser and EnsureOwner succeed (sanitizing the
  email), warn and fail closed if ListSystemAdmins fails, and keep all lines
  within the 120-character lll lint limit.
- Replace the broken TenantProvisioningNone test stub with real SQLite-backed
  registration tests covering case-insensitive matching, non-matching emails,
  existing-admin guard, and fail-closed error handling.
- Update bootstrap comments and website-docs to reflect immediate sign-up
  promotion alongside startup fallback.

Co-authored-by: NianJiu <180004567+NianJiuZst@users.noreply.github.com>
2026-11-21 12:36:33 +08:00
NianJiu 9a98c3aaca Merge pull request #5725 from NianJiuZst/fix/datasource-sync-item-failure
fix(datasource): isolate per-item ingest failures in streaming sync and classify validation rejections
2026-11-20 22:23:52 -06:00
NianJiu da8227d969 fix(datasource): preserve scheduled syncs across quiet failure rounds and recovery
Follow-up fixes for Tencent/WeKnora#5724:
1. Quiet incremental rounds with lingering isolated failures:
   - Previously, after a partial sync synced healthy items into the cursor while
     leaving one persistently failing item unadvanced for retry, the very next
     quiet incremental round skipped all unchanged items via the cursor fast-path
     and emitted only the 1 failing item (Total=1, Failed=1). That tripped
     allFetchedItemsFailedError, flipping ds.Status to error, burning 5 Asynq
     retries, and permanently disabling future cron ticks.
   - Add optional datasource.UnchangedItemRecorder / RecordUnchangedItem on
     StreamHandler so per-item-cursor streaming connectors (Feishu Wiki/Drive,
     Seafile, Nextcloud, Confluence) report cursor-verified unchanged items.
     When unchangedItems > 0 and the stream completed without aborting,
     processSyncStreaming records partial/active instead of failing the source.
     Global errors (quota/cancel), circuit-breaker trips, RetryOnFailure, and
     total-failure rounds (unchangedItems == 0) still fail and set error.
2. Scheduler recovery after error -> active transition:
   - Editing scope while ds.Status == error caused UpdateDataSource to remove
     the live cron entry, and a subsequent recovering manual sync restored
     ds.Status = active in DB without re-registering the cron job.
   - Re-read the persisted row (preserving any concurrent pause) and call
     s.scheduler.AddOrUpdate(fresh) when updateSyncRunResult transitions a
     source from error back to active.
3. Consistent folder-qualified labels on Feishu fetch failures:
   - Populate FileName from the resolved directory path on Feishu Drive/Wiki
     fetch-stage error items so fetch failures include folder paths in
     SyncItemError.Title just like ingest failures.
4. Tests & docs:
   - Add end-to-end tests for quiet rounds (Feishu Drive, Seafile), live
     Scheduler error->active cron restoration on SQLite, Feishu fetch-failure
     folder paths, Feishu multi-item docx attachment ingest failure with
     SubtreeKeep preservation on SQLite, and Confluence/Nextcloud FetchFullStream
     isolation + deletion reconciliation.
   - Update website-docs/03-features/10-datasource.md sync status rules.
2026-11-20 16:07:43 +08:00
NianJiu 8941b3a86c fix(datasource): isolate per-item ingest failures in streaming sync and classify validation rejections
Root cause (Tencent/WeKnora#5724):
1. In streaming sync, any unexpected item ingest error returned from
   streamSyncHandler.Emit immediately latched h.ingestErr and aborted the
   entire stream. Even for connectors whose cursor tracks each item
   independently (Feishu Wiki/Drive, Seafile, Nextcloud, Confluence), a
   single failing item at the head of a folder prevented all remaining files
   and any newly added folders/resources from ever being processed.
2. Several permanent per-item validation rejections during ingestion
   (illegal filename/folder characters via ErrValidation, ErrInvalidURL,
   malformed JSON replacement via ValidateJSONUploadContent, and unsupported
   file_url extensions) fell through into the generic blocking ingest_failed
   path instead of non-blocking rejections.
3. Streaming ingest aborts prefixed ErrorMessage with "Fetch failed:" even
   when fetching succeeded and ingestion failed, failed item labels dropped
   folder paths for bare-title connectors like Feishu, and ingest error
   codes lacked localized frontend syncError strings.

Changes & boundaries:
- Add datasource.ErrItemIngestFailed and optional ItemFailureIsolatingConnector
  interface implemented by per-item-cursor streaming connectors (Feishu
  Wiki/Drive, Seafile, Nextcloud, Confluence). Linear/commit-level connectors
  (such as GitLab) keep abort-on-error semantics to avoid skipping items.
- In streamSyncHandler.Emit, isolate individual unexpected ingest failures
  for isolating connectors while keeping global errors (context cancellation,
  StorageQuotaExceededError) immediately fatal and capping consecutive
  isolated failures (10, reset on successful create/update) to abort early
  during systemic storage/DB outages.
- Update Feishu, Seafile, Nextcloud, and Confluence streaming loops to leave
  isolated failed items unadvanced in their cursor (preserving prior entries
  and deletion identities for retry) while continuing to remaining items and
  resources.
- Classify permanent item-level ingest rejections (invalid_item_name,
  invalid_url, invalid_json_content, unsupported file_url) as non-blocking,
  and surface storage_quota_exceeded without leaking private diagnostics.
- Fix streaming ingest abort ErrorMessage to omit the misleading
  "Fetch failed:" prefix, include folder paths in SyncItemError.Title when
  available, and localize all ingest syncError codes across all 6 locales.
2026-11-20 15:27:47 +08:00
NianJiu 1b3a1febf3 Merge pull request #5713 from wzxsdf/codex/feishu-resolve-mentions
fix(feishu): resolve mentions in incoming messages
2026-11-20 00:54:49 -06:00
NianJiu a038951d54 Merge pull request #5715 from icearia0219/codex/embed-session-delete
feat(embed): allow deleting signed visitor sessions
2026-11-20 00:54:43 -06:00
NianJiu 965f33c632 Merge pull request #5721 from 30bef100w/fix/wiki-finalize-durable-handoff
fix(wiki): persist finalize work before settling ingest batches
2026-11-20 00:54:36 -06:00
NianJiu 5d3fde9eb9 Merge pull request #5689 from NianJiuZst/fix/data-analysis-excel-header
fix(data-analysis): auto-detect Excel header rows, check result consistency, and surface analysis failures
2026-11-20 00:05:30 -06:00
30bef100w 69417a238b fix(wiki): persist finalize work before settling ingest batches 2026-11-20 11:04:30 +08:00
icearia0219 a6449dea85 feat(embed): allow deleting signed visitor sessions 2026-11-19 23:49:11 +08:00
杰尼龟 c45922ce22 fix(feishu): resolve mentions in incoming messages 2026-11-19 19:48:58 +08:00
lyingbug 53ce747b5c feat(website): add eight community partners to showcase (#5690) 2026-11-19 15:38:08 +08:00
NianJiu 60dbbc80b2 fix(data-analysis): auto-detect Excel header rows, check result consistency, and surface analysis failures
Why:
- `LoadFromExcel` unconditionally executed `read_xlsx(..., header=true, all_varchar=true)` starting at row 1. For workbooks with a leading cross-column merged title banner, subtitle/metadata notes, or blank rows above the real header, DuckDB locked onto row 1 (even with `header=false`), collapsing the entire sheet to 1 column (`[2026 年度销售统计]`) and propagating the broken schema into `DataTableSummaryService` (`table_summary`/`table_column` chunks), `data_schema`, and SQL execution (#5627).
- `DataAnalysisTool.Execute` returned query rows without checking whether grand-total rows reconciled with detail sums or whether unfiltered partition share columns summed to ~1 / ~100%.
- When `PluginDataAnalysis` failed to load or execute SQL in the chat pipeline, it logged a warning and continued silently without informing the answer prompt, and the `data_analyst` system prompt did not explicitly forbid falling back to manual LLM arithmetic over raw table excerpts on failure.

What:
- Add streaming OOXML header detection (`internal/agent/tools/excel_header.go`, sharing workbook relationship resolution with `excel_sheets.go`) that samples leading non-empty rows, resolves only needed shared strings, inspects `<mergeCells>` and contiguous column bounds only when row 1 is narrower than subsequent rows (O(1) fast path for normal workbooks), and guards against pathological wide columns (e.g. stray `XFD` cells) that would OOM DuckDB.
- Update `LoadFromExcel` and `buildExcelCreateTableSQLWithRanges` to pass per-sheet `range = '<startCol><headerRow>:<endCol>'` with `stop_at_empty=true` (preventing DuckDB from materializing 1M trailing NULL rows when `range` is explicit) only for sheets with preamble rows, keeping legacy SQL byte-for-byte identical for normal sheets, CSVs, and multi-sheet `UNION ALL BY NAME` workbooks. Because `DataTableSummaryService` reuses `LoadFromKnowledge`, ingestion schema chunks and `data_schema` automatically receive the true columns.
- Add advisory SQL result consistency checks (`internal/agent/tools/data_analysis_consistency.go`) to warn when a single grand-total row disagrees with the sum of additive detail rows or when an unfiltered, non-limited partition share column fails to sum to ~1 / ~100%, skipping filtered/limited subsets and non-share rates/weights to avoid false alarms.
- Record `PipelineState.DataAnalysisFailure` in `PluginDataAnalysis.OnEvent` on load/SQL failure and append a sanitized `[Data Analysis Notice: ...]` in `prepareMessagesWithModelContext` (without polluting `MergeResult` citations or leaking UUIDs), and harden the `data_analyst` prompt template to require SQL computation for statistics and explicit failure reporting instead of manual arithmetic.
- Add end-to-end tests against real DuckDB covering merged banners, unmerged notes, multi-row/corner metadata preambles, offset tables, pivot headers, footer exclusion, mixed multi-sheet workbooks, renamed `.xls`, `DataTableSummaryService.Handle`, `PluginDataAnalysis` -> `prepareMessagesWithModelContext`, and consistency warnings.
2026-11-19 15:27:21 +08:00
NianJiu 74767642db Merge pull request #5677 from Kidz0419/codex/document-preview-mermaid
fix(frontend): render Mermaid in Markdown document preview
2026-11-19 01:08:24 -06:00
NianJiu d80d3c1e23 Merge pull request #5684 from Zaqqmm/fix/mcp-scope-navigation-5680
fix(mcp): load scope options when returning to configuration
2026-11-19 01:04:08 -06:00
NianJiu 4f3ad8a5b6 Merge pull request #5643 from NianJiuZst/fix/system-user-management-search
fix(system): support cross-page server-side search in platform user management
2026-11-18 23:15:44 -06:00
NianJiu 39f2ae1c7f fix(system): harden search error/lock state transitions and fix Go lint lll violations
Why:
- CI `golangci-lint` failed with 4 `lll` (>120 chars) violations in
  `internal/handler/system.go`, `internal/agent/operations/system_admin_test.go`,
  and `internal/handler/system_user_list_test.go`.
- In `UserManagement.vue`, mutating `appliedQuery` before `listAllUsers()`
  resolved left stale pagination buttons enabled and made `refreshUsers()`
  retry from the previous page offset instead of `0` whenever a search request
  failed from page 2+.
- If a row action or `ResetPasswordDialog` opened during the 250ms search
  debounce window, the blocked search was silently dropped and
  `hasPendingSearch` stayed `true` permanently after the dialog closed.
- Clearing `search` while the Users tab was inactive could trigger a background
  request because the empty-string branch skipped the `props.active` guard.

What:
- Wrap the 4 long Go lines within 120 characters and regenerate
  `docs/swagger.json` and `docs/swagger.yaml` so `TestSwaggerDocsSync` stays
  exact.
- Extend `TestListUsers_SearchAcrossPagesDisabledWildcardsAndDeleted` to also
  pin deterministic `id ASC` tie-breaking across page boundaries and literal
  `\` escaping alongside `%` and `_`.
- Commit `appliedQuery` in `UserManagement.vue` only on successful response,
  track `inFlightQuery` to invalidate superseded in-flight searches during
  typing without dropping trailing-space or Enter-submitted queries, guard the
  empty-clear branch on `props.active`, and flush any deferred search once
  modal/row locks release.
- Add component tests in `UserManagement.test.ts` covering failed-search retry
  from page 2, in-flight invalidation during debounce, deferred flush after
  closing `ResetPasswordDialog`, and inactive-tab clear isolation.
2026-11-19 12:17:18 +08:00
NianJiu 0bc7ca29dd fix(system): support cross-page server-side search in platform user management
Why:
- `GET /api/v1/system/admin/users` only accepted `offset` and `limit`, and
  `UserManagement.vue` filtered `users.value` (a single 20-row page) on the
  client. Once a deployment exceeded 20 users, accounts created earlier on
  page 2+ could not be found from the search box unless the administrator
  manually paged to their slice first (#5634).

What:
- Add optional `q` query parameter to `GET /api/v1/system/admin/users`
  (`SystemHandler.ListUsers` -> `UserService.ListAllUsers` ->
  `UserRepository.ListUsers`) for case-insensitive substring matching on
  `username` or `email`, escaping SQL `LIKE` wildcards (`%`, `_`, `\`) across
  PostgreSQL (`ILIKE`) and SQLite (`LOWER(...) LIKE LOWER(...) ESCAPE '\'`).
- Keep both active and disabled (`is_active = false`) accounts searchable so
  administrators can still locate disabled users to re-enable them, and break
  `created_at DESC` ties with `id ASC` for deterministic pagination.
- Sync Swagger specs (`docs/swagger.json`, `docs/swagger.yaml`), the
  `system_admin.list_users` `@x-agent` operation catalog metadata, and API /
  feature docs in `website-docs/`.
- Switch `UserManagement.vue` and `listAllUsers()` to debounced server-side
  search (`q`), resetting `offset` to `0` on query changes, clearing
  immediately without debounce, discarding out-of-order stale responses via
  request sequence tracking, clamping empty upper pages, and updating all 6
  locale bundles to remove outdated "(current page)" copy.
- Replace fake service mocks in `system_user_list_test.go` with full-chain
  router -> handler -> service -> SQLite repository tests, and add component
  integration tests in `UserManagement.test.ts`.

Fixes #5634
2026-11-19 12:17:18 +08:00
zaqqmm 84aeb50987 fix(mcp): load scope options when returning to configuration 2026-11-19 12:01:46 +08:00
NianJiu 32a9452c28 Merge pull request #5650 from NianJiuZst/fix/feishu-deleted-selected-node-sync
fix(feishu,ui): skip deleted selected wiki nodes and surface stale selections
2026-11-18 21:35:19 -06:00
Kidz0419 be0f8457e3 fix(frontend): render Mermaid in Markdown document preview 2026-11-19 11:11:48 +08:00
NianJiu 81a03046be Merge pull request #5658 from NianJiuZst/fix/lite-kb-clone-move-progress
fix(knowledge): support KB clone and document move without Redis in Lite / Desktop mode
2026-11-18 06:55:41 -06:00
NianJiu 5dec105bf8 fix(knowledge): prevent Lite reparse move from poisoning transfer phase and fix lint
Why:
- Under Lite / Desktop mode's in-process SyncTaskExecutor, enqueueMovedKnowledge dispatches ProcessDocument / ProcessManualUpdate immediately in a goroutine before acknowledgeMovedReparse commits phase="done".
- Two races resulted: (1) if the worker loaded the Knowledge row while _knowledge_transfer.phase was still "reparse_pending", its later full-row UpdateKnowledge saves rolled phase back to "reparse_pending", permanently rejecting any subsequent move of that document with "has an unfinished transfer"; (2) if the worker flipped parse_status before acknowledgeMovedReparse ran UpdateKnowledgeForTransfer, the single-shot CAS failed with "knowledge changed during transfer".
- In addition, internal/router/sync_task_transfer_test.go:316 exceeded the 120-character lll limit in golangci-lint, and tests/lite_smoke lacked KB copy and document move regression coverage.

What:
- Normalize in-memory _knowledge_transfer.phase from "reparse_pending" to "done" inside validateProcessingKnowledge for the target KB's worker, and retry the reload+CAS loop in acknowledgeMovedReparse across concurrent worker parse_status updates.
- Wrap the 137-char JSON string in internal/router/sync_task_transfer_test.go to satisfy golangci-lint (lll <= 120).
- Add TestMoveReparseConcurrentWorkerDoesNotPoisonTransferPhase and extend tests/lite_smoke/lite_e2e_test.go to cover KB copy and multi-document reuse_vectors -> reparse -> reuse_vectors moves without Redis.
2026-11-18 20:04:48 +08:00
NianJiu 3d74393861 fix(feishu,ui): preserve live nested drive shortcuts, guard ancestor reveal, and merge deleted titles
Why:
1. Directly selecting a live shortcut inside a Feishu Drive sub-folder (rootFolder:shortcutToken) fell back to WalkDriveTree(rootFolderToken) after 1061002; because ExpandDriveShortcut replaced DriveFile.Token with ShortcutInfo.TargetToken and dropped the shortcut token, filterDriveFileByToken returned empty and falsely classified live nested shortcuts as deleted. DriveConnector.ResolveResourceAncestors also omitted the immediate parent folder (returning root:root instead of root:subFolder) and DataSourceEditorDialog.loadDriveRoot flushed [folderToken] in edit mode before save, overwriting saved sub-selections on cancel.
2. Wiki Connector.ResolveResourceAncestors added spaceID and intermediate ParentNodeIDs before verifying GetWikiNode, causing Step 2 ensureChildrenLoaded to fail with HTTP 400 and abort before syncUnavailableSelections when a selected node or its space was deleted/unshared.
3. DataSourceService.updateSyncRunResult only preserved prior DeletedItems on failed syncs when len(result.DeletedItems) == 0, dropping cached titles for later deleted resource_ids when a sync failed mid-stream, and DataSourceEditorDialog.isSelectionWithin omitted Confluence space covers (page:<spaceId>:<pageId>) and DingTalk workspace/folder covers.

What:
- Retain DriveFile.ShortcutToken in ExpandDriveShortcut, fill missing ParentToken during WalkDriveTree / ListResources, match ShortcutToken before target fallback in filterDriveFileByToken, fix buildDriveAncestorChain to return [root, ..., parentSubFolder] only for resolved selections, and skip premature edit-mode updateDataSource flushes in loadDriveRoot when folder_token is unchanged.
- Defer adding spaceID and parent chain in Wiki Connector.ResolveResourceAncestors until the full ancestor chain resolves cleanly via GetWikiNode.
- Merge unseen prior DeletedItems (up to maxSyncResultErrors) into ds.LastSyncResult whenever status == SyncLogStatusFailed, and cover Confluence (page:<spaceId>:*) and DingTalk (dingtalk:v1?...) in isSelectionWithin.
- Add connector, DataSourceService ProcessSync, and DataSourceEditorDialog tests covering nested Drive shortcuts, deleted-space ancestor resolution, mid-stream failure title retention, edit-mode Drive cancel safety, and Confluence/DingTalk selection covers.
2026-11-18 20:00:53 +08:00
NianJiu 88f3282223 fix(feishu,ui): sweep attachments on deletion and harden deleted-resource UX
Why:
1. Deleting a Feishu Wiki/Drive docx document that had parsed file attachments
   (<nodeToken>#file#<attToken>) removed only the parent row in applyFetchedItem
   because Feishu cursors track only parent tokens and IsDeleted items did not
   carry ReplacesSubtree or run sweepStaleSubtree, leaving attachment sub-items
   orphaned in the KB.
2. Directly selecting a Feishu Drive file (rather than a folder) and deleting it
   upstream returns 1061002 ('params error') on the folder-list probe and an
   empty root-walk match, which bypassed SelectedResourceDeletedError so
   SyncDeletions=false and subsequent sync rounds dropped DeletedItems; meanwhile
   deleting a Drive subfolder emitted a spurious extra IsDeleted item for the
   folder token itself alongside its child files.
3. Deleting a parent Wiki node with child documents resolved the first child's
   title for the parent's SourceResourceID, and an intermediate failed sync
   overwrote ds.LastSyncResult with an empty DeletedItems list.
4. In DataSourceEditorDialog Step 2, checking a parent space kept superseded
   unavailable child rows visually checked via isSelectionWithin while
   uncheckResource could not clear them; Confluence Cloud spaces with
   cloud_top_level_containers could misclassify unexpanded folder pages as
   unavailable; and DataSourceSyncLogs computed deletedItemsCount from the
   50-item sliced array instead of the full deleted_items list.

What:
- Set ReplacesSubtree=true on Feishu engine IsDeleted items, emit
  deletedRes.Token only when no prior cursor tokens exist under resourceID, and
  invoke sweepStaleSubtree in applyFetchedItem's IsDeleted path.
- Return SelectedResourceDeletedError in listDriveFilesForResource when a
  non-folder token (1061002) is absent from a clean root walk, and wrap
  ErrResourceNotFound on HTTP-200 error envelopes in ListWikiNodes /
  GetDriveFolderMeta.
- Match ExternalID before unique SourceResourceID in resolveDeletedItemTitle and
  knownDeletedTitles, and preserve prior DeletedItems on ds.LastSyncResult
  across failed sync runs.
- Fix unavailable row check state / coverage in DataSourceEditorDialog, guard
  Confluence Cloud folder-limited spaces and Drive root token switches, and use
  the unsliced deleted_items length for deletedItemsCount in DataSourceSyncLogs.
- Add Go service+connector E2E tests and Vue component tests covering attachment
  sweeps, Drive file/subfolder deletions, parent-subtree titles across failed
  syncs, space-selection superseding, and Confluence Cloud folder limits.
2026-11-18 20:00:53 +08:00
NianJiu 04ca14dbac fix(feishu,ui): skip deleted selected wiki nodes and surface stale selections
Why:
1. When a user directly selects individual Feishu/Lark Wiki documents
   (`spaceID:nodeToken`) or Drive sub-resources (`rootToken:fileToken`) in
   `config.resource_ids` instead of the parent space/folder, and one selected
   document is later deleted in Feishu (`GET /open-apis/wiki/v2/spaces/get_node`
   returns HTTP 400 `code=131005: not found: node has been deleted`, or Drive
   returns `code=1061003`), `wikiOps.List` / `driveOps.List` treated the 404 as
   a fatal total listing failure and aborted `runSync` immediately. Every
   selected document ordered after the deleted one never synced, and the whole
   data source entered `error` status.
2. Neither the sync history drawer (`DataSourceSyncLogs.vue`) nor the Step 2
   resource picker (`DataSourceEditorDialog.vue`) surfaced which source
   documents had been deleted or allowed unchecking vanished `resource_ids`
   still stored in `config.resource_ids`.

What:
- Unwrap `datasource.ErrResourceNotFound` from `feishuAPIError` (and HTTP 200
  error envelopes) strictly for Feishu Wiki `131005` and Drive `1061003`, while
  keeping permission/auth/RPC/5xx errors (`131006`, `1061004`, etc.) failing
  without deleting KB data.
- Return `core.SelectedResourceDeletedError` from `wikiOps.List` and
  `driveOps.List` when a directly selected sub-resource is deleted upstream, so
  `runSync` emits `IsDeleted` items for all previously recorded cursor tokens
  under that `resourceID`, prunes its cursor entry, checkpoints, and continues
  syncing remaining `resourceIDs`.
- Record capped `DeletedItems []SyncDeletedItem` (`external_id`,
  `source_resource_id`, `title`) in `SyncResult` across KB deletion, subsequent
  idempotent syncs, and `sync_deletions=false` skips (retaining prior resolved
  titles across rounds).
- Render `deleted_items` in `DataSourceSyncLogs.vue` and surface vanished saved
  `resource_ids` at the top of `DataSourceEditorDialog.vue` Step 2 with a
  localized unavailable badge (refreshing stale list snapshots on demand via
  `getDataSource`) so users can inspect and uncheck them cleanly.
- Add i18n keys across all 6 locales (`zh-CN`, `zh-TW`, `en-US`, `ja-JP`,
  `ko-KR`, `ru-RU`), update `website-docs/03-features/10-datasource.md`, and
  add Go + Vue regression tests.

Fixes #5633
2026-11-18 20:00:53 +08:00
NianJiu c0ad1d0cea fix(knowledge): support KB clone and document move progress without Redis in Lite mode
Why:
- In Lite / Desktop mode (`REDIS_ADDR` unset, `s.redisClient == nil`, async tasks run via in-memory `SyncTaskExecutor`), all 6 transfer progress methods in `internal/application/service/knowledge_clone_move.go` (`saveKBCloneProgress`, `SaveKBCloneProgress`, `GetKBCloneProgress`, `saveKnowledgeMoveProgress`, `SaveKnowledgeMoveProgress`, `GetKnowledgeMoveProgress`) unconditionally dereferenced `s.redisClient`.
- Calling `POST /api/v1/knowledge-bases/copy`, `POST /api/v1/knowledge/move`, or either progress polling endpoint triggered a nil-pointer panic (HTTP 500), and `ProcessKBClone` / `ProcessKnowledgeMove` panicked inside `SyncTaskExecutor` on their first progress write—tearing multi-document move batches after item 1 and failing all retries.
- In addition, `ProcessKBClone` and `ProcessKnowledgeMove` only read `asynq.GetRetryCount` / `asynq.GetMaxRetry` (`0, false` outside Asynq), ignoring `types.TaskRetryMetadataFromContext(ctx)` injected by `SyncTaskExecutor` and treating attempt 0 of a retryable task as final.

What:
- Add race-safe, value-copied in-memory fallbacks (`memKBCloneProgress`, `memKnowledgeMoveProgress`) with 24h TTL parity, lazy/admission expiry eviction (no per-tick timers), `SetNX` (`onlyIfAbsent`) admission semantics so HTTP admission never clobbers an already-started worker, and `NotFound` errors on missing/expired task IDs.
- Resolve retry counters via `taskRetryState(ctx)` (`types.TaskRetryMetadataFromContext` first, then `asynq.GetRetryCount`/`GetMaxRetry`, plus `asynq.SkipRetry` terminal checks) in `ProcessKBClone` and `ProcessKnowledgeMove`.
- Add end-to-end router + `SyncTaskExecutor` + SQLite (`redisClient == nil`) HTTP tests, service admission-race/expiry/retry-metadata tests, and update `website-docs/02-architecture/05-async-tasks.md`.
2026-11-18 19:36:49 +08:00
NianJiu b72bc44e32 Merge pull request #5024 from Aling33/fix/reparse-preserve-indexed-content
fix(knowledge): keep a reparse searchable until its worker replaces the content
2026-11-18 05:06:30 -06:00
NianJiu fb2afd44a9 fix(knowledge): guard reparse resource swap, quota delta, and live retrieval state
Why:
1. Running cleanupKnowledgeResources in ProcessDocument before processChunks bypassed processChunks's abort, source-replaced, attempt-superseded, embedding-model, and vector-store guards, allowing a superseded worker to wipe a newer attempt's indexed content and deleting content before model/store checks ran.
2. Running cleanupKnowledgeResources after bindStoredImages released and deleted content-deduplicated resource:// image handles still referenced by the reparsed chunks.
3. Subtracting StorageSize up front only mutated knowledge.StorageSize in memory, causing retryable BatchIndex failures to subtract quota repeatedly while reparses in >50%-full workspaces failed the quota check; gating cleanup on payload.Attempt > 0 && StorageSize > 0 also leaked images and quota when OpenAttempt fell back (Attempt == 0) or vector indexing was disabled (StorageSize == 0).
4. Flipping enable_status to disabled and overwriting embedding_model_id / description at submission dropped queued or failed-reparse documents out of Graph Search and Agent QA listings and orphaned vectors when KB embedding dimensions changed, while skipping synchronous cleanup in ReplaceKnowledgeFile left retired source chunks searchable under the replacement filename.

What:
- Move obsolete-image and previous-dimension vector cleanup into processChunks after all abort/supersede and model/store guards succeed, filtering out image URLs still referenced by the replacement chunks.
- Account for tenant storage via delta (totalStorageSize - previousStorageSize), discount previousStorageSize during quota checks, and release previousStorageSize only if chunk/index swap fails terminally after deleting old rows.
- Preserve EnableStatus, EmbeddingModelID, StorageSize, Description, and ProcessedAt across in-place reparse submission (!tasksDequeued) while keeping synchronous cleanup for ReplaceKnowledgeFile (tasksDequeued).
- Replace internal helper mocks with SQLite + sqlite-vec + ResourceCatalog end-to-end tests covering batch reparse, DocReader failure, superseded attempt races, and file replacement.
2026-11-18 18:00:23 +08:00
Aling33 0831c185f2 fix(knowledge): keep a reparse searchable until its worker replaces the content
Submitting a reparse deleted every document's chunks, index rows, images
and graph data up front, so the whole batch left retrieval until each
document's own processing task ran, and a document whose parse then failed
stayed empty for good. The swap now happens in ProcessDocument, once the
replacement has been parsed, through the same helper the manual update
worker already uses.
2026-11-18 17:40:42 +08:00
NianJiu d95139b93e Merge pull request #5636 from NianJiuZst/ci/governance-gates
ci: close 6 production test gate blind spots and add Lite E2E smoke test
2026-11-18 03:04:55 -06:00