"; one data source syncs one
// library, so the picker refuses a selection that spans two libraries.
const isSeafileConnector = (type: string) => type === 'seafile'
@@ -825,7 +839,7 @@ watch(visible, async (v) => {
resource_ids: editConfig.resource_ids || [],
settings: props.dataSource.type === 'rss'
? hydrateRssFeedUrlsFromConfig(editConfig)
- : (editConfig.settings || {}),
+ : { ...(editConfig.settings || {}) },
},
sync_schedule: props.dataSource.sync_schedule,
sync_mode: props.dataSource.sync_mode,
@@ -906,6 +920,13 @@ function selectType(def: ConnectorDef) {
form.value.type = def.type
form.value.name = t(`datasource.connector.${def.type}`)
form.value.config.credentials = def.type === "confluence" ? { edition: "server" } : {}
+ if (isFeishuFamilyConnector(def.type)) {
+ form.value.config.settings.parse_mode = form.value.config.settings.parse_mode || 'blocks'
+ } else {
+ // Backtracking from a Feishu/Lark type must not leak parse_mode into
+ // other connectors' settings.
+ delete form.value.config.settings.parse_mode
+ }
if (def.type === 'confluence') {
form.value.config.settings = { ...form.value.config.settings, edition: 'server' }
}
@@ -1999,6 +2020,44 @@ const drawerConfirmText = computed(() => {
+
+
{{ t('datasource.syncDeletions') }}
diff --git a/internal/application/service/datasource_feishu_upgrade_test.go b/internal/application/service/datasource_feishu_upgrade_test.go
new file mode 100644
index 00000000..2d4c7a91
--- /dev/null
+++ b/internal/application/service/datasource_feishu_upgrade_test.go
@@ -0,0 +1,97 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/datasource"
+ "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
+ "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/drive"
+ "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/wiki"
+ "github.com/Tencent/WeKnora/internal/types"
+ secutils "github.com/Tencent/WeKnora/internal/utils"
+)
+
+func TestStreamingFetch_FeishuUpgradeKeepsDeletionBaseline(t *testing.T) {
+ t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
+ secutils.ResetSSRFWhitelistForTest()
+ defer secutils.ResetSSRFWhitelistForTest()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" {
+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
+ "code": 0, "tenant_access_token": "test", "expire": 7200,
+ })
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
+ "code": 0, "data": map[string]interface{}{"items": []interface{}{}, "has_more": false},
+ })
+ }))
+ defer server.Close()
+ for _, tc := range []struct {
+ name string
+ conn datasource.StreamingConnector
+ cursorKey string
+ }{
+ {"feishu", wiki.NewConnector(core.RegionFeishu), "space_node_times"},
+ {"lark", wiki.NewConnector(core.RegionLark), "space_node_times"},
+ {"feishu_drive", drive.NewDriveConnector(core.RegionFeishu), "file_times"},
+ {"lark_drive", drive.NewDriveConnector(core.RegionLark), "file_times"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cfg := &types.DataSourceConfig{
+ Type: tc.name,
+ Credentials: map[string]interface{}{"app_id": "a", "app_secret": "b", "base_url": server.URL},
+ ResourceIDs: []string{"resource1"}, Settings: map[string]interface{}{"resync_required": true},
+ }
+ baseline := &types.SyncCursor{ConnectorCursor: map[string]interface{}{
+ tc.cursorKey: map[string]interface{}{"resource1": map[string]interface{}{"gone": "100"}},
+ }}
+ conn := tc.conn
+
+ control := &feishuUpgradeHandler{}
+ if _, err := conn.FetchStream(context.Background(), cfg, baseline, control); err != nil {
+ t.Fatal(err)
+ }
+ if len(control.Items) != 1 || !control.Items[0].IsDeleted {
+ t.Fatalf("incremental control did not detect deletion: %+v", control.Items)
+ }
+ raw, err := baseline.ToJSON()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ds := &types.DataSource{LastSyncCursor: raw, SyncMode: types.SyncModeIncremental}
+ start, err := streamStartCursor(ds, resyncRequired(cfg), 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h := &feishuUpgradeHandler{}
+ next, err := streamingFetch(context.Background(), conn, cfg, true, start, baseline, h)
+ if err != nil {
+ t.Fatal(err)
+ }
+ subsequent := &feishuUpgradeHandler{}
+ if _, err = conn.FetchStream(context.Background(), cfg, next, subsequent); err != nil {
+ t.Fatal(err)
+ }
+ if len(h.Items) != 1 || !h.Items[0].IsDeleted || h.Items[0].ExternalID != "gone" {
+ t.Fatalf("full upgrade must emit the deletion: %+v", h.Items)
+ }
+ if len(subsequent.Items) != 0 {
+ t.Fatalf("next sync repeated a reconciled deletion: %+v", subsequent.Items)
+ }
+ })
+ }
+}
+
+type feishuUpgradeHandler struct{ Items []types.FetchedItem }
+
+func (h *feishuUpgradeHandler) Emit(_ context.Context, item types.FetchedItem) error {
+ h.Items = append(h.Items, item)
+ return nil
+}
+func (h *feishuUpgradeHandler) Checkpoint(context.Context, *types.SyncCursor) error { return nil }
diff --git a/internal/application/service/datasource_resync_test.go b/internal/application/service/datasource_resync_test.go
new file mode 100644
index 00000000..56ead40f
--- /dev/null
+++ b/internal/application/service/datasource_resync_test.go
@@ -0,0 +1,222 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/datasource"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/hibiken/asynq"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Feishu deep-adaptation legacy upgrade: legacy feishu data sources carry a
+// one-shot Settings["resync_required"] marker (stamped by migration 000122 /
+// sqlite 000040). The sync entry upgrades such a sync — even a scheduled
+// incremental one — to a full pass and clears the marker on success.
+// ─────────────────────────────────────────────────────────────────────────────
+
+// resyncStreamConnector records the start cursor each FetchStream received, so
+// tests can assert whether the sync ran full (nil cursor) or incremental.
+type resyncStreamConnector struct {
+ startCursors []*types.SyncCursor
+ failFetch bool
+}
+
+func (c *resyncStreamConnector) Type() string { return types.ConnectorTypeFeishu }
+func (c *resyncStreamConnector) Validate(context.Context, *types.DataSourceConfig) error {
+ return nil
+}
+
+func (c *resyncStreamConnector) ListResources(
+ context.Context, *types.DataSourceConfig, string,
+) ([]types.Resource, error) {
+ return nil, nil
+}
+
+func (c *resyncStreamConnector) ResolveResourceAncestors(
+ context.Context, *types.DataSourceConfig, []string,
+) ([]string, error) {
+ return nil, nil
+}
+
+func (c *resyncStreamConnector) FetchAll(
+ context.Context, *types.DataSourceConfig, []string,
+) ([]types.FetchedItem, error) {
+ return nil, nil
+}
+
+func (c *resyncStreamConnector) FetchIncremental(
+ context.Context, *types.DataSourceConfig, *types.SyncCursor,
+) ([]types.FetchedItem, *types.SyncCursor, error) {
+ return nil, nil, nil
+}
+
+func (c *resyncStreamConnector) FetchStream(
+ _ context.Context, _ *types.DataSourceConfig, cursor *types.SyncCursor, _ datasource.StreamHandler,
+) (*types.SyncCursor, error) {
+ c.startCursors = append(c.startCursors, cursor)
+ if c.failFetch {
+ return nil, errors.New("fetch failed")
+ }
+ return &types.SyncCursor{ConnectorCursor: map[string]interface{}{"space_node_times": map[string]interface{}{}}}, nil
+}
+
+// resyncDSRepo captures Config-writing Update calls (marker clear).
+type resyncDSRepo struct {
+ kbDeleteDSRepo
+ updates int
+ configs []types.JSON
+ syncStates int
+}
+
+func (r *resyncDSRepo) Update(_ context.Context, ds *types.DataSource) error {
+ r.updates++
+ r.configs = append(r.configs, ds.Config)
+ return nil
+}
+
+func (r *resyncDSRepo) UpdateSyncState(_ context.Context, _ *types.DataSource) error {
+ r.syncStates++
+ return nil
+}
+
+// newResyncHarness wires a DataSourceService around the streaming fake for a
+// feishu data source whose stored Config carries the given Settings.
+func newResyncHarness(
+ t *testing.T, settings map[string]interface{}, conn *resyncStreamConnector,
+) (*DataSourceService, *types.DataSource, *resyncDSRepo, *types.SyncLog) {
+ t.Helper()
+ cfg := &types.DataSourceConfig{
+ Type: types.ConnectorTypeFeishu,
+ Credentials: map[string]interface{}{"app_id": "cli-x", "app_secret": "sec"},
+ ResourceIDs: []string{"space1"},
+ Settings: settings,
+ }
+ configJSON, err := cfg.ToJSON()
+ require.NoError(t, err)
+
+ ds := &types.DataSource{
+ ID: "ds-resync",
+ TenantID: 1,
+ KnowledgeBaseID: "kb-1",
+ Name: "Feishu Legacy",
+ Type: types.ConnectorTypeFeishu,
+ Config: configJSON,
+ SyncMode: types.SyncModeIncremental,
+ Status: types.DataSourceStatusActive,
+ }
+ syncLog := &types.SyncLog{
+ ID: "log-resync",
+ DataSourceID: ds.ID,
+ TenantID: ds.TenantID,
+ Status: types.SyncLogStatusRunning,
+ StartedAt: time.Now().UTC(),
+ }
+ dsRepo := &resyncDSRepo{kbDeleteDSRepo: *newKBDeleteDSRepo(ds.KnowledgeBaseID, ds)}
+ registry := datasource.NewConnectorRegistry()
+ require.NoError(t, registry.Register(conn))
+
+ svc := &DataSourceService{
+ dsRepo: dsRepo,
+ syncLogRepo: &processSyncSyncLogRepo{
+ logs: map[string]*types.SyncLog{syncLog.ID: syncLog},
+ },
+ kbService: &processSyncKBService{
+ kb: &types.KnowledgeBase{ID: ds.KnowledgeBaseID, TenantID: ds.TenantID},
+ },
+ connectorRegistry: registry,
+ tenantRepo: &processSyncTenantRepo{tenant: &types.Tenant{ID: ds.TenantID}},
+ tagService: &processSyncTagService{},
+ }
+ return svc, ds, dsRepo, syncLog
+}
+
+func runResyncSync(t *testing.T, svc *DataSourceService, ds *types.DataSource, syncLog *types.SyncLog) *types.SyncLog {
+ t.Helper()
+ payload, err := json.Marshal(types.DataSourceSyncPayload{
+ DataSourceID: ds.ID,
+ TenantID: ds.TenantID,
+ SyncLogID: syncLog.ID,
+ })
+ require.NoError(t, err)
+ require.NoError(t, svc.ProcessSync(context.Background(), asynq.NewTask(types.TypeDataSourceSync, payload)))
+ return svc.syncLogRepo.(*processSyncSyncLogRepo).logs[syncLog.ID]
+}
+
+// settingsOf decodes a stored Config blob and returns its Settings map.
+func settingsOf(t *testing.T, blob types.JSON) map[string]interface{} {
+ t.Helper()
+ var raw struct {
+ Settings map[string]interface{} `json:"settings"`
+ }
+ require.NoError(t, json.Unmarshal(blob, &raw))
+ return raw.Settings
+}
+
+// A data source armed with the migration's resync_required marker runs FULL
+// even though it is incremental, and the marker is cleared once the run
+// succeeds.
+func TestProcessSync_ResyncMarkerRunsFullOnceAndClears(t *testing.T) {
+ conn := &resyncStreamConnector{}
+ svc, ds, dsRepo, syncLog := newResyncHarness(t, map[string]interface{}{"resync_required": true}, conn)
+
+ log := runResyncSync(t, svc, ds, syncLog)
+ assert.Equal(t, types.SyncLogStatusSuccess, log.Status)
+
+ // Full upgrade: the incremental sync started with no cursor.
+ require.Len(t, conn.startCursors, 1)
+ assert.Nil(t, conn.startCursors[0], "resync_required must upgrade the incremental sync to a full pass")
+
+ // One Config write: clearing the marker on success.
+ require.Equal(t, 1, dsRepo.updates)
+ final := settingsOf(t, dsRepo.configs[0])
+ assert.NotContains(t, final, "resync_required", "marker must be cleared after a successful upgrade")
+}
+
+// A data source without the marker stays incremental: no config writes.
+func TestProcessSync_NoMarkerStaysIncremental(t *testing.T) {
+ conn := &resyncStreamConnector{}
+ svc, ds, dsRepo, syncLog := newResyncHarness(t, map[string]interface{}{"parse_mode": "export"}, conn)
+ ds.LastSyncCursor = makeConnectorCursor(t, map[string]map[string]string{"space1": {"nt1": "100"}})
+
+ log := runResyncSync(t, svc, ds, syncLog)
+ assert.Equal(t, types.SyncLogStatusSuccess, log.Status)
+
+ require.Len(t, conn.startCursors, 1)
+ assert.NotNil(t, conn.startCursors[0], "no marker must keep the sync incremental")
+ assert.Equal(t, 0, dsRepo.updates, "no backfill or marker write may happen when parse_mode exists")
+}
+
+// A failed upgraded sync keeps the marker so the next run retries the full
+// upgrade instead of silently continuing incremental.
+func TestProcessSync_FailedResyncKeepsMarker(t *testing.T) {
+ conn := &resyncStreamConnector{failFetch: true}
+ svc, ds, dsRepo, syncLog := newResyncHarness(t, map[string]interface{}{"resync_required": true}, conn)
+
+ payload, err := json.Marshal(types.DataSourceSyncPayload{
+ DataSourceID: ds.ID,
+ TenantID: ds.TenantID,
+ SyncLogID: syncLog.ID,
+ })
+ require.NoError(t, err)
+ assert.Error(t, svc.ProcessSync(context.Background(), asynq.NewTask(types.TypeDataSourceSync, payload)))
+
+ // No config writes on the failed run: the marker stays armed.
+ assert.Equal(t, 0, dsRepo.updates)
+}
+
+// resyncRequired tolerates the encodings the marker may be written in.
+func TestResyncRequired_Encodings(t *testing.T) {
+ assert.False(t, resyncRequired(nil))
+ assert.False(t, resyncRequired(&types.DataSourceConfig{}))
+ assert.False(t, resyncRequired(&types.DataSourceConfig{Settings: map[string]interface{}{"resync_required": false}}))
+ assert.False(t, resyncRequired(&types.DataSourceConfig{Settings: map[string]interface{}{"resync_required": "no"}}))
+ assert.True(t, resyncRequired(&types.DataSourceConfig{Settings: map[string]interface{}{"resync_required": true}}))
+ assert.True(t, resyncRequired(&types.DataSourceConfig{Settings: map[string]interface{}{"resync_required": "true"}}))
+}
diff --git a/internal/application/service/datasource_service.go b/internal/application/service/datasource_service.go
index fe106dfe..d12beabc 100644
--- a/internal/application/service/datasource_service.go
+++ b/internal/application/service/datasource_service.go
@@ -676,10 +676,6 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e
_ = s.dsRepo.Update(ctx, ds)
return err
}
- // Surface the KB's multimodal/VLM state to the connector so it only extracts
- // embedded images for OCR when the KB can actually ingest them (never persisted).
- config.MultimodalEnabled = kb.IsMultimodalEnabled()
-
// Streaming path: connectors that support it interleave fetch→ingest→
// checkpoint so a large sync bounds memory and resumes after a timeout
// instead of restarting (Tencent/WeKnora#2136). Others fall back below.
@@ -960,16 +956,6 @@ func (s *DataSourceService) applyFetchedItem(
// Duplicate file/URL is not a failure — count as skipped.
logger.Infof(ctx, "item %q (external_id=%s) already exists, skipping", item.Title, item.ExternalID)
result.Skipped++
- case item.Metadata["embedded_image"] == "true":
- // An image extracted from a document for OCR is a best-effort
- // enrichment, not the document itself. If the KB cannot ingest it
- // (VLM/object-storage not configured for images, or a transient error),
- // skip it rather than failing the whole sync: the doc body already
- // synced, and the image stays in SubtreeKeep for a later retry once the
- // KB is configured.
- logger.Infof(ctx, "skipping embedded image %q (external_id=%s), not ingested: %v",
- item.Title, item.ExternalID, err)
- result.Skipped++
default:
logger.Warnf(ctx, "failed to ingest item %q (external_id=%s): %v", item.Title, item.ExternalID, err)
result.Failed++
@@ -998,6 +984,67 @@ func streamStartCursor(ds *types.DataSource, forceFull bool, attempt int) (*type
return ds.ParseSyncCursor()
}
+// feishuSettingResyncRequired is the one-shot upgrade marker key. Legacy
+// feishu/lark data sources are stamped by migration 000122 (sqlite 000040).
+const feishuSettingResyncRequired = "resync_required"
+
+// resyncRequired reads the one-shot upgrade marker out of parsed config
+// Settings. Tolerates both bool and string encodings. The marker is stamped
+// onto legacy feishu/lark data sources by migration 000122 (sqlite 000040)
+// when the per-source parse_mode shipped; it upgrades their next sync — even
+// a scheduled incremental one — to a full pass so existing documents re-ingest
+// with folder paths and block-level parsing.
+func resyncRequired(cfg *types.DataSourceConfig) bool {
+ if cfg == nil {
+ return false
+ }
+ switch v := cfg.Settings[feishuSettingResyncRequired].(type) {
+ case bool:
+ return v
+ case string:
+ return v == "true"
+ default:
+ return false
+ }
+}
+
+// clearResyncMarker removes the one-shot upgrade marker after the upgraded sync
+// succeeded so it never fires again. Streaming path only: the feishu/lark
+// connectors the migration tags all implement StreamingConnector.
+func (s *DataSourceService) clearResyncMarker(ctx context.Context, ds *types.DataSource) {
+ cfg, err := ds.ParseConfig()
+ if err == nil && cfg.Settings[feishuSettingResyncRequired] == nil {
+ return
+ }
+ // Re-read the row before writing: the upgraded sync may have run long, and
+ // a full-row Update from the sync-start snapshot would silently revert
+ // concurrent user edits (settings, resource_ids, schedule…). Only the
+ // marker removal is ours to persist.
+ fresh, err := s.dsRepo.FindByID(ctx, ds.ID)
+ if err != nil {
+ logger.Warnf(ctx, "failed to clear resync_required marker, re-read failed: ds=%s err=%v", ds.ID, err)
+ return
+ }
+ cfg, err = fresh.ParseConfig()
+ if err != nil {
+ logger.Warnf(ctx, "failed to clear resync_required marker, config unreadable: ds=%s err=%v", ds.ID, err)
+ return
+ }
+ if cfg.Settings[feishuSettingResyncRequired] == nil {
+ return
+ }
+ delete(cfg.Settings, feishuSettingResyncRequired)
+ blob, err := cfg.ToJSON()
+ if err != nil {
+ logger.Warnf(ctx, "failed to clear resync_required marker, config re-encode failed: ds=%s err=%v", ds.ID, err)
+ return
+ }
+ fresh.Config = blob
+ if err := s.dsRepo.Update(ctx, fresh); err != nil {
+ logger.Warnf(ctx, "failed to clear resync_required marker: ds=%s err=%v", ds.ID, err)
+ }
+}
+
// streamSyncHandler adapts a streaming fetch to the knowledge-base ingest path.
// Emit ingests each item as it arrives (bounding memory) and Checkpoint persists
// the connector cursor plus live progress counts at page boundaries.
@@ -1094,6 +1141,12 @@ func (s *DataSourceService) processSyncStreaming(
autoTagIDs := s.resolveAutoTagIDs(ctx, ds)
forceFull := payload.ForceFull || ds.SyncMode == types.SyncModeFull
+ if resyncRequired(config) {
+ // One-shot legacy upgrade (design §7). The marker is cleared only
+ // after the run succeeds below; a failure keeps it so the retry
+ // resumes the upgraded pass from its checkpoint.
+ forceFull = true
+ }
attempt, _ := asynq.GetRetryCount(ctx)
startCursor, err := streamStartCursor(ds, forceFull, attempt)
if err != nil {
@@ -1163,6 +1216,12 @@ func (s *DataSourceService) processSyncStreaming(
}
}
s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON, status, errMsg, wasPaused)
+ // The upgraded full pass succeeded (success or partial — per-document
+ // failures are a normal retryable condition): retire the marker so it
+ // never fires again. Failed runs returned earlier and keep it.
+ if resyncRequired(config) {
+ s.clearResyncMarker(ctx, ds)
+ }
logger.Infof(ctx, "streaming sync completed: ds=%s created=%d updated=%d deleted=%d skipped=%d failed=%d",
payload.DataSourceID, result.Created, result.Updated, result.Deleted, result.Skipped, result.Failed)
return nil
@@ -1344,6 +1403,9 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource
// Case 1: content already fetched → build a FileHeader from bytes and call CreateKnowledgeFromFile
if len(item.Content) > 0 {
+ // Images ride inline as base64 data URIs; ProcessDocument's image
+ // resolver stores them on the file service and swaps in persistent
+ // provider:// URLs before chunking.
fh, err := bytesToFileHeader(item.Content, item.FileName)
if err != nil {
return isUpdate, fmt.Errorf("build file header: %w", err)
diff --git a/internal/application/service/datasource_sweep_wiring_test.go b/internal/application/service/datasource_sweep_wiring_test.go
index e9ce5bc0..cdf1a4ab 100644
--- a/internal/application/service/datasource_sweep_wiring_test.go
+++ b/internal/application/service/datasource_sweep_wiring_test.go
@@ -315,38 +315,3 @@ func TestIngestItem_NoSweepWhenFlagUnset(t *testing.T) {
// (e.g. VLM/object-storage not configured for images), the failure is counted as
// Skipped, not Failed, so it never marks the whole document sync as failed. A
// non-image item with the same error must still count as Failed.
-func TestApplyFetchedItem_EmbeddedImageIngestFailureCountsAsSkip(t *testing.T) {
- ingestErr := errors.New("上传图片文件需要设置VLM模型")
- ds := &types.DataSource{ID: "ds-1", Type: "feishu", TenantID: 7, KnowledgeBaseID: "kb-1"}
- newItem := func(extID string, meta map[string]string) *types.FetchedItem {
- return &types.FetchedItem{
- ExternalID: extID,
- Title: "img",
- Content: []byte("\x89PNG\r\n\x1a\nxxxx"),
- ContentType: "image/png",
- FileName: "image-x.png",
- Metadata: meta,
- }
- }
-
- // Embedded image whose ingest fails → Skipped, not Failed.
- ksImg := &sweepFakeKS{repo: &sweepFakeRepo{}, createErr: ingestErr}
- sImg := &DataSourceService{knowledgeService: ksImg}
- resImg := &types.SyncResult{}
- sImg.applyFetchedItem(context.Background(), ds,
- newItem("nt#image#x", map[string]string{"embedded_image": "true"}), nil, resImg)
- if resImg.Skipped != 1 || resImg.Failed != 0 {
- t.Fatalf("embedded image failure: Skipped=%d Failed=%d, want Skipped=1 Failed=0",
- resImg.Skipped, resImg.Failed)
- }
-
- // Control: a non-image item with the same error → Failed.
- ksDoc := &sweepFakeKS{repo: &sweepFakeRepo{}, createErr: ingestErr}
- sDoc := &DataSourceService{knowledgeService: ksDoc}
- resDoc := &types.SyncResult{}
- sDoc.applyFetchedItem(context.Background(), ds, newItem("nt-doc", nil), nil, resDoc)
- if resDoc.Failed != 1 || resDoc.Skipped != 0 {
- t.Fatalf("non-image failure: Failed=%d Skipped=%d, want Failed=1 Skipped=0",
- resDoc.Failed, resDoc.Skipped)
- }
-}
diff --git a/internal/database/migration_feishu_resync_test.go b/internal/database/migration_feishu_resync_test.go
new file mode 100644
index 00000000..9795871b
--- /dev/null
+++ b/internal/database/migration_feishu_resync_test.go
@@ -0,0 +1,102 @@
+package database
+
+import (
+ "database/sql"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// Exercise the migration SQL itself with legacy API-created settings, and
+// preserve credentials, unrelated settings, explicit markers and other sources.
+func testFeishuResyncMigration(t *testing.T, db *sql.DB, dialect string) {
+ t.Helper()
+ tx, err := db.Begin()
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = tx.Rollback() })
+ jsonType := "TEXT"
+ migration := "sqlite/000040_feishu_deep_adaptation_resync"
+ if dialect == "postgres" {
+ jsonType = "JSONB"
+ migration = "versioned/000122_feishu_deep_adaptation_resync"
+ }
+ _, err = tx.Exec("CREATE TEMP TABLE data_sources " +
+ "(id TEXT PRIMARY KEY, type TEXT, config " + jsonType + ", deleted_at TEXT)")
+ require.NoError(t, err)
+ cases := []struct {
+ id, kind, config string
+ deleted bool
+ wantMarker bool
+ }{
+ {"missing", "feishu", `{"credentials":{"app_id":"a","app_secret":"s"},"resource_ids":["space"]}`, false, true},
+ {"null", "lark", `{"settings":null,"credentials":{"app_secret":"s"}}`, false, true},
+ {"empty", "feishu_drive", `{"settings":{}}`, false, true},
+ {"configured", "lark_drive", `{"settings":{"parse_mode":"export","timezone":"Asia/Shanghai"}}`, false, true},
+ {"false-marker", "feishu", `{"settings":{"resync_required":false,"parse_mode":"blocks"}}`, false, false},
+ {"true-marker", "lark", `{"settings":{"resync_required":true,"timezone":"UTC"}}`, false, true},
+ {"other", "gitlab", `{"settings":null}`, false, false},
+ {"deleted", "feishu", `{"settings":null}`, true, false},
+ }
+ for _, tt := range cases {
+ var deleted any
+ if tt.deleted {
+ deleted = "2026-01-01"
+ }
+ _, err = tx.Exec("INSERT INTO data_sources (id,type,config,deleted_at) VALUES ($1,$2,$3,$4)",
+ tt.id, tt.kind, tt.config, deleted)
+ require.NoError(t, err)
+ }
+ script, err := os.ReadFile(filepath.Join(sqliteRepoRoot(t), "migrations", migration+".up.sql"))
+ require.NoError(t, err)
+ for range 2 {
+ _, err = tx.Exec(string(script))
+ require.NoError(t, err)
+ }
+ for _, tt := range cases {
+ var raw string
+ require.NoError(t, tx.QueryRow("SELECT config FROM data_sources WHERE id=$1", tt.id).Scan(&raw))
+ var got, before map[string]any
+ require.NoError(t, json.Unmarshal([]byte(raw), &got))
+ require.NoError(t, json.Unmarshal([]byte(tt.config), &before))
+ if !tt.wantMarker {
+ require.Equal(t, before, got, tt.id)
+ continue
+ }
+ settings, ok := got["settings"].(map[string]any)
+ require.True(t, ok, tt.id)
+ require.Equal(t, true, settings["resync_required"], tt.id)
+ require.Equal(t, before["credentials"], got["credentials"], tt.id)
+ require.Equal(t, before["resource_ids"], got["resource_ids"], tt.id)
+ if old, ok := before["settings"].(map[string]any); ok {
+ for key, value := range old {
+ require.Equal(t, value, settings[key], tt.id+":"+key)
+ }
+ }
+ }
+ down, err := os.ReadFile(filepath.Join(sqliteRepoRoot(t), "migrations", migration+".down.sql"))
+ require.NoError(t, err)
+ _, err = tx.Exec(string(down))
+ require.NoError(t, err)
+ var raw string
+ require.NoError(t, tx.QueryRow("SELECT config FROM data_sources WHERE id='configured'").Scan(&raw))
+ require.JSONEq(t, `{"settings":{"parse_mode":"export","timezone":"Asia/Shanghai"}}`, raw)
+}
+
+func TestSQLiteFeishuResyncMigration(t *testing.T) {
+ db := openSQLiteDB(t, filepath.Join(t.TempDir(), "resync.db"))
+ testFeishuResyncMigration(t, db, "sqlite")
+}
+
+func TestPostgresFeishuResyncMigration(t *testing.T) {
+ dsn := os.Getenv("WEKNORA_MIGRATION_TEST_POSTGRES_DSN")
+ if dsn == "" {
+ t.Skip("set WEKNORA_MIGRATION_TEST_POSTGRES_DSN to run PostgreSQL migration tests")
+ }
+ db, err := sql.Open("postgres", dsn)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = db.Close() })
+ testFeishuResyncMigration(t, db, "postgres")
+}
diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go
index 69e1d57b..a639e7b9 100644
--- a/internal/database/migration_sqlite_versioned_schema_test.go
+++ b/internal/database/migration_sqlite_versioned_schema_test.go
@@ -75,7 +75,7 @@ var versionedSQLiteColumns = map[string][]string{
}, // 000028
}
-const expectedSQLiteMigrationVersion = 39
+const expectedSQLiteMigrationVersion = 40
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
diff --git a/internal/datasource/connector/feishu/core/blocks.go b/internal/datasource/connector/feishu/core/blocks.go
index 1e6cacdd..9077df47 100644
--- a/internal/datasource/connector/feishu/core/blocks.go
+++ b/internal/datasource/connector/feishu/core/blocks.go
@@ -15,42 +15,126 @@ import (
// Feishu docx block_type integer enum (subset this connector handles).
// https://open.feishu.cn/document/server-docs/docs/docs/docx-v1/docx-structure
const (
- BlockTypePage = 1
- BlockTypeText = 2
- BlockTypeHeading1 = 3
- blockTypeHeading9 = 11
- BlockTypeBullet = 12
- BlockTypeOrdered = 13
- BlockTypeCode = 14
- BlockTypeQuote = 15
- BlockTypeTodo = 17
- BlockTypeBitable = 18
- BlockTypeCallout = 19
- BlockTypeDivider = 22
- BlockTypeFile = 23
- BlockTypeImage = 27
- BlockTypeSheet = 30
- BlockTypeTable = 31
- BlockTypeTableCell = 32
+ BlockTypePage = 1
+ BlockTypeText = 2
+ BlockTypeHeading1 = 3
+ blockTypeHeading9 = 11
+ BlockTypeBullet = 12
+ BlockTypeOrdered = 13
+ BlockTypeCode = 14
+ BlockTypeQuote = 15
+ BlockTypeTodo = 17
+ BlockTypeBitable = 18
+ BlockTypeCallout = 19
+ BlockTypeChatCard = 20
+ BlockTypeDiagram = 21
+ BlockTypeDivider = 22
+ BlockTypeFile = 23
+ BlockTypeGrid = 24
+ BlockTypeGridColumn = 25
+ BlockTypeIframe = 26
+ BlockTypeImage = 27
+ BlockTypeISV = 28
+ BlockTypeMindnote = 29
+ BlockTypeSheet = 30
+ BlockTypeTable = 31
+ BlockTypeTableCell = 32
+
+ BlockTypeView = 33
+ BlockTypeQuoteContainer = 34
+ BlockTypeTask = 35
+ BlockTypeOKR = 36
+ BlockTypeOKRObjective = 37
+ BlockTypeOKRKeyResult = 38
+ BlockTypeOKRProgress = 39
+ BlockTypeAddOns = 40
+ BlockTypeJiraIssue = 41
+ BlockTypeWikiCatalog = 42
+ BlockTypeBoard = 43
+ BlockTypeAgenda = 44
+ BlockTypeAgendaItem = 45
+ BlockTypeAgendaItemTitle = 46
+ BlockTypeAgendaItemContent = 47
+ BlockTypeLinkPreview = 48
+ BlockTypeSourceSynced = 49
+ BlockTypeReferenceSynced = 50
+ BlockTypeSubPageList = 51
+ BlockTypeAITemplate = 52
)
// maxDocumentBlocks caps how many blocks a single document contributes, guarding
// against pathological/adversarial documents. Far above any real Feishu doc.
const maxDocumentBlocks = 50000
-// TextElement is one inline run inside a text-bearing block.
+// TextElementStyle is the inline style of a text element
+// (official docx-v1 TextElementStyle; color enums carry no GFM equivalent and
+// are not parsed).
+type TextElementStyle struct {
+ Bold bool `json:"bold"`
+ Italic bool `json:"italic"`
+ Strikethrough bool `json:"strikethrough"`
+ InlineCode bool `json:"inline_code"`
+ Link *TextElementLink `json:"link"`
+}
+
+// TextElementLink is the hyperlink payload of TextElementStyle.
+type TextElementLink struct {
+ URL string `json:"url"`
+}
+
// TextRun is the text_run payload of a TextElement.
type TextRun struct {
- Content string `json:"content"`
+ Content string `json:"content"`
+ TextElementStyle *TextElementStyle `json:"text_element_style"`
+}
+
+// MentionDoc is the mention_doc payload (@-mention of a cloud document). The
+// API carries no document title — only the link.
+type MentionDoc struct {
+ URL string `json:"url"`
+ TextElementStyle *TextElementStyle `json:"text_element_style"`
+}
+
+// MentionUser is the mention_user payload. It carries only the user OpenID —
+// never a display name — so the renderer can only Emit a generic @ marker.
+type MentionUser struct {
+ UserID string `json:"user_id"`
+ TextElementStyle *TextElementStyle `json:"text_element_style"`
+}
+
+// Equation is the equation payload; Content is KaTeX syntax.
+type Equation struct {
+ Content string `json:"content"`
+ TextElementStyle *TextElementStyle `json:"text_element_style"`
}
type TextElement struct {
- TextRun *TextRun `json:"text_run"`
+ TextRun *TextRun `json:"text_run"`
+ MentionUser *MentionUser `json:"mention_user"`
+ MentionDoc *MentionDoc `json:"mention_doc"`
+ Equation *Equation `json:"equation"`
+ // file / reminder / inline_block elements carry no renderable text (file
+ // is token-only and its token must never leak; reminder has no text body;
+ // inline_block is an ID reference), so they are not parsed.
+}
+
+// BlockTextStyle is the block-level style of text-bearing blocks. Code blocks
+// carry Language (CodeLanguage enum 1-75); ordered blocks carry Sequence (the
+// real list number: a specific value or "auto"; absent in historical docs and
+// docs created via OpenAPI).
+type BlockTextStyle struct {
+ Language int `json:"language"`
+ Sequence string `json:"sequence"`
+ Done bool `json:"done"` // todo blocks: item completed
+ // Align: 1 left / 2 center / 3 right. Absent from the API unless the
+ // author set an explicit non-default alignment.
+ Align int `json:"align"`
}
// BlockText is the shared shape of text-bearing blocks (text, headingN, bullet…).
type BlockText struct {
- Elements []TextElement `json:"elements"`
+ Elements []TextElement `json:"elements"`
+ Style *BlockTextStyle `json:"style"`
}
// BlockTokenRef is the shared shape of sheet/bitable/image block payloads
@@ -65,9 +149,98 @@ type BlockFileRef struct {
Name string `json:"name"`
}
+// Payload structs for the remaining docx block types (official docx-v1 block
+// data structures). Only the fields a renderer needs are parsed; the rest are
+// dropped by encoding/json.
+
+// BlockChatCard is block_type 20: a group-chat card embedded in the document.
+type BlockChatCard struct {
+ ChatID string `json:"chat_id"`
+ Align int `json:"align"`
+}
+
+// BlockDiagram is block_type 21: a flowchart / UML diagram reference (no
+// public render API — rendered as a placeholder note).
+type BlockDiagram struct {
+ DiagramType int `json:"diagram_type"`
+}
+
+// BlockGrid is block_type 24: a multi-column layout container; its children
+// are BlockGridColumn (25) wrappers rendered in column order.
+type BlockGrid struct {
+ ColumnSize int `json:"column_size"`
+}
+
+// BlockGridColumn is block_type 25: one column inside a BlockGrid.
+type BlockGridColumn struct {
+ WidthRatio int `json:"width_ratio"`
+}
+
+// BlockIframeComponent is the embedded-webpage payload of BlockIframe.
+type BlockIframeComponent struct {
+ Type int `json:"type"`
+ URL string `json:"url"`
+}
+
+// BlockIframe is block_type 26: an embedded webpage, rendered as a link.
+type BlockIframe struct {
+ Component *BlockIframeComponent `json:"component"`
+}
+
+// BlockView is block_type 33: a view container (e.g. tab views); its children
+// render in place, so the wrapper itself is transparent.
+type BlockView struct {
+ ViewType int `json:"view_type"`
+}
+
+// BlockAddOns is block_type 40: a document widget (timeline etc.) carrying its
+// full data inline in Record; recognized component types render as Markdown.
+type BlockAddOns struct {
+ ComponentID string `json:"component_id"`
+ ComponentTypeID string `json:"component_type_id"`
+ Record string `json:"record"`
+}
+
+// BlockJiraIssue is block_type 41: a Jira issue card (placeholder only — no
+// public content API).
+type BlockJiraIssue struct {
+ ID string `json:"id"`
+ Key string `json:"key"`
+}
+
+// BlockWikiCatalog is block_type 42: a Wiki child-page list (placeholder).
+type BlockWikiCatalog struct {
+ WikiToken string `json:"wiki_token"`
+}
+
+// BlockBoard is block_type 43: a whiteboard (mind notes ride the same path);
+// Token is exported via download_as_image and inlined as an image.
+type BlockBoard struct {
+ Token string `json:"token"`
+ Align int `json:"align"`
+ Width int `json:"width"`
+ Height int `json:"height"`
+}
+
+// BlockLinkPreview is block_type 48: a link preview card (placeholder).
+type BlockLinkPreview struct {
+ URL string `json:"url"`
+ URLType string `json:"url_type"`
+}
+
+// BlockTableMergeInfo is one entry of TableProperty.merge_info, parallel to the
+// table's cells array: entry i describes the merge anchored at cell i
+// (row = i / column_size, col = i % column_size). GFM has no cell span, so the
+// renderer fills covered cells with the anchor value.
+type BlockTableMergeInfo struct {
+ RowSpan int `json:"row_span"`
+ ColSpan int `json:"col_span"`
+}
+
// BlockTableProperty carries the table grid shape.
type BlockTableProperty struct {
- ColumnSize int `json:"column_size"`
+ ColumnSize int `json:"column_size"`
+ MergeInfo []BlockTableMergeInfo `json:"merge_info"`
}
// BlockTable is the table block payload: cell block IDs plus grid property.
@@ -100,6 +273,19 @@ type DocxBlock struct {
Todo *BlockText `json:"todo"`
Callout *BlockText `json:"callout"`
+ ChatCard *BlockChatCard `json:"chat_card"`
+ Diagram *BlockDiagram `json:"diagram"`
+ Grid *BlockGrid `json:"grid"`
+ GridColumn *BlockGridColumn `json:"grid_column"`
+ Iframe *BlockIframe `json:"iframe"`
+ Mindnote *BlockTokenRef `json:"mindnote"`
+ View *BlockView `json:"view"`
+ AddOns *BlockAddOns `json:"add_ons"`
+ JiraIssue *BlockJiraIssue `json:"jira_issue"`
+ WikiCatalog *BlockWikiCatalog `json:"wiki_catalog"`
+ Board *BlockBoard `json:"board"`
+ LinkPreview *BlockLinkPreview `json:"link_preview"`
+
Sheet *BlockTokenRef `json:"sheet"`
Bitable *BlockTokenRef `json:"bitable"`
File *BlockFileRef `json:"file"`
@@ -179,6 +365,69 @@ type sheetValuesResponse struct {
Data sheetValuesData `json:"data"`
}
+// flexInt decodes a JSON value that may be a number or a numeric string —
+// Feishu sheet APIs mix both spellings for row/column indices.
+type flexInt int
+
+func (f *flexInt) UnmarshalJSON(b []byte) error {
+ s := strings.Trim(string(b), `"`)
+ v, err := strconv.Atoi(s)
+ if err != nil {
+ return fmt.Errorf("invalid integer value %s", s)
+ }
+ *f = flexInt(v)
+ return nil
+}
+
+// sheetMergeRange is one merged-cell region of a sheet: 0-based CLOSED
+// row/column indices [start..end] as reported by the sheets-v3 metadata API.
+type sheetMergeRange struct {
+ StartRow flexInt `json:"start_row_index"`
+ EndRow flexInt `json:"end_row_index"`
+ StartCol flexInt `json:"start_column_index"`
+ EndCol flexInt `json:"end_column_index"`
+}
+
+// sheetQueryResponse is the response for the sheets-v3
+// spreadsheets/:spreadsheet_token/sheets/query metadata read.
+type sheetQueryResponse struct {
+ ApiResponse
+ Data struct {
+ Sheets []struct {
+ SheetID string `json:"sheet_id"`
+ Merges []sheetMergeRange `json:"merges"`
+ } `json:"sheets"`
+ } `json:"data"`
+}
+
+// sheetMerges returns the merged-cell regions of one sheet of a spreadsheet,
+// addressed by the sheet embed token ("spreadsheetToken_sheetId"). The sheet
+// entry is looked up by its sheet_id; a spreadsheet without merges carries no
+// merges field, which degrades to nil. Errors surface to the caller, which
+// silently skips merge filling — the information is cosmetic, never fatal.
+// Permission scope: sheets:spreadsheet:readonly (same token as the values read).
+func (c *Client) sheetMerges(ctx context.Context, embedToken string) ([]sheetMergeRange, error) {
+ idx := strings.LastIndex(embedToken, "_")
+ if idx < 0 {
+ return nil, fmt.Errorf("invalid sheet embed token: %q", embedToken)
+ }
+ spreadsheetToken, sheetID := embedToken[:idx], embedToken[idx+1:]
+ path := "/open-apis/sheets/v3/spreadsheets/" + url.PathEscape(spreadsheetToken) + "/sheets/query"
+ var resp sheetQueryResponse
+ if err := c.DoRequest(ctx, http.MethodGet, path, nil, &resp); err != nil {
+ return nil, fmt.Errorf("query sheet metadata: %w", err)
+ }
+ if resp.Code != 0 {
+ return nil, fmt.Errorf("query sheet metadata error: code=%d msg=%s", resp.Code, resp.Msg)
+ }
+ for _, s := range resp.Data.Sheets {
+ if s.SheetID == sheetID {
+ return s.Merges, nil
+ }
+ }
+ return nil, nil
+}
+
// readSheetRange reads the cell values of an embedded spreadsheet block.
// embedToken is the block's sheet.token, formatted "spreadsheetToken_sheetId".
// Cells are stringified (display value) for RAG text retrieval. Rows are capped
diff --git a/internal/datasource/connector/feishu/core/blocks_test.go b/internal/datasource/connector/feishu/core/blocks_test.go
index 31a4ff91..74b2c5e1 100644
--- a/internal/datasource/connector/feishu/core/blocks_test.go
+++ b/internal/datasource/connector/feishu/core/blocks_test.go
@@ -87,6 +87,70 @@ func TestReadSheetRange_SplitsTokenAndReadsValues(t *testing.T) {
}
}
+// TestSheetMerges_SplitsTokenAndReturnsRegions anchors the v3 metadata read:
+// the embed token splits on the last "_", the sheet entry is matched by
+// sheet_id, and merge indices decode from both JSON numbers and strings.
+func TestSheetMerges_SplitsTokenAndReturnsRegions(t *testing.T) {
+ var gotPath string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t", "expire": 7200})
+ return
+ }
+ gotPath = r.URL.Path
+ // One sheet with numeric merge indices, one with string form, and one
+ // with no merges field at all (a spreadsheet without merged cells).
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{
+ "sheets": []any{
+ map[string]any{"sheet_id": "0", "merges": []any{
+ map[string]any{
+ "start_row_index": 0, "end_row_index": 1,
+ "start_column_index": 1, "end_column_index": 2,
+ },
+ }},
+ map[string]any{"sheet_id": "9", "merges": []any{
+ map[string]any{
+ "start_row_index": "2", "end_row_index": "3",
+ "start_column_index": "0", "end_column_index": "0",
+ },
+ }},
+ map[string]any{"sheet_id": "7"},
+ },
+ }})
+ }))
+ defer srv.Close()
+
+ c := &Client{baseURL: srv.URL, appID: "a", appSecret: "s", httpClient: srv.Client()}
+ merges, err := c.sheetMerges(context.Background(), "sht_abc_0")
+ if err != nil {
+ t.Fatalf("sheetMerges: %v", err)
+ }
+ if gotPath != "/open-apis/sheets/v3/spreadsheets/sht_abc/sheets/query" {
+ t.Errorf("path = %q", gotPath)
+ }
+ if len(merges) != 1 ||
+ merges[0].StartRow != 0 || merges[0].EndRow != 1 ||
+ merges[0].StartCol != 1 || merges[0].EndCol != 2 {
+ t.Errorf("numeric merges = %+v", merges)
+ }
+
+ mergesStr, err := c.sheetMerges(context.Background(), "sht_abc_9")
+ if err != nil {
+ t.Fatalf("sheetMerges (string form): %v", err)
+ }
+ if len(mergesStr) != 1 || mergesStr[0].StartRow != 2 || mergesStr[0].EndCol != 0 {
+ t.Errorf("string merges = %+v", mergesStr)
+ }
+
+ mergesNone, err := c.sheetMerges(context.Background(), "sht_abc_7")
+ if err != nil {
+ t.Fatalf("sheetMerges (no merges field): %v", err)
+ }
+ if len(mergesNone) != 0 {
+ t.Errorf("expected no merges, got %+v", mergesNone)
+ }
+}
+
func TestReadSheetRange_TruncatesLargeTable(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" {
diff --git a/internal/datasource/connector/feishu/core/board.go b/internal/datasource/connector/feishu/core/board.go
new file mode 100644
index 00000000..d7284229
--- /dev/null
+++ b/internal/datasource/connector/feishu/core/board.go
@@ -0,0 +1,172 @@
+package core
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "image"
+ "image/draw"
+ "image/jpeg"
+ "image/png"
+ "net/url"
+)
+
+// board.go covers the docx board block (block_type 43): whiteboards embedded in
+// documents are exported to an image via the official download_as_image API and
+// ride the parent document's embedded-image pipeline.
+//
+// API: GET /open-apis/board/v1/whiteboards/:whiteboard_id/download_as_image —
+// responds with the raw image bytes (Content-Type image/png|jpeg|gif|svg+xml).
+// The render covers the WHOLE board canvas, not the content bounding box, and
+// editors routinely leave the canvas far larger than the drawing, so exports
+// surface with large blank areas (mostly below the content). trimBoardImage
+// crops those blank borders after download.
+//
+// Scope: board:whiteboard:node:read. 403 (code 2890005) means the app lacks
+// read permission on the board; the caller degrades to a Markdown note rather
+// than failing the document.
+
+// blankTolerance is the per-channel delta under which a pixel counts as the
+// background color — generous enough to absorb JPEG edge artifacts.
+const blankTolerance = 14
+
+// trimMargin keeps a visible white frame around the content bounding box —
+// the border reads as the content's edge rather than a tight crop.
+const trimMargin = 32
+
+// maxTrimPixels bounds the decode/scan cost; larger images pass through
+// untrimmed rather than risking a huge RGBA allocation.
+const maxTrimPixels = 64 << 20
+
+type boardPixel struct{ r, g, b, a uint8 }
+
+// downloadBoardAsImage fetches a whiteboard's thumbnail image bytes and crops
+// blank canvas borders. Transient failures (429/5xx/transport) retry via the
+// shared downloadRawBytes policy; the 512 MB maxFeishuDownloadBytes cap
+// applies too (a real whiteboard PNG is orders of magnitude smaller).
+func (c *Client) downloadBoardAsImage(ctx context.Context, boardToken string) ([]byte, error) {
+ path := fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/download_as_image", url.PathEscape(boardToken))
+ data, err := c.downloadRawBytes(ctx, path)
+ if err != nil {
+ return nil, err
+ }
+ return trimBoardImage(data), nil
+}
+
+// trimBoardImage crops near-uniform blank borders from a board export (PNG or
+// JPEG; anything undecodable or in another format returns unchanged). The
+// background color is the majority of the four corner pixels (>=3 must
+// agree); on a split vote content reaches the corners and the image passes
+// through untrimmed. Border rows/columns entirely within blankTolerance of
+// the background are trimmed, keeping trimMargin pixels around the content.
+func trimBoardImage(data []byte) []byte {
+ // Read dimensions before decoding: compressed exports can describe a huge
+ // canvas even when their download fits within the byte limit.
+ cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
+ if err != nil || (format != "png" && format != "jpeg") ||
+ cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxTrimPixels/cfg.Height {
+ return data
+ }
+ img, format, err := image.Decode(bytes.NewReader(data))
+ if err != nil || (format != "png" && format != "jpeg") {
+ return data
+ }
+ b := img.Bounds()
+ w, h := b.Dx(), b.Dy()
+ if w <= 0 || h <= 0 || w > maxTrimPixels/h {
+ return data
+ }
+ at := func(x, y int) boardPixel {
+ r, g, bl, a := img.At(x, y).RGBA()
+ return boardPixel{uint8(r >> 8), uint8(g >> 8), uint8(bl >> 8), uint8(a >> 8)}
+ }
+ withinTolerance := func(p, q boardPixel) bool {
+ d := func(a, c uint8) int {
+ diff := int(a) - int(c)
+ if diff < 0 {
+ return -diff
+ }
+ return diff
+ }
+ return d(p.r, q.r) <= blankTolerance && d(p.g, q.g) <= blankTolerance &&
+ d(p.b, q.b) <= blankTolerance && d(p.a, q.a) <= blankTolerance
+ }
+ // The background color must be unambiguous: require at least three of the
+ // four corners to agree on one color, else content reaches the corners and
+ // trimming could eat it (rows fully matching the seed would read as blank).
+ corners := [4]boardPixel{
+ at(b.Min.X, b.Min.Y), at(b.Max.X-1, b.Min.Y),
+ at(b.Min.X, b.Max.Y-1), at(b.Max.X-1, b.Max.Y-1),
+ }
+ bg, ok := boardPixel{}, false
+ for _, c := range corners {
+ n := 0
+ for _, d := range corners {
+ if withinTolerance(c, d) {
+ n++
+ }
+ }
+ if n >= 3 {
+ bg, ok = c, true
+ break
+ }
+ }
+ if !ok {
+ return data
+ }
+ rowBlank := func(y int) bool {
+ for x := b.Min.X; x < b.Max.X; x++ {
+ if !withinTolerance(at(x, y), bg) {
+ return false
+ }
+ }
+ return true
+ }
+ colBlank := func(x int) bool {
+ for y := b.Min.Y; y < b.Max.Y; y++ {
+ if !withinTolerance(at(x, y), bg) {
+ return false
+ }
+ }
+ return true
+ }
+ top, bottom := b.Min.Y, b.Max.Y-1
+ for top < bottom && rowBlank(top) {
+ top++
+ }
+ for bottom > top && rowBlank(bottom) {
+ bottom--
+ }
+ left, right := b.Min.X, b.Max.X-1
+ for left < right && colBlank(left) {
+ left++
+ }
+ for right > left && colBlank(right) {
+ right--
+ }
+ cw, ch := right-left+1, bottom-top+1
+ if cw <= 2 || ch <= 2 {
+ // Nothing but background (degenerate content box) — keep the original.
+ return data
+ }
+ if cw == w && ch == h {
+ return data
+ }
+ x0 := max(b.Min.X, left-trimMargin)
+ y0 := max(b.Min.Y, top-trimMargin)
+ x1 := min(b.Max.X, right+1+trimMargin)
+ y1 := min(b.Max.Y, bottom+1+trimMargin)
+ out := image.NewRGBA(image.Rect(0, 0, x1-x0, y1-y0))
+ draw.Draw(out, out.Bounds(), img, image.Point{X: x0, Y: y0}, draw.Src)
+ var buf bytes.Buffer
+ switch format {
+ case "jpeg":
+ err = jpeg.Encode(&buf, out, &jpeg.Options{Quality: 80})
+ case "png":
+ err = png.Encode(&buf, out)
+ }
+ if err != nil {
+ return data
+ }
+ return buf.Bytes()
+}
diff --git a/internal/datasource/connector/feishu/core/board_test.go b/internal/datasource/connector/feishu/core/board_test.go
new file mode 100644
index 00000000..51c207af
--- /dev/null
+++ b/internal/datasource/connector/feishu/core/board_test.go
@@ -0,0 +1,453 @@
+package core
+
+import (
+ "bytes"
+ "context"
+ "image"
+ "image/color"
+ "image/jpeg"
+ "image/png"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// P3 embedded-object pipeline tests: board blocks (block_type 43) exported via
+// download_as_image, oversize attachments degraded inline, and the marker →
+// image_map contract. These run against the real Client + Feishu-shaped fake
+// endpoints, exercising FetchDocxWithBlocks end to end.
+
+func fakeFeishuForBoard(t *testing.T, blocks []DocxBlock, boardStatus int, boardBody []byte) *httptest.Server {
+ t.Helper()
+ mux := http.NewServeMux()
+ mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, TokenResponse{
+ ApiResponse: ApiResponse{Code: 0},
+ TenantAccessToken: "fake-token", Expire: 7200,
+ })
+ })
+ mux.HandleFunc("/open-apis/docx/v1/documents/obj-board/blocks", func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, DocxBlocksResponse{
+ ApiResponse: ApiResponse{Code: 0},
+ Data: DocxBlocksData{Items: blocks},
+ })
+ })
+ mux.HandleFunc("/open-apis/board/v1/whiteboards/brd-1/download_as_image",
+ func(w http.ResponseWriter, _ *http.Request) {
+ if boardStatus != http.StatusOK {
+ http.Error(w, string(boardBody), boardStatus)
+ return
+ }
+ w.Header().Set("Content-Type", "image/png")
+ _, _ = w.Write(boardBody)
+ })
+ ts := httptest.NewServer(mux)
+ t.Cleanup(ts.Close)
+ return ts
+}
+
+func boardBlocks() []DocxBlock {
+ return []DocxBlock{
+ {BlockID: "b1", BlockType: BlockTypePage},
+ {
+ BlockID: "b2", BlockType: BlockTypeText, Text: &BlockText{
+ Elements: []TextElement{{TextRun: &TextRun{Content: "见画板"}}},
+ },
+ },
+ {BlockID: "b3", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-1"}},
+ }
+}
+
+func boardFetchInput() DocxFetchInput {
+ return DocxFetchInput{
+ DocToken: "nt-board",
+ ObjToken: "obj-board",
+ Title: "Board Doc",
+ URL: "https://example.feishu.cn/wiki/nt-board",
+ ResourceID: "space1:nt-board",
+ BaseMeta: map[string]string{"channel": types.ChannelFeishu},
+ }
+}
+
+func TestFetchDocxWithBlocks_BoardExportSuccess(t *testing.T) {
+ png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), MinAttachmentBytes)...)
+ ts := fakeFeishuForBoard(t, boardBlocks(), http.StatusOK, png)
+ client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
+
+ items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
+ if err != nil {
+ t.Fatalf("FetchDocxWithBlocks: %v", err)
+ }
+ // Orthodox flow: the board rides inline in the parent markdown as a
+ // base64 data URI — no image sub-item, no image_map.
+ if len(items) != 1 {
+ t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
+ }
+ main := items[0]
+ if !strings.Contains(string(main.Content), " {
+ t.Errorf("board not inlined as base64 data URI:\n%s", main.Content)
+ }
+ if strings.Contains(string(main.Content), "weknora-img://") {
+ t.Errorf("internal marker leaked into stored markdown:\n%s", main.Content)
+ }
+ if main.Metadata["image_map"] != "" {
+ t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
+ }
+ if !strings.Contains(string(main.Content), "见画板") {
+ t.Errorf("main markdown lost body text:\n%s", main.Content)
+ }
+}
+
+func TestFetchDocxWithBlocks_BoardExportForbiddenDegrades(t *testing.T) {
+ // 403 = app lacks board:whiteboard:node:read. No board item, no failure:
+ // the marker degrades to an inline note and the document still syncs.
+ ts := fakeFeishuForBoard(t, boardBlocks(), http.StatusForbidden, []byte(`{"code":2890005,"msg":"forbidden"}`))
+ client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
+
+ items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
+ if err != nil {
+ t.Fatalf("board export failure must not fail the document: %v", err)
+ }
+ if len(items) != 1 {
+ t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
+ }
+ main := items[0]
+ if !strings.Contains(string(main.Content), "![图片]()") {
+ t.Errorf("markdown missing board degrade note:\n%s", main.Content)
+ }
+ if strings.Contains(string(main.Content), "weknora-img") {
+ t.Errorf("unresolved board marker left in markdown:\n%s", main.Content)
+ }
+ if main.Metadata["image_map"] != "" {
+ t.Errorf("failed board must not appear in image_map, got %q", main.Metadata["image_map"])
+ }
+ if !strings.Contains(string(main.Content), "见画板") {
+ t.Errorf("main markdown lost body text:\n%s", main.Content)
+ }
+}
+
+func TestFetchDocxWithBlocks_AttachmentOverCapDegrades(t *testing.T) {
+ // The fake declares a Content-Length above maxFeishuDownloadBytes with a
+ // tiny body: downloadRawBytes must reject early on the header, without
+ // needing to serve half a gigabyte.
+ bigPDF := bytes.Repeat([]byte("A"), 1024)
+ blocks := []DocxBlock{
+ {BlockID: "b1", BlockType: BlockTypePage},
+ {BlockID: "b2", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "ft-huge", Name: "report.pdf"}},
+ }
+ mux := http.NewServeMux()
+ mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, TokenResponse{
+ ApiResponse: ApiResponse{Code: 0},
+ TenantAccessToken: "fake-token", Expire: 7200,
+ })
+ })
+ mux.HandleFunc("/open-apis/docx/v1/documents/obj-board/blocks", func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, DocxBlocksResponse{
+ ApiResponse: ApiResponse{Code: 0},
+ Data: DocxBlocksData{Items: blocks},
+ })
+ })
+ mux.HandleFunc("/open-apis/drive/v1/medias/ft-huge/download", func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Length", strconv.FormatInt(maxFeishuDownloadBytes+1, 10))
+ _, _ = w.Write(bigPDF)
+ })
+ ts := httptest.NewServer(mux)
+ t.Cleanup(ts.Close)
+ client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
+
+ in := boardFetchInput()
+ in.ObjToken = "obj-board"
+ items, err := FetchDocxWithBlocks(context.Background(), client, in)
+ if err != nil {
+ t.Fatalf("over-cap attachment must not fail the document: %v", err)
+ }
+ if len(items) != 1 {
+ t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
+ }
+ main := items[0]
+ // The over-cap file degrades to an inline reference carrying the source link.
+ if !strings.Contains(string(main.Content), "> [附件: report.pdf](") {
+ t.Errorf("markdown missing over-cap attachment placeholder:\n%s", main.Content)
+ }
+ if strings.Contains(string(main.Content), "- report.pdf") {
+ t.Errorf("over-cap attachment must not stay in the file-name list:\n%s", main.Content)
+ }
+ if main.Metadata["attachment_ids"] != "" {
+ t.Errorf("over-cap attachment must not appear in attachment_ids, got %q", main.Metadata["attachment_ids"])
+ }
+}
+
+// Regression for the line-text patch bug: an earlier bullet that happens to
+// carry the attachment's display name must survive the over-cap degrade, and
+// the attachment's own marker line is the one replaced.
+func TestFetchDocxWithBlocks_OverCapPatchHitsMarkerNotEarlierBullet(t *testing.T) {
+ bigPDF := bytes.Repeat([]byte("A"), 1024)
+ blocks := []DocxBlock{
+ {BlockID: "b1", BlockType: BlockTypePage},
+
+ {BlockID: "b3", BlockType: BlockTypeBullet, Bullet: &BlockText{Elements: []TextElement{
+ {TextRun: &TextRun{Content: "report.pdf"}},
+ }}},
+ {BlockID: "b4", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "ft-huge", Name: "report.pdf"}},
+ }
+ mux := http.NewServeMux()
+ mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, TokenResponse{
+ ApiResponse: ApiResponse{Code: 0},
+ TenantAccessToken: "fake-token", Expire: 7200,
+ })
+ })
+ mux.HandleFunc("/open-apis/docx/v1/documents/obj-board/blocks", func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, DocxBlocksResponse{
+ ApiResponse: ApiResponse{Code: 0},
+ Data: DocxBlocksData{Items: blocks},
+ })
+ })
+ mux.HandleFunc("/open-apis/drive/v1/medias/ft-huge/download", func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Length", strconv.FormatInt(maxFeishuDownloadBytes+1, 10))
+ _, _ = w.Write(bigPDF)
+ })
+ ts := httptest.NewServer(mux)
+ t.Cleanup(ts.Close)
+ client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL, ParseMode: ParseModeBlocks})
+
+ in := boardFetchInput()
+ in.ObjToken = "obj-board"
+ items, err := FetchDocxWithBlocks(context.Background(), client, in)
+ if err != nil {
+ t.Fatalf("over-cap attachment must not fail the document: %v", err)
+ }
+ main := items[len(items)-1]
+ if n := strings.Count(string(main.Content), "- report.pdf"); n != 1 {
+ t.Errorf("earlier bullet must survive exactly once, got %d:\n%s", n, main.Content)
+ }
+ if !strings.Contains(string(main.Content), "> [附件: report.pdf]") {
+ t.Errorf("over-cap degrade note missing:\n%s", main.Content)
+ }
+}
+
+// TestSupportedImageExtSVG pins the svg recovery: Go's sniffer reports SVG
+// markup as text/xml, but a board export carrying an