Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

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

Greenplumwine973d9d051f2d
diff --git a/.env.example b/.env.example
index 43c196e91..069f28296 100644
--- a/.env.example
+++ b/.env.example
@@ -539,19 +539,11 @@ OLLAMA_BASE_URL=http://host.docker.internal:11434
# WEKNORA_CHAT_ATTACHMENT_OCR_CONCURRENCY=8
# WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES=8
-# ========== E9. 飞书云文档解析模式 ==========
-# 控制飞书云盘 / 飞书知识库同步新版云文档(docx)时的解析路径:
-# export(默认,留空即可):走异步导出 API 下载 .docx 二进制,交给 docreader
-# 解析。图片 inline 进父文档(parent_chunk_id 同 knowledge 关联),检索 /
-# wiki / 智能体三个场景都能关联图片内容。代价:同步变慢;飞书 docx 内的
-# file block 附件不会随导出下载(会丢,需单独同步);若云文档中存在电子表格、
-# 多维表格等,导出后会变成内嵌在 docx 中的表格,weknora 会无法解析这些表格。
-# blocks:走 blocks API 转 Markdown。快,保留 docx 内附件;但图片渲染成空
-# `![图片]()` 占位符、并作为独立知识条目入库,与父文档无内容关联(检索 /
-# wiki / 智能体均无法把图片关联回文档);电子表格会解析成 markdown 表格,
-# 存在丢失合并单元格等样式风险。
-# 不需要图片关联、追求速度、要保留附件或需保留电子表格样式时设为 blocks。
-# 此方案为临时方案,若后续有更好的解析方案,会移除此环境变量并替换。
+# ========== E9. 飞书云文档解析模式(已废弃,仅一个版本的兼容) ==========
+# 解析模式已改为在知识库 → 数据源编辑页按数据源配置(settings.parse_mode,默认
+# blocks)。此环境变量仅在数据源未配置 parse_mode 时作为回退读取,并打印弃用
+# 警告,后续版本将移除。已显式设为 export 的部署升级后行为不变;新部署请直接
+# 在数据源编辑页选择解析模式。
# FEISHU_DOCX_PARSE_MODE=export
# 飞书导出创建 / 查询 / 下载、Wiki 子节点列表分别按应用共享配额(单进程)。
diff --git a/docker-compose.yml b/docker-compose.yml
index dcf5539eb..a9321ceae 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -385,8 +385,9 @@ services:
- OIDC_AUTH_SCOPES=${OIDC_AUTH_SCOPES:-}
- OIDC_USER_INFO_MAPPING_USER_NAME=${OIDC_USER_INFO_MAPPING_USER_NAME:-}
- OIDC_USER_INFO_MAPPING_EMAIL=${OIDC_USER_INFO_MAPPING_EMAIL:-}
- # 飞书云文档解析模式 export:导出为docx,blocks:根据飞书云文档块解析为markdown。默认为:export
- - FEISHU_DOCX_PARSE_MODE=${FEISHU_DOCX_PARSE_MODE:-export}
+ # 已废弃:解析模式改在数据源编辑页按数据源配置(默认 blocks)。此变量仅在
+ # 数据源未配置 parse_mode 时回退读取并打印弃用警告,后续版本将移除。
+ - FEISHU_DOCX_PARSE_MODE=${FEISHU_DOCX_PARSE_MODE:-}
depends_on:
redis:
condition: service_started
diff --git a/frontend/src/components/document-preview.vue b/frontend/src/components/document-preview.vue
index f6cacff2d..b443b9f24 100644
--- a/frontend/src/components/document-preview.vue
+++ b/frontend/src/components/document-preview.vue
@@ -9,7 +9,7 @@ import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
import 'katex/dist/katex.min.css';
import { useI18n } from 'vue-i18n';
-import { sanitizeHTML, sanitizeMarkdownHTML } from '@/utils/security';
+import { sanitizeHTML, sanitizeMarkdownHTML, hydrateProtectedFileImages } from '@/utils/security';
import { preparePptxPreview, isCompletePptxRender } from '@/utils/pptxPreview';
import { findMarkdownSourceRange } from '@/utils/markdownSourceLocate';
import { renderDocumentPreviewMarkdown } from '@/utils/documentPreviewMarkdown';
@@ -486,6 +486,10 @@ async function loadPreview() {
}
case 'markdown': {
await renderMarkdown(blob);
+ // Markdown 里的 resource:// 等受保护图片需要带鉴权换 blob(无 override
+ // 时走应用默认鉴权面:登录态 /files 代理)。已换过的元素幂等跳过。
+ await nextTick();
+ await hydrateProtectedFileImages(previewContent.value);
break;
}
case 'pptx': {
@@ -1493,6 +1497,32 @@ onUnmounted(() => {
}
ul, ol { padding-left: 24px; margin: 8px 0; }
li { margin: 4px 0; }
+ ul li:has(> .task-checkbox) { list-style: none; }
+ .task-checkbox {
+ display: inline-block;
+ width: 14px;
+ height: 14px;
+ margin-right: 6px;
+ border: 1px solid @border-color;
+ border-radius: var(--app-radius-xs);
+ vertical-align: -2px;
+ position: relative;
+ &.checked {
+ background: @accent;
+ border-color: @accent;
+ &::after {
+ content: '';
+ position: absolute;
+ left: 4px;
+ top: 1px;
+ width: 4px;
+ height: 8px;
+ border: solid #fff;
+ border-width: 0 2px 2px 0;
+ transform: rotate(45deg);
+ }
+ }
+ }
table {
.preview-table(@bg-muted; var(--td-bg-color-container-hover));
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index cad7c421a..bb7d0902a 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -7139,6 +7139,13 @@ export default {
pauseFailed: 'Failed to pause',
logs: 'Logs',
syncModeLabel: 'Sync mode',
+ parseModeLabel: 'Parse mode',
+ parseMode: {
+ inherit: 'Use server setting',
+ blocks: 'Blocks (default)',
+ export: 'Export (docx)',
+ },
+ parseModeHint: 'How Feishu cloud documents are parsed. Blocks is faster and keeps in-document attachments; Export converts documents to docx for parsing and keeps images associated with the document.',
syncMode: {
incremental: 'Incremental',
full: 'Full'
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 9d474676d..967a28243 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -7139,6 +7139,13 @@ export default {
pauseFailed: '一時停止に失敗しました',
logs: 'ログ',
syncModeLabel: '同期モード',
+ parseModeLabel: '解析モード',
+ parseMode: {
+ inherit: 'サーバー設定を使用',
+ blocks: 'ブロック解析(デフォルト)',
+ export: 'エクスポート解析(docx)',
+ },
+ parseModeHint: 'Feishuクラウドドキュメントの解析方式。ブロック解析は高速でドキュメント内の添付ファイルを保持します。エクスポート解析はdocxに変換して解析し、画像とドキュメントの関連付けがより正確になります。',
syncMode: {
incremental: '増分',
full: '全量'
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index e0eb66cc2..17bfe3d73 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -972,6 +972,13 @@ export default {
pauseFailed: '일시정지 실패',
logs: '로그',
syncModeLabel: '동기화 모드',
+ parseModeLabel: '구문 분석 모드',
+ parseMode: {
+ inherit: '서버 설정 사용',
+ blocks: '블록 분석 (기본값)',
+ export: '내보내기 분석 (docx)',
+ },
+ parseModeHint: 'Feishu 클라우드 문서의 구문 분석 방식입니다. 블록 분석은 더 빠르고 문서 내 첨부 파일을 유지합니다. 내보내기 분석은 docx로 변환하여 분석하며 이미지와 문서의 연관성이 더 잘 유지됩니다.',
createTitle: '데이터 소스 추가',
editTitle: '데이터 소스 편집',
nameLabel: '이름',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 8d4216c5c..91b91e32d 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -972,6 +972,13 @@ export default {
pauseFailed: 'Не удалось приостановить',
logs: 'Журнал',
syncModeLabel: 'Режим синхронизации',
+ parseModeLabel: 'Режим разбора',
+ parseMode: {
+ inherit: 'Использовать настройки сервера',
+ blocks: 'Блочный разбор (по умолчанию)',
+ export: 'Экспорт (docx)',
+ },
+ parseModeHint: 'Способ разбора облачных документов Feishu. Блочный разбор быстрее и сохраняет вложения документа; экспорт преобразует документ в docx и лучше сохраняет связь изображений с документом.',
createTitle: 'Добавить источник данных',
editTitle: 'Редактировать источник данных',
nameLabel: 'Название',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 01c3a84ce..8ca195266 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -972,6 +972,13 @@ export default {
pauseFailed: '暂停失败',
logs: '日志',
syncModeLabel: '同步模式',
+ parseModeLabel: '解析模式',
+ parseMode: {
+ inherit: '使用服务器配置',
+ blocks: '块级解析(默认)',
+ export: '导出解析(docx)',
+ },
+ parseModeHint: '飞书云文档的解析方式。块级解析更快并保留文档内附件;导出解析将文档导出为 docx 后解析,图片与文档的关联更完整。',
createTitle: '添加数据源',
editTitle: '编辑数据源',
nameLabel: '名称',
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index 68a3931d7..be5abf830 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -972,6 +972,13 @@ export default {
pauseFailed: '暫停失敗',
logs: '日誌',
syncModeLabel: '同步模式',
+ parseMode: {
+ inherit: '使用伺服器設定',
+ blocks: '塊級解析(預設)',
+ export: '導出解析(docx)',
+ },
+ parseModeHint: '飛書雲文檔的解析方式。塊級解析更快並保留文檔內附件;導出解析將文檔導出為 docx 後解析,圖片與文檔的關聯更完整。',
+ parseModeLabel: '解析模式',
createTitle: '新增資料源',
editTitle: '編輯資料源',
nameLabel: '名稱',
diff --git a/frontend/src/utils/documentPreviewMarkdown.test.ts b/frontend/src/utils/documentPreviewMarkdown.test.ts
index 7cd6441d6..3619eeaea 100644
--- a/frontend/src/utils/documentPreviewMarkdown.test.ts
+++ b/frontend/src/utils/documentPreviewMarkdown.test.ts
@@ -89,3 +89,24 @@ test('raw HTML images cannot override preview loading attributes', () => {
assert.equal(attributes.get('decoding'), 'async')
assert.equal(attributes.get('fetchpriority'), 'low')
})
+
+// GFM task lists must survive the preview pipeline as sanitizer-safe spans:
+// marked's default <input type="checkbox"> is stripped by the DOMPurify tag
+// allowlist, which degraded "- [x] 任务" to a plain bullet.
+test('task list items render styled checkbox spans, checked and unchecked', () => {
+ const html = renderDocumentPreviewMarkdown(
+ '- [x] 任务1\n\n- [ ] 任务2\n',
+ value => value,
+ )
+
+ assert.match(html, /<span class="task-checkbox checked"><\/span>任务1/)
+ assert.match(html, /<span class="task-checkbox"><\/span>任务2/)
+ assert.ok(!html.includes('<input'), 'no raw checkbox input may be emitted')
+})
+
+test('plain bullets are not affected by the task checkbox override', () => {
+ const html = renderDocumentPreviewMarkdown('- 普通项\n', value => value)
+
+ assert.match(html, /<li>普通项<\/li>/)
+ assert.ok(!html.includes('task-checkbox'))
+})
diff --git a/frontend/src/utils/documentPreviewMarkdown.ts b/frontend/src/utils/documentPreviewMarkdown.ts
index 9daae425d..79eee9d33 100644
--- a/frontend/src/utils/documentPreviewMarkdown.ts
+++ b/frontend/src/utils/documentPreviewMarkdown.ts
@@ -32,6 +32,10 @@ function highlightPreviewCode(source: string, lang?: string): string {
function createPreviewMarkdownRenderer(): Renderer {
const renderer = new Renderer()
+ // GFM task lists: marked emits <input type="checkbox">, which the DOMPurify
+ // tag allowlist strips (leaving a plain bullet) — render a styled span.
+ renderer.checkbox = ({ checked }) =>
+ `<span class="task-checkbox${checked ? ' checked' : ''}"></span>`
renderer.image = ({ href, title, text }) => {
if (!isSafePreviewImageHref(href)) return ''
const safeHref = href.trim().replace(/"/g, '&quot;')
diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts
index 1e19a3a4c..9028866e5 100644
--- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts
+++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts
@@ -394,3 +394,44 @@ test('Cloud hierarchy limitation stays visible after an empty space expansion',
assert.equal(f.vm.visibleTree.some((row: any) => row.noticeAfter), true)
} finally { f.close() }
})
+
+for (const type of ['feishu', 'lark', 'feishu_drive', 'lark_drive']) {
+ test(`${type} preserves inherited parse mode when saving unrelated settings`, async () => {
+ const settings = { timezone: 'Asia/Shanghai', resync_required: true }
+ const f = await fixture({ type, settings })
+ try {
+ assert.equal(f.vm.feishuParseMode, '')
+ assert.equal(f.vm.form.config.settings.parse_mode, undefined)
+ f.vm.form.name = 'Renamed source'
+ await f.vm.handleSubmit()
+ const saved = f.calls.find(call => call.method === 'updateDataSource')
+ assert.ok(saved)
+ assert.deepEqual(saved.args[1].config.settings, settings)
+ assert.equal('parse_mode' in settings, false, 'opening the editor must not mutate props')
+ } finally { f.close() }
+ })
+}
+
+test('Feishu explicit mode changes are saved without mutating the source configuration', async () => {
+ const settings = { parse_mode: 'export', timezone: 'Asia/Shanghai' }
+ const f = await fixture({ type: 'feishu', settings })
+ try {
+ assert.equal(f.vm.feishuParseMode, 'export')
+ f.vm.feishuParseMode = 'blocks'
+ assert.equal(settings.parse_mode, 'export')
+ assert.equal(f.vm.buildConfigPayload().settings.parse_mode, 'blocks')
+ f.vm.feishuParseMode = ''
+ assert.deepEqual(JSON.parse(JSON.stringify(f.vm.buildConfigPayload().settings)), { timezone: 'Asia/Shanghai' })
+ assert.equal(settings.parse_mode, 'export')
+ } finally { f.close() }
+})
+
+test('new Feishu sources keep the blocks default and do not leak it to another connector', async () => {
+ const f = await fixture({ create: true })
+ try {
+ f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'feishu'))
+ assert.equal(f.vm.feishuParseMode, 'blocks')
+ f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'gitlab'))
+ assert.equal(f.vm.form.config.settings.parse_mode, undefined)
+ } finally { f.close() }
+})
diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue
index f36c0968e..8be7b6555 100644
--- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue
+++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue
@@ -266,6 +266,20 @@ const driveFolderTokenError = ref('')
const driveRootLoaded = ref(false)
const isDriveConnector = (type: string) => type === 'feishu_drive' || type === 'lark_drive'
const isGitLabConnector = (type: string) => type === 'gitlab'
+// Feishu/Lark wiki + Drive connectors share the docx parse-mode setting.
+const isFeishuFamilyConnector = (type: string) =>
+ type === 'feishu' || type === 'lark' || type === 'feishu_drive' || type === 'lark_drive'
+// An unset legacy setting can inherit export from the server. Display that
+// state without materializing a client-side default on unrelated edits.
+const feishuParseMode = computed({
+ get: () => form.value.config.settings.parse_mode || '',
+ set: (mode: string) => {
+ const settings = { ...form.value.config.settings }
+ if (mode) settings.parse_mode = mode
+ else delete settings.parse_mode
+ form.value.config.settings = settings
+ },
+})
// Seafile resource IDs are "<repo_id>:<path>"; 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(() => {
</div>
</div>
+ <div v-if="isFeishuFamilyConnector(form.type)" class="form-item form-item--flat">
+ <label class="form-label">{{ t('datasource.parseModeLabel') }}</label>
+ <div class="option-group" role="radiogroup" :aria-label="t('datasource.parseModeLabel')">
+ <button
+ v-if="isEdit"
+ type="button"
+ class="option-pill"
+ :class="{ 'is-active': feishuParseMode === '' }"
+ role="radio"
+ :aria-checked="feishuParseMode === ''"
+ @click="feishuParseMode = ''"
+ >
+ {{ t('datasource.parseMode.inherit') }}
+ </button>
+ <button
+ type="button"
+ class="option-pill"
+ :class="{ 'is-active': feishuParseMode === 'blocks' }"
+ role="radio"
+ :aria-checked="feishuParseMode === 'blocks'"
+ @click="feishuParseMode = 'blocks'"
+ >
+ {{ t('datasource.parseMode.blocks') }}
+ </button>
+ <button
+ type="button"
+ class="option-pill"
+ :class="{ 'is-active': feishuParseMode === 'export' }"
+ role="radio"
+ :aria-checked="feishuParseMode === 'export'"
+ @click="feishuParseMode = 'export'"
+ >
+ {{ t('datasource.parseMode.export') }}
+ </button>
+ </div>
+ <p class="form-desc">{{ t('datasource.parseModeHint') }}</p>
+ </div>
+
<div class="form-item form-item--flat">
<t-checkbox v-model="form.sync_deletions">{{ t('datasource.syncDeletions') }}</t-checkbox>
</div>
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 000000000..2d4c7a91f
--- /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 000000000..56ead40fc
--- /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 fe106dfe1..d12beabc1 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 e9ce5bc0a..cdf1a4abe 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 000000000..9795871b7
--- /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 69e1d57b9..a639e7b9c 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 1e6cacdd2..9077df47f 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 31a4ff914..74b2c5e13 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 000000000..d72842296
--- /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 000000000..51c207af7
--- /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), "![图片](data:image/png;base64,") {
+ 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 <svg> document must be
+// treated as an inlinable image, not degraded to a placeholder.
+func TestSupportedImageExtSVG(t *testing.T) {
+ svg := []byte(`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>`)
+ ext, ct, ok := SupportedImageExt(svg)
+ if !ok || ext != ".svg" || ct != "image/svg+xml" {
+ t.Fatalf("SupportedImageExt(svg) = %q %q %v, want .svg image/svg+xml true", ext, ct, ok)
+ }
+ if _, _, ok := SupportedImageExt([]byte("<?xml version=\"1.0\"?><not-svg/>")); ok {
+ t.Fatal("non-svg xml must not be treated as an image")
+ }
+}
+
+// trimBoardImage tests: the board API renders the whole canvas, so exports
+// carry large blank borders (mostly below the content) — they must be cropped.
+
+func encodeTestImage(t *testing.T, img image.Image, format string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ var err error
+ if format == "jpeg" {
+ err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80})
+ } else {
+ err = png.Encode(&buf, img)
+ }
+ if err != nil {
+ t.Fatalf("encode %s: %v", format, err)
+ }
+ return buf.Bytes()
+}
+
+func TestTrimBoardImage_CropsBlankBottomAndRight(t *testing.T) {
+ for _, format := range []string{"png", "jpeg"} {
+ src := image.NewRGBA(image.Rect(0, 0, 120, 200))
+ content := color.RGBA{R: 30, G: 60, B: 200, A: 255}
+ for y := 0; y < 40; y++ {
+ for x := 0; x < 80; x++ {
+ src.Set(x, y, content)
+ }
+ }
+ trimmed := trimBoardImage(encodeTestImage(t, src, format))
+ out, gotFormat, err := image.Decode(bytes.NewReader(trimmed))
+ if err != nil {
+ t.Fatalf("%s: decode trimmed: %v", format, err)
+ }
+ if gotFormat != format {
+ t.Fatalf("%s: format changed to %s", format, gotFormat)
+ }
+ b := out.Bounds()
+ if b.Dx() > 80+2*trimMargin || b.Dy() > 40+2*trimMargin {
+ t.Fatalf("%s: blank canvas not trimmed, got %dx%d", format, b.Dx(), b.Dy())
+ }
+ if b.Dx() < 40 || b.Dy() < 20 {
+ t.Fatalf("%s: content lost, got %dx%d", format, b.Dx(), b.Dy())
+ }
+ if r, _, _, _ := out.At(b.Min.X+4, b.Min.Y+4).RGBA(); uint8(r>>8) != 30 {
+ t.Fatalf("%s: content pixel lost at margin", format)
+ }
+ }
+}
+
+func TestTrimBoardImage_NoBlankBorderReturnsOriginal(t *testing.T) {
+ src := image.NewRGBA(image.Rect(0, 0, 50, 50))
+ for y := 0; y < 50; y++ {
+ for x := 0; x < 50; x++ {
+ src.Set(x, y, color.RGBA{R: uint8(x * 5), G: uint8(y * 5), B: 90, A: 255})
+ }
+ }
+ data := encodeTestImage(t, src, "png")
+ if got := trimBoardImage(data); !bytes.Equal(got, data) {
+ t.Fatal("fully painted image must pass through byte-identical")
+ }
+}
+
+func TestTrimBoardImage_FullyBlankAndGarbagePassThrough(t *testing.T) {
+ blank := image.NewRGBA(image.Rect(0, 0, 60, 60))
+ data := encodeTestImage(t, blank, "png")
+ if got := trimBoardImage(data); !bytes.Equal(got, data) {
+ t.Fatal("fully blank export must pass through unchanged")
+ }
+ if got := trimBoardImage([]byte("not an image")); !bytes.Equal(got, []byte("not an image")) {
+ t.Fatal("undecodable bytes must pass through unchanged")
+ }
+}
+
+// Content spanning two opposite corners makes the corner vote 2:2 — trimming
+// must bail entirely rather than trust either color as the background.
+func TestTrimBoardImage_SplitCornerVoteSkipsTrimming(t *testing.T) {
+ src := image.NewRGBA(image.Rect(0, 0, 120, 200))
+ white := color.RGBA{R: 255, G: 255, B: 255, A: 255}
+ red := color.RGBA{R: 200, G: 30, B: 30, A: 255}
+ for y := 0; y < 200; y++ {
+ for x := 0; x < 120; x++ {
+ src.Set(x, y, white)
+ }
+ }
+ // Red band down the full left side: touches top-left and bottom-left.
+ for y := 0; y < 200; y++ {
+ for x := 0; x < 50; x++ {
+ src.Set(x, y, red)
+ }
+ }
+ data := encodeTestImage(t, src, "png")
+ if got := trimBoardImage(data); !bytes.Equal(got, data) {
+ t.Fatal("split corner vote (2:2) must pass through untrimmed")
+ }
+}
+
+// Content touching exactly one corner keeps the majority vote at 3 — the
+// blank borders away from that corner are still trimmed.
+func TestTrimBoardImage_ContentAtOneCornerStillTrims(t *testing.T) {
+ src := image.NewRGBA(image.Rect(0, 0, 120, 200))
+ white := color.RGBA{R: 255, G: 255, B: 255, A: 255}
+ red := color.RGBA{R: 200, G: 30, B: 30, A: 255}
+ for y := 0; y < 200; y++ {
+ for x := 0; x < 120; x++ {
+ src.Set(x, y, white)
+ }
+ }
+ // Content only in the top-left corner region.
+ for y := 0; y < 40; y++ {
+ for x := 0; x < 40; x++ {
+ src.Set(x, y, red)
+ }
+ }
+ trimmed := trimBoardImage(encodeTestImage(t, src, "png"))
+ out, _, err := image.Decode(bytes.NewReader(trimmed))
+ if err != nil {
+ t.Fatalf("decode trimmed: %v", err)
+ }
+ b := out.Bounds()
+ if b.Dy() > 40+2*trimMargin || b.Dx() > 40+2*trimMargin {
+ t.Fatalf("blank canvas not trimmed, got %dx%d", b.Dx(), b.Dy())
+ }
+ if r, _, _, _ := out.At(2, 2).RGBA(); uint8(r>>8) != 200 {
+ t.Fatal("corner-touching content must survive at its position")
+ }
+}
+
+// 云文档 mention links: FetchDocxWithBlocks backfills link text with the
+// referenced document's title via the drive metadata batch API; unresolved
+// refs (no permission, 403) degrade to the URL-as-text form.
+func TestFetchDocxWithBlocks_MentionDocTitleBackfill(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "r", BlockType: BlockTypePage},
+ {BlockID: "p", BlockType: BlockTypeText, Text: &BlockText{
+ Elements: []TextElement{{MentionDoc: &MentionDoc{
+ URL: "https://my.feishu.cn/docx/RefDoc001",
+ }}},
+ }},
+ }
+ run := func(metasStatus int, metasBody string, _ string) *types.FetchedItem {
+ 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-doc/blocks", func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, DocxBlocksResponse{
+ ApiResponse: ApiResponse{Code: 0},
+ Data: DocxBlocksData{Items: blocks},
+ })
+ })
+ mux.HandleFunc("/open-apis/drive/v1/metas/batch_query", func(w http.ResponseWriter, _ *http.Request) {
+ if metasStatus != http.StatusOK {
+ http.Error(w, metasBody, metasStatus)
+ return
+ }
+ _, _ = w.Write([]byte(metasBody))
+ })
+ ts := httptest.NewServer(mux)
+ t.Cleanup(ts.Close)
+
+ client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL})
+ items, err := FetchDocxWithBlocks(context.Background(), client, DocxFetchInput{
+ DocToken: "nt-doc", ObjToken: "obj-doc", Title: "父文档",
+ URL: "https://my.feishu.cn/docx/obj-doc",
+ })
+ if err != nil {
+ t.Fatalf("fetch: %v", err)
+ }
+ return items[len(items)-1]
+ }
+
+ main := run(http.StatusOK,
+ `{"code":0,"data":{"metas":[{"doc_token":"RefDoc001","doc_type":"docx","title":"引用的文档"}]}}`,
+ "引用的文档")
+ if !strings.Contains(string(main.Content), "[引用的文档](https://my.feishu.cn/docx/RefDoc001)") {
+ t.Errorf("title not backfilled, got:\n%s", main.Content)
+ }
+
+ // Permission denied on the metadata API → falls back to URL-as-text.
+ main = run(http.StatusForbidden, `forbidden`, "")
+ if !strings.Contains(string(main.Content),
+ "[https://my.feishu.cn/docx/RefDoc001](https://my.feishu.cn/docx/RefDoc001)") {
+ t.Errorf("fallback form missing, got:\n%s", main.Content)
+ }
+}
+
+// A header can advertise dimensions far beyond the compressed download size.
+// The sentinel codec proves that the full pixel decoder is never invoked.
+func TestTrimBoardImageRejectsOversizeBeforeDecode(t *testing.T) {
+ const magic = "weknora-oversized-board-test"
+ image.RegisterFormat("png", magic,
+ func(io.Reader) (image.Image, error) {
+ panic("oversized board reached pixel decoder")
+ },
+ func(io.Reader) (image.Config, error) {
+ return image.Config{Width: maxTrimPixels + 1, Height: 1}, nil
+ })
+ data := []byte(magic)
+ if got := trimBoardImage(data); !bytes.Equal(got, data) {
+ t.Fatal("oversized image must pass through unchanged")
+ }
+}
diff --git a/internal/datasource/connector/feishu/core/client.go b/internal/datasource/connector/feishu/core/client.go
index d8eef921c..2bc342ba3 100644
--- a/internal/datasource/connector/feishu/core/client.go
+++ b/internal/datasource/connector/feishu/core/client.go
@@ -203,8 +203,16 @@ const (
const maxFeishuErrorPreviewBytes = 4 << 10
// maxFeishuDownloadBytes bounds a single file download to protect the sync
-// worker from adversarial or pathological oversized responses.
-const maxFeishuDownloadBytes = 512 * 1024 * 1024 // 512 MB
+// worker from adversarial or pathological oversized responses. downloadRawBytes
+// rejects early on an honest Content-Length, and tests exercise the
+// oversize-degrade path by declaring a huge Content-Length.
+const maxFeishuDownloadBytes = int64(512 * 1024 * 1024) // 512 MB
+
+// ErrDownloadTooLarge marks a download rejected by the maxFeishuDownloadBytes
+// cap (errors.Is-able). The connector degrades oversized attachments to an
+// inline Markdown placeholder instead of an error item — the file exists and is
+// fine, it just doesn't fit the sync budget.
+var ErrDownloadTooLarge = errors.New("download exceeds max size")
var feishuRetryBackoff = []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second}
@@ -826,10 +834,17 @@ func (c *Client) downloadRawBytes(ctx context.Context, path string) ([]byte, err
return nil, fmt.Errorf("download failed: status=%d body=%s", resp.StatusCode, truncate(string(body), 500))
}
+ // Early reject on an honest Content-Length: avoids buffering a
+ // hopeless 512 MB body just to hit the LimitReader check below.
+ if resp.ContentLength > maxFeishuDownloadBytes {
+ _ = resp.Body.Close()
+ return nil, fmt.Errorf("%w (Content-Length %d): %s", ErrDownloadTooLarge, resp.ContentLength, path)
+ }
+
data, readErr := io.ReadAll(io.LimitReader(resp.Body, maxFeishuDownloadBytes+1))
if readErr == nil && int64(len(data)) > maxFeishuDownloadBytes {
resp.Body.Close()
- return nil, fmt.Errorf("download exceeds max size (%d bytes): %s", maxFeishuDownloadBytes, path)
+ return nil, fmt.Errorf("%w (%d bytes): %s", ErrDownloadTooLarge, maxFeishuDownloadBytes, path)
}
resp.Body.Close()
if readErr != nil {
@@ -936,23 +951,25 @@ func (c *Client) ListDriveFilesAllPages(ctx context.Context, folderToken string)
return all, nil
}
-// ListDriveFilesRecursiveFrom walks a Drive folder subtree depth-first,
-// returning all non-folder files. Mirrors ListWikiNodesRecursiveFrom.
+// WalkDriveTree walks a Drive folder subtree depth-first and is the single
+// recursive Drive walker shared by the drive connector (it resurrects the
+// former ListDriveFilesRecursiveFrom semantics, which could not hand back
+// folder names). Contract:
+// - folder -> recurse
+// - shortcut -> expand to its target (target_type is never "folder")
+// - other -> collect
//
-// - folder -> recurse (visited is a pure-defensive cycle guard; Drive folders
-// have no shortcut concept so cycles are not expected - see glossary).
-// - shortcut -> expand to its target (target_type is never "folder", verified)
-// and include the target as a regular file. No extra API call: shortcut_info
-// is returned by the list API.
-// - other -> collect.
-//
-// Partial failures (a sub-folder listing returns an error) are collected into a
-// *PartialDriveFileListError and the walk continues, mirroring the wiki
-// connector's PartialWikiNodeListError semantics.
-func (c *Client) ListDriveFilesRecursiveFrom(ctx context.Context, folderToken string) ([]DriveFile, error) {
+// Listing failures are collected into the returned failures and the walk
+// continues (PartialDriveFileListError semantics). dirPaths maps every visited
+// folder token to its cleaned directory path relative to the selected root;
+// the walk root's own prefix is baseDir (the root folder's display name for a
+// bare root selection, "<根名>/<子文件夹名>" for a sub-folder selection; ""
+// when the root name could not be resolved, mirroring pre-root-mirror paths).
+func WalkDriveTree(
+ ctx context.Context, client *Client, rootToken, baseDir string,
+) (files []DriveFile, dirPaths map[string]string, failures []DriveFileListFailure) {
+ dirPaths = map[string]string{rootToken: baseDir}
visited := make(map[string]bool)
- var all []DriveFile
- var failures []DriveFileListFailure
var walk func(folderToken string)
walk = func(folderToken string) {
@@ -961,7 +978,7 @@ func (c *Client) ListDriveFilesRecursiveFrom(ctx context.Context, folderToken st
}
visited[folderToken] = true
- files, err := c.ListDriveFilesAllPages(ctx, folderToken)
+ entries, err := client.ListDriveFilesAllPages(ctx, folderToken)
if err != nil {
wrappedErr := fmt.Errorf("list children of %s: %w", folderToken, err)
failures = append(failures, DriveFileListFailure{
@@ -973,35 +990,116 @@ func (c *Client) ListDriveFilesRecursiveFrom(ctx context.Context, folderToken st
return
}
- for _, f := range files {
+ for _, f := range entries {
switch f.Type {
case "folder":
+ name := SanitizeFileName(f.Name)
+ if parent := dirPaths[folderToken]; parent != "" {
+ name = parent + "/" + name
+ }
+ dirPaths[f.Token] = name
walk(f.Token)
case "shortcut":
- // Expand to target. target_type is never "folder" (verified), so
- // no recursion here - the target is a regular file.
- if f.ShortcutInfo != nil && f.ShortcutInfo.TargetToken != "" {
- expanded := DriveFile{
- Token: f.ShortcutInfo.TargetToken,
- Name: f.Name,
- Type: f.ShortcutInfo.TargetType,
- ParentToken: f.ParentToken,
- URL: f.URL,
- CreatedTime: f.CreatedTime,
- ModifiedTime: f.ModifiedTime,
- OwnerID: f.OwnerID,
- }
- all = append(all, expanded)
+ if target, ok := ExpandDriveShortcut(f); ok {
+ files = append(files, target)
}
default:
- all = append(all, f)
+ files = append(files, f)
}
}
}
- walk(folderToken)
- if len(failures) > 0 {
- return all, &PartialDriveFileListError{Failures: failures}
+ walk(rootToken)
+ return files, dirPaths, failures
+}
+
+// ExpandDriveShortcut preserves the shortcut's display name and location while
+// addressing its content by the target token. Folder targets are unsupported.
+func ExpandDriveShortcut(f DriveFile) (DriveFile, bool) {
+ if f.Type != "shortcut" {
+ return f, true
}
- return all, nil
+ if f.ShortcutInfo == nil || f.ShortcutInfo.TargetToken == "" || f.ShortcutInfo.TargetType == "folder" {
+ return DriveFile{}, false
+ }
+ f.Token, f.Type = f.ShortcutInfo.TargetToken, f.ShortcutInfo.TargetType
+ f.ShortcutInfo = nil
+ return f, true
+}
+
+// userNameResponse is the GET /contact/v3/users/:userID payload;
+// data.user.name is the user's display name.
+type userNameResponse struct {
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+ Data struct {
+ User struct {
+ Name string `json:"name"`
+ } `json:"user"`
+ } `json:"data"`
+}
+
+// DocTitles resolves display titles for document tokens via the drive
+// metadata batch API (one call for all refs, capped at the API's 200-item
+// limit). Tokens whose metadata is unavailable — no permission (970003),
+// deleted/mismatched (970005) — are simply absent from the result;
+// transport-level failures return nil. Callers degrade to the URL as link
+// text, so failures never block ingestion.
+func (c *Client) DocTitles(ctx context.Context, refs []pendingDocName) map[string]string {
+ if len(refs) == 0 {
+ return nil
+ }
+ type reqDoc struct {
+ DocToken string `json:"doc_token"`
+ DocType string `json:"doc_type"`
+ }
+ reqs := make([]reqDoc, 0, len(refs))
+ for _, r := range refs {
+ if len(reqs) == 200 {
+ break
+ }
+ reqs = append(reqs, reqDoc{DocToken: r.Token, DocType: r.DocType})
+ }
+ var resp struct {
+ ApiResponse
+ Data struct {
+ Metas []struct {
+ DocToken string `json:"doc_token"`
+ Title string `json:"title"`
+ } `json:"metas"`
+ } `json:"data"`
+ }
+ path := "/open-apis/drive/v1/metas/batch_query"
+ if err := c.DoRequest(ctx, http.MethodPost, path, map[string]any{"request_docs": reqs}, &resp); err != nil {
+ return nil
+ }
+ if resp.Code != 0 {
+ return nil
+ }
+ out := make(map[string]string, len(resp.Data.Metas))
+ for _, m := range resp.Data.Metas {
+ out[m.DocToken] = m.Title
+ }
+ return out
+}
+
+// UserName fetches a user's display name by OpenID via the contact API.
+// mention_user.user_id carries an OpenID, hence user_id_type=open_id. Requires
+// a contact read scope (contact:user.base:readonly / contact:contact:readonly);
+// callers degrade to a generic @ marker on any failure, so errors here never
+// block ingestion.
+func (c *Client) UserName(ctx context.Context, userID string) (string, error) {
+ if userID == "" {
+ return "", fmt.Errorf("empty user id")
+ }
+ path := fmt.Sprintf("/open-apis/contact/v3/users/%s?user_id_type=open_id", url.PathEscape(userID))
+
+ var resp userNameResponse
+ if err := c.DoRequest(ctx, http.MethodGet, path, nil, &resp); err != nil {
+ return "", fmt.Errorf("get user %s: %w", userID, err)
+ }
+ if resp.Code != 0 {
+ return "", fmt.Errorf("get user %s error: code=%d msg=%s", userID, resp.Code, resp.Msg)
+ }
+ return resp.Data.User.Name, nil
}
diff --git a/internal/datasource/connector/feishu/core/engine.go b/internal/datasource/connector/feishu/core/engine.go
index efdca0f8f..59e0ee48a 100644
--- a/internal/datasource/connector/feishu/core/engine.go
+++ b/internal/datasource/connector/feishu/core/engine.go
@@ -41,12 +41,12 @@ type NodeOps[N any] interface {
Token(n N) string
Title(n N) string
ObjType(n N) string
- // EditTime is the change-detection timestamp string stored in the cursor.
+ // EditTime is an opaque change key stored in the cursor (time and/or path).
EditTime(n N) string
// fetch retrieves one node's content; (nil, nil) means an unsupported
// type that yields no item.
- Fetch(ctx context.Context, client *Client, n N, resourceID string, multimodal bool) ([]*types.FetchedItem, error)
+ Fetch(ctx context.Context, client *Client, n N, resourceID string) ([]*types.FetchedItem, error)
// ListFailureItems converts a partial-listing error into error FetchedItems.
ListFailureItems(resourceID string, partial error) []types.FetchedItem
@@ -81,23 +81,48 @@ func (h *CollectHandler) Emit(_ context.Context, item types.FetchedItem) error {
func (h *CollectHandler) Checkpoint(_ context.Context, _ *types.SyncCursor) error { return nil }
+// fullSyncPending is checkpoint-only state. A retried full pass must skip work
+// completed before the checkpoint while keeping unseen deletion identities.
+const fullSyncPending = "feishu_full_sync_pending"
+
// runSync is the single implementation behind FetchStream / FetchAll /
// FetchIncremental. With cursor == nil it fetches everything (full sync);
// with a cursor it skips nodes whose recorded edit time is unchanged
-// (incremental + resume). resourceIDs comes from the caller: FetchStream /
+// (incremental + resume), unless forceFull is set. Full runs retain cursor
+// identities for deletion tracking. resourceIDs comes from the caller: FetchStream /
// FetchIncremental pass config.ResourceIDs (after a non-empty check),
// FetchAll passes its own argument without one.
func runSync[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
resourceIDs []string, cursor *types.SyncCursor, h datasource.StreamHandler,
- ops NodeOps[N],
+ ops NodeOps[N], forceFull bool,
) (*types.SyncCursor, error) {
var prevTimes map[string]map[string]string
if cursor != nil && cursor.ConnectorCursor != nil {
prevTimes = ops.DecodeCursorTimes(cursor.ConnectorCursor)
}
+ resumingFull := false
+ if cursor != nil {
+ resumingFull, _ = cursor.ConnectorCursor[fullSyncPending].(bool)
+ }
+ fullRun := forceFull || resumingFull
+ forceFull = forceFull && !resumingFull
+
+ // Keep unseen entries in checkpoints until a complete listing proves them
+ // deleted. This also preserves later resources if a run is interrupted.
newTimes := make(map[string]map[string]string)
+ for _, resourceID := range resourceIDs {
+ newTimes[resourceID] = make(map[string]string)
+ for token, edit := range prevTimes[resourceID] {
+ if forceFull {
+ // Invalidating the value (not the identity) makes failed full
+ // fetches retryable even if the source timestamp is unchanged.
+ edit = "!pending-full-fetch"
+ }
+ newTimes[resourceID][token] = edit
+ }
+ }
lastSync := time.Now()
processed := 0
@@ -115,17 +140,6 @@ func runSync[N any](
}
}
- newTimes[resourceID] = make(map[string]string)
- // On a partial listing, carry prior edit times forward so a later full
- // listing can still detect changes and deletions.
- if partial != nil && prevTimes != nil {
- if prev, ok := prevTimes[resourceID]; ok {
- for tok, et := range prev {
- newTimes[resourceID][tok] = et
- }
- }
- }
-
currentNodes := make(map[string]bool)
tally := newFetchTally(len(nodes))
for i, node := range nodes {
@@ -144,21 +158,20 @@ func runSync[N any](
// Resume/incremental fast-path: a node recorded at its current edit
// time is unchanged (or already synced this run) - keep the record
// and Skip re-fetching.
- if hadPrev && prevEdit == editTimeStr {
+ if !forceFull && hadPrev && prevEdit == editTimeStr {
newTimes[resourceID][tok] = editTimeStr
continue
}
- items, ferr := ops.Fetch(ctx, client, node, resourceID, config.MultimodalEnabled)
+ items, ferr := ops.Fetch(ctx, client, node, resourceID)
if ferr != nil {
tally.fail()
// Do NOT advance the cursor: the content was never fetched.
// Retain the prior edit time (if any) so prev != current next
// run and the node is retried, instead of being permanently
// skipped on a transient export failure (Tencent/WeKnora#2136).
- if hadPrev {
- newTimes[resourceID][tok] = prevEdit
- }
+ // The seeded entry keeps the prior key, or the invalidated
+ // full-fetch key, without losing its deletion identity.
if eerr := h.Emit(ctx, types.FetchedItem{
ExternalID: tok,
Title: ops.Title(node),
@@ -186,7 +199,11 @@ func runSync[N any](
processed++
if processed%FeishuStreamCheckpointInterval == 0 || time.Since(lastCheckpoint) >= FeishuStreamCheckpointMaxInterval {
- if cerr := h.Checkpoint(ctx, ops.EncodeCursor(newTimes, lastSync)); cerr != nil {
+ checkpoint := ops.EncodeCursor(newTimes, lastSync)
+ if fullRun {
+ checkpoint.ConnectorCursor[fullSyncPending] = true
+ }
+ if cerr := h.Checkpoint(ctx, checkpoint); cerr != nil {
logger.Warnf(ctx, "%s stream Checkpoint failed: %v", ops.LogTag(), cerr)
}
lastCheckpoint = time.Now()
@@ -211,6 +228,7 @@ func runSync[N any](
}); eerr != nil {
return nil, eerr
}
+ delete(newTimes[resourceID], tok)
}
}
}
@@ -228,7 +246,15 @@ func FetchStreamEngine[N any](
ctx context.Context, client *Client, config *types.DataSourceConfig,
cursor *types.SyncCursor, h datasource.StreamHandler, ops NodeOps[N],
) (*types.SyncCursor, error) {
- return runSync(ctx, client, config, config.ResourceIDs, cursor, h, ops)
+ return runSync(ctx, client, config, config.ResourceIDs, cursor, h, ops, false)
+}
+
+// FetchFullStreamEngine refetches all nodes while retaining deletion identities.
+func FetchFullStreamEngine[N any](
+ ctx context.Context, client *Client, config *types.DataSourceConfig,
+ cursor *types.SyncCursor, h datasource.StreamHandler, ops NodeOps[N],
+) (*types.SyncCursor, error) {
+ return runSync(ctx, client, config, config.ResourceIDs, cursor, h, ops, true)
}
// FetchAllEngine runs a full sync, collecting every item into a slice. It
@@ -241,7 +267,7 @@ func FetchAllEngine[N any](
resourceIDs []string, ops NodeOps[N],
) ([]types.FetchedItem, error) {
ch := &CollectHandler{}
- if _, err := runSync(ctx, client, config, resourceIDs, nil, ch, ops); err != nil {
+ if _, err := runSync(ctx, client, config, resourceIDs, nil, ch, ops, false); err != nil {
return nil, err
}
return ch.items, nil
@@ -255,7 +281,7 @@ func FetchIncrementalEngine[N any](
cursor *types.SyncCursor, ops NodeOps[N],
) ([]types.FetchedItem, *types.SyncCursor, error) {
ch := &CollectHandler{}
- next, err := runSync(ctx, client, config, config.ResourceIDs, cursor, ch, ops)
+ next, err := runSync(ctx, client, config, config.ResourceIDs, cursor, ch, ops, false)
if err != nil {
return nil, nil, err
}
diff --git a/internal/datasource/connector/feishu/core/engine_full_test.go b/internal/datasource/connector/feishu/core/engine_full_test.go
new file mode 100644
index 000000000..f68ff9203
--- /dev/null
+++ b/internal/datasource/connector/feishu/core/engine_full_test.go
@@ -0,0 +1,146 @@
+package core
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+type fullSyncOps struct {
+ nodes map[string][]string
+ partial bool
+ fail map[string]bool
+ fetched []string
+}
+
+func (o *fullSyncOps) List(_ context.Context, _ *Client, resource string) ([]string, error, error) {
+ if o.partial {
+ return o.nodes[resource], errors.New("partial listing"), nil
+ }
+ return o.nodes[resource], nil, nil
+}
+func (*fullSyncOps) Token(n string) string { return n }
+func (*fullSyncOps) Title(n string) string { return n }
+func (*fullSyncOps) ObjType(string) string { return "file" }
+func (*fullSyncOps) EditTime(string) string { return "100" }
+func (o *fullSyncOps) Fetch(_ context.Context, _ *Client, n, resource string) ([]*types.FetchedItem, error) {
+ o.fetched = append(o.fetched, n)
+ if o.fail[n] {
+ return nil, errors.New("transient fetch failure")
+ }
+ return []*types.FetchedItem{{ExternalID: n, SourceResourceID: resource}}, nil
+}
+func (*fullSyncOps) ListFailureItems(string, error) []types.FetchedItem { return nil }
+func (*fullSyncOps) ResourceNoun() string { return "nodes" }
+func (*fullSyncOps) EmptyResourceIDsError() string { return "empty resources" }
+func (*fullSyncOps) LogTag() string { return "[test]" }
+func (*fullSyncOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
+ return m["times"].(map[string]map[string]string)
+}
+
+func (*fullSyncOps) EncodeCursor(m map[string]map[string]string, _ time.Time) *types.SyncCursor {
+ snapshot := make(map[string]map[string]string)
+ for resource, times := range m {
+ snapshot[resource] = make(map[string]string)
+ for k, v := range times {
+ snapshot[resource][k] = v
+ }
+ }
+ return &types.SyncCursor{ConnectorCursor: map[string]interface{}{"times": snapshot}}
+}
+
+type fullSyncHandler struct {
+ CollectHandler
+ checkpoint *types.SyncCursor
+ stopAfterCheckpoint bool
+}
+
+func (h *fullSyncHandler) Emit(ctx context.Context, item types.FetchedItem) error {
+ if h.stopAfterCheckpoint && h.checkpoint != nil {
+ return errors.New("interrupted")
+ }
+ return h.CollectHandler.Emit(ctx, item)
+}
+
+func (h *fullSyncHandler) Checkpoint(_ context.Context, cur *types.SyncCursor) error {
+ h.checkpoint = cur
+ return nil
+}
+
+func TestFullSyncRefetchesAndReconcilesDeletions(t *testing.T) {
+ ops := &fullSyncOps{nodes: map[string][]string{"r": {"kept"}}}
+ cfg := &types.DataSourceConfig{ResourceIDs: []string{"r"}}
+ old := ops.EncodeCursor(map[string]map[string]string{"r": {"kept": "100", "gone": "100"}}, time.Now())
+ h := &fullSyncHandler{}
+ next, err := FetchFullStreamEngine(context.Background(), nil, cfg, old, h, ops)
+ require.NoError(t, err)
+ require.Equal(t, []string{"kept"}, ops.fetched)
+ require.Len(t, h.items, 2)
+ require.True(t, h.items[1].IsDeleted)
+ require.Equal(t, "gone", h.items[1].ExternalID)
+ require.Equal(t, map[string]string{"kept": "100"}, ops.DecodeCursorTimes(next.ConnectorCursor)["r"])
+ require.Contains(t, ops.DecodeCursorTimes(old.ConnectorCursor)["r"], "gone", "input baseline must remain immutable")
+}
+
+func TestFullSyncFailuresRetryWithoutLosingDeletionIdentity(t *testing.T) {
+ ops := &fullSyncOps{nodes: map[string][]string{"r": {"kept"}}, partial: true, fail: map[string]bool{"kept": true}}
+ cfg := &types.DataSourceConfig{ResourceIDs: []string{"r"}}
+ old := ops.EncodeCursor(map[string]map[string]string{"r": {"kept": "100", "unseen": "100"}}, time.Now())
+ h := &fullSyncHandler{}
+ next, err := FetchFullStreamEngine(context.Background(), nil, cfg, old, h, ops)
+ require.NoError(t, err)
+ require.Len(t, h.items, 1)
+ require.NotEmpty(t, h.items[0].Metadata["error"])
+ require.Contains(t, ops.DecodeCursorTimes(next.ConnectorCursor)["r"], "unseen")
+ ops.partial = false
+ ops.fail = nil
+ ops.fetched = nil
+ h = &fullSyncHandler{}
+ _, err = FetchStreamEngine(context.Background(), nil, cfg, next, h, ops)
+ require.NoError(t, err)
+ require.Equal(t, []string{"kept"}, ops.fetched,
+ "failed full fetch must retry despite an unchanged source timestamp")
+ require.Len(t, h.items, 2)
+ require.True(t, h.items[1].IsDeleted)
+ require.Equal(t, "unseen", h.items[1].ExternalID)
+}
+
+func TestFullSyncCheckpointRetainsUnseenDeletionBaseline(t *testing.T) {
+ ops := &fullSyncOps{nodes: map[string][]string{"first": {}}}
+ for i := 0; i < FeishuStreamCheckpointInterval+1; i++ {
+ ops.nodes["first"] = append(ops.nodes["first"], fmt.Sprintf("node%d", i))
+ }
+ cfg := &types.DataSourceConfig{ResourceIDs: []string{"first", "later"}}
+ old := ops.EncodeCursor(map[string]map[string]string{
+ "first": {"gone": "100"}, "later": {"gone-later": "100"},
+ }, time.Now())
+ h := &fullSyncHandler{stopAfterCheckpoint: true}
+ _, err := FetchFullStreamEngine(context.Background(), nil, cfg, old, h, ops)
+ require.Error(t, err)
+ require.NotNil(t, h.checkpoint)
+ require.Equal(t, true, h.checkpoint.ConnectorCursor[fullSyncPending])
+ ops.fetched = nil
+ resume := &fullSyncHandler{}
+ next, err := FetchFullStreamEngine(context.Background(), nil, cfg, h.checkpoint, resume, ops)
+ require.NoError(t, err)
+ deleted := []string{}
+ for _, item := range resume.items {
+ if item.IsDeleted {
+ deleted = append(deleted, item.ExternalID)
+ }
+ }
+ require.ElementsMatch(t, []string{"gone", "gone-later"}, deleted)
+ require.Equal(t, []string{fmt.Sprintf("node%d", FeishuStreamCheckpointInterval)}, ops.fetched,
+ "a retried full pass must not repeat successfully checkpointed fetches")
+ require.NotContains(t, next.ConnectorCursor, fullSyncPending)
+ ops.fetched = nil
+ _, err = FetchFullStreamEngine(context.Background(), nil, cfg, next, &fullSyncHandler{}, ops)
+ require.NoError(t, err)
+ require.Len(t, ops.fetched, len(ops.nodes["first"]),
+ "a later independent full sync must refetch everything")
+}
diff --git a/internal/datasource/connector/feishu/core/markdown.go b/internal/datasource/connector/feishu/core/markdown.go
index faf395375..822824997 100644
--- a/internal/datasource/connector/feishu/core/markdown.go
+++ b/internal/datasource/connector/feishu/core/markdown.go
@@ -2,7 +2,12 @@ package core
import (
"context"
+ "encoding/json"
"fmt"
+ "hash/fnv"
+ "net/url"
+ "path/filepath"
+ "strconv"
"strings"
)
@@ -11,6 +16,7 @@ import (
type sheetReader interface {
readSheetRange(ctx context.Context, embedToken string) ([][]string, bool, error)
readBitableRecords(ctx context.Context, embedToken string) ([][]string, bool, error)
+ sheetMerges(ctx context.Context, embedToken string) ([]sheetMergeRange, error)
}
// pendingAttachment is an embedded file block awaiting a download decision by
@@ -20,90 +26,420 @@ type pendingAttachment struct {
Name string
}
+// pendingDocName is one 云文档 mention link awaiting a title backfill: the
+// renderer emits "[weknora-docname://<token>](<url>)" placeholders (it has no
+// access to document titles) and FetchDocxWithBlocks resolves the titles via
+// the drive metadata batch API, patching the link text in place.
+type pendingDocName struct {
+ Token string
+ DocType string // drive metas doc_type: docx/doc/sheet/bitable/wiki/...
+ URL string
+}
+
+// pendingImage is one image/board marker emitted into the Markdown, in
+// document order: N is the 1-based marker sequence number, Kind is the
+// SubtreeChildID discriminator ("image" or "board"), Token the Feishu media or
+// whiteboard token. The connector downloads each token and patches its marker
+// in place — an inline base64 data URI on success, a plain ![图片]()
+// placeholder on failure (no image sub-items are created).
+type pendingImage struct {
+ N int
+ Kind string
+ Token string
+}
+
+// mdRenderer carries per-document rendering state: the block index for
+// container recursion, download candidates, and the ordered-list counter.
+type mdRenderer struct {
+ ctx context.Context
+ client sheetReader
+ byID map[string]DocxBlock
+ atts []pendingAttachment
+ imgs []pendingImage
+ docNames []pendingDocName
+ docNameSeen map[string]bool
+ imgN int // last marker sequence number assigned
+ markerNonce string // per-document nonce keeping user text from matching markers
+ docURL string // parent document's web URL, for non-whitelisted attachment placeholders
+
+ // userName resolves a mention_user OpenID to a display name; "" means
+ // unresolved (renders the generic @成员). Nil-safe via the default set in
+ // blocksToMarkdown.
+ userName func(string) string
+
+ orderedActive bool // an ordered-list run is in progress
+ lastOrderedParent string // ParentID of the most recent ordered item
+ orderedNext int // next number for "auto"/absent sequence
+ rendering map[string]bool // guard malformed cyclic container children
+}
+
+// nextImageNo assigns the next marker sequence number. The renderer and the
+// recorded pendingImage share this single counter, so the marker in the
+// Markdown and the pendingImage can never disagree.
+func (r *mdRenderer) nextImageNo(kind, token string) int {
+ r.imgN++
+ r.imgs = append(r.imgs, pendingImage{N: r.imgN, Kind: kind, Token: token})
+ return r.imgN
+}
+
+// imageMarker renders the synthetic placeholder for image/board N. The nonce
+// keeps user-typed look-alike text (a literal ![图片](weknora-img://1) in a
+// text run) from ever matching the connector's patch needle — only this
+// renderer and the patcher share the derivation (imageMarkerNonce).
+func (r *mdRenderer) imageMarker(n int) string {
+ return fmt.Sprintf("![图片](weknora-img://%d-%s)", n, r.markerNonce)
+}
+
+// imageMarkerNonce derives the per-document marker nonce from the doc URL.
+func imageMarkerNonce(seed string) string {
+ h := fnv.New32a()
+ _, _ = h.Write([]byte(seed))
+ return fmt.Sprintf("%08x", h.Sum32())
+}
+
// blocksToMarkdown renders a flat docx block array to Markdown, inlining
-// embedded spreadsheet/bitable tables (Task 5) and collecting downloadable
-// attachments. client may be nil when the block set has no downdrill blocks.
-func blocksToMarkdown(ctx context.Context, client sheetReader, blocks []DocxBlock) ([]byte, []pendingAttachment, error) {
+// embedded spreadsheet/bitable tables, collecting downloadable
+// attachments, and numbering image/board blocks as weknora-img://N markers.
+// docURL is the parent document's web URL used in non-whitelisted attachment
+// placeholders (empty → placeholder without link). client may be nil when the
+// block set has no downdrill blocks. userName resolves mention_user OpenIDs to
+// display names (nil → generic @成员 for every mention; documents without
+// mentions never invoke it, so it costs zero API calls).
+func blocksToMarkdown(
+ ctx context.Context, client sheetReader, blocks []DocxBlock, docURL string, userName func(string) string,
+) ([]byte, []pendingAttachment, []pendingImage, []pendingDocName, error) {
byID := make(map[string]DocxBlock, len(blocks))
for _, b := range blocks {
byID[b.BlockID] = b
}
- // Blocks nested inside a native table (its cells and their content blocks)
- // are rendered by renderNativeTable. Mark them so the flat loop below does
- // not also Emit them as stray top-level paragraphs.
+ // Blocks nested inside a native table are rendered by renderNativeTable;
+ // blocks nested inside a container the main loop renders recursively
+ // (callout / grid / quote_container) are rendered by that container. Mark
+ // both so the flat loop below never Emits them a second time.
consumed := tableDescendants(blocks, byID)
+ markContainerDescendants(blocks, byID, consumed)
+ if userName == nil {
+ userName = func(string) string { return "" }
+ }
+ r := &mdRenderer{
+ ctx: ctx, client: client, byID: byID, docURL: docURL,
+ userName: userName, markerNonce: imageMarkerNonce(docURL),
+ }
var sb strings.Builder
- var atts []pendingAttachment
for _, b := range blocks {
+ if consumed[b.BlockID] {
+ continue
+ }
+ writePara(&sb, r.renderBlock(b))
+ }
+ out := strings.TrimRight(sb.String(), "\n")
+ // listDocumentBlocks stops collecting at maxDocumentBlocks, so a full-size
+ // array means content was dropped silently. Annotate it like the
+ // embedded-table truncation does instead of failing the document.
+ if len(blocks) >= maxDocumentBlocks {
+ out += fmt.Sprintf("\n> 文档已截断(仅显示前 %d 个块)", maxDocumentBlocks)
+ }
+ if out != "" {
+ out += "\n"
+ }
+ return []byte(out), r.atts, r.imgs, r.docNames, nil
+}
+
+// markContainerDescendants marks every block reachable through the children of
+// the container blocks the main loop renders recursively (callout, grid — its
+// columns' content is rendered per column — quote_container, and view).
+func markContainerDescendants(blocks []DocxBlock, byID map[string]DocxBlock, consumed map[string]bool) {
+ var mark func(id string)
+ mark = func(id string) {
+ b, ok := byID[id]
+ if !ok || consumed[id] {
+ return
+ }
+ consumed[id] = true
+ for _, c := range b.Children {
+ mark(c)
+ }
+ }
+ for _, b := range blocks {
+ // A table-owned container is not recursively rendered. Its media
+ // must remain available to the flat pass, just like direct cell media.
if consumed[b.BlockID] {
continue
}
switch b.BlockType {
- case BlockTypePage:
- continue // root container, no text of its own
- case BlockTypeText:
- writePara(&sb, plainText(textBearingField(b)))
- case BlockTypeBullet:
- writePara(&sb, "- "+plainText(textBearingField(b)))
- case BlockTypeOrdered:
- writePara(&sb, "1. "+plainText(textBearingField(b)))
- case BlockTypeCode:
- writePara(&sb, "```\n"+plainText(textBearingField(b))+"\n```")
- case BlockTypeQuote:
- writePara(&sb, "> "+plainText(textBearingField(b)))
- case BlockTypeDivider:
- writePara(&sb, "---")
- case BlockTypeTable:
- writePara(&sb, renderNativeTable(b, byID))
- case BlockTypeTableCell:
- continue // rendered by its parent table (also covered by `consumed`)
- case BlockTypeSheet:
- if b.Sheet != nil {
- writePara(&sb, inlineTable(ctx, client, b.Sheet.Token, "sheet"))
+ case BlockTypeCallout, BlockTypeGrid, BlockTypeQuoteContainer, BlockTypeView:
+ for _, c := range b.Children {
+ mark(c)
+ }
+ }
+ }
+}
+
+// renderBlock renders one block, recursing into containers. Returns "" when
+// the block contributes nothing.
+func (r *mdRenderer) renderBlock(b DocxBlock) string {
+ // Only a sibling of the last ordered item ends an ordered run. Ordered
+ // items share one parent, while their child blocks render flat between
+ // items carrying the item's own ID — those must not renumber the run.
+ if b.BlockType != BlockTypeOrdered {
+ if b.ParentID == r.lastOrderedParent {
+ r.orderedActive = false
+ }
+ } else {
+ r.lastOrderedParent = b.ParentID
+ }
+ switch b.BlockType {
+ case BlockTypePage, BlockTypeTableCell:
+ return "" // containers rendered elsewhere
+ case BlockTypeText:
+ return r.richText(textBearingField(b))
+ case BlockTypeBullet:
+ return "- " + r.richText(b.Bullet)
+ case BlockTypeOrdered:
+ return fmt.Sprintf("%d. %s", r.nextOrderedNo(textBearingField(b)), r.richText(b.Ordered))
+ case BlockTypeCode:
+ return r.renderCode(b)
+ case BlockTypeQuote:
+ return "> " + r.richText(b.Quote)
+ case BlockTypeTodo:
+ bt := textBearingField(b)
+ if t := r.richText(bt); t != "" {
+ if bt != nil && bt.Style != nil && bt.Style.Done {
+ return "- [x] " + t
+ }
+ return "- [ ] " + t
+ }
+ case BlockTypeDivider:
+ return "---"
+ case BlockTypeCallout:
+ return r.renderQuotedContainer(b, r.richText(b.Callout))
+ case BlockTypeQuoteContainer:
+ return r.renderQuotedContainer(b, "")
+ case BlockTypeGrid:
+ return r.renderGrid(b)
+ case BlockTypeView:
+ // view is a pure container (e.g. the file-list "视图" wrapping file
+ // blocks): render its children inline, no placeholder. An empty view
+ // contributes nothing.
+ var lines []string
+ for _, cid := range b.Children {
+ if child, ok := r.byID[cid]; ok {
+ if s := r.renderContainerChild(child); s != "" {
+ lines = append(lines, strings.Split(s, "\n")...)
+ }
+ }
+ }
+ return strings.Join(lines, "\n")
+ case BlockTypeTable:
+ return renderNativeTable(b, r.byID)
+ case BlockTypeSheet:
+ if b.Sheet != nil {
+ return inlineTable(r.ctx, r.client, b.Sheet.Token, "sheet")
+ }
+ case BlockTypeBitable:
+ if b.Bitable != nil {
+ return inlineTable(r.ctx, r.client, b.Bitable.Token, "bitable")
+ }
+ case BlockTypeImage:
+ // Token-free numbered marker: the media token never enters the Markdown;
+ // the connector downloads it and patches the marker in place.
+ var tok string
+ if b.Image != nil {
+ tok = b.Image.Token
+ }
+ n := r.nextImageNo("image", tok)
+ return r.imageMarker(n)
+ case BlockTypeBoard:
+ if b.Board == nil || b.Board.Token == "" {
+ return unsupportedBlockNote(b)
+ }
+ // Boards ride the same image pipeline: the connector downloads the
+ // whiteboard export and inlines it. On failure it patches this marker
+ // back to a plain placeholder.
+ n := r.nextImageNo("board", b.Board.Token)
+ return r.imageMarker(n)
+ case BlockTypeFile:
+ if b.File != nil {
+ name := b.File.Name
+ if name == "" {
+ name = b.File.Token
}
- case BlockTypeBitable:
- if b.Bitable != nil {
- writePara(&sb, inlineTable(ctx, client, b.Bitable.Token, "bitable"))
+ if parseableAttachmentExts[strings.ToLower(filepath.Ext(name))] {
+ r.atts = append(r.atts, pendingAttachment{FileToken: b.File.Token, Name: b.File.Name})
+ // Unique token line, not the display name: the connector swaps
+ // this exact line after the download attempt (name on success /
+ // tiny, degrade note over cap), so an identical earlier bullet
+ // can never be replaced by mistake.
+ return "- weknora-att://" + b.File.Token
}
- case BlockTypeImage:
- // Emit a token-free placeholder: images carry no retrievable text, and
- // leaking the internal media token would pollute embeddings. A neutral
- // marker preserves surrounding context (e.g. "如下图所示").
- writePara(&sb, "![图片]()")
- case BlockTypeTodo:
- if t := plainText(textBearingField(b)); t != "" {
- writePara(&sb, "- [ ] "+t)
+ // Not ingestible (wrong type / video): keep a visible reference with
+ // the source link when available.
+ if r.docURL != "" {
+ return "> [附件: " + name + "](" + escapeURL(r.docURL) + ")"
}
- case BlockTypeCallout:
- // Callout is a container; its body is usually in child blocks (rendered
- // separately). Emit its own text only if it carries direct inline text,
- // so the container case is a safe no-op.
- if t := plainText(textBearingField(b)); t != "" {
- writePara(&sb, "> "+t)
+ return "> [附件: " + name + "]"
+ }
+ case BlockTypeIframe:
+ if b.Iframe != nil && b.Iframe.Component != nil && b.Iframe.Component.URL != "" {
+ return "[内嵌网页](" + escapeURL(b.Iframe.Component.URL) + ")"
+ }
+ return unsupportedBlockNote(b)
+ case BlockTypeAddOns:
+ // 文档小组件 carry their full data inline in `record` (JSON string);
+ // there is no server-side render to download. Recognized component
+ // types degrade to structured Markdown, unknown ones keep the note.
+ if b.AddOns != nil && b.AddOns.ComponentTypeID == addOnsTimelineTypeID {
+ if md := renderTimelineAddOn(b.AddOns.Record); md != "" {
+ return md
}
- case BlockTypeFile:
- if b.File != nil {
- name := b.File.Name
- if name == "" {
- name = b.File.Token
+ }
+ return unsupportedBlockNote(b)
+ default:
+ if b.BlockType >= BlockTypeHeading1 && b.BlockType <= blockTypeHeading9 {
+ level := b.BlockType - BlockTypeHeading1 + 1
+ if level <= 6 {
+ return strings.Repeat("#", level) + " " + r.richText(headingText(b))
+ }
+ // GFM headings stop at H6; Feishu heading7-9 degrade to bold text
+ // (a 7-hash "heading" is plain text to every Markdown renderer).
+ return "**" + r.richText(headingText(b)) + "**"
+ }
+ return unsupportedBlockNote(b)
+ }
+ return ""
+}
+
+// renderQuotedContainer renders a container block (callout / quote_container):
+// its own inline text (if any) plus each child block, every line prefixed with
+// "> ".
+func (r *mdRenderer) renderQuotedContainer(b DocxBlock, own string) string {
+ var lines []string
+ if own != "" {
+ lines = append(lines, own)
+ }
+ for _, cid := range b.Children {
+ child, ok := r.byID[cid]
+ if !ok {
+ continue
+ }
+ if s := r.renderContainerChild(child); s != "" {
+ lines = append(lines, strings.Split(s, "\n")...)
+ }
+ }
+ if len(lines) == 0 {
+ return ""
+ }
+ for i, l := range lines {
+ lines[i] = "> " + l
+ }
+ return strings.Join(lines, "\n")
+}
+
+// renderGrid renders a 分栏 (grid) block: each child column's content is
+// rendered in column order, columns separated by a horizontal rule.
+func (r *mdRenderer) renderGrid(b DocxBlock) string {
+ var cols []string
+ for _, cid := range b.Children {
+ col, ok := r.byID[cid]
+ if !ok {
+ continue
+ }
+ var parts []string
+ if col.BlockType == BlockTypeGridColumn {
+ for _, ccid := range col.Children {
+ if cb, ok := r.byID[ccid]; ok {
+ if s := r.renderContainerChild(cb); s != "" {
+ parts = append(parts, s)
+ }
}
- writePara(&sb, "📎 附件:"+name)
- atts = append(atts, pendingAttachment{FileToken: b.File.Token, Name: b.File.Name})
}
- default:
- if b.BlockType >= BlockTypeHeading1 && b.BlockType <= blockTypeHeading9 {
- level := b.BlockType - BlockTypeHeading1 + 1
- writePara(&sb, strings.Repeat("#", level)+" "+plainText(textBearingField(b)))
+ } else if s := r.renderContainerChild(col); s != "" {
+ // Malformed grid whose child is not a grid_column: keep its content.
+ parts = append(parts, s)
+ }
+ if len(parts) > 0 {
+ cols = append(cols, strings.Join(parts, "\n\n"))
+ }
+ }
+ return strings.Join(cols, "\n\n---\n\n")
+}
+
+// renderContainerChild renders all descendants consumed on behalf of a
+// container. Outside containers the flat API listing still renders ordinary
+// list/paragraph children, so renderBlock itself must not recurse into them.
+func (r *mdRenderer) renderContainerChild(b DocxBlock) string {
+ if r.rendering == nil {
+ r.rendering = make(map[string]bool)
+ }
+ if r.rendering[b.BlockID] {
+ return ""
+ }
+ r.rendering[b.BlockID] = true
+ defer delete(r.rendering, b.BlockID)
+
+ own := r.renderBlock(b)
+ switch b.BlockType {
+ case BlockTypeCallout, BlockTypeGrid, BlockTypeQuoteContainer, BlockTypeView:
+ return own // these render their own descendants; table media stays in the flat pass
+ case BlockTypeTable:
+ if tableRenderable(b) {
+ return own // malformed tables must retain their descendants as loose text
+ }
+ }
+ active, parent, next := r.orderedActive, r.lastOrderedParent, r.orderedNext
+ defer func() { r.orderedActive, r.lastOrderedParent, r.orderedNext = active, parent, next }()
+ // Nested ordered runs must not share their parent's counter.
+ r.orderedActive = false
+ var parts []string
+ if own != "" {
+ parts = append(parts, own)
+ }
+ indent := ""
+ switch b.BlockType {
+ case BlockTypeBullet, BlockTypeTodo:
+ indent = " "
+ case BlockTypeOrdered:
+ if i := strings.Index(own, ". "); i >= 0 {
+ indent = strings.Repeat(" ", i+2)
+ }
+ }
+ for _, id := range b.Children {
+ child, ok := r.byID[id]
+ if !ok {
+ continue
+ }
+ if s := r.renderContainerChild(child); s != "" {
+ if indent != "" {
+ s = indent + strings.ReplaceAll(s, "\n", "\n"+indent)
}
+ parts = append(parts, s)
}
}
+ return strings.Join(parts, "\n\n")
+}
- out := strings.TrimRight(sb.String(), "\n")
- if out != "" {
- out += "\n"
+// nextOrderedNo returns the real number for an ordered list item. Feishu stores
+// it in style.sequence: a specific value starts or restarts the list ("3"),
+// "auto" continues it. Historical/OpenAPI-created docs omit the field entirely;
+// there we fall back to relative numbering, incrementing until a non-ordered
+// block resets the run.
+func (r *mdRenderer) nextOrderedNo(bt *BlockText) int {
+ if bt != nil && bt.Style != nil {
+ if n, err := strconv.Atoi(bt.Style.Sequence); err == nil && n > 0 {
+ r.orderedActive = true
+ r.orderedNext = n + 1
+ return n
+ }
}
- return []byte(out), atts, nil
+ if !r.orderedActive {
+ r.orderedActive = true
+ r.orderedNext = 2
+ return 1
+ }
+ n := r.orderedNext
+ r.orderedNext++
+ return n
}
// writePara appends a block of text followed by a blank line; empty text is skipped.
@@ -115,7 +451,8 @@ func writePara(sb *strings.Builder, s string) {
sb.WriteString("\n\n")
}
-// plainText concatenates the text runs of a text-bearing block.
+// plainText concatenates the raw text runs of a text-bearing block (no inline
+// styling — used for table cells, where GFM styling would break the row).
func plainText(bt *BlockText) string {
if bt == nil {
return ""
@@ -129,6 +466,224 @@ func plainText(bt *BlockText) string {
return sb.String()
}
+// mentionDocTypeByPathSegment maps Feishu URL path segments to drive metas
+// doc_type values. Wiki links resolve through this table too — the metadata
+// API supports wiki tokens for titles (content fetching is another matter).
+var mentionDocTypeByPathSegment = map[string]string{
+ "doc": "doc",
+ "docx": "docx",
+ "sheets": "sheet",
+ "base": "bitable",
+ "wiki": "wiki",
+ "mindnote": "mindnote",
+ "slides": "slides",
+ "file": "file",
+}
+
+// parseMentionDocRef extracts (token, doc_type) from a Feishu document URL
+// like https://x.feishu.cn/docx/<token>. Returns ok=false for anything that
+// is not a recognizable Feishu doc URL (the link then stays as-is).
+func parseMentionDocRef(u string) (pendingDocName, bool) {
+ parsed, err := url.Parse(u)
+ if err != nil {
+ return pendingDocName{}, false
+ }
+ segs := strings.Split(strings.Trim(parsed.Path, "/"), "/")
+ for i, seg := range segs {
+ docType, ok := mentionDocTypeByPathSegment[seg]
+ if !ok || i+1 >= len(segs) {
+ continue
+ }
+ token := segs[i+1]
+ if token == "" {
+ continue
+ }
+ for _, r := range token {
+ if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r < '0' || r > '9') {
+ return pendingDocName{}, false
+ }
+ }
+ return pendingDocName{Token: token, DocType: docType, URL: u}, true
+ }
+ return pendingDocName{}, false
+}
+
+// escapeURL renders a Feishu-provided URL as a safe Markdown href. The docx
+// API percent-encodes link targets (e.g. http%3A%2F%2F...), so that encoding
+// is reversed first — a value that does not decode cleanly passes through
+// untouched — and only then are characters that would break the inline-link
+// syntax re-escaped.
+func escapeURL(u string) string {
+ if d, err := url.PathUnescape(u); err == nil {
+ u = d
+ }
+ r := strings.NewReplacer(" ", "%20", ")", "%29", "(", "%28")
+ return r.Replace(u)
+}
+
+func (r *mdRenderer) richText(bt *BlockText) string {
+ if bt == nil {
+ return ""
+ }
+ var sb strings.Builder
+ for _, e := range bt.Elements {
+ switch {
+ case e.TextRun != nil:
+ sb.WriteString(styleRun(e.TextRun.Content, e.TextRun.TextElementStyle))
+ case e.MentionDoc != nil && e.MentionDoc.URL != "":
+ // The payload carries no document title. Feishu doc URLs emit a
+ // title placeholder that FetchDocxWithBlocks backfills via the
+ // drive metadata API; anything else keeps the URL as link text.
+ u := e.MentionDoc.URL
+ if ref, ok := parseMentionDocRef(u); ok {
+ if r.docNameSeen == nil {
+ r.docNameSeen = map[string]bool{}
+ }
+ if !r.docNameSeen[ref.Token] {
+ r.docNameSeen[ref.Token] = true
+ r.docNames = append(r.docNames, ref)
+ }
+ sb.WriteString("[weknora-docname://" + ref.Token + "](" + escapeURL(u) + ")")
+ } else {
+ sb.WriteString("[" + u + "](" + escapeURL(u) + ")")
+ }
+ case e.MentionUser != nil:
+ // The API carries only the user OpenID; the caller-supplied
+ // resolver (cached, degrading) turns it into a display name when
+ // it can. Unresolved → generic @成员, never an error.
+ if name := r.userName(e.MentionUser.UserID); name != "" {
+ sb.WriteString("@" + name)
+ } else {
+ sb.WriteString("@成员")
+ }
+ case e.Equation != nil && strings.TrimSpace(e.Equation.Content) != "":
+ sb.WriteString("$" + strings.TrimSpace(e.Equation.Content) + "$")
+ }
+ }
+ return sb.String()
+}
+
+// styleRun wraps a text run in the GFM markers of its inline style.
+func styleRun(content string, st *TextElementStyle) string {
+ if content == "" {
+ return ""
+ }
+ if st == nil {
+ return content
+ }
+ if st.InlineCode {
+ content = "`" + content + "`"
+ }
+ if st.Bold {
+ content = "**" + content + "**"
+ }
+ if st.Italic {
+ content = "*" + content + "*"
+ }
+ if st.Strikethrough {
+ content = "~~" + content + "~~"
+ }
+ if st.Link != nil && st.Link.URL != "" {
+ content = "[" + content + "](" + escapeURL(st.Link.URL) + ")"
+ }
+ return content
+}
+
+// gfmCodeLanguages maps the Feishu CodeLanguage enum (1-75, official docx-v1
+// docs) to GFM fence info strings. 1 (PlainText) and unknown values render an
+// untagged fence.
+var gfmCodeLanguages = map[int]string{
+ 2: "abap", 3: "ada", 4: "apache", 5: "apex", 6: "asm", 7: "bash",
+ 8: "c#", 9: "cpp", 10: "c", 11: "cobol", 12: "css", 13: "coffeescript",
+ 14: "d", 15: "dart", 16: "delphi", 17: "django", 18: "dockerfile",
+ 19: "erlang", 20: "fortran", 21: "foxpro", 22: "go", 23: "groovy",
+ 24: "html", 25: "htmlbars", 26: "http", 27: "haskell", 28: "json",
+ 29: "java", 30: "javascript", 31: "julia", 32: "kotlin", 33: "latex",
+ 34: "lisp", 35: "logo", 36: "lua", 37: "matlab", 38: "makefile",
+ 39: "markdown", 40: "nginx", 41: "objective-c", 42: "openedgeabl",
+ 43: "php", 44: "perl", 45: "postscript", 46: "powershell", 47: "prolog",
+ 48: "protobuf", 49: "python", 50: "r", 51: "rpg", 52: "ruby", 53: "rust",
+ 54: "sas", 55: "scss", 56: "sql", 57: "scala", 58: "scheme", 59: "scratch",
+ 60: "shell", 61: "swift", 62: "thrift", 63: "typescript", 64: "vbscript",
+ 65: "vb", 66: "xml", 67: "yaml", 68: "cmake", 69: "diff", 70: "gherkin",
+ 71: "graphql", 72: "glsl", 73: "properties", 74: "solidity", 75: "toml",
+}
+
+// renderCode renders a code block, tagging the fence with the GFM alias of the
+// block's CodeLanguage when one is known. The fence grows past any backtick
+// run inside the content so a line of ``` in the code cannot close it early.
+func (r *mdRenderer) renderCode(b DocxBlock) string {
+ lang := ""
+ if b.Code != nil && b.Code.Style != nil {
+ lang = gfmCodeLanguages[b.Code.Style.Language]
+ }
+ content := r.richText(b.Code)
+ n := codeFenceLength(content)
+ open := strings.Repeat("`", n)
+ if lang != "" {
+ open += lang
+ }
+ // CommonMark: the closing fence carries no info string — reusing the
+ // opening fence (with language) would leave the block unterminated.
+ return open + "\n" + content + "\n" + strings.Repeat("`", n)
+}
+
+// codeFenceLength returns a fence length strictly longer than the longest
+// leading backtick run on any content line (≥3), per the CommonMark fencing rule.
+func codeFenceLength(content string) int {
+ longest := 2
+ for _, line := range strings.Split(content, "\n") {
+ n := 0
+ for n < len(line) && line[n] == '`' {
+ n++
+ }
+ if n > longest {
+ longest = n
+ }
+ }
+ return longest + 1
+}
+
+// blockTypeNames maps docx block types this converter does not unpack to their
+// names, for the degraded placeholder line. Board (43) is only reached here when
+// its block carries no token (the token case rides the image pipeline);
+// mindnote (29) has no content API at all (token-only placeholder per Feishu
+// docs).
+var blockTypeNames = map[int]string{
+ BlockTypeChatCard: "会话卡片",
+ BlockTypeDiagram: "流程图&UML",
+ BlockTypeGridColumn: "分栏列",
+ BlockTypeISV: "开放平台小组件",
+ BlockTypeMindnote: "思维笔记",
+ BlockTypeTask: "任务",
+ BlockTypeOKR: "OKR",
+ BlockTypeOKRObjective: "OKR目标",
+ BlockTypeOKRKeyResult: "OKR关键结果",
+ BlockTypeOKRProgress: "OKR进展",
+ BlockTypeAddOns: "文档小组件",
+ BlockTypeJiraIssue: "Jira问题",
+ BlockTypeWikiCatalog: "Wiki子页面列表",
+ BlockTypeBoard: "画板",
+ BlockTypeAgenda: "议程",
+ BlockTypeAgendaItem: "议程项",
+ BlockTypeAgendaItemTitle: "议程项标题",
+ BlockTypeAgendaItemContent: "议程项内容",
+ BlockTypeLinkPreview: "链接预览",
+ BlockTypeSourceSynced: "源同步块",
+ BlockTypeReferenceSynced: "引用同步块",
+ BlockTypeSubPageList: "Wiki子页面列表(新版)",
+ BlockTypeAITemplate: "AI模板",
+}
+
+// unsupportedBlockNote renders the degraded placeholder for a block type this
+// converter does not unpack. Tokens are never included (no-leak constraint).
+func unsupportedBlockNote(b DocxBlock) string {
+ if name, ok := blockTypeNames[b.BlockType]; ok {
+ return "> [飞书块: " + name + "]"
+ }
+ return fmt.Sprintf("> [飞书块: 未知类型(%d)]", b.BlockType)
+}
+
// headingText returns the heading field for the block's level, or Text as fallback.
func headingText(b DocxBlock) *BlockText {
fields := []*BlockText{
@@ -156,7 +711,7 @@ func tableDescendants(blocks []DocxBlock, byID map[string]DocxBlock) map[string]
// Attachment/media blocks nested in a cell must still be collected (and
// their reference emitted) by the main loop — the table renderer only
// extracts text — so do not consume them, only their text structure.
- if b.BlockType == BlockTypeFile || b.BlockType == BlockTypeImage {
+ if b.BlockType == BlockTypeFile || b.BlockType == BlockTypeImage || b.BlockType == BlockTypeBoard {
return
}
consumed[id] = true
@@ -183,7 +738,7 @@ func tableDescendants(blocks []DocxBlock, byID map[string]DocxBlock) map[string]
// single predicate shared by the consume pass and the render pass so the two
// never disagree about which tables are handled by the table renderer.
func tableRenderable(b DocxBlock) bool {
- return b.Table != nil && b.Table.Property != nil && b.Table.Property.ColumnSize > 0
+ return b.Table != nil && b.Table.Property != nil && b.Table.Property.ColumnSize > 0 && len(b.Table.Cells) > 0
}
// textBearingField returns the inline-text payload for whichever type-named
@@ -212,17 +767,24 @@ func textBearingField(b DocxBlock) *BlockText {
return b.Text
}
-// cellText renders a native table cell to a single string. A Feishu table_cell
+// cellTextAndAlign renders a native table cell to a single string and reports
+// the cell's column alignment (0 when default). A Feishu table_cell
// (block_type 32) is a container: its text lives in child blocks, not on the
-// cell itself, so we concatenate the text of each child block.
-func cellText(cell DocxBlock, byID map[string]DocxBlock) string {
+// cell itself, so we concatenate the text of each child block; the first child
+// carrying an explicit style alignment (2 center / 3 right) wins.
+func cellTextAndAlign(cell DocxBlock, byID map[string]DocxBlock) (string, int) {
var parts []string
+ align := 0
for _, childID := range cell.Children {
- if t := plainText(textBearingField(byID[childID])); t != "" {
+ child := byID[childID]
+ if t := plainText(textBearingField(child)); t != "" {
parts = append(parts, t)
}
+ if align == 0 && child.Text != nil && child.Text.Style != nil && child.Text.Style.Align != 0 {
+ align = child.Text.Style.Align
+ }
}
- return strings.Join(parts, " ")
+ return strings.Join(parts, " "), align
}
// renderNativeTable renders a native docx table block into a Markdown table.
@@ -230,10 +792,17 @@ func renderNativeTable(b DocxBlock, byID map[string]DocxBlock) string {
if !tableRenderable(b) {
return ""
}
- cols := b.Table.Property.ColumnSize
+ // Remote metadata must not allocate more columns than the supplied cells.
+ // A truncated or malformed table can declare an arbitrarily large width.
+ cols := min(b.Table.Property.ColumnSize, len(b.Table.Cells))
var cells []string
- for _, cid := range b.Table.Cells {
- cells = append(cells, cellText(byID[cid], byID))
+ aligns := make([]int, cols)
+ for i, cid := range b.Table.Cells {
+ text, align := cellTextAndAlign(byID[cid], byID)
+ cells = append(cells, text)
+ if col := i % cols; align != 0 && aligns[col] == 0 {
+ aligns[col] = align
+ }
}
var rows [][]string
for i := 0; i < len(cells); i += cols {
@@ -243,21 +812,105 @@ func renderNativeTable(b DocxBlock, byID map[string]DocxBlock) string {
}
rows = append(rows, cells[i:end])
}
- return markdownTable(rows)
+ fillMergedCells(rows, cols, b.Table.Property.MergeInfo)
+ return markdownTable(rows, aligns)
+}
+
+// fillMergedCells propagates each merged region's top-left value into the cells
+// it covers — GFM has no row/col span, and dropping the covered cells' content
+// would lose text, so the anchor value fills them instead. merge_info entries
+// are parallel to the table's cells array; entries beyond the rendered grid are
+// ignored. (Embedded sheet merge ranges come from the v3 metadata API instead —
+// see fillSheetMerges; bitable has no merge concept.)
+func fillMergedCells(rows [][]string, cols int, merge []BlockTableMergeInfo) {
+ if cols <= 0 || len(merge) == 0 || len(rows) == 0 {
+ return
+ }
+
+ // Valid merged regions do not overlap. Bound total visits too, so repeated
+ // or overlapping malformed regions cannot turn the work quadratic.
+ remaining := 0
+ for _, row := range rows {
+ remaining += len(row)
+ }
+ for i, mi := range merge {
+ if mi.RowSpan <= 1 && mi.ColSpan <= 1 {
+ continue
+ }
+ r0, c0 := i/cols, i%cols
+ if r0 >= len(rows) || c0 >= len(rows[r0]) {
+ continue
+ }
+ v := rows[r0][c0]
+ // Bound work before iterating or adding spans, not inside the loops:
+ // oversized metadata must neither overflow indices nor consume CPU
+ // proportional to cells that are not present in the rendered table.
+ for dr := range min(mi.RowSpan, len(rows)-r0) {
+ rr := r0 + dr
+ for dc := range min(mi.ColSpan, len(rows[rr])-c0) {
+ if remaining == 0 {
+ return
+ }
+ remaining--
+ if dr != 0 || dc != 0 {
+ rows[rr][c0+dc] = v
+ }
+ }
+ }
+ }
+}
+
+// fillSheetMerges propagates each embedded-sheet merged region's top-left value
+// across the whole region — same GFM-no-span rationale as fillMergedCells. The
+// v3 metadata API reports 0-based CLOSED intervals [start..end]; regions beyond
+// the rendered (row-capped) grid are clamped or skipped. If a real-world check
+// shows one cell too many per region, the intervals are half-open — switch
+// `i <= endRow` / `j <= endCol` to `<`.
+func fillSheetMerges(rows [][]string, merges []sheetMergeRange) {
+ for _, m := range merges {
+ startRow, startCol := int(m.StartRow), int(m.StartCol)
+ if startRow < 0 || startRow >= len(rows) || startCol < 0 || startCol >= len(rows[startRow]) {
+ continue
+ }
+ anchor := rows[startRow][startCol]
+ endRow := min(int(m.EndRow), len(rows)-1)
+ for i := startRow; i <= endRow; i++ {
+ endCol := min(int(m.EndCol), len(rows[i])-1)
+ for j := startCol; j <= endCol; j++ {
+ rows[i][j] = anchor
+ }
+ }
+ }
}
// markdownTable renders a [][]string (first row = header) as a GFM table.
-func markdownTable(rows [][]string) string {
+// aligns carries per-column alignment (0/1 left, 2 center, 3 right — the docx
+// style.align values) rendered as GFM colons; nil or zero entries yield the
+// plain left-aligned separator.
+func markdownTable(rows [][]string, aligns []int) string {
// A zero-column header (an embedded sheet/bitable with no columns) would Emit
// a header line of "| |" and a separator of just "|" — malformed GFM. Render
// nothing instead.
if len(rows) == 0 || len(rows[0]) == 0 {
return ""
}
+ sep := func(col int) string {
+ switch {
+ case col < len(aligns) && aligns[col] == 2:
+ return ":---:"
+ case col < len(aligns) && aligns[col] == 3:
+ return "---:"
+ default:
+ return "---"
+ }
+ }
var sb strings.Builder
cols := len(rows[0])
- sb.WriteString("| " + strings.Join(escapePipes(rows[0]), " | ") + " |\n")
- sb.WriteString("|" + strings.Repeat(" --- |", cols) + "\n")
+ sb.WriteString("| " + strings.Join(escapePipes(rows[0]), " | ") + " |\n|")
+ for c := range cols {
+ sb.WriteString(" " + sep(c) + " |")
+ }
+ sb.WriteString("\n")
for _, r := range rows[1:] {
// Ragged data: a row wider than the header would Emit more cells than the
// header/separator declare, producing a malformed GFM table. Clamp to the
@@ -273,6 +926,59 @@ func markdownTable(rows [][]string) string {
return strings.TrimRight(sb.String(), "\n")
}
+// addOnsTimelineTypeID is the component_type_id of the timeline 文档小组件.
+// Add-on blocks are client-rendered from their inline `record` JSON — there
+// is no server asset to download — so recognized types degrade to structured
+// Markdown.
+const addOnsTimelineTypeID = "blk_6358a421bca0001c22536e4c"
+
+type addOnsTimelineRecord struct {
+ ContentShow struct {
+ Text bool `json:"text"`
+ Time bool `json:"time"`
+ Title bool `json:"title"`
+ } `json:"contentShow"`
+ Items []struct {
+ Text string `json:"text"`
+ Time string `json:"time"`
+ Title string `json:"title"`
+ } `json:"items"`
+}
+
+// renderTimelineAddOn renders a timeline widget's record as a Markdown list:
+// `- **time · title**:text`, omitting the segments the widget hides
+// (contentShow) or that are empty. Returns "" for malformed or empty records
+// (the caller falls back to the placeholder note).
+func renderTimelineAddOn(record string) string {
+ var rec addOnsTimelineRecord
+ if json.Unmarshal([]byte(record), &rec) != nil || len(rec.Items) == 0 {
+ return ""
+ }
+ lines := make([]string, 0, len(rec.Items))
+ for _, it := range rec.Items {
+ var head []string
+ if rec.ContentShow.Time && it.Time != "" {
+ head = append(head, it.Time)
+ }
+ if rec.ContentShow.Title && it.Title != "" {
+ head = append(head, it.Title)
+ }
+ line := "-"
+ if len(head) > 0 {
+ line = "- **" + strings.Join(head, " · ") + "**"
+ }
+ if rec.ContentShow.Text && it.Text != "" {
+ if len(head) > 0 {
+ line += ":" + it.Text
+ } else {
+ line += " " + it.Text
+ }
+ }
+ lines = append(lines, line)
+ }
+ return strings.Join(lines, "\n\n")
+}
+
// escapePipes makes cell values safe for a single Markdown table row.
func escapePipes(row []string) []string {
out := make([]string, len(row))
@@ -306,10 +1012,18 @@ func inlineTable(ctx context.Context, client sheetReader, token, kind string) st
if err != nil {
return fmt.Sprintf("> [无法读取%s]", noun)
}
+ // Embedded sheets (unlike native tables) only expose merge regions through
+ // the v3 metadata API; fetch them for the fill below. A failure degrades to
+ // the raw values — merge info is cosmetic. Bitable has no merge concept.
+ if kind == "sheet" {
+ if merges, merr := client.sheetMerges(ctx, token); merr == nil && len(merges) > 0 {
+ fillSheetMerges(rows, merges)
+ }
+ }
// markdownTable returns "" when there is nothing renderable (no rows, or a
// header with no columns). Skip the truncation note too in that case, since it
// would otherwise dangle without a table above it.
- table := markdownTable(rows)
+ table := markdownTable(rows, nil) // sheet/bitable values carry no alignment
if table == "" {
return ""
}
diff --git a/internal/datasource/connector/feishu/core/markdown_bounds_test.go b/internal/datasource/connector/feishu/core/markdown_bounds_test.go
new file mode 100644
index 000000000..dfd8717c9
--- /dev/null
+++ b/internal/datasource/connector/feishu/core/markdown_bounds_test.go
@@ -0,0 +1,33 @@
+package core
+
+import (
+ "math"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestNativeTableBoundsUntrustedColumnCount(t *testing.T) {
+ block := DocxBlock{BlockType: BlockTypeTable, Table: &BlockTable{
+ Cells: []string{"cell"}, Property: &BlockTableProperty{ColumnSize: math.MaxInt},
+ }}
+ byID := map[string]DocxBlock{
+ "cell": {BlockID: "cell", Children: []string{"text"}},
+ "text": {BlockID: "text", BlockType: BlockTypeText, Text: txt("kept")},
+ }
+ require.NotPanics(t, func() { require.Contains(t, renderNativeTable(block, byID), "kept") })
+ block.Table.Cells = nil
+ require.NotPanics(t, func() { require.Empty(t, renderNativeTable(block, byID)) })
+}
+
+func TestNativeTableBoundsMergedRegions(t *testing.T) {
+ rows := [][]string{{"anchor", ""}, {""}, {"", ""}}
+ fillMergedCells(rows, 2, []BlockTableMergeInfo{{RowSpan: math.MaxInt, ColSpan: math.MaxInt}})
+ require.Equal(t, [][]string{{"anchor", "anchor"}, {"anchor"}, {"anchor", "anchor"}}, rows)
+ // A merge entry beyond the supplied cells cannot index or iterate an absent row.
+ fillMergedCells(rows, 2, []BlockTableMergeInfo{
+ {}, {}, {}, {}, {}, {}, {RowSpan: math.MaxInt, ColSpan: math.MaxInt},
+ })
+ require.Equal(t, "anchor", rows[0][0])
+ require.NotPanics(t, func() { fillMergedCells(rows, 0, []BlockTableMergeInfo{{RowSpan: 2, ColSpan: 2}}) })
+}
diff --git a/internal/datasource/connector/feishu/core/markdown_nested_test.go b/internal/datasource/connector/feishu/core/markdown_nested_test.go
new file mode 100644
index 000000000..85d7ff480
--- /dev/null
+++ b/internal/datasource/connector/feishu/core/markdown_nested_test.go
@@ -0,0 +1,130 @@
+package core
+
+import (
+ "bytes"
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestContainerPreservesNestedListContent(t *testing.T) {
+ for _, kind := range []int{BlockTypeCallout, BlockTypeQuoteContainer, BlockTypeGrid, BlockTypeView} {
+ t.Run(blockNameForTest(kind), func(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "container", BlockType: kind, Children: []string{"list"}},
+ {
+ BlockID: "list", ParentID: "container", BlockType: BlockTypeBullet,
+ Bullet: txt("parent"), Children: []string{"nested"},
+ },
+ {
+ BlockID: "nested", ParentID: "list", BlockType: BlockTypeOrdered,
+ Ordered: txt("nested"), Children: []string{"text", "image", "file"},
+ },
+ {BlockID: "text", ParentID: "nested", BlockType: BlockTypeText, Text: txt("important nested content")},
+ {BlockID: "image", ParentID: "nested", BlockType: BlockTypeImage, Image: &BlockTokenRef{Token: "img"}},
+ {
+ BlockID: "file", ParentID: "nested", BlockType: BlockTypeFile,
+ File: &BlockFileRef{Token: "pdf", Name: "report.pdf"},
+ },
+ }
+ if kind == BlockTypeGrid {
+ blocks[0].Children = []string{"column"}
+ blocks = append(blocks, DocxBlock{
+ BlockID: "column", BlockType: BlockTypeGridColumn, Children: []string{"list"},
+ })
+ }
+ md, atts, imgs, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ require.NoError(t, err)
+ for _, text := range []string{"parent", "nested content", "weknora-att://pdf", "weknora-img://"} {
+ require.Equal(t, 1, strings.Count(string(md), text), "content must appear exactly once: %s", md)
+ }
+ require.Len(t, atts, 1)
+ require.Len(t, imgs, 1)
+ require.Contains(t, string(md), " 1. nested")
+ })
+ }
+}
+
+func blockNameForTest(kind int) string {
+ switch kind {
+ case BlockTypeCallout:
+ return "callout"
+ case BlockTypeQuoteContainer:
+ return "quote"
+ case BlockTypeGrid:
+ return "grid"
+ default:
+ return "view"
+ }
+}
+
+func TestContainerNestedOrderedListKeepsParentSequence(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "container", BlockType: BlockTypeView, Children: []string{"first", "second"}},
+ {
+ BlockID: "first", ParentID: "container", BlockType: BlockTypeOrdered,
+ Ordered: txt("parent one"), Children: []string{"nested"},
+ },
+ {BlockID: "nested", ParentID: "first", BlockType: BlockTypeOrdered, Ordered: txt("child one")},
+ {BlockID: "second", ParentID: "container", BlockType: BlockTypeOrdered, Ordered: txt("parent two")},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ require.NoError(t, err)
+ require.Contains(t, string(md), "1. parent one\n\n 1. child one\n2. parent two")
+}
+
+func TestBoardInNativeTableIsDownloaded(t *testing.T) {
+ for _, inContainer := range []bool{false, true} {
+ t.Run(map[bool]string{false: "table", true: "table in callout"}[inContainer], func(t *testing.T) {
+ blocks := []DocxBlock{
+ {
+ BlockID: "table", BlockType: BlockTypeTable, Children: []string{"cell"},
+ Table: &BlockTable{Cells: []string{"cell"}, Property: &BlockTableProperty{ColumnSize: 1}},
+ },
+ {BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"text", "board"}},
+ {BlockID: "text", BlockType: BlockTypeText, Text: txt("board caption")},
+ {BlockID: "board", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-1"}},
+ }
+ if inContainer {
+ blocks = append([]DocxBlock{
+ {BlockID: "callout", BlockType: BlockTypeCallout, Children: []string{"table"}},
+ }, blocks...)
+ }
+ png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), MinAttachmentBytes)...)
+ server := fakeFeishuForBoard(t, blocks, http.StatusOK, png)
+ client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: server.URL})
+ items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
+ require.NoError(t, err)
+ require.Len(t, items, 1)
+ md := string(items[0].Content)
+ require.Equal(t, 1, strings.Count(md, "data:image/png;base64,"))
+ require.Equal(t, 1, strings.Count(md, "board caption"))
+ require.NotContains(t, md, "weknora-img://")
+ })
+ }
+}
+
+func TestContainerPreservesMalformedTableChildren(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "view", BlockType: BlockTypeView, Children: []string{"table"}},
+ {BlockID: "table", BlockType: BlockTypeTable, Children: []string{"cell"}},
+ {BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"text"}},
+ {BlockID: "text", BlockType: BlockTypeText, Text: txt("retained content")},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ require.NoError(t, err)
+ require.Equal(t, 1, strings.Count(string(md), "retained content"))
+}
+
+func TestContainerCyclicChildrenTerminate(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "view", BlockType: BlockTypeView, Children: []string{"list"}},
+ {BlockID: "list", BlockType: BlockTypeBullet, Bullet: txt("cyclic content"), Children: []string{"list"}},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ require.NoError(t, err)
+ require.Equal(t, 1, strings.Count(string(md), "cyclic content"))
+}
diff --git a/internal/datasource/connector/feishu/core/markdown_test.go b/internal/datasource/connector/feishu/core/markdown_test.go
index 579ec8020..c049be811 100644
--- a/internal/datasource/connector/feishu/core/markdown_test.go
+++ b/internal/datasource/connector/feishu/core/markdown_test.go
@@ -3,6 +3,7 @@ package core
import (
"context"
"fmt"
+ "strconv"
"strings"
"testing"
)
@@ -16,6 +17,8 @@ type fakeReader struct {
sheet [][]string
sheetTruncated bool
sheetErr error
+ merges []sheetMergeRange
+ sheetMergesErr error
bitable [][]string
bitableTruncated bool
bitableErr error
@@ -29,6 +32,10 @@ func (f fakeReader) readBitableRecords(_ context.Context, _ string) ([][]string,
return f.bitable, f.bitableTruncated, f.bitableErr
}
+func (f fakeReader) sheetMerges(_ context.Context, _ string) ([]sheetMergeRange, error) {
+ return f.merges, f.sheetMergesErr
+}
+
func TestBlocksToMarkdown_EmbeddedSheetAndFile(t *testing.T) {
blocks := []DocxBlock{
{BlockID: "root", BlockType: BlockTypePage},
@@ -37,15 +44,18 @@ func TestBlocksToMarkdown_EmbeddedSheetAndFile(t *testing.T) {
{BlockID: "f", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "file_t", Name: "报表.pdf"}},
}
fr := fakeReader{sheet: [][]string{{"名称", "数量"}, {"苹果", "3"}}}
- md, atts, err := blocksToMarkdown(context.Background(), fr, blocks)
+ md, atts, imgs, _, err := blocksToMarkdown(context.Background(), fr, blocks, "", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if !strings.Contains(string(md), "| 名称 | 数量 |") || !strings.Contains(string(md), "| 苹果 | 3 |") {
t.Errorf("sheet not inlined:\n%s", md)
}
- if !strings.Contains(string(md), "![图片]()") {
- t.Errorf("image placeholder missing:\n%s", md)
+ if !strings.Contains(string(md), fmt.Sprintf("![图片](weknora-img://1-%s)", imageMarkerNonce(""))) {
+ t.Errorf("numbered image marker missing:\n%s", md)
+ }
+ if len(imgs) != 1 || imgs[0].N != 1 || imgs[0].Kind != "image" || imgs[0].Token != "img_t" {
+ t.Errorf("pendingImages = %+v", imgs)
}
if strings.Contains(string(md), "feishu-media") {
t.Errorf("internal media token leaked into markdown:\n%s", md)
@@ -53,8 +63,64 @@ func TestBlocksToMarkdown_EmbeddedSheetAndFile(t *testing.T) {
if len(atts) != 1 || atts[0].FileToken != "file_t" || atts[0].Name != "报表.pdf" {
t.Errorf("attachments = %+v", atts)
}
- if !strings.Contains(string(md), "📎 附件:报表.pdf") {
- t.Errorf("attachment inline reference missing:\n%s", md)
+ if !strings.Contains(string(md), "- weknora-att://file_t") {
+ t.Errorf("attachment marker line missing:\n%s", md)
+ }
+}
+
+func TestBlocksToMarkdown_SheetMergesFilled(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "s", BlockType: BlockTypeSheet, Sheet: &BlockTokenRef{Token: "sht_a_0"}},
+ }
+ // 3x3 grid: B1:rule merged region spanning rows 0-1 col 1, and the whole
+ // bottom row merged across cols 0-2. Indices are 0-based CLOSED.
+ sheet := [][]string{
+ {"名称", "分类", "备注"},
+ {"苹果", "水果", ""},
+ {"香蕉", "", ""},
+ }
+ fr := fakeReader{
+ sheet: sheet,
+ merges: []sheetMergeRange{
+ {StartRow: 0, EndRow: 1, StartCol: 1, EndCol: 1}, // 分类 covers rows 0-1
+ {StartRow: 2, EndRow: 2, StartCol: 0, EndCol: 2}, // bottom row merged
+ },
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), fr, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ for _, want := range []string{
+ "| 名称 | 分类 | 备注 |",
+ // 分类 is the merged region's anchor and fills the covered cell below.
+ "| 苹果 | 分类 | |",
+ // Bottom row: the anchor value fills the whole merged region.
+ "| 香蕉 | 香蕉 | 香蕉 |",
+ } {
+ if !strings.Contains(s, want) {
+ t.Errorf("merged sheet table missing %q:\n%s", want, s)
+ }
+ }
+}
+
+func TestBlocksToMarkdown_SheetMergeFetchFailureDegrades(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "s", BlockType: BlockTypeSheet, Sheet: &BlockTokenRef{Token: "sht_a_0"}},
+ }
+ fr := fakeReader{
+ sheet: [][]string{{"名称", "数量"}, {"苹果", "3"}},
+ merges: nil,
+ sheetMergesErr: fmt.Errorf("permission denied"),
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), fr, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("merge fetch failure must not fail the document, got: %v", err)
+ }
+ if !strings.Contains(string(md), "| 苹果 | 3 |") {
+ t.Errorf("raw values must survive merge fetch failure:\n%s", md)
}
}
@@ -64,7 +130,7 @@ func TestBlocksToMarkdown_SheetTruncatedNote(t *testing.T) {
{BlockID: "s", BlockType: BlockTypeSheet, Sheet: &BlockTokenRef{Token: "sht_a_0"}},
}
fr := fakeReader{sheet: [][]string{{"h"}, {"1"}}, sheetTruncated: true}
- md, _, err := blocksToMarkdown(context.Background(), fr, blocks)
+ md, _, _, _, err := blocksToMarkdown(context.Background(), fr, blocks, "", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
@@ -79,7 +145,7 @@ func TestBlocksToMarkdown_SheetPermissionDegrades(t *testing.T) {
{BlockID: "s", BlockType: BlockTypeSheet, Sheet: &BlockTokenRef{Token: "sht_a_0"}},
}
fr := fakeReader{sheetErr: fmt.Errorf("code=99991672 permission denied")}
- md, _, err := blocksToMarkdown(context.Background(), fr, blocks)
+ md, _, _, _, err := blocksToMarkdown(context.Background(), fr, blocks, "", nil)
if err != nil {
t.Fatalf("should not fail on permission error, got %v", err)
}
@@ -94,7 +160,7 @@ func TestBlocksToMarkdown_BitableInlinedAndDegrades(t *testing.T) {
{BlockID: "root", BlockType: BlockTypePage},
{BlockID: "bt", BlockType: BlockTypeBitable, Bitable: &BlockTokenRef{Token: "bascabc_tblxyz"}},
}
- md, _, err := blocksToMarkdown(context.Background(), fr, blocks)
+ md, _, _, _, err := blocksToMarkdown(context.Background(), fr, blocks, "", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
@@ -123,7 +189,7 @@ func TestBlocksToMarkdown_NativeTableFromCellChildren(t *testing.T) {
cellTextBlk("c1", "姓名"), cellTextBlk("c2", "分数"),
cellTextBlk("c3", "张三"), cellTextBlk("c4", "95"),
}
- md, _, err := blocksToMarkdown(context.Background(), nil, blocks)
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
@@ -147,7 +213,7 @@ func TestBlocksToMarkdown_AttachmentInsideTableCellStillCollected(t *testing.T)
{BlockID: "c1", BlockType: BlockTypeTableCell, Children: []string{"f1"}},
{BlockID: "f1", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "tok-in-cell", Name: "内嵌.pdf"}},
}
- _, atts, err := blocksToMarkdown(context.Background(), nil, blocks)
+ _, atts, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
@@ -164,7 +230,7 @@ func TestMarkdownTable_RaggedRowClampedToHeader(t *testing.T) {
{"名称", "数量"},
{"苹果", "3", "多余1", "多余2"},
}
- out := markdownTable(rows)
+ out := markdownTable(rows, nil)
lines := strings.Split(out, "\n")
if len(lines) != 3 {
t.Fatalf("want 3 lines (header, separator, 1 row), got %d:\n%s", len(lines), out)
@@ -190,7 +256,7 @@ func TestMarkdownTable_ZeroColumnRendersNothing(t *testing.T) {
{{}}, // one empty header row, no data
{{}, {}, {}}, // empty header + empty data rows
} {
- out := markdownTable(rows)
+ out := markdownTable(rows, nil)
if out != "" {
t.Errorf("zero-column table must render nothing, got %q for rows=%+v", out, rows)
}
@@ -209,7 +275,7 @@ func TestBlocksToMarkdown_UnrenderableTablePreservesCellText(t *testing.T) {
{BlockID: "c1", BlockType: BlockTypeTableCell, Children: []string{"c1_txt"}},
cellTextBlk("c1", "重要内容"),
}
- md, _, err := blocksToMarkdown(context.Background(), nil, blocks)
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
@@ -225,7 +291,7 @@ func TestBlocksToMarkdown_TextConstructs(t *testing.T) {
{BlockID: "p", BlockType: BlockTypeText, Text: txt("一段正文")},
{BlockID: "b", BlockType: BlockTypeBullet, Bullet: txt("要点")},
}
- md, atts, err := blocksToMarkdown(context.Background(), nil, blocks)
+ md, atts, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatalf("blocksToMarkdown: %v", err)
}
@@ -249,7 +315,7 @@ func TestBlocksToMarkdown_BlankDocRendersEmpty(t *testing.T) {
{BlockID: "root", BlockType: BlockTypePage, Children: []string{"p"}},
{BlockID: "p", BlockType: BlockTypeText, Text: txt("")},
}
- md, atts, err := blocksToMarkdown(context.Background(), nil, blocks)
+ md, atts, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatalf("blocksToMarkdown: %v", err)
}
@@ -267,7 +333,7 @@ func TestBlocksToMarkdown_TodoAndCallout(t *testing.T) {
{BlockID: "t", BlockType: BlockTypeTodo, Todo: txt("买牛奶")},
{BlockID: "c", BlockType: BlockTypeCallout, Callout: txt("注意事项")},
}
- md, _, err := blocksToMarkdown(context.Background(), nil, blocks)
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
@@ -277,6 +343,19 @@ func TestBlocksToMarkdown_TodoAndCallout(t *testing.T) {
if !strings.Contains(string(md), "> 注意事项") {
t.Errorf("callout direct text not rendered:\n%s", md)
}
+ done := txt("已办结")
+ done.Style = &BlockTextStyle{Done: true}
+ blocks = []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "d", BlockType: BlockTypeTodo, Todo: done},
+ }
+ md, _, _, _, err = blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if !strings.Contains(string(md), "- [x] 已办结") {
+ t.Errorf("completed todo must render checked:\n%s", md)
+ }
}
func TestBlocksToMarkdown_CalloutContainerNoOp(t *testing.T) {
@@ -285,7 +364,7 @@ func TestBlocksToMarkdown_CalloutContainerNoOp(t *testing.T) {
{BlockID: "root", BlockType: BlockTypePage},
{BlockID: "c", BlockType: BlockTypeCallout},
}
- md, _, err := blocksToMarkdown(context.Background(), nil, blocks)
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
@@ -293,3 +372,695 @@ func TestBlocksToMarkdown_CalloutContainerNoOp(t *testing.T) {
t.Errorf("empty callout should Emit nothing, got:\n%q", md)
}
}
+
+func TestBlocksToMarkdown_CalloutQuotesChildren(t *testing.T) {
+ // A callout container renders its child blocks recursively with "> "
+ // prefixes — and must not also Emit them a second time as loose paragraphs.
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "c", BlockType: BlockTypeCallout, Children: []string{"h", "p"}},
+ {BlockID: "h", BlockType: 4, Heading2: txt("注意")},
+ {BlockID: "p", BlockType: BlockTypeText, Text: txt("正文内容")},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ if !strings.Contains(s, "> ## 注意") || !strings.Contains(s, "> 正文内容") {
+ t.Errorf("callout children not quoted:\n%s", s)
+ }
+ if n := strings.Count(s, "正文内容"); n != 1 {
+ t.Errorf("callout child duplicated (count=%d):\n%s", n, s)
+ }
+}
+
+func TestBlocksToMarkdown_QuoteContainerQuotesChildren(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "q", BlockType: BlockTypeQuoteContainer, Children: []string{"p"}},
+ {BlockID: "p", BlockType: BlockTypeText, Text: txt("引用内容")},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ if !strings.Contains(s, "> 引用内容") {
+ t.Errorf("quote_container children not quoted:\n%s", s)
+ }
+ if n := strings.Count(s, "引用内容"); n != 1 {
+ t.Errorf("quote_container child duplicated (count=%d):\n%s", n, s)
+ }
+}
+
+func TestBlocksToMarkdown_GridColumnsJoinedByRule(t *testing.T) {
+ // 分栏: each grid_column's content renders in column order, columns
+ // separated by ---, and nothing leaks out as stray paragraphs.
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {
+ BlockID: "g", BlockType: BlockTypeGrid,
+ Grid: &BlockGrid{ColumnSize: 2}, Children: []string{"c1", "c2"},
+ },
+ {
+ BlockID: "c1", BlockType: BlockTypeGridColumn,
+ GridColumn: &BlockGridColumn{WidthRatio: 50}, Children: []string{"p1"},
+ },
+ {
+ BlockID: "c2", BlockType: BlockTypeGridColumn,
+ GridColumn: &BlockGridColumn{WidthRatio: 50}, Children: []string{"p2"},
+ },
+ {BlockID: "p1", BlockType: BlockTypeText, Text: txt("左栏")},
+ {BlockID: "p2", BlockType: BlockTypeText, Text: txt("右栏")},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ want := "左栏\n\n---\n\n右栏"
+ if !strings.Contains(s, want) {
+ t.Errorf("grid columns not joined by ---, want substring %q, got:\n%s", want, s)
+ }
+ for _, p := range []string{"左栏", "右栏"} {
+ if n := strings.Count(s, p); n != 1 {
+ t.Errorf("grid column content %q duplicated (count=%d):\n%s", p, n, s)
+ }
+ }
+}
+
+func TestBlocksToMarkdown_IframeLink(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "f", BlockType: BlockTypeIframe, Iframe: &BlockIframe{
+ Component: &BlockIframeComponent{Type: 1, URL: "https://example.com/embed"},
+ }},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if !strings.Contains(string(md), "[内嵌网页](https://example.com/embed)") {
+ t.Errorf("iframe not rendered as link:\n%s", md)
+ }
+}
+
+func TestBlocksToMarkdown_UnsupportedBlocksPlaceholdersNoTokenLeak(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "mn", BlockType: BlockTypeMindnote, Mindnote: &BlockTokenRef{Token: "bmnbSECRET"}},
+ {BlockID: "bd", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brdSECRET"}},
+ {BlockID: "dg", BlockType: BlockTypeDiagram, Diagram: &BlockDiagram{DiagramType: 1}},
+ {BlockID: "cc", BlockType: BlockTypeChatCard, ChatCard: &BlockChatCard{ChatID: "oc_SECRET"}},
+ {BlockID: "jira", BlockType: BlockTypeJiraIssue, JiraIssue: &BlockJiraIssue{ID: "1", Key: "AB-1"}},
+ // view (33) is no longer a placeholder: an empty view emits nothing.
+ {BlockID: "v", BlockType: BlockTypeView},
+ {BlockID: "unk", BlockType: 999},
+ }
+ md, atts, imgs, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ for _, want := range []string{
+ "> [飞书块: 思维笔记]", "> [飞书块: 流程图&UML]",
+ "> [飞书块: 会话卡片]", "> [飞书块: Jira问题]", "> [飞书块: 未知类型(999)]",
+ } {
+ if !strings.Contains(s, want) {
+ t.Errorf("missing placeholder %q, got:\n%s", want, s)
+ }
+ }
+ // Removed from the placeholder set: view renders its children (none here).
+ if strings.Contains(s, "飞书块: 视图") {
+ t.Errorf("empty view must not emit a placeholder:\n%s", s)
+ }
+ // Board (43) now rides the image pipeline: a token-bearing board renders a
+ // numbered weknora-img:// marker and records a pendingImage for the
+ // connector's whiteboard download.
+ if !strings.Contains(s, fmt.Sprintf("![图片](weknora-img://1-%s)", imageMarkerNonce(""))) {
+ t.Errorf("board marker missing:\n%s", s)
+ }
+ if len(imgs) != 1 || imgs[0].Kind != "board" || imgs[0].Token != "brdSECRET" {
+ t.Errorf("pendingImages = %+v", imgs)
+ }
+ // No-leak: internal media tokens must never reach the markdown.
+ for _, tok := range []string{"SECRET", "bmnb", "brd", "oc_"} {
+ if strings.Contains(s, tok) {
+ t.Errorf("token fragment %q leaked into markdown:\n%s", tok, s)
+ }
+ }
+ if len(atts) != 0 {
+ t.Errorf("placeholders must not collect attachments, got %+v", atts)
+ }
+}
+
+// TestBlocksToMarkdown_ViewContainerRendersChildren anchors the view (33)
+// handling: the view is the file-list container seen in real smoke tests, so
+// its children (file blocks etc.) must render inline, exactly once, and an
+// empty view must contribute nothing — no `> [飞书块: 视图]` placeholder.
+func TestBlocksToMarkdown_ViewContainerRendersChildren(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "view", BlockType: BlockTypeView, Children: []string{"f1", "f2"}},
+ {BlockID: "f1", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "ftok1", Name: "报表.pdf"}},
+ {BlockID: "f2", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "ftok2", Name: "手册.pdf"}},
+ }
+ md, atts, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ if strings.Contains(s, "飞书块: 视图") {
+ t.Errorf("view must not render a placeholder:\n%s", s)
+ }
+ // Raw render emits unique per-token marker lines; FetchDocxWithBlocks
+ // patches them to the display names after the download attempt.
+ if n := strings.Count(s, "- weknora-att://ftok1"); n != 1 {
+ t.Errorf("file child rendered %d times, want exactly 1:\n%s", n, s)
+ }
+ if !strings.Contains(s, "- weknora-att://ftok1\n- weknora-att://ftok2") {
+ t.Errorf("view children not rendered as one list:\n%s", s)
+ }
+ if len(atts) != 2 {
+ t.Errorf("view children must still be collected as attachments, got %+v", atts)
+ }
+}
+
+func TestBlocksToMarkdown_RichTextElements(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "p", BlockType: BlockTypeText, Text: &BlockText{Elements: []TextElement{
+ {TextRun: &TextRun{Content: "加粗", TextElementStyle: &TextElementStyle{Bold: true}}},
+ {TextRun: &TextRun{Content: "code", TextElementStyle: &TextElementStyle{InlineCode: true}}},
+ {TextRun: &TextRun{
+ Content: "删除",
+ TextElementStyle: &TextElementStyle{Strikethrough: true, Italic: true},
+ }},
+ {TextRun: &TextRun{
+ Content: "链接",
+ TextElementStyle: &TextElementStyle{Link: &TextElementLink{URL: "https://x.cn"}},
+ }},
+ {MentionDoc: &MentionDoc{URL: "https://x.cn/doc"}},
+ {MentionUser: &MentionUser{UserID: "ou_1"}},
+ {Equation: &Equation{Content: "E=mc^2"}},
+ }}},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ for _, want := range []string{
+ "**加粗**", "`code`", "~~*删除*~~", "[链接](https://x.cn)",
+ "[https://x.cn/doc](https://x.cn/doc)", "@成员", "$E=mc^2$",
+ } {
+ if !strings.Contains(s, want) {
+ t.Errorf("missing rich text %q, got:\n%s", want, s)
+ }
+ }
+}
+
+func TestBlocksToMarkdown_CodeBlockLanguage(t *testing.T) {
+ mk := func(lang int) string {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {
+ BlockID: "c", BlockType: BlockTypeCode,
+ Code: &BlockText{
+ Style: &BlockTextStyle{Language: lang},
+ Elements: []TextElement{{TextRun: &TextRun{Content: "x"}}},
+ },
+ },
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ return string(md)
+ }
+ cases := map[int]string{
+ 22: "```go\nx\n```", // Go
+ 9: "```cpp\nx\n```", // C++
+ 8: "```c#\nx\n```", // CSharp
+ 46: "```powershell\nx\n```", // Power Shell
+ 1: "```\nx\n```", // PlainText → untagged
+ 99: "```\nx\n```", // unknown → untagged
+ }
+ for lang, want := range cases {
+ if got := mk(lang); !strings.Contains(got, want) {
+ t.Errorf("language %d: want %q in output, got:\n%s", lang, want, got)
+ }
+ }
+}
+
+// TestBlocksToMarkdown_CodeFenceClosingBare pins the CommonMark rule that the
+// closing fence carries no info string: reusing the tagged opening fence left
+// a final "```java" line and the block never terminated.
+func TestBlocksToMarkdown_CodeFenceClosingBare(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {
+ BlockID: "c", BlockType: BlockTypeCode,
+ Code: &BlockText{
+ Style: &BlockTextStyle{Language: 29},
+ Elements: []TextElement{{TextRun: &TextRun{Content: "System.out.print(1);"}}},
+ },
+ },
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if got, want := strings.TrimRight(string(md), "\n"), "```java\nSystem.out.print(1);\n```"; got != want {
+ t.Errorf("code block:\n got: %q\nwant: %q", got, want)
+ }
+}
+
+// TestBlocksToMarkdown_Heading7to9DegradeToBold pins the GFM cap: Feishu
+// heading7-9 render as bold text — a 7-hash "heading" is invalid GFM and
+// every renderer shows the raw hashes as literal text.
+func TestBlocksToMarkdown_Heading7to9DegradeToBold(t *testing.T) {
+ cases := map[int]string{
+ 9: "**七级**",
+ 10: "**八级**",
+ 11: "**九级**",
+ }
+ for bt, want := range cases {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "h", BlockType: bt, Text: txt(strings.Trim(want, "*"))},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("block %d: err: %v", bt, err)
+ }
+ if !strings.Contains(string(md), want) {
+ t.Errorf("block %d: want %q in output, got:\n%s", bt, want, md)
+ }
+ if strings.Contains(string(md), "#######") {
+ t.Errorf("block %d: emitted invalid 7-hash heading:\n%s", bt, md)
+ }
+ }
+}
+
+// TestBlocksToMarkdown_LinkURLPercentDecoded pins that the docx API's
+// percent-encoded link targets are reversed before markdown escaping:
+// "http%3A%2F%2Fwww.baidu.com" must render as a usable http:// URL.
+func TestBlocksToMarkdown_LinkURLPercentDecoded(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "p", BlockType: BlockTypeText, Text: &BlockText{
+ Elements: []TextElement{{TextRun: &TextRun{Content: "百度", TextElementStyle: &TextElementStyle{
+ Link: &TextElementLink{URL: "http%3A%2F%2Fwww.baidu.com"},
+ }}}},
+ }},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if !strings.Contains(string(md), "[百度](http://www.baidu.com)") {
+ t.Errorf("encoded URL not decoded, got:\n%s", md)
+ }
+}
+
+func TestBlocksToMarkdown_OrderedListRealSequence(t *testing.T) {
+ ord := func(seq string, content string) DocxBlock {
+ b := DocxBlock{BlockID: content, BlockType: BlockTypeOrdered}
+ b.Ordered = txt(content)
+ if seq != "" {
+ b.Ordered.Style = &BlockTextStyle{Sequence: seq}
+ }
+ return b
+ }
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ ord("1", "甲"), ord("auto", "乙"), ord("auto", "丙"),
+ {BlockID: "sep", BlockType: BlockTypeText, Text: txt("分隔")},
+ ord("5", "戊"), ord("auto", "己"),
+ ord("", "无序号"), ord("", "续"),
+ {BlockID: "sep2", BlockType: BlockTypeText, Text: txt("第二段")},
+ ord("", "新列表"),
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ for _, want := range []string{"1. 甲", "2. 乙", "3. 丙", "5. 戊", "6. 己", "7. 无序号", "8. 续", "1. 新列表"} {
+ if !strings.Contains(s, want) {
+ t.Errorf("missing ordered item %q, got:\n%s", want, s)
+ }
+ }
+}
+
+func TestBlocksToMarkdown_NativeTableMergedCellsFilled(t *testing.T) {
+ // merge_info[0] anchors at cell 0 with row_span=2, col_span=2: the anchor
+ // value must fill all four covered cells (GFM has no cell span).
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ tableBlk("t", 3, "c1", "c2", "c3", "c4", "c5", "c6"),
+ cellBlk("c1"), cellBlk("c2"), cellBlk("c3"),
+ cellBlk("c4"), cellBlk("c5"), cellBlk("c6"),
+ cellTextBlk("c1", "合并"), cellTextBlk("c2", ""), cellTextBlk("c3", "B"),
+ cellTextBlk("c4", "C"), cellTextBlk("c5", "D"), cellTextBlk("c6", "E"),
+ }
+ blocks[1].Table.Property.MergeInfo = []BlockTableMergeInfo{{RowSpan: 2, ColSpan: 2}}
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ // Cells covered by the merge (c2, c4, c5) take the anchor value; uncovered
+ // cells (c3=B, c6=E) keep their own.
+ if !strings.Contains(s, "| 合并 | 合并 | B |") || !strings.Contains(s, "| 合并 | 合并 | E |") {
+ t.Errorf("merged cells not filled with anchor value:\n%s", s)
+ }
+ if strings.Contains(s, "C") || strings.Contains(s, "D") {
+ t.Errorf("covered cells must show the anchor value, not their own:\n%s", s)
+ }
+}
+
+func TestBlocksToMarkdown_DocumentTruncationNote(t *testing.T) {
+ // A block array at the maxDocumentBlocks cap means listDocumentBlocks
+ // dropped content; the markdown must end with an explicit note (aligned
+ // with the embedded-table truncation note) instead of failing silently.
+ blocks := make([]DocxBlock, maxDocumentBlocks)
+ for i := range blocks {
+ blocks[i] = DocxBlock{BlockID: strconv.Itoa(i), BlockType: BlockTypeText, Text: txt("块")}
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if !strings.Contains(string(md), "文档已截断") {
+ t.Errorf("missing document truncation note:\n...%s", md[len(md)-200:])
+ }
+}
+
+func TestBlocksToMarkdown_ImageNumberingStableOrder(t *testing.T) {
+ // Marker sequence numbers must follow document order across image, board,
+ // and file blocks interleaved — shared.go fans sub-items out from the same
+ // pendingImage list, so renderer-side numbering is the single source of truth.
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "p", BlockType: BlockTypeText, Text: txt("引言")},
+ {BlockID: "i1", BlockType: BlockTypeImage, Image: &BlockTokenRef{Token: "tok-a"}},
+ {BlockID: "f1", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "ft-1", Name: "附录.pdf"}},
+ {BlockID: "i2", BlockType: BlockTypeImage, Image: &BlockTokenRef{Token: "tok-b"}},
+ {BlockID: "bd", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-9"}},
+ }
+ md, _, imgs, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ s := string(md)
+ nonce := imageMarkerNonce("")
+ for _, want := range []string{
+ fmt.Sprintf("![图片](weknora-img://1-%s)", nonce),
+ fmt.Sprintf("![图片](weknora-img://2-%s)", nonce),
+ fmt.Sprintf("![图片](weknora-img://3-%s)", nonce),
+ } {
+ if !strings.Contains(s, want) {
+ t.Errorf("marker %q missing:\n%s", want, s)
+ }
+ }
+ wantList := []pendingImage{
+ {N: 1, Kind: "image", Token: "tok-a"},
+ {N: 2, Kind: "image", Token: "tok-b"},
+ {N: 3, Kind: "board", Token: "brd-9"},
+ }
+ if len(imgs) != len(wantList) {
+ t.Fatalf("imgs = %+v, want %+v", imgs, wantList)
+ }
+ for i, w := range wantList {
+ if imgs[i] != w {
+ t.Errorf("imgs[%d] = %+v, want %+v", i, imgs[i], w)
+ }
+ }
+}
+
+func TestBlocksToMarkdown_LinkURLWithSpacesAndParens(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "p", BlockType: BlockTypeText, Text: &BlockText{
+ Elements: []TextElement{
+ {TextRun: &TextRun{Content: "文档", TextElementStyle: &TextElementStyle{
+ Link: &TextElementLink{URL: "https://example.com/a (1).pdf"},
+ }}},
+ },
+ }},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ // The rendered target must decode back to the original URL: a raw space or
+ // ")" would terminate the link target early.
+ if !strings.Contains(string(md), "](https://example.com/a%20%281%29.pdf)") &&
+ !strings.Contains(string(md), "](<https://example.com/a (1).pdf>)") {
+ t.Errorf("URL not escaped for Markdown:\n%s", md)
+ }
+}
+
+// TestBlocksToMarkdown_CodeFenceSurvivesBackticks pins fence sizing: code
+// content containing a ``` line must not close the fence early.
+func TestBlocksToMarkdown_CodeFenceSurvivesBackticks(t *testing.T) {
+ content := "x := 1\n```\nthis line must stay fenced"
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "code", BlockType: BlockTypeCode, Code: txt(content)},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ out := string(md)
+ if !strings.HasPrefix(out, "````\n") {
+ t.Errorf("fence must grow past the inner ``` run:\n%s", out)
+ }
+ if !strings.Contains(out, "this line must stay fenced\n````") {
+ t.Errorf("content after the inner ``` run leaked out of the fence:\n%s", out)
+ }
+}
+
+// TestBlocksToMarkdown_OrderedChildrenKeepNumbering pins the sibling-only
+// reset: child blocks between ordered items must not renumber an "auto" run.
+func TestBlocksToMarkdown_OrderedChildrenKeepNumbering(t *testing.T) {
+ child := txt("子项")
+ auto := func(id, parent string) DocxBlock {
+ b := DocxBlock{BlockID: id, ParentID: parent, BlockType: BlockTypeOrdered, Ordered: txt("项")}
+ b.Ordered.Style = &BlockTextStyle{Sequence: "auto"}
+ return b
+ }
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ auto("i1", "root"),
+ {BlockID: "c1", ParentID: "i1", BlockType: BlockTypeBullet, Bullet: child},
+ auto("i2", "root"),
+ {BlockID: "p", ParentID: "root", BlockType: BlockTypeText, Text: txt("正文")},
+ auto("i3", "root"),
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ out := string(md)
+ if !strings.Contains(out, "2. 项") {
+ t.Errorf("child block between items must not renumber the run:\n%s", out)
+ }
+ if strings.Contains(out, "3. 项") {
+ t.Errorf("run must not continue across the intervening paragraph:\n%s", out)
+ }
+ if !strings.Contains(out, "正文\n\n1. 项") {
+ t.Errorf("a top-level sibling must restart the numbering:\n%s", out)
+ }
+}
+
+// TestBlocksToMarkdown_TimelineAddOn pins the list-style degradation of the
+// timeline 文档小组件 (block_type 40): its record JSON carries the full data
+// inline, and the renderer must emit one bullet per item honoring contentShow.
+func TestBlocksToMarkdown_TimelineAddOn(t *testing.T) {
+ record := `{"blockId":"x","contentShow":{"text":true,"time":true,"title":true},` +
+ `"items":[{"id":"a","text":"1","time":"2026-09-19","title":"昨天"},` +
+ `{"id":"b","text":"2","time":"2026-09-20","title":"今天"},` +
+ `{"id":"c","text":"3","time":"2026-09-21","title":"明天"}],"mode":"horizontal_alternating"}`
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "tl", BlockType: BlockTypeAddOns, AddOns: &BlockAddOns{
+ ComponentTypeID: "blk_6358a421bca0001c22536e4c", Record: record,
+ }},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ for _, want := range []string{
+ "- **2026-09-19 · 昨天**:1",
+ "- **2026-09-20 · 今天**:2",
+ "- **2026-09-21 · 明天**:3",
+ } {
+ if !strings.Contains(string(md), want) {
+ t.Errorf("missing timeline line %q, got:\n%s", want, md)
+ }
+ }
+ if strings.Contains(string(md), "文档小组件") {
+ t.Errorf("timeline must not fall back to the placeholder, got:\n%s", md)
+ }
+}
+
+func TestBlocksToMarkdown_TimelineAddOnHiddenAndUnknown(t *testing.T) {
+ record := `{"contentShow":{"text":false,"time":true,"title":true},` +
+ `"items":[{"text":"1","time":"2026-09-19","title":"昨天"},{"text":"2","time":"","title":""}]}`
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "tl", BlockType: BlockTypeAddOns, AddOns: &BlockAddOns{
+ ComponentTypeID: "blk_6358a421bca0001c22536e4c", Record: record,
+ }},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if !strings.Contains(string(md), "- **2026-09-19 · 昨天**") {
+ t.Errorf("hidden text must be omitted, got:\n%s", md)
+ }
+ // Both head segments empty and text hidden → bare bullet.
+ if !strings.Contains(string(md), "-\n") && !strings.HasSuffix(strings.TrimRight(string(md), "\n"), "-") {
+ t.Errorf("bare bullet expected for empty item, got:\n%s", md)
+ }
+
+ // Unknown component type keeps the placeholder; malformed record too.
+ for _, rec := range []string{`{"items":broken`, ""} {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "tl", BlockType: BlockTypeAddOns, AddOns: &BlockAddOns{
+ ComponentTypeID: "blk_6358a421bca0001c22536e4c", Record: rec,
+ }},
+ }
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if !strings.Contains(string(md), "文档小组件") {
+ t.Errorf("malformed record must keep the placeholder, got:\n%s", md)
+ }
+ }
+ unknown := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "w", BlockType: BlockTypeAddOns, AddOns: &BlockAddOns{
+ ComponentTypeID: "blk_unknown", Record: `{"items":[]}`,
+ }},
+ }
+ md, _, _, _, err = blocksToMarkdown(context.Background(), nil, unknown, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if !strings.Contains(string(md), "文档小组件") {
+ t.Errorf("unknown component type must keep the placeholder, got:\n%s", md)
+ }
+}
+
+// TestMarkdownTable_ColumnAlignment pins the GFM colon rendering of the docx
+// style.align values (2 center / 3 right) in the separator row.
+func TestMarkdownTable_ColumnAlignment(t *testing.T) {
+ rows := [][]string{{"A", "B", "C"}, {"a", "b", "c"}}
+ out := markdownTable(rows, []int{0, 2, 3})
+ want := "| A | B | C |\n| --- | :---: | ---: |\n| a | b | c |"
+ if out != want {
+ t.Errorf("alignment separators:\n got: %q\nwant: %q", out, want)
+ }
+}
+
+func TestBlocksToMarkdown_TableCellAlignment(t *testing.T) {
+ // Column 2's cell text carries align=2 (center); column 3 align=3 (right).
+ mk := func(content string, align int) DocxBlock {
+ return DocxBlock{BlockID: content, BlockType: BlockTypeText, Text: &BlockText{
+ Elements: []TextElement{{TextRun: &TextRun{Content: content}}},
+ Style: &BlockTextStyle{Align: align},
+ }}
+ }
+ // Feishu's table.cells reference table_cell CONTAINER blocks (type 32);
+ // the text blocks hang off each cell's children.
+ texts := []DocxBlock{mk("h1", 0), mk("h2", 0), mk("h3", 0), mk("a", 0), mk("b", 2), mk("c", 3)}
+ var cells []string
+ var cellBlocks []DocxBlock
+ for _, tid := range []string{"h1", "h2", "h3", "a", "b", "c"} {
+ cid := "cell" + tid
+ cells = append(cells, cid)
+ cellBlocks = append(cellBlocks, DocxBlock{
+ BlockID: cid, BlockType: BlockTypeTableCell, Children: []string{tid},
+ })
+ }
+ table := DocxBlock{
+ BlockID: "t", BlockType: BlockTypeTable,
+ Table: &BlockTable{
+ Cells: cells,
+ Property: &BlockTableProperty{ColumnSize: 3},
+ },
+ }
+ root := DocxBlock{BlockID: "root", BlockType: BlockTypePage}
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil,
+ append([]DocxBlock{root, table}, append(cellBlocks, texts...)...), "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ out := string(md)
+ if !strings.Contains(out, "| --- | :---: | ---: |") {
+ t.Errorf("alignment not rendered, got:\n%s", out)
+ }
+}
+
+// TestParseMentionDocRef pins the Feishu URL → (token, doc_type) table used
+// for the 云文档 link-title backfill.
+func TestParseMentionDocRef(t *testing.T) {
+ cases := []struct {
+ url string
+ token string
+ docType string
+ ok bool
+ }{
+ {"https://my.feishu.cn/docx/MHU6d4eixo1UdCxNzGbcspVSnfg", "MHU6d4eixo1UdCxNzGbcspVSnfg", "docx", true},
+ {"https://x.feishu.cn/sheets/Abc123", "Abc123", "sheet", true},
+ {"https://x.feishu.cn/base/Tok01", "Tok01", "bitable", true},
+ {"https://x.feishu.cn/wiki/wik123", "wik123", "wiki", true},
+ {"https://www.baidu.com/s?wd=x", "", "", false},
+ {"https://x.cn/doc", "", "", false}, // type segment without token
+ {"https://x.feishu.cn/docx/not-a-token", "", "", false}, // dash = not a token
+ }
+ for _, c := range cases {
+ ref, ok := parseMentionDocRef(c.url)
+ if ok != c.ok {
+ t.Errorf("%s: ok=%v want %v", c.url, ok, c.ok)
+ continue
+ }
+ if ok && (ref.Token != c.token || ref.DocType != c.docType) {
+ t.Errorf("%s: got %s/%s want %s/%s", c.url, ref.Token, ref.DocType, c.token, c.docType)
+ }
+ }
+}
+
+// TestBlocksToMarkdown_MentionDocTitlePlaceholder pins the placeholder form
+// emitted for Feishu doc mention links (the connector backfills real titles).
+func TestBlocksToMarkdown_MentionDocTitlePlaceholder(t *testing.T) {
+ blocks := []DocxBlock{
+ {BlockID: "root", BlockType: BlockTypePage},
+ {BlockID: "p", BlockType: BlockTypeText, Text: &BlockText{
+ Elements: []TextElement{{MentionDoc: &MentionDoc{
+ URL: "https://my.feishu.cn/docx/MHU6d4eixo1UdCxNzGbcspVSnfg",
+ }}},
+ }},
+ }
+ md, _, _, docs, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ url := "https://my.feishu.cn/docx/MHU6d4eixo1UdCxNzGbcspVSnfg"
+ if !strings.Contains(string(md), "[weknora-docname://MHU6d4eixo1UdCxNzGbcspVSnfg]("+escapeURL(url)+")") {
+ t.Errorf("title placeholder missing, got:\n%s", md)
+ }
+ if len(docs) != 1 || docs[0].Token != "MHU6d4eixo1UdCxNzGbcspVSnfg" || docs[0].DocType != "docx" {
+ t.Errorf("pending doc refs wrong: %+v", docs)
+ }
+}
diff --git a/internal/datasource/connector/feishu/core/media_regression_test.go b/internal/datasource/connector/feishu/core/media_regression_test.go
new file mode 100644
index 000000000..1a6c5461c
--- /dev/null
+++ b/internal/datasource/connector/feishu/core/media_regression_test.go
@@ -0,0 +1,76 @@
+package core
+
+import (
+ "bytes"
+ "context"
+ "image"
+ "image/color"
+ "image/draw"
+ "image/png"
+ "net/http"
+ "strings"
+ "testing"
+)
+
+func TestTableViewKeepsFileAndBoard(t *testing.T) {
+ for _, kind := range []int{BlockTypeView, BlockTypeCallout, BlockTypeQuoteContainer, BlockTypeGrid} {
+ t.Run(blockNameForTest(kind), func(t *testing.T) {
+ blocks := []DocxBlock{
+ {
+ BlockID: "table", BlockType: BlockTypeTable, Children: []string{"cell"},
+ Table: &BlockTable{Cells: []string{"cell"}, Property: &BlockTableProperty{ColumnSize: 1}},
+ },
+ {BlockID: "cell", BlockType: BlockTypeTableCell, Children: []string{"view"}},
+ {BlockID: "view", BlockType: kind, Children: []string{"file", "board"}},
+ {BlockID: "file", BlockType: BlockTypeFile, File: &BlockFileRef{Token: "pdf", Name: "report.pdf"}},
+ {BlockID: "board", BlockType: BlockTypeBoard, Board: &BlockBoard{Token: "brd-1"}},
+ }
+ for _, outer := range []bool{false, true} {
+ if outer {
+ blocks = append([]DocxBlock{
+ {BlockID: "outer", BlockType: BlockTypeView, Children: []string{"table"}},
+ }, blocks...)
+ }
+ md, atts, imgs, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(atts) != 1 || len(imgs) != 1 {
+ t.Fatalf("table view media lost: attachments=%d images=%d markdown=%q", len(atts), len(imgs), md)
+ }
+ if strings.Count(string(md), "weknora-att://pdf") != 1 ||
+ strings.Count(string(md), "weknora-img://") != 1 {
+ t.Fatalf("media must render exactly once: %s", md)
+ }
+ }
+ })
+ }
+}
+
+func TestTrimmedBoardKeepsMeaningfulDiagram(t *testing.T) {
+ img := image.NewRGBA(image.Rect(0, 0, 1600, 1200))
+ draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
+ draw.Draw(img, image.Rect(400, 400, 700, 600), image.NewUniform(color.Black), image.Point{}, draw.Src)
+ var b bytes.Buffer
+ if err := png.Encode(&b, img); err != nil {
+ t.Fatal(err)
+ }
+ cropped := trimBoardImage(b.Bytes())
+ cfg, _, err := image.DecodeConfig(bytes.NewReader(cropped))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(cropped) >= MinAttachmentBytes || cfg.Width < 64 || cfg.Height < 64 {
+ t.Fatalf("fixture must be a sub-2KB diagram with meaningful dimensions: bytes=%d dims=%dx%d",
+ len(cropped), cfg.Width, cfg.Height)
+ }
+ server := fakeFeishuForBoard(t, boardBlocks(), http.StatusOK, b.Bytes())
+ client := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: server.URL})
+ items, err := FetchDocxWithBlocks(context.Background(), client, boardFetchInput())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(items[len(items)-1].Content), "data:image/png;base64,") {
+ t.Fatalf("valid board disappeared: %s", items[len(items)-1].Content)
+ }
+}
diff --git a/internal/datasource/connector/feishu/core/mention_user_test.go b/internal/datasource/connector/feishu/core/mention_user_test.go
new file mode 100644
index 000000000..01912528d
--- /dev/null
+++ b/internal/datasource/connector/feishu/core/mention_user_test.go
@@ -0,0 +1,180 @@
+package core
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+// mentionBlk builds a text block whose only inline element is an @mention of
+// the given OpenID.
+func mentionBlk(id, openID string) DocxBlock {
+ return DocxBlock{
+ BlockID: id, BlockType: BlockTypeText,
+ Text: &BlockText{Elements: []TextElement{{MentionUser: &MentionUser{UserID: openID}}}},
+ }
+}
+
+// mentionUserCase renders blocks and asserts the resolved display names hit
+// (named) and miss/403-degrade (generic @成员) paths.
+func mentionUserCase(t *testing.T, name string, resolver func(string) string, blocks []DocxBlock, want []string) {
+ t.Helper()
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", resolver)
+ if err != nil {
+ t.Fatalf("%s: err: %v", name, err)
+ }
+ for _, w := range want {
+ if !strings.Contains(string(md), w) {
+ t.Errorf("%s: missing %q, got:\n%s", name, w, md)
+ }
+ }
+}
+
+func TestBlocksToMarkdown_MentionUserName(t *testing.T) {
+ // Hit: OpenID resolves to a real display name.
+ resolved := map[string]string{"ou_zhang": "张三", "ou_li": "李四"}
+ mentionUserCase(t, "hit", func(id string) string { return resolved[id] },
+ []DocxBlock{
+ {BlockID: "p1", BlockType: BlockTypeText, Text: &BlockText{Elements: []TextElement{
+ {TextRun: &TextRun{Content: "请 "}},
+ {MentionUser: &MentionUser{UserID: "ou_zhang"}},
+ }}},
+ mentionBlk("p2", "ou_li"),
+ },
+ []string{"@张三", "@李四"})
+
+ // Miss (unknown user / API failure): degrade to the generic marker, and
+ // the document still renders — the failure never surfaces as an error.
+ var calls int
+ mentionUserCase(t, "miss", func(_ string) string {
+ calls++
+ return ""
+ }, []DocxBlock{mentionBlk("p1", "ou_gone")},
+ []string{"@成员"})
+ if calls != 1 {
+ t.Errorf("resolver calls = %d, want 1", calls)
+ }
+}
+
+func TestBlocksToMarkdown_MentionUserName_OncePerElement(t *testing.T) {
+ var calls int
+ resolver := func(_ string) string {
+ calls++
+ return "张三"
+ }
+ blocks := []DocxBlock{mentionBlk("p1", "ou_x"), mentionBlk("p2", "ou_x"), mentionBlk("p3", "ou_y")}
+ md, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", resolver)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ // The renderer consults the resolver once per mention element; dedup
+ // caching lives in the userNameResolver closure (tested with real HTTP
+ // traffic in TestUserNameResolver_NegativeCache).
+ if calls != 3 {
+ t.Errorf("resolver calls = %d, want 3 (one per mention element)", calls)
+ }
+ if got := strings.Count(string(md), "@张三"); got != 3 {
+ t.Errorf("mentions rendered = %d, want 3, got:\n%s", got, md)
+ }
+}
+
+func TestBlocksToMarkdown_NoMention_ZeroResolverCalls(t *testing.T) {
+ var calls int
+ resolver := func(_ string) string {
+ calls++
+ return "张三"
+ }
+ blocks := []DocxBlock{
+ {BlockID: "p1", BlockType: BlockTypeText, Text: txt("没有提及的普通段落")},
+ {BlockID: "p2", BlockType: BlockTypeText, Text: txt("另一段")},
+ }
+ if _, _, _, _, err := blocksToMarkdown(context.Background(), nil, blocks, "", resolver); err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if calls != 0 {
+ t.Errorf("resolver calls = %d, want 0 (no API traffic without mentions)", calls)
+ }
+}
+
+func TestUserName(t *testing.T) {
+ ts, cfg := retryTestServer(t, "/open-apis/contact/v3/users/ou_1", func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Query().Get("user_id_type") != "open_id" {
+ t.Errorf("user_id_type = %q, want open_id", r.URL.Query().Get("user_id_type"))
+ }
+ writeJSON(w, map[string]any{"code": 0, "data": map[string]any{
+ "user": map[string]any{"name": "张三"},
+ }})
+ })
+ defer ts.Close()
+
+ c := NewClient(cfg)
+ name, err := c.UserName(context.Background(), "ou_1")
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if name != "张三" {
+ t.Errorf("name = %q, want 张三", name)
+ }
+
+ // 403 (no contact scope): error, caller degrades.
+ ts403, cfg403 := retryTestServer(t, "/open-apis/contact/v3/users/ou_1",
+ func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusForbidden)
+ _, _ = w.Write([]byte(`{"code":99991679,"msg":"permission denied"}`))
+ })
+ defer ts403.Close()
+ if _, err := NewClient(cfg403).UserName(context.Background(), "ou_1"); err == nil {
+ t.Error("403 must return an error for the caller to degrade")
+ }
+
+ // HTTP 200 but business error code: also an error.
+ tsCode, cfgCode := retryTestServer(t, "/open-apis/contact/v3/users/ou_1",
+ func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, map[string]any{"code": 99991672, "msg": "no permission"})
+ })
+ defer tsCode.Close()
+ if _, err := NewClient(cfgCode).UserName(context.Background(), "ou_1"); err == nil {
+ t.Error("non-zero body code must return an error")
+ }
+}
+
+func TestUserNameResolver_NegativeCache(t *testing.T) {
+ var hits atomic.Int64
+ ts, cfg := retryTestServer(t, "/open-apis/contact/v3/users/", func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ if strings.Contains(r.URL.Path, "ou_ok") {
+ writeJSON(w, map[string]any{"code": 0, "data": map[string]any{
+ "user": map[string]any{"name": "张三"},
+ }})
+ return
+ }
+ // No permission for the other user, forever.
+ w.WriteHeader(http.StatusForbidden)
+ })
+ defer ts.Close()
+
+ resolver := userNameResolver(context.Background(), NewClient(cfg))
+ // Same user three times: resolved once; failed user three times: one
+ // negative-cached attempt. Total HTTP traffic must be 2.
+ got := []string{
+ resolver("ou_ok"), resolver("ou_ok"), resolver("ou_ok"),
+ resolver("ou_bad"), resolver("ou_bad"), resolver("ou_bad"),
+ }
+ for i, g := range got {
+ want := "张三"
+ if i >= 3 {
+ want = ""
+ }
+ if g != want {
+ t.Errorf("resolver[%d] = %q, want %q", i, g, want)
+ }
+ }
+ if n := hits.Load(); n != 2 {
+ t.Errorf("contact API hits = %d, want 2 (per-user cache incl. negative)", n)
+ }
+ if _, err := NewClient(cfg).UserName(context.Background(), ""); err == nil {
+ t.Error("empty user id must be rejected without an API call")
+ }
+}
diff --git a/internal/datasource/connector/feishu/core/parse_mode_test.go b/internal/datasource/connector/feishu/core/parse_mode_test.go
new file mode 100644
index 000000000..5408731b0
--- /dev/null
+++ b/internal/datasource/connector/feishu/core/parse_mode_test.go
@@ -0,0 +1,112 @@
+package core
+
+import (
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// parseModeConfig builds a minimal valid DataSourceConfig with the given
+// Settings, enough for ParseFeishuConfig to succeed.
+func parseModeConfig(settings map[string]interface{}) *types.DataSourceConfig {
+ return &types.DataSourceConfig{
+ Type: types.ConnectorTypeFeishu,
+ Credentials: map[string]interface{}{"app_id": "cli-x", "app_secret": "sec"},
+ ResourceIDs: []string{"space1"},
+ Settings: settings,
+ }
+}
+
+// ParseFeishuConfig resolves Settings["parse_mode"] into Config.ParseMode.
+// The default is blocks since parse_mode moved to the data source (2026-09
+// deep adaptation): unset and empty both mean blocks, an explicit export is
+// preserved as the image-association escape hatch, and an unrecognized value
+// falls back to blocks instead of failing the sync. The retired
+// FEISHU_DOCX_PARSE_MODE env var is still honored as a deprecated fallback
+// while the per-source setting is unset.
+func TestParseFeishuConfig_ParseMode(t *testing.T) {
+ // Hermetic baseline: neutralize any ambient FEISHU_DOCX_PARSE_MODE so the
+ // default cases below never depend on the host environment.
+ t.Setenv("FEISHU_DOCX_PARSE_MODE", "")
+
+ t.Run("unset settings default to blocks", func(t *testing.T) {
+ cfg, err := ParseFeishuConfig(parseModeConfig(nil), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
+ })
+
+ t.Run("settings without parse_mode default to blocks", func(t *testing.T) {
+ cfg, err := ParseFeishuConfig(
+ parseModeConfig(map[string]interface{}{"timezone": "Asia/Shanghai"}), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
+ })
+
+ t.Run("explicit blocks", func(t *testing.T) {
+ cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "blocks"}), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
+ })
+
+ t.Run("explicit export is preserved", func(t *testing.T) {
+ cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "export"}), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeExport, cfg.ParseMode)
+ })
+
+ t.Run("case and whitespace insensitive", func(t *testing.T) {
+ cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": " Export "}), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeExport, cfg.ParseMode)
+ })
+
+ t.Run("invalid value falls back to blocks", func(t *testing.T) {
+ cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "yaml"}), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
+ })
+
+ t.Run("empty value falls back to blocks", func(t *testing.T) {
+ cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": " "}), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
+ })
+
+ t.Run("deprecated env fallback honored while settings unset", func(t *testing.T) {
+ t.Setenv("FEISHU_DOCX_PARSE_MODE", "export")
+ cfg, err := ParseFeishuConfig(parseModeConfig(nil), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeExport, cfg.ParseMode)
+ })
+
+ t.Run("deprecated env fallback is case and whitespace insensitive", func(t *testing.T) {
+ t.Setenv("FEISHU_DOCX_PARSE_MODE", " Export ")
+ cfg, err := ParseFeishuConfig(
+ parseModeConfig(map[string]interface{}{"timezone": "Asia/Shanghai"}), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeExport, cfg.ParseMode)
+ })
+
+ t.Run("per-source parse_mode overrides deprecated env", func(t *testing.T) {
+ t.Setenv("FEISHU_DOCX_PARSE_MODE", "export")
+ cfg, err := ParseFeishuConfig(parseModeConfig(map[string]interface{}{"parse_mode": "blocks"}), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
+ })
+
+ t.Run("invalid deprecated env value falls back to blocks", func(t *testing.T) {
+ t.Setenv("FEISHU_DOCX_PARSE_MODE", "yaml")
+ cfg, err := ParseFeishuConfig(parseModeConfig(nil), RegionFeishu)
+ require.NoError(t, err)
+ assert.Equal(t, ParseModeBlocks, cfg.ParseMode)
+ })
+}
+
+// ParseMode threading: DocxFetchInput.ParseMode is the single transport
+// (connector entry resolves it via ParseFeishuConfig and passes it through
+// ops → fetchNodeContent → DocxFetchInput). Empty degrades to blocks inside
+// FetchDocxWithBlocks; resolution itself is covered by
+// TestParseFeishuConfig_ParseMode above, and the wiki/drive suites exercise
+// the blocks default end-to-end with ops built without an explicit mode.
diff --git a/internal/datasource/connector/feishu/core/shared.go b/internal/datasource/connector/feishu/core/shared.go
index eec1cce57..04d36901f 100644
--- a/internal/datasource/connector/feishu/core/shared.go
+++ b/internal/datasource/connector/feishu/core/shared.go
@@ -1,7 +1,9 @@
package core
import (
+ "bytes"
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -12,6 +14,7 @@ import (
"regexp"
"strconv"
"strings"
+ "sync"
"time"
"unicode/utf8"
@@ -143,15 +146,27 @@ func FeishuErrorItemMeta(err error, extra map[string]string) map[string]string {
}
// parseableAttachmentExts are attachment extensions worth ingesting as their
-// own knowledge entries; other files (icons, tiny decor) are skipped.
+// own knowledge entries. This is the shared contract list (pdf/md/markdown/
+// xlsx/xls/csv/doc/docx/ppt/pptx); everything else — images (which ride the
+// embedded-image pipeline instead), videos, archives — degrades to an inline
+// Markdown reference. markdown.go's attachment rendering reads this same map,
+// so the inline `- 文件名` list and the produced sub-items can never disagree.
var parseableAttachmentExts = map[string]bool{
- ".pdf": true, ".doc": true, ".docx": true, ".xls": true, ".xlsx": true,
- ".ppt": true, ".pptx": true, ".txt": true, ".md": true, ".csv": true,
+ ".pdf": true, ".md": true, ".markdown": true,
+ ".xlsx": true, ".xls": true, ".csv": true,
+ ".doc": true, ".docx": true, ".ppt": true, ".pptx": true,
}
// MinAttachmentBytes filters out decorative micro-files.
const MinAttachmentBytes = 2 * 1024
+// maxInlineImageBytes caps a single image inlined as a base64 data URI. It
+// mirrors the document-processing image resolver's per-image budget
+// (docparser maxRemoteImageSize): anything larger would be downloaded,
+// base64-expanded ~1.37x into the markdown, then silently skipped by the
+// resolver — a permanent raw-base64 blob in stored content.
+const maxInlineImageBytes = 10 * 1024 * 1024
+
// SupportedImageExt sniffs image bytes and returns the filename extension and
// content type WeKnora accepts for a standalone image knowledge item (png/jpg/
// gif — the image set isValidFileType admits). ok is false for non-image or
@@ -167,6 +182,12 @@ func SupportedImageExt(data []byte) (ext, contentType string, ok bool) {
case "image/gif":
return ".gif", ct, true
default:
+ // Go's sniffer reports SVG markup as text/xml; recover the real type
+ // when the payload is an <svg> document (board download_as_image may
+ // return SVG), and the platform resolver stores .svg natively.
+ if strings.HasPrefix(ct, "text/xml") && bytes.Contains(data[:min(len(data), 512)], []byte("<svg")) {
+ return ".svg", "image/svg+xml", true
+ }
return "", ct, false
}
}
@@ -208,6 +229,41 @@ func ParseFeishuConfig(config *types.DataSourceConfig, region Region) (*Config,
}
}
+ // parse_mode is likewise a per-data-source display setting, read from
+ // Settings (set on the data source edit form). When the per-source setting
+ // is unset, the deprecated FEISHU_DOCX_PARSE_MODE env var is still honored
+ // for one release (with a warning) so deployments that pinned "export"
+ // keep their behavior across the upgrade. Everything unset (or
+ // unrecognized) resolves to blocks — the default; an unrecognized value
+ // falls back to blocks with a warning rather than failing the whole sync.
+ parseMode := ""
+ if config.Settings != nil {
+ if pm, ok := config.Settings["parse_mode"].(string); ok {
+ parseMode = strings.ToLower(strings.TrimSpace(pm))
+ }
+ }
+ if parseMode == "" {
+ if legacy := strings.TrimSpace(os.Getenv("FEISHU_DOCX_PARSE_MODE")); legacy != "" {
+ logger.Warnf(context.Background(),
+ "[Feishu] FEISHU_DOCX_PARSE_MODE=%q is deprecated and will be removed; "+
+ "set parse_mode on the data source edit form instead",
+ legacy)
+ parseMode = strings.ToLower(legacy)
+ }
+ }
+ switch parseMode {
+ case "", ParseModeBlocks:
+ feishuConfig.ParseMode = ParseModeBlocks
+ case ParseModeExport:
+ // keep the explicit export selection
+ feishuConfig.ParseMode = ParseModeExport
+ default:
+ logger.Warnf(context.Background(),
+ "[Feishu] invalid parse_mode %q, falling back to %q",
+ parseMode, ParseModeBlocks)
+ feishuConfig.ParseMode = ParseModeBlocks
+ }
+
if err := datasource.ValidateConnectorBaseURL(feishuConfig.GetBaseURL()); err != nil {
return nil, err
}
@@ -215,6 +271,18 @@ func ParseFeishuConfig(config *types.DataSourceConfig, region Region) (*Config,
return &feishuConfig, nil
}
+// DocxChangeKey invalidates cached docx content when its effective parser changes.
+// Other file types do not depend on the docx parser setting.
+func DocxChangeKey(editTime, objType, parseMode string) string {
+ if objType != "docx" {
+ return editTime
+ }
+ if parseMode == "" {
+ parseMode = ParseModeBlocks
+ }
+ return editTime + ":parse=" + parseMode
+}
+
// IsSupportedDocType checks if a Feishu document type can be synced.
// mindnote and slides have no content read API and are skipped.
func IsSupportedDocType(objType string) bool {
@@ -286,6 +354,31 @@ func truncateUTF8(s string, maxBytes int) string {
return s
}
+// userNameResolver returns a per-document @mention display-name resolver for
+// the contact API. The cache (OpenID → name) means each user costs at most one
+// contact call per document; failures and empty names negative-cache too, so a
+// user without contact permission renders every later mention of themselves as
+// the generic @成员 without re-hitting the API. Errors never propagate — they
+// only log at debug level; ingestion is never blocked or failed by this.
+func userNameResolver(ctx context.Context, client *Client) func(string) string {
+ var cache sync.Map // OpenID → display name ("" = lookup failed)
+ return func(userID string) string {
+ if userID == "" {
+ return ""
+ }
+ if v, ok := cache.Load(userID); ok {
+ return v.(string)
+ }
+ name, err := client.UserName(ctx, userID)
+ if err != nil {
+ logger.Debugf(ctx, "[Feishu] resolve mention user %s: %v (degrading to @成员)", userID, err)
+ name = ""
+ }
+ cache.Store(userID, name)
+ return name
+ }
+}
+
// DocxFetchInput is the unified description of one docx document from either
// source (wiki node or Drive file) that FetchDocxWithBlocks needs.
type DocxFetchInput struct {
@@ -298,32 +391,37 @@ type DocxFetchInput struct {
ResourceID string
EditTime time.Time
// CreateTime is the document creation time in Feishu; zero when unknown.
- CreateTime time.Time
- BaseMeta map[string]string
- MultimodalEnabled bool
+ CreateTime time.Time
+ BaseMeta map[string]string
+ // ParseMode selects the docx parsing path ("blocks" | "export"), resolved
+ // from Settings["parse_mode"] by ParseFeishuConfig and threaded from the
+ // connector entry points. Empty means blocks (the default).
+ ParseMode string
}
-// FetchDocxWithBlocks retrieves a docx document via the blocks API, converts it
-// to Markdown, and returns a main item plus any parseable attachment/image
-// sub-items. Falls back to the export API if the blocks API errors or renders
-// empty. Shared by the wiki Connector and the Drive DriveConnector.
+// FetchDocxWithBlocks retrieves a docx document via the blocks API, converts
+// it to Markdown, and returns the main item with attachment sub-items. Image
+// and board blocks render as nonce-tagged markers that this function patches
+// in place with inline base64 data URIs (placeholders on failure); the
+// document-processing image resolver stores them later. Falls back to the
+// export API if the blocks API errors or renders empty. Shared by the wiki
+// Connector and the Drive DriveConnector.
func FetchDocxWithBlocks(ctx context.Context, client *Client, in DocxFetchInput) ([]*types.FetchedItem, error) {
- // FEISHU_DOCX_PARSE_MODE selects the docx parsing path. The blocks path
- // renders image blocks as empty `![图片]()` placeholders and fans images out
- // into separate knowledge items, which breaks image↔document association in
- // retrieval/wiki/agent. The export path yields a .docx that docreader parses
- // inline, so images are bound to the parent document via parent_chunk_id
- // (same as a regular docx upload). Default (unset / "export") uses export so
- // images associate with the document; set "blocks" for the blocks-first
- // behaviour (faster, keeps docx attachments, but images are detached).
-
- // This is a temporary solution. If a better parsing solution is available later, this environment variable will be removed and replaced with a better one.
- parsingMode := strings.TrimSpace(os.Getenv("FEISHU_DOCX_PARSE_MODE"))
+ // The parse mode comes from the data source's Settings["parse_mode"],
+ // resolved by ParseFeishuConfig and threaded in via DocxFetchInput.ParseMode.
+ // The blocks path (default) inlines images/boards into the parent
+ // Markdown as base64 data URIs (via weknora-img://N markers) and fans
+ // attachments out into sub-items wired to the parent via attachment_ids
+ // metadata. The export path yields a .docx that docreader
+ // parses inline, so images are bound to the parent document via
+ // parent_chunk_id (same as a regular docx upload) — kept as the per-data-
+ // source escape hatch.
+ parsingMode := in.ParseMode
if parsingMode == "" {
- parsingMode = "export"
+ parsingMode = ParseModeBlocks
}
- if strings.EqualFold(parsingMode, "export") {
+ if strings.EqualFold(parsingMode, ParseModeExport) {
item, err := exportDocxFallback(ctx, client, in)
if err != nil {
return nil, err
@@ -345,12 +443,30 @@ func FetchDocxWithBlocks(ctx context.Context, client *Client, in DocxFetchInput)
return []*types.FetchedItem{item}, nil
}
- md, atts, err := blocksToMarkdown(ctx, client, blocks)
+ // Images/boards ride the marker pipeline: the renderer numbers them in
+ // document order, and the patches below inline each image's bytes as a
+ // base64 data URI (or a plain placeholder on failure) in a single pass.
+ mdBytes, atts, imgs, docNames, err := blocksToMarkdown(ctx, client, blocks, in.URL, userNameResolver(ctx, client))
if err != nil {
return nil, fmt.Errorf("convert blocks %s: %w", in.Title, err)
}
+ md := string(mdBytes)
- if len(strings.TrimSpace(string(md))) == 0 {
+ // Export image-heavy documents before downloading any media or attachments.
+ // The native document parser carries images as ImageRefs, which do not use
+ // the Markdown data-URI count budget. Never silently leave excess base64
+ // in persisted Markdown, and do not raise the shared parser's resource cap.
+ var exported *types.FetchedItem
+ if len(imgs) > types.MaxInlineDocumentImages {
+ logger.Infof(ctx, "[Feishu] doc %s has %d images; falling back to export", in.ObjToken, len(imgs))
+ item, ferr := exportDocxFallback(ctx, client, in)
+ if ferr != nil {
+ return nil, ferr
+ }
+ exported = item
+ }
+
+ if len(strings.TrimSpace(md)) == 0 {
logger.Infof(ctx, "[Feishu] doc %s (%s): blocks rendered empty Markdown, falling back to export",
in.Title, in.ObjToken)
item, ferr := exportDocxFallback(ctx, client, in)
@@ -360,45 +476,73 @@ func FetchDocxWithBlocks(ctx context.Context, client *Client, in DocxFetchInput)
return []*types.FetchedItem{item}, nil
}
- main := &types.FetchedItem{
- ExternalID: in.DocToken,
- Title: in.Title,
- Content: md,
- ContentType: "text/markdown",
- FileName: SanitizeFileName(in.Title) + ".md",
- URL: in.URL,
- UpdatedAt: in.EditTime,
- CreatedAt: in.CreateTime,
- SourceResourceID: in.ResourceID,
- Metadata: in.BaseMeta,
- ReplacesSubtree: true, // sweep stale attachment sub-items on re-sync
- }
- items := []*types.FetchedItem{main}
-
+ // Attachments stay sub-items (they are documents in their own right and
+ // are emitted BEFORE the parent so SubtreeKeep/sweep semantics hold).
+ var children []*types.FetchedItem
keep := make([]string, 0, len(atts))
+ attachmentIDs := make([]string, 0, len(atts))
+
childMeta := func() map[string]string {
m := maps.Clone(in.BaseMeta)
m["parent_node_token"] = in.DocToken
+ m["parent_doc_id"] = in.DocToken
m["attachment"] = "true"
return m
}
+ // patchMarker swaps one numbered image marker in the rendered Markdown for
+ // its final form: an inline base64 data URI on success, a plain
+ // ![图片]() placeholder or a degrade note on failure. Markers are unique
+ // per N, and N is assigned once per image/board block.
+ patchMarker := func(n int, replacement string) {
+ needle := fmt.Sprintf("![图片](weknora-img://%d-%s)", n, imageMarkerNonce(in.URL))
+ md = strings.Replace(md, needle, replacement, 1)
+ }
+
+ // ── file attachments ──
for _, a := range atts {
childID := types.SubtreeChildID(in.DocToken, "file", a.FileToken)
keep = append(keep, childID) // present in the doc → never sweep as stale
- ext := strings.ToLower(filepath.Ext(a.Name))
- if ext == "" {
- logger.Warnf(ctx, "[Feishu] doc %s: skipping attachment with no usable filename (token=%s name=%q)",
- in.ObjToken, a.FileToken, a.Name)
- continue
- }
- if !parseableAttachmentExts[ext] {
- continue
+ // The renderer emitted the unique line "- weknora-att://<token>" for
+ // this attachment; patch that exact line so an identical earlier
+ // bullet can never be replaced by mistake. Anchoring on the token's
+ // end (newline or end of markdown) keeps a token that is a strict
+ // prefix of another attachment's token from matching inside it.
+ patchAtt := func(line string) {
+ needle := "- weknora-att://" + a.FileToken
+ if anchored := needle + "\n"; strings.Contains(md, anchored) {
+ md = strings.Replace(md, anchored, line+"\n", 1)
+ return
+ }
+ if strings.HasSuffix(md, needle) {
+ md = md[:len(md)-len(needle)] + line
+ }
}
+ // The renderer only collects whitelisted extensions into atts, so
+ // non-whitelisted/video files never reach this loop (their inline
+ // `> [附件: …]` reference is already in the Markdown).
data, derr := client.downloadMediaFile(ctx, a.FileToken)
if derr != nil {
+ if errors.Is(derr, ErrDownloadTooLarge) {
+ // The file is fine, just over the sync cap: degrade inline
+ // instead of failing or error-iteming the document.
+ logger.Warnf(ctx,
+ "[Feishu] doc %s: attachment %q (token=%s) over download cap, degrading to placeholder",
+ in.ObjToken, a.Name, a.FileToken)
+ displayName := a.Name
+ if displayName == "" {
+ displayName = a.FileToken
+ }
+ note := "> [附件: " + displayName + "]"
+ if in.URL != "" {
+ note = "> [附件: " + displayName + "](" + escapeURL(in.URL) + ")"
+ }
+ patchAtt(note)
+ continue
+ }
logger.Warnf(ctx, "[Feishu] doc %s: attachment %q (token=%s) download failed: %v",
in.ObjToken, a.Name, a.FileToken, derr)
- items = append(items, &types.FetchedItem{
+ patchAtt("- " + a.Name)
+ children = append(children, &types.FetchedItem{
ExternalID: childID,
Title: a.Name,
SourceResourceID: in.ResourceID,
@@ -409,9 +553,11 @@ func FetchDocxWithBlocks(ctx context.Context, client *Client, in DocxFetchInput)
if len(data) < MinAttachmentBytes {
logger.Infof(ctx, "[Feishu] doc %s: skipping tiny attachment %q (token=%s, %d bytes < %d)",
in.ObjToken, a.Name, a.FileToken, len(data), MinAttachmentBytes)
+ patchAtt("- " + a.Name)
continue
}
- items = append(items, &types.FetchedItem{
+ patchAtt("- " + a.Name)
+ children = append(children, &types.FetchedItem{
ExternalID: childID,
Title: a.Name,
Content: data,
@@ -423,60 +569,124 @@ func FetchDocxWithBlocks(ctx context.Context, client *Client, in DocxFetchInput)
SourceResourceID: in.ResourceID,
Metadata: childMeta(),
})
+ attachmentIDs = append(attachmentIDs, childID)
+ }
+
+ if exported != nil {
+ // A successful blocks listing still provides authoritative attachments.
+ // Preserve those children even though the parent's images use native
+ // export parsing; ordinary export alone omits file block attachments.
+ exported.ReplacesSubtree = true
+ exported.SubtreeKeep = keep
+ if len(attachmentIDs) > 0 {
+ if exported.Metadata == nil {
+ exported.Metadata = make(map[string]string)
+ }
+ ids, _ := json.Marshal(attachmentIDs)
+ exported.Metadata["attachment_ids"] = string(ids)
+ }
+ return append(children, exported), nil
+ }
+
+ // ── 云文档 mention links: backfill document titles ──
+ // The renderer emits "[weknora-docname://<token>](<url>)" placeholders; the
+ // drive metadata batch API resolves every title in one call. Refs that
+ // cannot be resolved (no permission, deleted, unsupported type) keep the
+ // URL as the link text — exactly the form rendered before this backfill.
+ if len(docNames) > 0 {
+ titles := client.DocTitles(ctx, docNames)
+ for _, dn := range docNames {
+ needle := "[weknora-docname://" + dn.Token + "](" + escapeURL(dn.URL) + ")"
+ repl := "[" + dn.URL + "](" + escapeURL(dn.URL) + ")"
+ if title := titles[dn.Token]; title != "" {
+ clean := strings.NewReplacer("[", "[", "]", "]", "\n", " ", "\r", "").Replace(title)
+ repl = "[" + clean + "](" + escapeURL(dn.URL) + ")"
+ } else {
+ logger.Warnf(ctx, "[Feishu] doc %s: no metadata for referenced doc %s (%s), keeping URL as link text",
+ in.Title, dn.Token, dn.DocType)
+ }
+ md = strings.ReplaceAll(md, needle, repl)
+ }
}
- imgMeta := func() map[string]string {
- m := maps.Clone(in.BaseMeta)
- m["parent_node_token"] = in.DocToken
- m["embedded_image"] = "true"
- return m
- }
- for _, b := range blocks {
- if b.BlockType != BlockTypeImage || b.Image == nil || b.Image.Token == "" {
+ // ── embedded images and whiteboard blocks (block_type 43) ──
+ // Orthodox platform flow (same as the docparser for parsed PDFs/Word):
+ // the image bytes ride INSIDE the parent markdown as a base64 data URI;
+ // the document-processing pipeline's image resolver stores them on the
+ // tenant file service, swaps in the persistent provider:// URL and (when
+ // a VLM is configured) produces OCR/caption child chunks. No image
+ // knowledge rows are created.
+ for _, pi := range imgs {
+ if pi.Token == "" {
+ // Malformed block: degrade the marker to a plain placeholder.
+ patchMarker(pi.N, "![图片]()")
continue
}
- childID := types.SubtreeChildID(in.DocToken, "image", b.Image.Token)
- keep = append(keep, childID) // present in the doc → never sweep as stale
- if !in.MultimodalEnabled {
- continue // KB can't OCR images; the inline placeholder is all we keep
+
+ var (
+ data []byte
+ derr error
+ )
+ if pi.Kind == "board" {
+ data, derr = client.downloadBoardAsImage(ctx, pi.Token)
+ } else {
+ data, derr = client.downloadMediaFile(ctx, pi.Token)
}
- data, derr := client.downloadMediaFile(ctx, b.Image.Token)
if derr != nil {
- logger.Warnf(ctx, "[Feishu] doc %s: image (token=%s) download failed: %v",
- in.ObjToken, b.Image.Token, derr)
- items = append(items, &types.FetchedItem{
- ExternalID: childID,
- Title: fmt.Sprintf("%s(内嵌图片)", in.Title),
- SourceResourceID: in.ResourceID,
- Metadata: FeishuErrorItemMeta(derr, imgMeta()),
- })
+ // 403 (no board:whiteboard:node:read for boards) or transient
+ // failure: degrade inline, never fail the document.
+ logger.Warnf(ctx, "[Feishu] doc %s: %s %s download failed: %v",
+ in.ObjToken, pi.Kind, pi.Token, derr)
+ patchMarker(pi.N, "![图片]()")
continue
}
- if len(data) < MinAttachmentBytes {
- continue // decorative micro-image (icon/spacer)
- }
ext, contentType, ok := SupportedImageExt(data)
if !ok {
- logger.Warnf(ctx, "[Feishu] doc %s: skipping image (token=%s) of unsupported type %q",
- in.ObjToken, b.Image.Token, contentType)
+ // Reject non-images here. The image resolver filters icons by
+ // dimensions; compressed diagrams can be well below 2 KB.
+ logger.Infof(ctx, "[Feishu] doc %s: %s %s not a usable image (type=%q bytes=%d)",
+ in.ObjToken, pi.Kind, pi.Token, contentType, len(data))
+ patchMarker(pi.N, "![图片]()")
continue
}
- items = append(items, &types.FetchedItem{
- ExternalID: childID,
- Title: fmt.Sprintf("%s(内嵌图片)", in.Title),
- Content: data,
- ContentType: contentType,
- FileName: "image-" + b.Image.Token + ext,
- URL: in.URL,
- UpdatedAt: in.EditTime,
- CreatedAt: in.CreateTime,
- SourceResourceID: in.ResourceID,
- Metadata: imgMeta(),
- })
+ if len(data) > maxInlineImageBytes {
+ // The document-processing image resolver skips data URIs over its
+ // 10 MB budget (image_resolver maxRemoteImageSize); inlining one
+ // would leave a raw base64 blob in the stored markdown forever.
+ // Degrade here instead — same handling as an oversized attachment.
+ logger.Warnf(ctx, "[Feishu] doc %s: %s %s (%d bytes) over inline image cap, degrading to placeholder",
+ in.ObjToken, pi.Kind, pi.Token, len(data))
+ patchMarker(pi.N, "![图片]()")
+ continue
+ }
+
+ dataURI := "data:" + contentType + ";base64," + base64.StdEncoding.EncodeToString(data)
+ patchMarker(pi.N, "![图片]("+dataURI+")")
+ _ = ext // ext is implied by contentType in the data URI
}
+ meta := maps.Clone(in.BaseMeta)
+ if len(attachmentIDs) > 0 {
+ if b, merr := json.Marshal(attachmentIDs); merr == nil {
+ meta["attachment_ids"] = string(b)
+ }
+ }
+
+ main := &types.FetchedItem{
+ ExternalID: in.DocToken,
+ Title: in.Title,
+ Content: []byte(md),
+ ContentType: "text/markdown",
+ FileName: SanitizeFileName(in.Title) + ".md",
+ URL: in.URL,
+ UpdatedAt: in.EditTime,
+ CreatedAt: in.CreateTime,
+ SourceResourceID: in.ResourceID,
+ Metadata: meta,
+ ReplacesSubtree: true, // sweep stale attachment sub-items on re-sync
+ }
main.SubtreeKeep = keep
- return items, nil
+ return append(children, main), nil
}
// exportDocxFallback exports a docx document via the async export API and
diff --git a/internal/datasource/connector/feishu/core/types.go b/internal/datasource/connector/feishu/core/types.go
index 997d6f9ef..be0c5e2b5 100644
--- a/internal/datasource/connector/feishu/core/types.go
+++ b/internal/datasource/connector/feishu/core/types.go
@@ -34,8 +34,25 @@ type Config struct {
// rendering in UTC shifts the date. Empty defaults to GMT+8, which matches
// Feishu (mainland) tenants; set it for Lark tenants in other zones.
Timezone string `json:"timezone,omitempty"`
+
+ // ParseMode selects the docx parsing path: "blocks" (default) renders the
+ // blocks API into Markdown with attachment sub-items; "export" exports
+ // a .docx binary that docreader parses inline, keeping image↔document
+ // association via parent_chunk_id. Parsed from Settings["parse_mode"] by
+ // ParseFeishuConfig and threaded via DocxFetchInput.ParseMode; see
+ // FetchDocxWithBlocks.
+ ParseMode string `json:"parse_mode,omitempty"`
}
+// Docx parse modes (Config.ParseMode, from Settings["parse_mode"]).
+const (
+ // ParseModeBlocks renders docx via the blocks API into Markdown (default).
+ ParseModeBlocks = "blocks"
+ // ParseModeExport exports docx as a binary and lets docreader parse it
+ // inline — the escape hatch when image↔document association matters.
+ ParseModeExport = "export"
+)
+
// defaultTimezoneOffsetSeconds is GMT+8 (the Feishu mainland default), used when
// no timezone is configured. A fixed zone avoids any dependency on system tzdata,
// which minimal container images may omit.
diff --git a/internal/datasource/connector/feishu/drive/connector.go b/internal/datasource/connector/feishu/drive/connector.go
index 41acdb5a1..3ad219078 100644
--- a/internal/datasource/connector/feishu/drive/connector.go
+++ b/internal/datasource/connector/feishu/drive/connector.go
@@ -32,6 +32,7 @@ func NewDriveConnector(region core.Region) *DriveConnector {
// Drive supports resumable streaming sync; the service prefers FetchStream over
// FetchAll/FetchIncremental when a connector implements StreamingConnector.
var _ datasource.StreamingConnector = (*DriveConnector)(nil)
+var _ datasource.FullStreamingConnector = (*DriveConnector)(nil)
// Type returns the connector type identifier.
func (c *DriveConnector) Type() string {
@@ -236,7 +237,8 @@ func (c *DriveConnector) FetchAll(
return nil, err
}
client := core.NewClient(feishuConfig)
- return core.FetchAllEngine(ctx, client, config, resourceIDs, driveOps{region: c.region})
+ return core.FetchAllEngine(ctx, client, config, resourceIDs,
+ &driveOps{region: c.region, parseMode: feishuConfig.ParseMode})
}
// FetchIncremental performs an incremental sync by comparing file modified_time
@@ -251,7 +253,7 @@ func (c *DriveConnector) FetchIncremental(
return nil, nil, err
}
client := core.NewClient(feishuConfig)
- ops := driveOps{region: c.region}
+ ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, nil, errors.New(ops.EmptyResourceIDsError())
}
@@ -275,22 +277,47 @@ func (c *DriveConnector) FetchStream(
return nil, err
}
client := core.NewClient(feishuConfig)
- ops := driveOps{region: c.region}
+ ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchStreamEngine(ctx, client, config, cursor, h, ops)
}
+// FetchFullStream refetches content without discarding the deletion baseline.
+func (c *DriveConnector) FetchFullStream(
+ ctx context.Context, config *types.DataSourceConfig,
+ cursor *types.SyncCursor, h datasource.StreamHandler,
+) (*types.SyncCursor, error) {
+ feishuConfig, err := core.ParseFeishuConfig(config, c.region)
+ if err != nil {
+ return nil, err
+ }
+ client := core.NewClient(feishuConfig)
+ ops := &driveOps{region: c.region, parseMode: feishuConfig.ParseMode}
+ if len(config.ResourceIDs) == 0 {
+ return nil, errors.New(ops.EmptyResourceIDsError())
+ }
+ return core.FetchFullStreamEngine(ctx, client, config, cursor, h, ops)
+}
+
// driveOps adapts the Drive DriveConnector to the generic sync engine. It
-// carries the region (for channel + URL) and encodes/decodes the Drive cursor
-// wire format (core.FeishuDriveCursor / file_times) so the engine stays format-agnostic.
+// carries the region (for channel + URL), encodes/decodes the Drive cursor
+// wire format (core.FeishuDriveCursor / file_times), and holds the per-run
+// directory mapping state (P1): folderNames caches resolved folder display
+// names, dirPaths maps folder token → cleaned directory path for the resource
+// being synced. List builds the state; Fetch reads it. runSync processes one
+// resource at a time, so the mutation is race-free.
type driveOps struct {
- region core.Region
+ region core.Region
+ parseMode string
+ folderNames map[string]string
+ dirPaths map[string]string
+ rootEntries map[string][]core.DriveFile // successful shallow listings, per run
}
-func (o driveOps) List(ctx context.Context, client *core.Client, resourceID string) ([]core.DriveFile, error, error) {
- files, err := listDriveFilesForResource(ctx, client, resourceID)
+func (o *driveOps) List(ctx context.Context, client *core.Client, resourceID string) ([]core.DriveFile, error, error) {
+ files, err := o.listDriveFilesForResource(ctx, client, resourceID)
if err == nil {
return files, nil, nil
}
@@ -301,16 +328,27 @@ func (o driveOps) List(ctx context.Context, client *core.Client, resourceID stri
return files, nil, err
}
-func (o driveOps) Token(n core.DriveFile) string { return n.Token }
-func (o driveOps) Title(n core.DriveFile) string { return n.Name }
-func (o driveOps) ObjType(n core.DriveFile) string { return n.Type }
-func (o driveOps) EditTime(n core.DriveFile) string { return n.ModifiedTime }
+func (o *driveOps) Token(n core.DriveFile) string { return n.Token }
+func (o *driveOps) Title(n core.DriveFile) string { return n.Name }
+func (o *driveOps) ObjType(n core.DriveFile) string { return n.Type }
+func (o *driveOps) EditTime(n core.DriveFile) string {
+ return core.DocxChangeKey(n.ModifiedTime, n.Type, o.parseMode)
+}
-func (o driveOps) Fetch(ctx context.Context, client *core.Client, n core.DriveFile, resourceID string, multimodal bool) ([]*types.FetchedItem, error) {
- return fetchDriveFileContent(ctx, client, n, resourceID, multimodal, o.region)
+func (o *driveOps) Fetch(
+ ctx context.Context, client *core.Client, n core.DriveFile, resourceID string,
+) ([]*types.FetchedItem, error) {
+ items, err := fetchDriveFileContent(ctx, client, n, resourceID, o.region, o.parseMode)
+ if err != nil {
+ return nil, err
+ }
+ // P1 directory mapping: prefix the FileName with the containing folder's
+ // cleaned directory path so ingestion derives the KB folder_path from it.
+ qualifyItemFileNames(items, o.dirPaths[n.ParentToken])
+ return items, nil
}
-func (o driveOps) ListFailureItems(resourceID string, partial error) []types.FetchedItem {
+func (o *driveOps) ListFailureItems(resourceID string, partial error) []types.FetchedItem {
var pe *core.PartialDriveFileListError
if errors.As(partial, &pe) {
return appendDriveFileListFailureItems(nil, resourceID, o.channel(), pe.Failures)
@@ -318,27 +356,27 @@ func (o driveOps) ListFailureItems(resourceID string, partial error) []types.Fet
return nil
}
-func (o driveOps) channel() string {
+func (o *driveOps) channel() string {
if o.region.ConnectorType == types.ConnectorTypeLarkDrive {
return types.ChannelLarkDrive
}
return types.ChannelFeishuDrive
}
-func (o driveOps) ResourceNoun() string { return "files" }
-func (o driveOps) EmptyResourceIDsError() string {
+func (o *driveOps) ResourceNoun() string { return "files" }
+func (o *driveOps) EmptyResourceIDsError() string {
return "no resource IDs (Drive folder tokens) configured"
}
-func (o driveOps) LogTag() string { return "[FeishuDrive]" }
+func (o *driveOps) LogTag() string { return "[FeishuDrive]" }
-func (o driveOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
+func (o *driveOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
var prev core.FeishuDriveCursor
b, _ := json.Marshal(m)
_ = json.Unmarshal(b, &prev)
return prev.FileTimes
}
-func (o driveOps) EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor {
+func (o *driveOps) EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor {
fc := core.FeishuDriveCursor{LastSyncTime: lastSync, FileTimes: times}
m := make(map[string]interface{})
b, _ := json.Marshal(fc)
@@ -349,14 +387,15 @@ func (o driveOps) EncodeCursor(times map[string]map[string]string, lastSync time
// fetchDriveFileContent fetches the content of a single Drive file and converts
// it to FetchedItems. Dispatches by file.Type, mirroring the wiki
// fetchNodeContent. Shortcuts have already been expanded to their target by
-// ListDriveFilesRecursiveFrom, so this only sees the target type.
+// walkDriveTree, so this only sees the target type.
//
// - docx -> blocks API (Markdown) with export fallback; may return attachments/images
// - doc/sheet/bitable -> ExportAndDownload -> docx/xlsx
// - file -> DownloadDriveFile -> original file
// - mindnote/slides/board -> Skip (no API), returns (nil, nil)
func fetchDriveFileContent(
- ctx context.Context, client *core.Client, file core.DriveFile, resourceID string, multimodalEnabled bool, region core.Region,
+ ctx context.Context, client *core.Client, file core.DriveFile,
+ resourceID string, region core.Region, parseMode string,
) ([]*types.FetchedItem, error) {
if !core.IsSupportedDocType(file.Type) {
return nil, nil
@@ -382,15 +421,15 @@ func fetchDriveFileContent(
switch file.Type {
case "docx":
return core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
- DocToken: file.Token,
- ObjToken: file.Token,
- Title: file.Name,
- URL: file.URL,
- ResourceID: resourceID,
- EditTime: editTime,
- CreateTime: createTime,
- BaseMeta: baseMeta,
- MultimodalEnabled: multimodalEnabled,
+ DocToken: file.Token,
+ ObjToken: file.Token,
+ Title: file.Name,
+ URL: file.URL,
+ ResourceID: resourceID,
+ EditTime: editTime,
+ CreateTime: createTime,
+ ParseMode: parseMode,
+ BaseMeta: baseMeta,
})
case "doc", "sheet", "bitable":
@@ -425,7 +464,7 @@ func fetchDriveFileContent(
return nil, fmt.Errorf("download file %s (%s): %w", file.Name, file.Token, err)
}
- fileName := file.Name
+ fileName := core.SanitizeFileName(file.Name)
if fileName == "" {
fileName = file.Token
}
@@ -466,49 +505,6 @@ func parseDriveResourceID(resourceID string) (rootFolderToken, fileToken string)
return rootFolderToken, fileToken
}
-// listDriveFilesForResource lists the files to sync for a given resourceID.
-// A resourceID is either a bare root folderToken (sync the whole subtree) or
-// "rootFolderToken:fileToken" (sync a single selected file or sub-folder).
-//
-// For a single-file selection we cannot pass the fileToken to
-// ListDriveFilesRecursiveFrom - that API expects a folder and returns 1061002
-// (params error) for a file token. Instead we walk the root folder subtree (the
-// file's parent) and filter to just the selected fileToken. This mirrors the
-// wiki connector, which resolves a single selected node via GetWikiNode; Drive
-// has no single-file meta API, so filtering the subtree walk is the equivalent.
-//
-// A sub-folder selection (fileToken is itself a folder) is handled by walking
-// that sub-folder's subtree directly - ListDriveFilesRecursiveFrom accepts a
-// folder token, so no filtering is needed there.
-func listDriveFilesForResource(
- ctx context.Context, client *core.Client, resourceID string,
-) ([]core.DriveFile, error) {
- rootFolderToken, fileToken := parseDriveResourceID(resourceID)
- if fileToken == "" {
- return client.ListDriveFilesRecursiveFrom(ctx, rootFolderToken)
- }
- files, err := client.ListDriveFilesRecursiveFrom(ctx, fileToken)
- if err == nil {
- return files, nil
- }
- if !isDriveNotFolderError(err) {
- return nil, err
- }
- all, walkErr := client.ListDriveFilesRecursiveFrom(ctx, rootFolderToken)
- if walkErr != nil {
- var partialErr *core.PartialDriveFileListError
- if !errors.As(walkErr, &partialErr) {
- return nil, walkErr
- }
- all = filterDriveFileByToken(all, fileToken)
- if len(all) == 0 {
- return nil, walkErr
- }
- return all, walkErr
- }
- return filterDriveFileByToken(all, fileToken), nil
-}
-
// isDriveNotFolderError reports whether err indicates the token was not a
// folder (1061002 params error from the list API when a file token is passed).
func isDriveNotFolderError(err error) bool {
diff --git a/internal/datasource/connector/feishu/drive/connector_paths_test.go b/internal/datasource/connector/feishu/drive/connector_paths_test.go
new file mode 100644
index 000000000..bc4b9748d
--- /dev/null
+++ b/internal/datasource/connector/feishu/drive/connector_paths_test.go
@@ -0,0 +1,428 @@
+package drive
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// ──────────────────────────────────────────────────────────────────────
+// P1 directory mapping tests for the Drive connector: path-qualified
+// FileName, deletion mirroring, partial-listing suppression, move following.
+// ──────────────────────────────────────────────────────────────────────
+
+// fakeDriveTree serves a mutable Drive folder tree keyed by folder_token.
+// folders maps folder token → direct children (folders recurse, files sync);
+// failing folders return HTTP 500 to model a partial listing; metaNames maps
+// folder token → display name for the folder meta endpoint (absent = error).
+type fakeDriveTree struct {
+ folders map[string][]core.DriveFile
+ failing map[string]bool
+ metaNames map[string]string
+ // listCalls / metaCalls count API hits per token, so tests can assert a
+ // file token is never probed with folder APIs.
+ listCalls map[string]int
+ metaCalls map[string]int
+ ts *httptest.Server
+ cfg *core.Config
+}
+
+func newFakeDriveTree(t *testing.T, folders map[string][]core.DriveFile) *fakeDriveTree {
+ t.Helper()
+ f := &fakeDriveTree{
+ folders: folders, failing: map[string]bool{},
+ listCalls: map[string]int{}, metaCalls: map[string]int{},
+ }
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal",
+ func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, core.TokenResponse{
+ ApiResponse: core.ApiResponse{Code: 0},
+ TenantAccessToken: "fake-token", Expire: 7200,
+ })
+ })
+ // Folder listing (paged endpoint, exact path) and file download (subtree).
+ mux.HandleFunc("/open-apis/drive/v1/files", func(w http.ResponseWriter, r *http.Request) {
+ token := r.URL.Query().Get("folder_token")
+ f.listCalls[token]++
+ if f.failing[token] {
+ w.WriteHeader(http.StatusInternalServerError)
+ _, _ = w.Write([]byte(`{"code":1663,"msg":"internal error"}`))
+ return
+ }
+ writeJSON(w, core.DriveFileListResponse{
+ ApiResponse: core.ApiResponse{Code: 0},
+ Data: core.DriveFileListData{Files: f.folders[token]},
+ })
+ })
+ mux.HandleFunc("/open-apis/drive/v1/files/", func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasSuffix(r.URL.Path, "/download") {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "application/octet-stream")
+ _, _ = w.Write([]byte("fake-drive-file-content"))
+ })
+ mux.HandleFunc("/open-apis/drive/explorer/v2/folder/", func(w http.ResponseWriter, r *http.Request) {
+ // path: /open-apis/drive/explorer/v2/folder/<token>/meta
+ p := strings.TrimPrefix(r.URL.Path, "/open-apis/drive/explorer/v2/folder/")
+ token := strings.TrimSuffix(p, "/meta")
+ f.metaCalls[token]++
+ name, ok := f.metaNames[token]
+ if !ok {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"code":1061004,"msg":"not found"}`))
+ return
+ }
+ writeJSON(w, map[string]interface{}{
+ "code": 0,
+ "data": map[string]interface{}{"name": name},
+ })
+ })
+
+ f.ts = httptest.NewServer(mux)
+ t.Cleanup(f.ts.Close)
+ f.cfg = &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: f.ts.URL}
+ return f
+}
+
+// driveFile builds a regular file entry; folder builds a folder entry.
+func driveFile(token, name, parent string, modified string) core.DriveFile {
+ return core.DriveFile{Token: token, Name: name, Type: "file", ParentToken: parent, ModifiedTime: modified}
+}
+
+func driveFolder(token, name, parent string) core.DriveFile {
+ return core.DriveFile{Token: token, Name: name, Type: "folder", ParentToken: parent}
+}
+
+// fetchedByToken indexes emitted non-deleted items by external_id.
+func fetchedByToken(items []types.FetchedItem) map[string]types.FetchedItem {
+ m := make(map[string]types.FetchedItem, len(items))
+ for _, it := range items {
+ if !it.IsDeleted {
+ m[it.ExternalID] = it
+ }
+ }
+ return m
+}
+
+func deletedIDs(items []types.FetchedItem) []string {
+ var ids []string
+ for _, it := range items {
+ if it.IsDeleted {
+ ids = append(ids, it.ExternalID)
+ }
+ }
+ return ids
+}
+
+// TestDriveFetchIncremental_PathQualifiedMultiLevel anchors the directory
+// mapping: the selected root folder mirrors as a top-level KB folder named
+// after it, so paths are <根名>/<子目录...>/<文件名>, Chinese names kept,
+// "/" in a folder name sanitised to "_", multi-level nesting resolved from
+// the same walk.
+func TestDriveFetchIncremental_PathQualifiedMultiLevel(t *testing.T) {
+ f := newFakeDriveTree(t, map[string][]core.DriveFile{
+ "fold-root": {
+ driveFolder("fold-spec", "规格", "fold-root"),
+ driveFolder("fold-bad", "a/b", "fold-root"), // "/" in the name → "_"
+ driveFile("f-root", "说明.pdf", "fold-root", "100"),
+ },
+ "fold-spec": {driveFile("f-spec", "详细.pdf", "fold-spec", "200")},
+ "fold-bad": {driveFile("f-bad", "child.pdf", "fold-bad", "300")},
+ })
+ f.metaNames = map[string]string{"fold-root": "团队资料"}
+
+ c := NewDriveConnector(core.RegionFeishuDrive)
+ items, _, err := c.FetchIncremental(context.Background(), makeDriveConfig(f.cfg, []string{"fold-root"}), nil)
+ if err != nil {
+ t.Fatalf("FetchIncremental() error: %v", err)
+ }
+
+ want := map[string]string{
+ // The selected root folder mirrors as a top-level KB folder ("团队资料"
+ // via the meta mock): every item's path starts with the root name,
+ // deeper ones then carry the sub-directory path.
+ "f-root": "团队资料/说明.pdf",
+ "f-spec": "团队资料/规格/详细.pdf",
+ "f-bad": "团队资料/a_b/child.pdf",
+ }
+ got := fetchedByToken(items)
+ if len(got) != len(want) {
+ t.Fatalf("got %d items (%v), want %d", len(got), got, len(want))
+ }
+ for id, wantPath := range want {
+ if got[id].FileName != wantPath {
+ t.Errorf("FileName for %s = %q, want %q", id, got[id].FileName, wantPath)
+ }
+ }
+}
+
+// TestDriveFetchIncremental_DeletionMirror anchors the deletion engine: a
+// second full listing that misses a previously synced token emits exactly one
+// IsDeleted item for it; the first sync (no cursor) emits none.
+func TestDriveFetchIncremental_DeletionMirror(t *testing.T) {
+ f := newFakeDriveTree(t, map[string][]core.DriveFile{
+ "fold-root": {
+ driveFile("f-a", "a.pdf", "fold-root", "100"),
+ driveFile("f-b", "b.pdf", "fold-root", "200"),
+ },
+ })
+ f.metaNames = map[string]string{"fold-root": "团队资料"}
+
+ c := NewDriveConnector(core.RegionFeishuDrive)
+ cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
+
+ items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
+ if err != nil {
+ t.Fatalf("first sync error: %v", err)
+ }
+ if ids := deletedIDs(items1); len(ids) != 0 {
+ t.Errorf("first sync emitted IsDeleted items %v — deletion must be suppressed without a prior cursor", ids)
+ }
+
+ // f-a disappears from the tree.
+ f.folders["fold-root"] = []core.DriveFile{driveFile("f-b", "b.pdf", "fold-root", "200")}
+
+ items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
+ if err != nil {
+ t.Fatalf("second sync error: %v", err)
+ }
+ ids := deletedIDs(items2)
+ if len(ids) != 1 || ids[0] != "f-a" {
+ t.Errorf("second sync deleted ids = %v, want [f-a]", ids)
+ }
+}
+
+// TestDriveFetchIncremental_PartialListingDoesNotDelete anchors the partial
+// safety: when a sub-folder cannot be listed, deletion detection is suppressed
+// even though a previously seen token is missing from the (incomplete) listing.
+func TestDriveFetchIncremental_PartialListingDoesNotDelete(t *testing.T) {
+ f := newFakeDriveTree(t, map[string][]core.DriveFile{
+ "fold-root": {
+ driveFolder("fold-doomed", "doomed", "fold-root"),
+ driveFile("f-a", "a.pdf", "fold-root", "100"),
+ },
+ "fold-doomed": {driveFile("f-deep", "deep.pdf", "fold-doomed", "300")},
+ })
+ f.metaNames = map[string]string{"fold-root": "团队资料"}
+ f.failing["fold-doomed"] = true
+
+ c := NewDriveConnector(core.RegionFeishuDrive)
+ cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
+
+ items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
+ if err != nil {
+ t.Fatalf("first sync error: %v", err)
+ }
+ if _, ok := fetchedByToken(items1)["f-a"]; !ok {
+ t.Fatalf("first sync missing f-a: %+v", items1)
+ }
+
+ // f-a disappears while the sub-folder listing stays broken: the listing is
+ // partial, so the missing token must NOT be reported as deleted.
+ f.folders["fold-root"] = []core.DriveFile{driveFolder("fold-doomed", "doomed", "fold-root")}
+
+ items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
+ if err != nil {
+ t.Fatalf("second sync error: %v", err)
+ }
+ if ids := deletedIDs(items2); len(ids) != 0 {
+ t.Errorf("partial listing emitted IsDeleted items %v — deletion must be suppressed on a partial listing", ids)
+ }
+}
+
+// TestDriveFetchIncremental_MoveFollowsNewPath anchors the move story at the
+// connector level: the same external_id re-fetched after being moved between
+// folders comes back with the NEW path-qualified FileName (ingestion's
+// update=delete+recreate then lands it in the new folder_path).
+func TestDriveFetchIncremental_MoveFollowsNewPath(t *testing.T) {
+ f := newFakeDriveTree(t, map[string][]core.DriveFile{
+ "fold-root": {
+ driveFolder("fold-a", "目录A", "fold-root"),
+ },
+ "fold-a": {driveFile("f-doc", "文档.pdf", "fold-a", "100")},
+ })
+ f.metaNames = map[string]string{"fold-root": "团队资料"}
+
+ c := NewDriveConnector(core.RegionFeishuDrive)
+ cfg := makeDriveConfig(f.cfg, []string{"fold-root"})
+
+ items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
+ if err != nil {
+ t.Fatalf("first sync error: %v", err)
+ }
+ if got := fetchedByToken(items1)["f-doc"].FileName; got != "团队资料/目录A/文档.pdf" {
+ t.Fatalf("first sync f-doc FileName = %q, want 团队资料/目录A/文档.pdf", got)
+ }
+
+ // Move f-doc to a new folder 目录B and bump its modified time.
+ f.folders["fold-root"] = []core.DriveFile{
+ driveFolder("fold-a", "目录A", "fold-root"),
+ driveFolder("fold-b", "目录B", "fold-root"),
+ }
+ f.folders["fold-b"] = []core.DriveFile{driveFile("f-doc", "文档.pdf", "fold-b", "200")}
+
+ items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
+ if err != nil {
+ t.Fatalf("second sync error: %v", err)
+ }
+ moved, ok := fetchedByToken(items2)["f-doc"]
+ if !ok {
+ t.Fatalf("moved file not re-fetched on second sync: %+v", items2)
+ }
+ if moved.FileName != "团队资料/目录B/文档.pdf" {
+ t.Errorf("moved file FileName = %q, want 团队资料/目录B/文档.pdf (same external_id, new folder)", moved.FileName)
+ }
+}
+
+// TestDriveFetchIncremental_SingleFileSelectionSkipsFolderProbes anchors the
+// sub-selection fix: a selected file's kind is read off the root subtree
+// listing, so no folder meta/list API is ever called with the file token —
+// probing used to fail with 91202/1061002 and log API errors on every sync.
+func TestDriveFetchIncremental_SingleFileSelectionSkipsFolderProbes(t *testing.T) {
+ f := newFakeDriveTree(t, map[string][]core.DriveFile{
+ "fold-root": {driveFile("f-doc", "文档.docx", "fold-root", "100")},
+ })
+
+ c := NewDriveConnector(core.RegionFeishuDrive)
+ items, _, err := c.FetchIncremental(context.Background(), makeDriveConfig(f.cfg, []string{"fold-root:f-doc"}), nil)
+ if err != nil {
+ t.Fatalf("FetchIncremental() error: %v", err)
+ }
+
+ got := fetchedByToken(items)
+ if len(got) != 1 || got["f-doc"].FileName != "文档.docx" {
+ t.Fatalf("got %d items (%v), want exactly f-doc with its own name", len(got), got)
+ }
+ if f.listCalls["f-doc"] != 0 {
+ t.Errorf("folder list probed the file token %d time(s)", f.listCalls["f-doc"])
+ }
+ if f.metaCalls["f-doc"] != 0 {
+ t.Errorf("folder meta probed the file token %d time(s)", f.metaCalls["f-doc"])
+ }
+}
+
+// TestDriveFetchIncremental_SubFolderSelection pins the sub-folder semantics:
+// only the selected subtree syncs, prefixed with the sub-folder's own name.
+func TestDriveFetchIncremental_SubFolderSelection(t *testing.T) {
+ f := newFakeDriveTree(t, map[string][]core.DriveFile{
+ "fold-root": {
+ driveFolder("fold-spec", "规格", "fold-root"),
+ driveFile("f-root", "说明.pdf", "fold-root", "100"),
+ },
+ "fold-spec": {driveFile("f-spec", "详细.pdf", "fold-spec", "200")},
+ })
+ f.metaNames = map[string]string{"fold-spec": "规格"}
+
+ c := NewDriveConnector(core.RegionFeishuDrive)
+ items, _, err := c.FetchIncremental(
+ context.Background(), makeDriveConfig(f.cfg, []string{"fold-root:fold-spec"}), nil)
+ if err != nil {
+ t.Fatalf("FetchIncremental() error: %v", err)
+ }
+
+ got := fetchedByToken(items)
+ if len(got) != 1 {
+ t.Fatalf("got %d items (%v), want only the selected subtree", len(got), got)
+ }
+ if got["f-spec"].FileName != "规格/详细.pdf" {
+ t.Errorf("FileName for f-spec = %q, want %q", got["f-spec"].FileName, "规格/详细.pdf")
+ }
+}
+
+func TestDriveSubfolderDoesNotWalkUnselectedSiblings(t *testing.T) {
+ for _, nested := range []bool{false, true} {
+ t.Run(map[bool]string{false: "direct", true: "nested"}[nested], func(t *testing.T) {
+ f := newFakeDriveTree(t, map[string][]core.DriveFile{
+ "root": {
+ driveFolder("selected", "Selected", "root"), driveFolder("unselected", "Unselected", "root"),
+ },
+ "selected": {driveFile("doc", "doc.pdf", "selected", "100")},
+ })
+ if nested {
+ f.folders["root"] = []core.DriveFile{driveFolder("unselected", "Unselected", "root")}
+ }
+ f.metaNames = map[string]string{"root": "Root", "selected": "Selected"}
+ // A failure in an unrelated folder must not add retries or partial errors.
+ f.failing["unselected"] = true
+ conn := NewDriveConnector(core.RegionFeishuDrive)
+ cfg := makeDriveConfig(f.cfg, []string{"root:selected"})
+ items, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 1 || items[0].FileName != "Root/Selected/doc.pdf" {
+ t.Fatalf("unexpected items: %+v", items)
+ }
+ if f.listCalls["unselected"] != 0 || f.listCalls["selected"] != 1 {
+ t.Fatalf("unexpected list calls: %v", f.listCalls)
+ }
+ f.folders["selected"] = nil
+ items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ids := deletedIDs(items); len(ids) != 1 || ids[0] != "doc" {
+ t.Fatalf("selected deletion lost: %+v", items)
+ }
+ })
+ }
+}
+
+func TestDriveSelectionsShareShallowRootListing(t *testing.T) {
+ f := newFakeDriveTree(t, map[string][]core.DriveFile{
+ "root": {
+ driveFolder("a", "A", "root"), driveFolder("b", "B", "root"), driveFile("doc", "root.pdf", "root", "100"),
+ },
+ "a": {driveFile("doc-a", "a.pdf", "a", "100")},
+ "b": {driveFile("doc-b", "b.pdf", "b", "100")},
+ })
+ f.metaNames = map[string]string{"root": "Root"}
+ conn := NewDriveConnector(core.RegionFeishuDrive)
+ cfg := makeDriveConfig(f.cfg, []string{"root:a", "root:b", "root:doc"})
+ items, _, err := conn.FetchIncremental(context.Background(), cfg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 3 {
+ t.Fatalf("items=%+v", items)
+ }
+ if f.listCalls["root"] != 1 || f.listCalls["a"] != 1 || f.listCalls["b"] != 1 || f.listCalls["doc"] != 0 {
+ t.Fatalf("unexpected calls: %v", f.listCalls)
+ }
+}
+
+func TestDriveSelectedShortcutKeepsDisplayNameAndTarget(t *testing.T) {
+ for _, selected := range []string{"shortcut", "target"} {
+ t.Run(selected, func(t *testing.T) {
+ var shortcut core.DriveFile
+ raw := `{"token":"shortcut","type":"shortcut","name":"reference.pdf","modified_time":"100",
+ "shortcut_info":{"target_token":"target","target_type":"file"}}`
+ if err := json.Unmarshal([]byte(raw), &shortcut); err != nil {
+ t.Fatal(err)
+ }
+ f := newFakeDriveTree(t, map[string][]core.DriveFile{"root": {shortcut}})
+ f.metaNames = map[string]string{"root": "Root"}
+ conn := NewDriveConnector(core.RegionFeishuDrive)
+ cfg := makeDriveConfig(f.cfg, []string{"root:" + selected})
+ items, _, err := conn.FetchIncremental(context.Background(), cfg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 1 || items[0].ExternalID != "target" || items[0].FileName != "Root/reference.pdf" {
+ t.Fatalf("unexpected shortcut item: %+v", items)
+ }
+ if f.listCalls["target"] != 0 || f.listCalls["shortcut"] != 0 || f.listCalls["root"] != 1 {
+ t.Fatalf("shortcut must not trigger folder probes: %v", f.listCalls)
+ }
+ })
+ }
+}
diff --git a/internal/datasource/connector/feishu/drive/drive_blocks_test.go b/internal/datasource/connector/feishu/drive/drive_blocks_test.go
index d057d3831..6ed362efc 100644
--- a/internal/datasource/connector/feishu/drive/drive_blocks_test.go
+++ b/internal/datasource/connector/feishu/drive/drive_blocks_test.go
@@ -3,9 +3,13 @@ package drive
import (
"bytes"
"context"
+ "encoding/base64"
+ "fmt"
"net/http"
"net/http/httptest"
+ "strconv"
"strings"
+ "sync/atomic"
"testing"
"github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
@@ -13,11 +17,10 @@ import (
)
// makeDriveConfig builds a DataSourceConfig for the Drive connector, mirroring
-// makeConfig but with the drive connector type and a multimodal toggle.
-func makeDriveConfig(cfg *core.Config, resourceIDs []string, multimodal bool) *types.DataSourceConfig {
+// makeConfig but with the drive connector type.
+func makeDriveConfig(cfg *core.Config, resourceIDs []string) *types.DataSourceConfig {
c := makeConfig(cfg, resourceIDs)
c.Type = types.ConnectorTypeFeishuDrive
- c.MultimodalEnabled = multimodal
return c
}
@@ -131,7 +134,6 @@ func driveDocxFile() core.DriveFile {
// A drive docx goes through the blocks path: main Markdown item (external_id =
// file token, channel = feishu_drive) plus the attachment sub-item.
func TestDriveFetchStream_DocxBlocksMultiItem(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const (
attToken = "ft-drv-att"
attName = "report.pdf"
@@ -143,54 +145,57 @@ func TestDriveFetchStream_DocxBlocksMultiItem(t *testing.T) {
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
- _, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}, false), nil, h)
+ _, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
if len(h.emitted) != 2 {
- t.Fatalf("expected 2 emitted items (main doc + attachment), got %d: %+v", len(h.emitted), h.emitted)
+ t.Fatalf("expected 2 emitted items (attachment + main doc), got %d: %+v", len(h.emitted), h.emitted)
}
- main := h.emitted[0]
+ // P3 contract: sub-items are emitted BEFORE the parent document.
+ att := h.emitted[0]
+ wantAttID := driveDocxFileToken + "#file#" + attToken
+ if att.ExternalID != wantAttID {
+ t.Errorf("items[0].ExternalID = %q, want %q", att.ExternalID, wantAttID)
+ }
+ if att.Metadata["attachment"] != "true" {
+ t.Errorf("items[0].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"])
+ }
+ if att.Metadata["parent_doc_id"] != driveDocxFileToken {
+ t.Errorf("items[0].Metadata[parent_doc_id] = %q, want %q", att.Metadata["parent_doc_id"], driveDocxFileToken)
+ }
+
+ main := h.emitted[1]
if main.ExternalID != driveDocxFileToken {
- t.Errorf("items[0].ExternalID = %q, want %q", main.ExternalID, driveDocxFileToken)
+ t.Errorf("items[1].ExternalID = %q, want %q", main.ExternalID, driveDocxFileToken)
}
if main.ContentType != "text/markdown" {
- t.Errorf("items[0].ContentType = %q, want text/markdown", main.ContentType)
+ t.Errorf("items[1].ContentType = %q, want text/markdown", main.ContentType)
}
if !main.ReplacesSubtree {
- t.Errorf("items[0].ReplacesSubtree = false, want true")
+ t.Errorf("items[1].ReplacesSubtree = false, want true")
}
if main.Metadata["channel"] != types.ChannelFeishuDrive {
- t.Errorf("items[0].Metadata[channel] = %q, want %q", main.Metadata["channel"], types.ChannelFeishuDrive)
+ t.Errorf("items[1].Metadata[channel] = %q, want %q", main.Metadata["channel"], types.ChannelFeishuDrive)
}
if main.URL != "https://example.feishu.cn/file/"+driveDocxFileToken {
- t.Errorf("items[0].URL = %q, want drive file URL passthrough", main.URL)
+ t.Errorf("items[1].URL = %q, want drive file URL passthrough", main.URL)
}
if !strings.Contains(string(main.Content), "Hello drive") {
- t.Errorf("items[0].Content missing expected text; got %q", string(main.Content))
- }
-
- att := h.emitted[1]
- wantAttID := driveDocxFileToken + "#file#" + attToken
- if att.ExternalID != wantAttID {
- t.Errorf("items[1].ExternalID = %q, want %q", att.ExternalID, wantAttID)
- }
- if att.Metadata["attachment"] != "true" {
- t.Errorf("items[1].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"])
+ t.Errorf("items[1].Content missing expected text; got %q", string(main.Content))
}
}
// Blocks API failure falls back to export: exactly one octet-stream item, no
// ReplacesSubtree (must not sweep good prior children on a transient failure).
func TestDriveFetchStream_DocxBlocksFailFallsBackToExport(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, nil, "fail", nil)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
- _, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}, false), nil, h)
+ _, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
@@ -216,12 +221,11 @@ func TestDriveFetchStream_DocxBlocksFailFallsBackToExport(t *testing.T) {
// Blocks rendering to empty Markdown also falls back to export (a blank page
// would otherwise ingest as a login-gated URL core.Fetch and fail).
func TestDriveFetchStream_DocxBlocksEmptyFallsBackToExport(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
_, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, nil, "empty", nil)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
- _, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}, false), nil, h)
+ _, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
@@ -238,11 +242,10 @@ func TestDriveFetchStream_DocxBlocksEmptyFallsBackToExport(t *testing.T) {
}
}
-// With multimodal disabled, an embedded image is not downloaded or emitted,
-// but its external_id is still in SubtreeKeep so a later toggle-on does not
-// sweep it, and toggling VLM off later does not delete previously OCR'd images.
-func TestDriveFetchStream_DocxImageMultimodalOff(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
+// Image items are unconditional (not gated by the KB multimodal switch): the
+// download produces a PNG sub-item, the parent's Markdown carries the numbered
+// marker, and the external_id stays in SubtreeKeep.
+func TestDriveFetchStream_DocxImageEmitted(t *testing.T) {
const imgToken = "img-drv-1"
blocks := []core.DocxBlock{
{BlockID: "b1", BlockType: core.BlockTypePage},
@@ -251,27 +254,164 @@ func TestDriveFetchStream_DocxImageMultimodalOff(t *testing.T) {
}},
{BlockID: "b3", BlockType: core.BlockTypeImage, Image: &core.BlockTokenRef{Token: imgToken}},
}
- _, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, blocks, "ok", nil)
+ png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
+ _, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, blocks, "ok", png)
c := NewDriveConnector(core.RegionFeishuDrive)
h := &recordingHandler{}
- _, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}, false), nil, h)
+ _, err := c.FetchStream(context.Background(), makeDriveConfig(cfg, []string{"folder1"}), nil, h)
if err != nil {
t.Fatalf("FetchStream() error: %v", err)
}
+ // Orthodox flow: the image rides inline in the parent markdown as a base64
+ // data URI — one emitted item, no image sub-item, no image_map.
if len(h.emitted) != 1 {
- t.Fatalf("expected 1 emitted item (main only, image core.Skipped), got %d: %+v", len(h.emitted), h.emitted)
+ t.Fatalf("expected 1 emitted item (main only), got %d: %+v", len(h.emitted), h.emitted)
}
main := h.emitted[0]
- wantKeep := driveDocxFileToken + "#image#" + imgToken
- found := false
- for _, k := range main.SubtreeKeep {
- if k == wantKeep {
- found = true
+ if main.ExternalID != driveDocxFileToken {
+ t.Errorf("main ExternalID = %q, want %q", main.ExternalID, driveDocxFileToken)
+ }
+ wantURI := "![图片](data:image/png;base64," + base64.StdEncoding.EncodeToString(png) + ")"
+ if !strings.Contains(string(main.Content), wantURI) {
+ t.Errorf("image not inlined as base64 data URI:\n%s", main.Content)
+ }
+ if main.Metadata["image_map"] != "" {
+ t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
+ }
+}
+
+func TestDriveParseModeChangeRefetchesExistingDocument(t *testing.T) {
+ ts, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
+ driveDocxBlocks("", ""), "ok", nil)
+ defer ts.Close()
+ conf := makeDriveConfig(cfg, []string{"folder1"})
+ conf.Settings = map[string]interface{}{"parse_mode": "export"}
+ c := NewDriveConnector(core.RegionFeishu)
+ items, cursor, err := c.FetchIncremental(context.Background(), conf, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 1 {
+ t.Fatalf("initial sync: %d items", len(items))
+ }
+ for _, mode := range []string{"blocks", "export"} {
+ conf.Settings["parse_mode"] = mode
+ items, cursor, err = c.FetchIncremental(context.Background(), conf, cursor)
+ if err != nil {
+ t.Fatal(err)
}
+ if len(items) != 1 {
+ t.Fatalf("mode %s: want one refreshed document, got %d", mode, len(items))
+ }
+ items, _, err = c.FetchIncremental(context.Background(), conf, cursor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 0 {
+ t.Fatalf("unchanged mode %s unexpectedly refetched", mode)
+ }
+ }
+}
+
+// Image-heavy documents must take the native export path, whose ImageRefs do
+// not have the Markdown data-URI count limit. In particular, no excess base64
+// may be persisted as searchable document text.
+func TestDriveImageBudgetFallsBackToNativeExport(t *testing.T) {
+ for _, count := range []int{types.MaxInlineDocumentImages, types.MaxInlineDocumentImages + 1, 61} {
+ t.Run(strconv.Itoa(count), func(t *testing.T) {
+ blocks := []core.DocxBlock{{BlockID: "page", BlockType: core.BlockTypePage}}
+ for i := 0; i < count; i++ {
+ blocks = append(blocks, core.DocxBlock{
+ BlockID: fmt.Sprintf("img%d", i), BlockType: core.BlockTypeImage,
+ Image: &core.BlockTokenRef{Token: "img"},
+ })
+ }
+ data := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
+ _, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken, blocks, "ok", data)
+ items, err := core.FetchDocxWithBlocks(context.Background(), core.NewClient(cfg), core.DocxFetchInput{
+ DocToken: driveDocxFileToken, ObjToken: driveDocxFileToken, Title: "Images",
+ BaseMeta: map[string]string{}, ParseMode: core.ParseModeBlocks,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 1 {
+ t.Fatalf("want one document, got %d", len(items))
+ }
+ if count <= types.MaxInlineDocumentImages {
+ if n := strings.Count(string(items[0].Content), "data:image/png;base64,"); n != count {
+ t.Fatalf("inline images=%d, want %d", n, count)
+ }
+ } else {
+ if !strings.HasSuffix(items[0].FileName, ".docx") ||
+ string(items[0].Content) != "fake-drive-export-binary" {
+ t.Fatalf("image-heavy document was not exported: %s", items[0].FileName)
+ }
+ if !items[0].ReplacesSubtree {
+ t.Fatal("complete blocks listing must retain attachment reconciliation")
+ }
+ }
+ })
}
- if !found {
- t.Errorf("SubtreeKeep = %v, want it to contain %q", main.SubtreeKeep, wantKeep)
+}
+
+func TestDriveImageBudgetPreservesAttachmentsAndExportFailures(t *testing.T) {
+ for _, failExport := range []bool{false, true} {
+ t.Run(strconv.FormatBool(failExport), func(t *testing.T) {
+ blocks := driveDocxBlocks("attachment", "report.pdf")
+ for i := 0; i < 61; i++ {
+ blocks = append(blocks, core.DocxBlock{
+ BlockID: fmt.Sprintf("img%d", i), BlockType: core.BlockTypeImage,
+ Image: &core.BlockTokenRef{Token: "img"},
+ })
+ }
+ ts, cfg := fakeFeishuDriveDocx(t, []core.DriveFile{driveDocxFile()}, driveDocxFileToken,
+ blocks, "ok", bytes.Repeat([]byte("pdf"), 1024))
+ handler := ts.Config.Handler
+ var mediaDownloads atomic.Int32
+ ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.Contains(r.URL.Path, "/medias/") {
+ mediaDownloads.Add(1)
+ }
+ if failExport && r.URL.Path == "/open-apis/drive/v1/export_tasks" {
+ writeJSON(w, core.ApiResponse{Code: 1, Msg: "export unavailable"})
+ return
+ }
+ handler.ServeHTTP(w, r)
+ })
+ items, err := core.FetchDocxWithBlocks(context.Background(), core.NewClient(cfg), core.DocxFetchInput{
+ DocToken: driveDocxFileToken, ObjToken: driveDocxFileToken, Title: "Images",
+ BaseMeta: map[string]string{}, ParseMode: core.ParseModeBlocks,
+ })
+ if failExport {
+ if err == nil || len(items) != 0 {
+ t.Fatalf("failed export must remain retryable: err=%v items=%d", err, len(items))
+ }
+ if mediaDownloads.Load() != 0 {
+ t.Fatal("media downloaded despite failed parent export")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 2 {
+ t.Fatalf("want attachment and exported parent, got %d", len(items))
+ }
+ parent := items[1]
+ childID := types.SubtreeChildID(driveDocxFileToken, "file", "attachment")
+ if items[0].ExternalID != childID || items[0].Metadata["parent_doc_id"] != parent.ExternalID {
+ t.Fatal("lost attachment association")
+ }
+ if !parent.ReplacesSubtree || len(parent.SubtreeKeep) != 1 || parent.SubtreeKeep[0] != childID ||
+ !strings.Contains(parent.Metadata["attachment_ids"], childID) {
+ t.Fatalf("lost attachment keep list: %+v", parent)
+ }
+ if mediaDownloads.Load() != 1 {
+ t.Fatalf("want only attachment download, got %d", mediaDownloads.Load())
+ }
+ })
}
}
diff --git a/internal/datasource/connector/feishu/drive/paths.go b/internal/datasource/connector/feishu/drive/paths.go
new file mode 100644
index 000000000..75558a072
--- /dev/null
+++ b/internal/datasource/connector/feishu/drive/paths.go
@@ -0,0 +1,158 @@
+package drive
+
+import (
+ "context"
+
+ "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// This file implements the P1 directory mapping for the Drive connector:
+// FetchedItem.FileName becomes "<根文件夹名>/<子目录...>/<文件名>" rooted at
+// the selected sync root's own display name (the root folder = a top-level KB
+// folder) so ingestion's types.SplitKnowledgeRelativePath derives the KB
+// folder_path. The recursive
+// walk itself is core.WalkDriveTree (the Drive connector's single walker,
+// shared with core): DFS order, shortcut expansion, partial-failure
+// aggregation — plus a folder-token → cleaned directory path table built in
+// the same pass, so no extra API calls are made. This file only resolves the
+// per-resource root and feeds the walk results into Fetch.
+
+// driveFolderName resolves a folder's display name via GetDriveFolderMeta,
+// one call per token per sync run (cached on success only — a failure is not
+// cached, so the next resource in the same run retries). resolved is false
+// when the meta call failed or returned no name — that folder's path prefix
+// segment (root or sub-folder) is then skipped.
+func (o *driveOps) driveFolderName(
+ ctx context.Context, client *core.Client, folderToken string,
+) (name string, resolved bool) {
+ if o.folderNames == nil {
+ o.folderNames = make(map[string]string)
+ }
+ if name, ok := o.folderNames[folderToken]; ok {
+ return name, true
+ }
+ meta, err := client.GetDriveFolderMeta(ctx, folderToken)
+ if err != nil {
+ logger.Warnf(ctx, "[FeishuDrive] resolve folder name for %s: %v (falling back)", folderToken, err)
+ return "", false
+ }
+ if meta.Data.Name == "" {
+ return "", false
+ }
+ name = core.SanitizeFileName(meta.Data.Name)
+ o.folderNames[folderToken] = name
+ return name, true
+}
+
+// listDriveFilesForResource lists the files to sync for a resourceID and
+// records the directory-path table for Fetch. A resourceID is either a bare
+// rootFolderToken (sync the whole subtree) or "rootFolderToken:fileToken"
+// (sync a single selected file or sub-folder). Every walk is rooted at the
+// root folder's own display name, so the synced folder appears as a top-level
+// KB folder holding its subtree (an unresolved root name falls back to no
+// prefix, mirroring pre-root-mirror behaviour).
+func (o *driveOps) listDriveFilesForResource(
+ ctx context.Context, client *core.Client, resourceID string,
+) ([]core.DriveFile, error) {
+ rootFolderToken, fileToken := parseDriveResourceID(resourceID)
+
+ rootBase := ""
+ if rootName, ok := o.driveFolderName(ctx, client, rootFolderToken); ok {
+ rootBase = rootName
+ }
+
+ if fileToken == "" {
+ // The selected root folder maps to a top-level KB folder named after
+ // it: documents directly under it land in folder_path "<根名>".
+ files, dirPaths, failures := core.WalkDriveTree(ctx, client, rootFolderToken, rootBase)
+ o.dirPaths = dirPaths
+ return files, partialDriveError(failures)
+ }
+
+ // A shallow root listing identifies direct files without probing them with
+ // folder APIs, and direct folders without visiting unselected siblings.
+ if o.rootEntries == nil {
+ o.rootEntries = make(map[string][]core.DriveFile)
+ }
+ entries, cached := o.rootEntries[rootFolderToken]
+ if !cached {
+ if listed, err := client.ListDriveFilesAllPages(ctx, rootFolderToken); err == nil {
+ entries = listed
+ o.rootEntries[rootFolderToken] = listed
+ }
+ }
+ base := rootBase
+ folderFound := false
+ for _, entry := range entries {
+ f, ok := core.ExpandDriveShortcut(entry)
+ if !ok || (entry.Token != fileToken && f.Token != fileToken) {
+ continue
+ }
+ if f.Type != "folder" {
+ // Some list responses omit parent_token; the listing itself tells
+ // us the containing directory.
+ f.ParentToken = rootFolderToken
+ o.dirPaths = map[string]string{rootFolderToken: rootBase}
+ return []core.DriveFile{f}, nil
+ }
+ folderFound = true
+ base = joinDriveDir(rootBase, core.SanitizeFileName(f.Name))
+ break
+ }
+ if !folderFound {
+ // A nested selected folder can be walked directly, even when the
+ // caller cannot list its parent. No full-root discovery is needed.
+ if subName, ok := o.driveFolderName(ctx, client, fileToken); ok {
+ base = joinDriveDir(rootBase, subName)
+ }
+ }
+ files, dirPaths, failures := core.WalkDriveTree(ctx, client, fileToken, base)
+ for _, failure := range failures {
+ if failure.FolderToken == fileToken && isDriveNotFolderError(failure.Err) {
+ // Only nested single files need the legacy root search: Drive
+ // exposes no single-file parent query. Never use this fallback for
+ // permission/transport failures, which must retain the old cursor.
+ rootFiles, rootDirs, rootFailures := core.WalkDriveTree(ctx, client, rootFolderToken, rootBase)
+ o.dirPaths = rootDirs
+ return filterDriveFileByToken(rootFiles, fileToken), partialDriveError(rootFailures)
+ }
+ }
+ o.dirPaths = dirPaths
+ return files, partialDriveError(failures)
+}
+
+func joinDriveDir(parent, name string) string {
+ if parent == "" {
+ return name
+ }
+ if name == "" {
+ return parent
+ }
+ return parent + "/" + name
+}
+
+// partialDriveError wraps collected failures into a
+// *core.PartialDriveFileListError (nil when there are none).
+func partialDriveError(failures []core.DriveFileListFailure) error {
+ if len(failures) == 0 {
+ return nil
+ }
+ return &core.PartialDriveFileListError{Failures: failures}
+}
+
+// qualifyItemFileNames prefixes every fetched item's FileName with dir so
+// ingestion derives the KB folder path. The prefix applies to the main item
+// and to attachment/image sub-items alike — they all live in the same folder.
+// An empty dir (parent folder not in the current walk) or FileName is untouched.
+func qualifyItemFileNames(items []*types.FetchedItem, dir string) {
+ if dir == "" {
+ return
+ }
+ for _, it := range items {
+ if it != nil && it.FileName != "" {
+ it.FileName = dir + "/" + it.FileName
+ }
+ }
+}
diff --git a/internal/datasource/connector/feishu/wiki/connector.go b/internal/datasource/connector/feishu/wiki/connector.go
index 761c2705b..c3fec3921 100644
--- a/internal/datasource/connector/feishu/wiki/connector.go
+++ b/internal/datasource/connector/feishu/wiki/connector.go
@@ -2,9 +2,11 @@ package wiki
import (
"context"
+ "crypto/sha256"
"encoding/json"
"errors"
"fmt"
+ "strconv"
"strings"
"time"
@@ -29,6 +31,7 @@ func NewConnector(region core.Region) *Connector {
// Feishu supports resumable streaming sync; the service prefers FetchStream over
// FetchAll/FetchIncremental when a connector implements StreamingConnector.
var _ datasource.StreamingConnector = (*Connector)(nil)
+var _ datasource.FullStreamingConnector = (*Connector)(nil)
// Type returns the connector type identifier.
func (c *Connector) Type() string {
@@ -171,7 +174,8 @@ func (c *Connector) FetchAll(ctx context.Context, config *types.DataSourceConfig
return nil, err
}
client := core.NewClient(feishuConfig)
- return core.FetchAllEngine(ctx, client, config, resourceIDs, wikiOps{region: c.region})
+ return core.FetchAllEngine(ctx, client, config, resourceIDs,
+ &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode})
}
// FetchIncremental performs an incremental sync by comparing node edit times
@@ -185,7 +189,7 @@ func (c *Connector) FetchIncremental(ctx context.Context, config *types.DataSour
return nil, nil, err
}
client := core.NewClient(feishuConfig)
- ops := wikiOps{region: c.region}
+ ops := &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, nil, errors.New(ops.EmptyResourceIDsError())
}
@@ -209,56 +213,148 @@ func (c *Connector) FetchStream(
return nil, err
}
client := core.NewClient(feishuConfig)
- ops := wikiOps{region: c.region}
+ ops := &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode}
if len(config.ResourceIDs) == 0 {
return nil, errors.New(ops.EmptyResourceIDsError())
}
return core.FetchStreamEngine(ctx, client, config, cursor, h, ops)
}
+// FetchFullStream refetches content without discarding the deletion baseline.
+func (c *Connector) FetchFullStream(
+ ctx context.Context, config *types.DataSourceConfig,
+ cursor *types.SyncCursor, h datasource.StreamHandler,
+) (*types.SyncCursor, error) {
+ feishuConfig, err := core.ParseFeishuConfig(config, c.region)
+ if err != nil {
+ return nil, err
+ }
+ client := core.NewClient(feishuConfig)
+ ops := &wikiOps{region: c.region, parseMode: feishuConfig.ParseMode}
+ if len(config.ResourceIDs) == 0 {
+ return nil, errors.New(ops.EmptyResourceIDsError())
+ }
+ return core.FetchFullStreamEngine(ctx, client, config, cursor, h, ops)
+}
+
// wikiOps adapts the wiki Connector to the generic sync engine. It carries the
-// region (for URL rendering) and encodes/decodes the wiki cursor wire format
-// (core.FeishuCursor / space_node_times) so the engine can stay format-agnostic.
+// region (for URL rendering), encodes/decodes the wiki cursor wire format
+// (core.FeishuCursor / space_node_times), and holds the per-run directory
+// mapping state (P1): dirPaths maps node token → cleaned directory prefix
+// rooted at the space's own name, so every synced space lands in a top-level
+// KB folder named after the space. List builds the state for the resource
+// being synced; Fetch reads it. runSync processes one resource at a time, so
+// the mutation is race-free.
type wikiOps struct {
- region core.Region
+ region core.Region
+ parseMode string
+ dirPaths map[string]string
+ // spacePrefixes caches spaceID → sanitized folder prefix for the run, so
+ // syncing K selected spaces costs one ListWikiSpaces paging pass total
+ // instead of one per space (failures cache "" and do not retry mid-run).
+ spacePrefixes map[string]string
+}
+
+// spaceDirPrefix resolves the synced space's display name (sanitized) as the
+// top-level KB folder for this run, cached per space for the whole run.
+// An unresolved name yields "" and the documents fall back to landing at the
+// KB root (pre-mirror behaviour) rather than failing the sync.
+func (o *wikiOps) spaceDirPrefix(ctx context.Context, client *core.Client, spaceID string) string {
+ if o.spacePrefixes == nil {
+ o.spacePrefixes = make(map[string]string)
+ }
+ if prefix, ok := o.spacePrefixes[spaceID]; ok {
+ return prefix
+ }
+ prefix := ""
+ spaces, err := client.ListWikiSpaces(ctx)
+ if err != nil {
+ logger.Warnf(ctx, "[Feishu] list wiki spaces for space folder prefix %s: %v", spaceID, err)
+ } else {
+ for _, s := range spaces {
+ if s.SpaceID == spaceID && s.Name != "" {
+ prefix = core.SanitizeFileName(s.Name)
+ break
+ }
+ }
+ }
+ o.spacePrefixes[spaceID] = prefix
+ return prefix
}
-func (o wikiOps) List(ctx context.Context, client *core.Client, resourceID string) ([]core.WikiNode, error, error) {
+func (o *wikiOps) List(ctx context.Context, client *core.Client, resourceID string) ([]core.WikiNode, error, error) {
spaceID, nodeToken := parseWikiResourceID(resourceID)
nodes, err := client.ListWikiNodesRecursiveFrom(ctx, spaceID, nodeToken)
- if err == nil {
- return nodes, nil, nil
- }
- var partial *core.PartialWikiNodeListError
- if errors.As(err, &partial) {
+ if err != nil {
+ var partial *core.PartialWikiNodeListError
+ if !errors.As(err, &partial) {
+ // Total listing failure: nothing usable — abort the sync.
+ return nodes, nil, err
+ }
// Partial listing: nodes are still usable; the failed sub-trees are
// surfaced via ListFailureItems, and the sync continues.
+ }
+ // On a partial listing the original's descendants may be missing even
+ // when the original node itself is present. Keep the accessible shortcut.
+ if err == nil {
+ nodes = filterShortcutSubtrees(nodes)
+ }
+ o.prepareDirPaths(nodes, o.spaceDirPrefix(ctx, client, spaceID))
+ if err != nil {
return nodes, err, nil
}
- return nodes, nil, err
+ return nodes, nil, nil
}
-func (o wikiOps) Token(n core.WikiNode) string { return n.NodeToken }
-func (o wikiOps) Title(n core.WikiNode) string { return n.Title }
-func (o wikiOps) ObjType(n core.WikiNode) string { return n.ObjType }
+func (o *wikiOps) Token(n core.WikiNode) string { return n.NodeToken }
+func (o *wikiOps) Title(n core.WikiNode) string { return n.Title }
+func (o *wikiOps) ObjType(n core.WikiNode) string { return n.ObjType }
+
+// EditTime is an opaque change key including the effective destination path.
+// An ancestor rename/move changes that path without touching this node's times.
+// Timestamp-only legacy cursors refresh once; source_updated_at still uses
+// contentEditTime and never contains the path fingerprint.
+func (o *wikiOps) EditTime(n core.WikiNode) string {
+ timestamp := core.DocxChangeKey(wikiNodeEditTime(n), n.ObjType, o.parseMode)
+ if dir, ok := o.dirPaths[n.NodeToken]; ok {
+ pathHash := sha256.Sum256([]byte(dir + "\x00" + core.SanitizeFileName(n.Title)))
+ return fmt.Sprintf("%s:%x", timestamp, pathHash)
+ }
+ return timestamp
+}
-// EditTime is the change-detection timestamp: ObjEditTime (document content)
-// with a NodeEditTime fallback for nodes that lack obj_edit_time. It drives the
-// cursor comparison and, parsed, FetchedItem.UpdatedAt (see contentEditTime),
-// so the persisted source_updated_at tracks content edits, not node moves.
-func (o wikiOps) EditTime(n core.WikiNode) string {
- if n.ObjEditTime != "" {
+func wikiNodeEditTime(n core.WikiNode) string {
+ obj, objErr := strconv.ParseInt(n.ObjEditTime, 10, 64)
+ node, nodeErr := strconv.ParseInt(n.NodeEditTime, 10, 64)
+ switch {
+ case objErr != nil && nodeErr != nil:
+ return n.ObjEditTime
+ case objErr != nil:
+ return n.NodeEditTime
+ case nodeErr != nil:
+ return n.ObjEditTime
+ case node > obj:
+ return n.NodeEditTime
+ default:
return n.ObjEditTime
}
- return n.NodeEditTime
}
-func (o wikiOps) Fetch(ctx context.Context, client *core.Client, n core.WikiNode, resourceID string, multimodal bool) ([]*types.FetchedItem, error) {
+func (o *wikiOps) Fetch(
+ ctx context.Context, client *core.Client, n core.WikiNode, resourceID string,
+) ([]*types.FetchedItem, error) {
spaceID, _ := parseWikiResourceID(resourceID)
- return fetchNodeContent(ctx, client, n, spaceID, resourceID, multimodal, o.region)
+ items, err := fetchNodeContent(ctx, client, n, spaceID, resourceID, o.region, o.parseMode)
+ if err != nil {
+ return nil, err
+ }
+ // P1 directory mapping: prefix the FileName with the node's cleaned
+ // directory path so ingestion derives the KB folder_path from it.
+ qualifyItemFileNames(items, o.dirPaths[n.NodeToken])
+ return items, nil
}
-func (o wikiOps) ListFailureItems(resourceID string, partial error) []types.FetchedItem {
+func (o *wikiOps) ListFailureItems(resourceID string, partial error) []types.FetchedItem {
spaceID, _ := parseWikiResourceID(resourceID)
var pe *core.PartialWikiNodeListError
if errors.As(partial, &pe) {
@@ -267,20 +363,20 @@ func (o wikiOps) ListFailureItems(resourceID string, partial error) []types.Fetc
return nil
}
-func (o wikiOps) ResourceNoun() string { return "nodes" }
-func (o wikiOps) EmptyResourceIDsError() string {
+func (o *wikiOps) ResourceNoun() string { return "nodes" }
+func (o *wikiOps) EmptyResourceIDsError() string {
return "no resource IDs (wiki space IDs or wiki node IDs) configured"
}
-func (o wikiOps) LogTag() string { return "[Feishu]" }
+func (o *wikiOps) LogTag() string { return "[Feishu]" }
-func (o wikiOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
+func (o *wikiOps) DecodeCursorTimes(m map[string]interface{}) map[string]map[string]string {
var prev core.FeishuCursor
b, _ := json.Marshal(m)
_ = json.Unmarshal(b, &prev)
return prev.SpaceNodeTimes
}
-func (o wikiOps) EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor {
+func (o *wikiOps) EncodeCursor(times map[string]map[string]string, lastSync time.Time) *types.SyncCursor {
fc := core.FeishuCursor{LastSyncTime: lastSync, SpaceNodeTimes: times}
m := make(map[string]interface{})
b, _ := json.Marshal(fc)
@@ -319,7 +415,10 @@ func appendWikiNodeListFailureItems(items []types.FetchedItem, spaceID string, r
// - file → drive download → original file (PDF/Word/image/etc.)
// - mindnote → Skip (no API)
// - slides → Skip (no API)
-func fetchNodeContent(ctx context.Context, client *core.Client, node core.WikiNode, spaceID string, resourceID string, multimodalEnabled bool, region core.Region) ([]*types.FetchedItem, error) {
+func fetchNodeContent(
+ ctx context.Context, client *core.Client, node core.WikiNode,
+ spaceID string, resourceID string, region core.Region, parseMode string,
+) ([]*types.FetchedItem, error) {
if !core.IsSupportedDocType(node.ObjType) {
return nil, nil
}
@@ -339,15 +438,15 @@ func fetchNodeContent(ctx context.Context, client *core.Client, node core.WikiNo
switch node.ObjType {
case "docx":
return core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
- DocToken: node.NodeToken,
- ObjToken: node.ObjToken,
- Title: node.Title,
- URL: region.WikiURL(node.NodeToken),
- ResourceID: resourceID,
- EditTime: editTime,
- CreateTime: createTime,
- BaseMeta: baseMeta,
- MultimodalEnabled: multimodalEnabled,
+ DocToken: node.NodeToken,
+ ObjToken: node.ObjToken,
+ Title: node.Title,
+ URL: region.WikiURL(node.NodeToken),
+ ResourceID: resourceID,
+ EditTime: editTime,
+ CreateTime: createTime,
+ ParseMode: parseMode,
+ BaseMeta: baseMeta,
})
case "doc", "sheet", "bitable":
item, err := fetchViaExport(ctx, client, node, resourceID, editTime, baseMeta, region)
@@ -409,7 +508,7 @@ func fetchDriveFile(ctx context.Context, client *core.Client, node core.WikiNode
}
// Use the node title as file name; it usually preserves the original extension
- fileName := node.Title
+ fileName := core.SanitizeFileName(node.Title)
if fileName == "" {
fileName = node.ObjToken
}
diff --git a/internal/datasource/connector/feishu/wiki/connector_golden_test.go b/internal/datasource/connector/feishu/wiki/connector_golden_test.go
index a7702210c..48425629a 100644
--- a/internal/datasource/connector/feishu/wiki/connector_golden_test.go
+++ b/internal/datasource/connector/feishu/wiki/connector_golden_test.go
@@ -125,15 +125,23 @@ func fakeFeishuGolden(nodes []core.WikiNode, docToken string, blocks []core.Docx
w.Write(data)
})
+ // ParseMode is set explicitly even though blocks is now the default, so the
+ // golden baseline stays valid if the default ever flips again (the env var
+ // FEISHU_DOCX_PARSE_MODE was retired in favor of per-data-source Settings).
ts := httptest.NewServer(mux)
- return ts, &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}
+ return ts, &core.Config{
+ AppID: "test-app-id", AppSecret: "test-app-secret",
+ BaseURL: ts.URL, ParseMode: core.ParseModeBlocks,
+ }
}
func TestGolden_RichDocxAllCapabilities(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const docToken = "obj-golden"
bigPDF := bytes.Repeat([]byte("A"), core.MinAttachmentBytes+512) // kept
tinyPDF := bytes.Repeat([]byte("B"), 100) // whitelisted but too small → dropped
+ // Valid PNG for the embedded image block (image items are unconditional in
+ // the P3 marker pipeline; the media token stays out of the Markdown).
+ png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte("x"), core.MinAttachmentBytes)...)
blocks := []core.DocxBlock{
{BlockID: "root", BlockType: core.BlockTypePage},
@@ -165,7 +173,7 @@ func TestGolden_RichDocxAllCapabilities(t *testing.T) {
NodeToken: "nt-golden", ObjToken: docToken, ObjType: "docx",
Title: "季度报告文档", NodeEditTime: "1711468800",
}}
- media := map[string][]byte{"tok-big": bigPDF, "tok-small": tinyPDF}
+ media := map[string][]byte{"tok-big": bigPDF, "tok-small": tinyPDF, "img-tok-SECRET": png}
ts, cfg := fakeFeishuGolden(nodes, docToken, blocks, media)
defer ts.Close()
@@ -176,21 +184,29 @@ func TestGolden_RichDocxAllCapabilities(t *testing.T) {
t.Fatalf("FetchAll error: %v", err)
}
- // ── main markdown item + exactly one attachment sub-item ──
+ // ── sub-items first (attachment), then the main markdown item ──
+ // Orthodox image flow (2026-09-20): images ride inline in the parent
+ // markdown as base64 data URIs — no image sub-items at all.
if len(items) != 2 {
- t.Fatalf("want 2 items (main + 1 kept attachment), got %d:\n%+v", len(items), items)
+ t.Fatalf("want 2 items (1 kept attachment + main), got %d:\n%+v", len(items), items)
}
var main, att *types.FetchedItem
for i := range items {
- if items[i].ExternalID == "nt-golden" {
+ switch items[i].ExternalID {
+ case "nt-golden":
main = &items[i]
- } else {
+ case "nt-golden#file#tok-big":
att = &items[i]
}
}
if main == nil {
t.Fatal("main markdown item missing")
}
+ // P3 contract: sub-items precede the parent document.
+ if items[len(items)-1].ExternalID != "nt-golden" {
+ order := []string{items[0].ExternalID, items[1].ExternalID, items[2].ExternalID}
+ t.Errorf("main item must be emitted last, got order: %v", order)
+ }
if main.ContentType != "text/markdown" {
t.Errorf("main ContentType = %q, want text/markdown", main.ContentType)
}
@@ -203,6 +219,11 @@ func TestGolden_RichDocxAllCapabilities(t *testing.T) {
md := string(main.Content)
// ── every text construct rendered correctly ──
+ // Baseline re-recorded (2026-09-20, orthodox image flow): image blocks
+ // render inline base64 data URIs (stored to provider:// URLs by the
+ // doc-process image resolver), and file blocks render as
+ // `- 文件名` list entries (whitelisted) or `> [附件: …](链接)` references
+ // (non-whitelisted), replacing the old `📎 附件:…` placeholder.
fragments := []string{
"# 季度报告",
"本季度概览。",
@@ -214,16 +235,16 @@ func TestGolden_RichDocxAllCapabilities(t *testing.T) {
"- [ ] 完成复盘",
"> 注意风险",
"---",
- "| 列A | 列B |", // native docx table header
- "| 1 | 2 |", // native docx table row
- "| 名称 | 数量 |", // embedded sheet header
- "| 苹果 | 3 |", // embedded sheet row
- "| 任务 | 状态 |", // embedded bitable header
- "| 写码 | 完成 |", // embedded bitable row
- "![图片]()", // token-free image placeholder
- "📎 附件:手册.pdf",
- "📎 附件:logo.png",
- "📎 附件:small.pdf",
+ "| 列A | 列B |", // native docx table header
+ "| 1 | 2 |", // native docx table row
+ "| 名称 | 数量 |", // embedded sheet header
+ "| 苹果 | 3 |", // embedded sheet row
+ "| 任务 | 状态 |", // embedded bitable header
+ "| 写码 | 完成 |", // embedded bitable row
+ "![图片](data:image/png;base64,", // image inlined as base64 data URI
+ "- 手册.pdf",
+ "> [附件: logo.png](",
+ "- small.pdf",
}
for _, f := range fragments {
if !strings.Contains(md, f) {
@@ -232,7 +253,7 @@ func TestGolden_RichDocxAllCapabilities(t *testing.T) {
}
// ── document order preserved (heading before table before attachments) ──
- order := []string{"# 季度报告", "## 关键指标", "| 列A | 列B |", "| 名称 | 数量 |", "| 任务 | 状态 |", "📎 附件:手册.pdf"}
+ order := []string{"# 季度报告", "## 关键指标", "| 列A | 列B |", "| 名称 | 数量 |", "| 任务 | 状态 |", "- 手册.pdf"}
last := -1
for _, f := range order {
idx := strings.Index(md, f)
@@ -246,6 +267,13 @@ func TestGolden_RichDocxAllCapabilities(t *testing.T) {
if strings.Contains(md, "img-tok-SECRET") {
t.Errorf("internal image token leaked into markdown:\n%s", md)
}
+ // The internal image media token must map to nothing: markers are gone.
+ if main.Metadata["image_map"] != "" {
+ t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
+ }
+ if !strings.Contains(main.Metadata["attachment_ids"], "nt-golden#file#tok-big") {
+ t.Errorf("main.Metadata[attachment_ids] = %q, want it to contain tok-big", main.Metadata["attachment_ids"])
+ }
// ── attachment filtering: only the big whitelisted PDF becomes a sub-item ──
if att == nil {
diff --git a/internal/datasource/connector/feishu/wiki/connector_stream_test.go b/internal/datasource/connector/feishu/wiki/connector_stream_test.go
index 16f087683..7c80865ca 100644
--- a/internal/datasource/connector/feishu/wiki/connector_stream_test.go
+++ b/internal/datasource/connector/feishu/wiki/connector_stream_test.go
@@ -189,11 +189,15 @@ func TestFetchStream_SkipsUnchangedNodesFromCursor(t *testing.T) {
ts, cfg := fakeFeishu(nodes)
defer ts.Close()
- cursor := makeStreamCursor(t, map[string]map[string]string{
- "space1": {"nt1": "100"}, // nt1 unchanged; nt3 unknown → new
- })
-
c := NewConnector(core.RegionFeishu)
+ _, firstCursor, err := c.FetchIncremental(context.Background(), makeConfig(cfg, []string{"space1"}), nil)
+ if err != nil {
+ t.Fatalf("first sync: %v", err)
+ }
+ first := (&wikiOps{}).DecodeCursorTimes(firstCursor.ConnectorCursor)
+ delete(first["space1"], "nt3") // nt1 unchanged; nt3 unknown → new
+ cursor := makeStreamCursor(t, first)
+
h := &recordingHandler{}
if _, err := c.FetchStream(context.Background(), makeConfig(cfg, []string{"space1"}), cursor, h); err != nil {
t.Fatalf("FetchStream() error: %v", err)
@@ -305,7 +309,6 @@ func TestFetchStream_EmitErrorAborts(t *testing.T) {
// no export endpoint is registered, so any accidental fall-through to the export
// path would 404 and surface as a core.Fetch error.
func TestFetchStream_DocxMultiItem(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const (
nodeToken = "nt-blocks"
objToken = "obj-blocks"
@@ -333,27 +336,28 @@ func TestFetchStream_DocxMultiItem(t *testing.T) {
}
if len(h.emitted) != 2 {
- t.Fatalf("expected 2 emitted items (main doc + attachment), got %d: %+v", len(h.emitted), h.emitted)
+ t.Fatalf("expected 2 emitted items (attachment + main doc), got %d: %+v", len(h.emitted), h.emitted)
}
- main := h.emitted[0]
+ // P3 contract: sub-items are emitted BEFORE the parent document.
+ att := h.emitted[0]
+ wantAttID := nodeToken + "#file#" + attToken
+ if att.ExternalID != wantAttID {
+ t.Errorf("items[0].ExternalID = %q, want %q", att.ExternalID, wantAttID)
+ }
+ if att.Metadata["attachment"] != "true" {
+ t.Errorf("items[0].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"])
+ }
+
+ main := h.emitted[1]
if main.ExternalID != nodeToken {
- t.Errorf("items[0].ExternalID = %q, want %q", main.ExternalID, nodeToken)
+ t.Errorf("items[1].ExternalID = %q, want %q", main.ExternalID, nodeToken)
}
if main.ContentType != "text/markdown" {
- t.Errorf("items[0].ContentType = %q, want text/markdown", main.ContentType)
+ t.Errorf("items[1].ContentType = %q, want text/markdown", main.ContentType)
}
if !main.ReplacesSubtree {
- t.Errorf("items[0].ReplacesSubtree = false, want true")
- }
-
- att := h.emitted[1]
- wantAttID := nodeToken + "#file#" + attToken
- if att.ExternalID != wantAttID {
- t.Errorf("items[1].ExternalID = %q, want %q", att.ExternalID, wantAttID)
- }
- if att.Metadata["attachment"] != "true" {
- t.Errorf("items[1].Metadata[attachment] = %q, want \"true\"", att.Metadata["attachment"])
+ t.Errorf("items[1].ReplacesSubtree = false, want true")
}
}
@@ -441,7 +445,6 @@ func fakeFeishuWithBlocksFallback(nodes []core.WikiNode, docToken string) (*http
// "application/octet-stream", not "text/markdown". No hard failure occurs —
// the sync completes successfully with the exported binary.
func TestFetchStream_DocxBlocksFallback(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const (
nodeToken = "nt-fallback"
objToken = "obj-fallback"
diff --git a/internal/datasource/connector/feishu/wiki/connector_test.go b/internal/datasource/connector/feishu/wiki/connector_test.go
index 32999eb4f..fafdbcef7 100644
--- a/internal/datasource/connector/feishu/wiki/connector_test.go
+++ b/internal/datasource/connector/feishu/wiki/connector_test.go
@@ -3,6 +3,7 @@ package wiki
import (
"bytes"
"context"
+ "encoding/base64"
"encoding/json"
"fmt"
"net/http"
@@ -611,8 +612,8 @@ func TestFetchAll_DocxNode(t *testing.T) {
if string(item.Content) != "fake-docx-content" {
t.Errorf("Content = %q, want %q", string(item.Content), "fake-docx-content")
}
- if item.FileName != "exported.docx" {
- t.Errorf("FileName = %q, want %q", item.FileName, "exported.docx")
+ if item.FileName != "Test Space/exported.docx" {
+ t.Errorf("FileName = %q, want %q (space folder + top-level node)", item.FileName, "Test Space/exported.docx")
}
if item.Metadata["obj_type"] != "docx" {
t.Errorf("Metadata[obj_type] = %q", item.Metadata["obj_type"])
@@ -717,8 +718,8 @@ func TestFetchAll_FileNode(t *testing.T) {
if string(item.Content) != "fake-pdf-binary" {
t.Errorf("Content = %q, want %q", string(item.Content), "fake-pdf-binary")
}
- if item.FileName != "manual.pdf" {
- t.Errorf("FileName = %q, want %q", item.FileName, "manual.pdf")
+ if item.FileName != "Test Space/manual.pdf" {
+ t.Errorf("FileName = %q, want %q (space folder + top-level node)", item.FileName, "Test Space/manual.pdf")
}
if item.Metadata["obj_type"] != "file" {
t.Errorf("obj_type = %q, want file", item.Metadata["obj_type"])
@@ -920,6 +921,14 @@ func TestFetchIncremental_FirstSync(t *testing.T) {
if len(items) != 2 {
t.Fatalf("expected 2 items on first sync, got %d", len(items))
}
+ // Deletion detection must not fire on a first sync: with no prior cursor
+ // there is nothing to compare against, so no IsDeleted items may appear.
+ for _, item := range items {
+ if item.IsDeleted {
+ t.Errorf("first sync emitted IsDeleted item for %q — deletion must be suppressed without a prior cursor",
+ item.ExternalID)
+ }
+ }
if cursor == nil {
t.Fatal("expected non-nil cursor")
}
@@ -1093,7 +1102,8 @@ func TestFetchIncremental_ChildNodeListErrorDoesNotDeletePreviouslySeenChildren(
if err := json.Unmarshal(cursorBytes, &restored); err != nil {
t.Fatalf("restore cursor: %v", err)
}
- if restored.SpaceNodeTimes["space1"]["nt-child"] != "150" {
+ previous := (&wikiOps{}).DecodeCursorTimes(cursor.ConnectorCursor)
+ if restored.SpaceNodeTimes["space1"]["nt-child"] != previous["space1"]["nt-child"] {
t.Fatalf("partial sync should preserve previous child cursor entry, got %+v", restored.SpaceNodeTimes["space1"])
}
}
@@ -1391,7 +1401,6 @@ func fakeFeishuWithBlocks(nodes []core.WikiNode, docToken, attToken, attName str
// TestFetchDocxWithBlocks_MultiItem verifies that a docx node returns a main
// Markdown item plus an attachment sub-item when the blocks API succeeds.
func TestFetchDocxWithBlocks_MultiItem(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const (
nodeToken = "nt-docx"
objToken = "obj-docx"
@@ -1417,34 +1426,40 @@ func TestFetchDocxWithBlocks_MultiItem(t *testing.T) {
t.Fatalf("FetchAll() error: %v", err)
}
+ // P3 contract: sub-items are emitted BEFORE the parent document.
if len(items) != 2 {
- t.Fatalf("want 2 items (main doc + attachment), got %d: %+v", len(items), items)
+ t.Fatalf("want 2 items (attachment + main doc), got %d: %+v", len(items), items)
}
- main := items[0]
+ att := items[0]
+ wantAttID := nodeToken + "#file#" + attToken
+ if att.ExternalID != wantAttID {
+ t.Errorf("items[0].ExternalID = %q, want %q", att.ExternalID, wantAttID)
+ }
+ if att.Metadata["attachment"] != "true" {
+ t.Errorf("items[0].Metadata[attachment] = %q, want true", att.Metadata["attachment"])
+ }
+ if att.Metadata["parent_doc_id"] != nodeToken {
+ t.Errorf("items[0].Metadata[parent_doc_id] = %q, want %q", att.Metadata["parent_doc_id"], nodeToken)
+ }
+
+ main := items[1]
if main.ExternalID != nodeToken {
- t.Errorf("items[0].ExternalID = %q, want %q", main.ExternalID, nodeToken)
+ t.Errorf("items[1].ExternalID = %q, want %q", main.ExternalID, nodeToken)
}
if main.ContentType != "text/markdown" {
- t.Errorf("items[0].ContentType = %q, want text/markdown", main.ContentType)
+ t.Errorf("items[1].ContentType = %q, want text/markdown", main.ContentType)
}
if !main.ReplacesSubtree {
- t.Errorf("items[0].ReplacesSubtree = false, want true")
+ t.Errorf("items[1].ReplacesSubtree = false, want true")
}
if !strings.Contains(string(main.Content), "Hello blocks") {
- t.Errorf("items[0].Content missing expected text; got %q", string(main.Content))
- }
-
- att := items[1]
- wantAttID := nodeToken + "#file#" + attToken
- if att.ExternalID != wantAttID {
- t.Errorf("items[1].ExternalID = %q, want %q", att.ExternalID, wantAttID)
- }
- if att.Metadata["attachment"] != "true" {
- t.Errorf("items[1].Metadata[attachment] = %q, want true", att.Metadata["attachment"])
+ t.Errorf("items[1].Content missing expected text; got %q", string(main.Content))
}
- if att.Title != attName {
- t.Errorf("items[1].Title = %q, want %q", att.Title, attName)
+ // The produced attachment is recorded on the parent's attachment_ids.
+ if !strings.Contains(main.Metadata["attachment_ids"], wantAttID) {
+ t.Errorf("main.Metadata[attachment_ids] = %q, want it to contain %q",
+ main.Metadata["attachment_ids"], wantAttID)
}
}
@@ -1513,7 +1528,6 @@ func fakeFeishuWithBlocksAndDownloadStatus(nodes []core.WikiNode, docToken, attT
// subtree sweep is suppressed so a transient failure never deletes the good prior
// copy of the attachment. One bad attachment must not block the whole document.
func TestFetchDocxWithBlocks_AttachmentDownloadFailure(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const (
nodeToken = "nt-docx-fail"
objToken = "obj-docx-fail"
@@ -1542,14 +1556,13 @@ func TestFetchDocxWithBlocks_AttachmentDownloadFailure(t *testing.T) {
"channel": types.ChannelFeishu,
}
items, err := core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
- DocToken: nodeToken,
- ObjToken: objToken,
- Title: "Doc With Bad Attachment",
- URL: conn.region.WikiURL(nodeToken),
- ResourceID: "space1:nt-docx-fail",
- EditTime: core.ParseFeishuTimestamp("1711468800"),
- BaseMeta: baseMeta,
- MultimodalEnabled: true,
+ DocToken: nodeToken,
+ ObjToken: objToken,
+ Title: "Doc With Bad Attachment",
+ URL: conn.region.WikiURL(nodeToken),
+ ResourceID: "space1:nt-docx-fail",
+ EditTime: core.ParseFeishuTimestamp("1711468800"),
+ BaseMeta: baseMeta,
})
if err != nil {
t.Fatalf("a failed attachment must not fail the whole node, got error: %v", err)
@@ -1594,12 +1607,12 @@ func TestFetchDocxWithBlocks_AttachmentDownloadFailure(t *testing.T) {
}
}
-// TestFetchDocxWithBlocks_EmbeddedImage verifies that embedded images are emitted
-// as standalone sub-items (whose bytes flow into the VLM OCR pipeline) only when
-// the KB has multimodal enabled, but their external_id is ALWAYS kept in
-// SubtreeKeep so toggling VLM off later does not sweep previously OCR'd images.
+// TestFetchDocxWithBlocks_EmbeddedImage verifies that embedded images are
+// always emitted as standalone sub-items (the image pipeline is not gated by
+// the KB multimodal switch — that only affects ImageMultimodal sub-chunks in
+// the service layer), the parent carries the image_map marker mapping, and the
+// external_id stays in SubtreeKeep so a later removal doesn't sweep it.
func TestFetchDocxWithBlocks_EmbeddedImage(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const (
nodeToken = "nt-docx-img"
objToken = "obj-docx-img"
@@ -1639,97 +1652,44 @@ func TestFetchDocxWithBlocks_EmbeddedImage(t *testing.T) {
defer ts.Close()
cfg := &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}
- conn := NewConnector(core.RegionFeishu)
ctx := context.Background()
client := core.NewClient(cfg)
node := core.WikiNode{NodeToken: nodeToken, ObjToken: objToken, ObjType: "docx", Title: "Doc With Image", NodeEditTime: "1711468800"}
- baseMeta := map[string]string{"node_token": nodeToken, "channel": types.ChannelFeishu}
- imgChildID := nodeToken + "#image#" + imgToken
- // multimodal ON → image emitted as a sub-item and kept.
+ // Orthodox flow: the image rides inline in the parent markdown as a base64
+ // data URI — no image sub-item, no image_map.
items, err := core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
- DocToken: node.NodeToken,
- ObjToken: node.ObjToken,
- Title: node.Title,
- URL: conn.region.WikiURL(node.NodeToken),
- ResourceID: "space1:" + nodeToken,
- EditTime: core.ParseFeishuTimestamp("1711468800"),
- BaseMeta: baseMeta,
- MultimodalEnabled: true,
+ DocToken: node.NodeToken,
+ ObjToken: node.ObjToken,
+ Title: node.Title,
+ URL: "https://example.feishu.cn/wiki/" + nodeToken,
+ ResourceID: "space1:" + nodeToken,
+ EditTime: core.ParseFeishuTimestamp("1711468800"),
+ BaseMeta: map[string]string{"node_token": nodeToken, "channel": types.ChannelFeishu},
})
if err != nil {
- t.Fatalf("core.FetchDocxWithBlocks (multimodal on): %v", err)
- }
- var main, img *types.FetchedItem
- for _, it := range items {
- switch it.ExternalID {
- case nodeToken:
- main = it
- case imgChildID:
- img = it
- }
- }
- if main == nil {
- t.Fatal("main doc item missing")
- }
- if img == nil {
- t.Fatalf("embedded image sub-item missing; got %+v", items)
- }
- if !strings.HasSuffix(img.FileName, ".png") {
- t.Errorf("image FileName = %q, want a .png extension", img.FileName)
- }
- if img.Metadata["embedded_image"] != "true" {
- t.Errorf("image Metadata[embedded_image] = %q, want true", img.Metadata["embedded_image"])
- }
- if img.Metadata["attachment"] == "true" {
- t.Error("an embedded image must not be marked as a file attachment")
+ t.Fatalf("core.FetchDocxWithBlocks: %v", err)
}
- if len(img.Content) != len(pngBytes) {
- t.Errorf("image Content = %d bytes, want %d", len(img.Content), len(pngBytes))
- }
- if !slices.Contains(main.SubtreeKeep, imgChildID) {
- t.Errorf("SubtreeKeep must contain image %q, got %+v", imgChildID, main.SubtreeKeep)
- }
-
- // multimodal OFF → no image sub-item, but the id is still kept (not swept).
- itemsOff, err := core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
- DocToken: node.NodeToken,
- ObjToken: node.ObjToken,
- Title: node.Title,
- URL: conn.region.WikiURL(node.NodeToken),
- ResourceID: "space1:" + nodeToken,
- EditTime: core.ParseFeishuTimestamp("1711468800"),
- BaseMeta: baseMeta,
- MultimodalEnabled: false,
- })
- if err != nil {
- t.Fatalf("core.FetchDocxWithBlocks (multimodal off): %v", err)
+ if len(items) != 1 {
+ t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
}
- var mainOff *types.FetchedItem
- for _, it := range itemsOff {
- if it.ExternalID == imgChildID {
- t.Errorf("multimodal off must NOT Emit an image sub-item, got %+v", it)
- }
- if it.ExternalID == nodeToken {
- mainOff = it
- }
+ main := items[0]
+ wantURI := "![图片](data:image/png;base64," + base64.StdEncoding.EncodeToString(pngBytes) + ")"
+ if !strings.Contains(string(main.Content), wantURI) {
+ t.Errorf("image not inlined as base64 data URI:\n%s", main.Content[:min(len(main.Content), 400)])
}
- if mainOff == nil {
- t.Fatal("main doc item missing (multimodal off)")
+ if strings.Contains(string(main.Content), "weknora-img://") {
+ t.Errorf("internal marker leaked into stored markdown:\n%s", main.Content[:400])
}
- if !slices.Contains(mainOff.SubtreeKeep, imgChildID) {
- t.Errorf("SubtreeKeep must contain image %q even when multimodal off (so it isn't swept), got %+v",
- imgChildID, mainOff.SubtreeKeep)
+ if main.Metadata["image_map"] != "" {
+ t.Errorf("image_map must be gone, got %q", main.Metadata["image_map"])
}
}
// TestFetchDocxWithBlocks_ImageDownloadFailure verifies that a failed image
-// download (a genuine core.Fetch failure — revoked token, permission gap, transient
-// error) surfaces a visible error sub-item exactly like a failed attachment
-// download, rather than being silently dropped to a server log. The image is
-// still kept in SubtreeKeep so any prior OCR'd copy is preserved.
+// download degrades inline to a plain placeholder: the document still syncs,
+// no error sub-item is produced, and no marker leaks.
func TestFetchDocxWithBlocks_ImageDownloadFailure(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const (
nodeToken = "nt-docx-img-fail"
objToken = "obj-docx-img-fail"
@@ -1746,88 +1706,42 @@ func TestFetchDocxWithBlocks_ImageDownloadFailure(t *testing.T) {
Data: core.DocxBlocksData{
Items: []core.DocxBlock{
{BlockID: "b1", BlockType: core.BlockTypePage},
- {BlockID: "b2", BlockType: core.BlockTypeImage, Image: &core.BlockTokenRef{Token: imgToken}},
+ {BlockID: "b3", BlockType: core.BlockTypeImage, Image: &core.BlockTokenRef{Token: imgToken}},
},
},
})
})
- // Media download always fails.
mux.HandleFunc("/open-apis/drive/v1/medias/", func(w http.ResponseWriter, r *http.Request) {
- http.Error(w, "boom", http.StatusInternalServerError)
+ http.Error(w, "denied", http.StatusForbidden)
})
ts := httptest.NewServer(mux)
defer ts.Close()
cfg := &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: ts.URL}
- conn := NewConnector(core.RegionFeishu)
ctx := context.Background()
client := core.NewClient(cfg)
- node := core.WikiNode{NodeToken: nodeToken, ObjToken: objToken, ObjType: "docx", Title: "Doc With Bad Image", NodeEditTime: "1711468800"}
- baseMeta := map[string]string{"node_token": nodeToken, "channel": types.ChannelFeishu}
- imgChildID := nodeToken + "#image#" + imgToken
+ node := core.WikiNode{NodeToken: nodeToken, ObjToken: objToken, ObjType: "docx", Title: "Doc With Broken Image"}
- // multimodal ON → the download is attempted and fails → a visible error item.
items, err := core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
- DocToken: node.NodeToken,
- ObjToken: node.ObjToken,
- Title: node.Title,
- URL: conn.region.WikiURL(node.NodeToken),
- ResourceID: "space1:" + nodeToken,
- EditTime: core.ParseFeishuTimestamp("1711468800"),
- BaseMeta: baseMeta,
- MultimodalEnabled: true,
+ DocToken: node.NodeToken,
+ ObjToken: node.ObjToken,
+ Title: node.Title,
+ URL: "https://example.feishu.cn/wiki/" + nodeToken,
+ ResourceID: "space1:" + nodeToken,
+ BaseMeta: map[string]string{"node_token": nodeToken, "channel": types.ChannelFeishu},
})
if err != nil {
- t.Fatalf("a failed image download must not fail the whole node, got error: %v", err)
- }
- var main, errItem *types.FetchedItem
- for _, it := range items {
- switch it.ExternalID {
- case nodeToken:
- main = it
- case imgChildID:
- errItem = it
- }
- }
- if main == nil {
- t.Fatal("main doc item missing")
- }
- if errItem == nil {
- t.Fatalf("failed image download must Emit a visible error sub-item, got %+v", items)
+ t.Fatalf("core.FetchDocxWithBlocks: %v", err)
}
- if len(errItem.Content) != 0 {
- t.Errorf("image error item must carry no content, got %d bytes", len(errItem.Content))
+ if len(items) != 1 {
+ t.Fatalf("want 1 item (main only), got %d: %+v", len(items), items)
}
- if errItem.Metadata["error"] == "" {
- t.Error("image error item must carry error metadata for UI visibility")
- }
- if errItem.Metadata["embedded_image"] != "true" {
- t.Errorf("image error item must stay tagged embedded_image=true, got %q", errItem.Metadata["embedded_image"])
- }
- if !slices.Contains(main.SubtreeKeep, imgChildID) {
- t.Errorf("SubtreeKeep must contain the failed image %q so its prior copy is preserved, got %+v",
- imgChildID, main.SubtreeKeep)
- }
-
- // multimodal OFF → the download is never attempted, so no error item, but the
- // id is still kept (not swept).
- itemsOff, err := core.FetchDocxWithBlocks(ctx, client, core.DocxFetchInput{
- DocToken: node.NodeToken,
- ObjToken: node.ObjToken,
- Title: node.Title,
- URL: conn.region.WikiURL(node.NodeToken),
- ResourceID: "space1:" + nodeToken,
- EditTime: core.ParseFeishuTimestamp("1711468800"),
- BaseMeta: baseMeta,
- MultimodalEnabled: false,
- })
- if err != nil {
- t.Fatalf("core.FetchDocxWithBlocks (multimodal off): %v", err)
+ main := items[0]
+ if !strings.Contains(string(main.Content), "![图片]()") {
+ t.Errorf("broken image must degrade to a placeholder:\n%s", main.Content)
}
- for _, it := range itemsOff {
- if it.ExternalID == imgChildID {
- t.Errorf("multimodal off must NOT attempt the image download or Emit an item, got %+v", it)
- }
+ if strings.Contains(string(main.Content), "weknora-img://") {
+ t.Errorf("internal marker leaked into stored markdown:\n%s", main.Content)
}
}
@@ -1835,7 +1749,6 @@ func TestFetchDocxWithBlocks_ImageDownloadFailure(t *testing.T) {
// whose extension is not in the parseable-attachment whitelist (e.g. .png) is NOT
// promoted to a sub-item, but its inline reference IS present in the main document.
func TestFetchDocxWithBlocks_NonWhitelistedExtNotPromoted(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const (
nodeToken = "nt-docx-png"
objToken = "obj-docx-png"
@@ -1866,7 +1779,8 @@ func TestFetchDocxWithBlocks_NonWhitelistedExtNotPromoted(t *testing.T) {
t.Fatalf("want 1 item (main doc only, .png not promoted), got %d: %+v", len(items), items)
}
mainContent := string(items[0].Content)
- if !strings.Contains(mainContent, "📎 附件:icon.png") {
+ // Non-whitelisted files degrade to a reference carrying the source link.
+ if !strings.Contains(mainContent, "> [附件: icon.png](") {
t.Errorf("main doc missing inline reference for icon.png; got:\n%s", mainContent)
}
}
@@ -1875,7 +1789,6 @@ func TestFetchDocxWithBlocks_NonWhitelistedExtNotPromoted(t *testing.T) {
// whitelisted-extension file block whose download is smaller than core.MinAttachmentBytes
// is NOT promoted to a sub-item, but its inline reference IS present in the main doc.
func TestFetchDocxWithBlocks_WhitelistedTinyAttachmentNotPromoted(t *testing.T) {
- t.Setenv("FEISHU_DOCX_PARSE_MODE", "blocks")
const (
nodeToken = "nt-docx-tiny"
objToken = "obj-docx-tiny"
@@ -1906,8 +1819,10 @@ func TestFetchDocxWithBlocks_WhitelistedTinyAttachmentNotPromoted(t *testing.T)
t.Fatalf("want 1 item (main doc only, tiny .pdf not promoted), got %d: %+v", len(items), items)
}
mainContent := string(items[0].Content)
- if !strings.Contains(mainContent, "📎 附件:tiny.pdf") {
- t.Errorf("main doc missing inline reference for tiny.pdf; got:\n%s", mainContent)
+ // A whitelisted file block always renders as a file-name list entry, even
+ // when the download itself is too small to promote.
+ if !strings.Contains(mainContent, "- tiny.pdf") {
+ t.Errorf("main doc missing file-name list entry for tiny.pdf; got:\n%s", mainContent)
}
}
diff --git a/internal/datasource/connector/feishu/wiki/parse_mode_sync_test.go b/internal/datasource/connector/feishu/wiki/parse_mode_sync_test.go
new file mode 100644
index 000000000..42cc78d2c
--- /dev/null
+++ b/internal/datasource/connector/feishu/wiki/parse_mode_sync_test.go
@@ -0,0 +1,43 @@
+package wiki
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
+)
+
+func TestParseModeChangeRefetchesExistingDocument(t *testing.T) {
+ nodes := []core.WikiNode{{NodeToken: "nt1", ObjToken: "obj1", ObjType: "docx", Title: "Doc", ObjEditTime: "100"}}
+ ts, cfg := fakeFeishu(nodes)
+ defer ts.Close()
+ conf := makeConfig(cfg, []string{"space1"})
+ conf.Settings = map[string]interface{}{"parse_mode": "export"}
+ c := NewConnector(core.RegionFeishu)
+ items, cursor, err := c.FetchIncremental(context.Background(), conf, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 1 {
+ t.Fatalf("first sync items=%d", len(items))
+ }
+ t.Setenv("FEISHU_DOCX_PARSE_MODE", "export")
+ for _, mode := range []string{"blocks", "", "blocks", "export"} {
+ conf.Settings["parse_mode"] = mode
+ items, cursor, err = c.FetchIncremental(context.Background(), conf, cursor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 1 {
+ t.Fatalf("parse_mode change must refetch the document: got %d items", len(items))
+ }
+ items, _, err = c.FetchIncremental(context.Background(), conf, cursor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 0 {
+ t.Fatalf("unchanged effective mode must skip document: got %d items", len(items))
+ }
+
+ }
+}
diff --git a/internal/datasource/connector/feishu/wiki/paths.go b/internal/datasource/connector/feishu/wiki/paths.go
new file mode 100644
index 000000000..9601d0fa8
--- /dev/null
+++ b/internal/datasource/connector/feishu/wiki/paths.go
@@ -0,0 +1,142 @@
+package wiki
+
+import (
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// This file implements the P1 directory mapping: FetchedItem.FileName becomes
+// "<空间名>/<目录A>/<目录B>/<文档名>.md" rooted at the synced space's own name
+// (the space = a top-level KB folder) so ingestion's
+// types.SplitKnowledgeRelativePath derives the KB folder_path (GitLab-style).
+// The path table is built per sync run from the recursive node listing — zero
+// engine changes. external_id stays the node token, so a move/rename lands in
+// the new folder through the existing update=delete+recreate path.
+
+// filterShortcutSubtrees drops only shortcuts whose original subtree is also
+// in this complete listing. Never follow origins outside the selected scope:
+// the shortcut can be the only accessible copy of a document.
+func filterShortcutSubtrees(nodes []core.WikiNode) []core.WikiNode {
+ byToken := make(map[string]core.WikiNode, len(nodes))
+ for _, n := range nodes {
+ byToken[n.NodeToken] = n
+ }
+ redundant := make(map[string]bool)
+ for _, n := range nodes {
+ origin, ok := byToken[n.OriginNodeID]
+ if n.NodeType != "shortcut" || !ok || origin.NodeType == "shortcut" {
+ continue
+ }
+ if n.OriginSpaceID != "" && origin.SpaceID != "" && n.OriginSpaceID != origin.SpaceID {
+ continue
+ }
+ // An origin reached only through a shortcut is not an independently
+ // enumerated copy. In particular, do not discard mutually linked trees.
+ if !underShortcut(origin, byToken) {
+ redundant[n.NodeToken] = true
+ }
+ }
+ kept := make([]core.WikiNode, 0, len(nodes))
+ for _, n := range nodes {
+ if underFilteredNode(n, byToken, redundant) {
+ continue
+ }
+ kept = append(kept, n)
+ }
+ return kept
+}
+
+func underFilteredNode(n core.WikiNode, byToken map[string]core.WikiNode, filtered map[string]bool) bool {
+ visited := make(map[string]bool)
+ for token := n.NodeToken; token != "" && !visited[token]; token = byToken[token].ParentNodeID {
+ if filtered[token] {
+ return true
+ }
+ visited[token] = true
+ }
+ return false
+}
+
+// underShortcut reports whether n is itself a shortcut or has one on its
+// ancestor chain within the listed set. An ancestor missing from the listing
+// (subtree root's parent, or a partial listing) ends the walk as "no shortcut".
+func underShortcut(n core.WikiNode, byToken map[string]core.WikiNode) bool {
+ if n.NodeType == "shortcut" {
+ return true
+ }
+ visited := make(map[string]bool)
+ for p := n.ParentNodeID; p != "" && !visited[p]; p = byToken[p].ParentNodeID {
+ visited[p] = true
+ parent, ok := byToken[p]
+ if !ok {
+ return false
+ }
+ if parent.NodeType == "shortcut" {
+ return true
+ }
+ }
+ return false
+}
+
+// buildWikiDirPaths maps each node token to its cleaned directory prefix,
+// rooted at spacePrefix (the synced space's sanitized name): a top-level node
+// maps to spacePrefix (its document lands in the space's own KB folder) and
+// deeper nodes to "<space>/<父目录标题...>". Ancestors are resolved bottom-up
+// through ParentNodeID within the listing; for a sub-tree selection the
+// ancestors above the sub-tree root are unknown, so its documents land
+// directly in the space folder. A docx node that also has children is both a
+// document and a directory — its own item sits beside the child folder it
+// forms. An empty spacePrefix (space name unresolved) falls back to paths
+// relative to the listing root.
+func buildWikiDirPaths(nodes []core.WikiNode, spacePrefix string) map[string]string {
+ byToken := make(map[string]core.WikiNode, len(nodes))
+ for _, n := range nodes {
+ byToken[n.NodeToken] = n
+ }
+ paths := make(map[string]string, len(nodes))
+ for _, n := range nodes {
+ // Walk up collecting ancestor titles, then reverse so the topmost
+ // directory leads; the space name itself leads the chain.
+ var ancestors []string
+ visited := make(map[string]bool)
+ for p := n.ParentNodeID; p != "" && !visited[p]; p = byToken[p].ParentNodeID {
+ visited[p] = true
+ parent, ok := byToken[p]
+ if !ok {
+ break
+ }
+ ancestors = append(ancestors, core.SanitizeFileName(parent.Title))
+ }
+ for i, j := 0, len(ancestors)-1; i < j; i, j = i+1, j-1 {
+ ancestors[i], ancestors[j] = ancestors[j], ancestors[i]
+ }
+ if spacePrefix != "" {
+ ancestors = append([]string{spacePrefix}, ancestors...)
+ }
+ paths[n.NodeToken] = strings.Join(ancestors, "/")
+ }
+ return paths
+}
+
+// prepareDirPaths rebuilds the per-resource directory table. Called from List
+// after removing redundant shortcut subtrees.
+func (o *wikiOps) prepareDirPaths(nodes []core.WikiNode, spacePrefix string) {
+ o.dirPaths = buildWikiDirPaths(nodes, spacePrefix)
+}
+
+// qualifyItemFileNames prefixes every fetched item's FileName with dir so
+// ingestion derives the KB folder path. The prefix applies to the main item
+// and to attachment/image sub-items alike — they all live in the same folder.
+// An empty dir (node not in the current listing) or FileName is untouched.
+func qualifyItemFileNames(items []*types.FetchedItem, dir string) {
+ if dir == "" {
+ return
+ }
+ for _, it := range items {
+ if it != nil && it.FileName != "" {
+ it.FileName = dir + "/" + it.FileName
+ }
+ }
+}
diff --git a/internal/datasource/connector/feishu/wiki/paths_regression_test.go b/internal/datasource/connector/feishu/wiki/paths_regression_test.go
new file mode 100644
index 000000000..cdefcc5db
--- /dev/null
+++ b/internal/datasource/connector/feishu/wiki/paths_regression_test.go
@@ -0,0 +1,147 @@
+package wiki
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+func TestWikiShortcutOutsideSelectionRemainsSyncable(t *testing.T) {
+ for _, resource := range []string{"space1", "space1:shortcut"} {
+ t.Run(resource, func(t *testing.T) {
+ shortcut := fileNode("shortcut", "reference.pdf", func(n *core.WikiNode) {
+ n.NodeType = "shortcut"
+ n.OriginNodeID = "outside"
+ n.OriginSpaceID = "space2"
+ n.HasChild = true
+ })
+ f := newFakeWikiTree(t, []core.WikiNode{shortcut}, map[string][]core.WikiNode{
+ "shortcut": {fileNode("child", "child.pdf")},
+ })
+ conn := NewConnector(core.RegionFeishu)
+ cfg := makeConfig(f.cfg, []string{resource})
+ items, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
+ require.NoError(t, err)
+ require.Len(t, items, 2)
+ require.Equal(t, "shortcut", items[0].ExternalID)
+ require.Equal(t, "Test Space/reference.pdf/child.pdf", items[1].FileName)
+ items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
+ require.NoError(t, err)
+ require.Empty(t, items, "unchanged shortcuts must not be deleted or fetched again")
+ })
+ }
+}
+
+func TestWikiShortcutDedupRequiresIndependentOrigin(t *testing.T) {
+ cases := []struct {
+ name string
+ nodes []core.WikiNode
+ want []string
+ }{
+ {"original in same listing", []core.WikiNode{
+ {NodeToken: "original", NodeType: "origin"},
+ {NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "original"},
+ {NodeToken: "child", ParentNodeID: "shortcut"},
+ }, []string{"original"}},
+ {"original outside selected subtree", []core.WikiNode{
+ {NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "outside"},
+ {NodeToken: "child", ParentNodeID: "shortcut"},
+ }, []string{"shortcut", "child"}},
+ {"origin exists only below shortcut", []core.WikiNode{
+ {NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "original"},
+ {NodeToken: "original", ParentNodeID: "shortcut", NodeType: "origin"},
+ }, []string{"shortcut", "original"}},
+ {"mismatched origin space", []core.WikiNode{
+ {NodeToken: "original", NodeType: "origin", SpaceID: "space1"},
+ {NodeToken: "shortcut", NodeType: "shortcut", OriginNodeID: "original", OriginSpaceID: "space2"},
+ }, []string{"original", "shortcut"}},
+ }
+ for _, tt := range cases {
+ t.Run(tt.name, func(t *testing.T) {
+ var ids []string
+ for _, n := range filterShortcutSubtrees(tt.nodes) {
+ ids = append(ids, n.NodeToken)
+ }
+ require.Equal(t, tt.want, ids)
+ })
+ }
+}
+
+func TestWikiAncestorChangesRefreshDescendants(t *testing.T) {
+ for _, change := range []string{"rename", "move"} {
+ t.Run(change, func(t *testing.T) {
+ parent := fileNode("parent", "Old", func(n *core.WikiNode) { n.HasChild = true })
+ f := newFakeWikiTree(t, []core.WikiNode{parent}, map[string][]core.WikiNode{
+ "parent": {fileNode("child", "child.pdf")},
+ })
+ conn := NewConnector(core.RegionFeishu)
+ cfg := makeConfig(f.cfg, []string{"space1"})
+ _, cursor, err := conn.FetchIncremental(context.Background(), cfg, nil)
+ require.NoError(t, err)
+ want := "Test Space/New/child.pdf"
+ if change == "rename" {
+ f.top[0].Title = "New"
+ f.top[0].NodeEditTime = "200"
+ } else {
+ parent.NodeEditTime = "200"
+ f.top = []core.WikiNode{fileNode("new-parent", "New", func(n *core.WikiNode) { n.HasChild = true })}
+ f.children["new-parent"] = []core.WikiNode{parent}
+ want = "Test Space/New/Old/child.pdf"
+ }
+ items, next, err := conn.FetchIncremental(context.Background(), cfg, cursor)
+ require.NoError(t, err)
+ var child *types.FetchedItem
+ for i := range items {
+ if items[i].ExternalID == "child" {
+ child = &items[i]
+ }
+ }
+ require.NotNil(t, child, "unchanged child must follow its ancestor's path")
+ require.Equal(t, want, child.FileName)
+ require.EqualValues(t, 100, child.UpdatedAt.Unix(), "source timestamp must remain the document's own")
+ items, _, err = conn.FetchIncremental(context.Background(), cfg, next)
+ require.NoError(t, err)
+ require.Empty(t, items)
+ })
+ }
+}
+
+func TestWikiLegacyTimestampCursorRefreshesOnce(t *testing.T) {
+ f := newFakeWikiTree(t, []core.WikiNode{fileNode("doc", "doc.pdf")}, nil)
+ conn := NewConnector(core.RegionFeishu)
+ cfg := makeConfig(f.cfg, []string{"space1"})
+ legacy := makeStreamCursor(t, map[string]map[string]string{"space1": {"doc": "100"}})
+ items, cursor, err := conn.FetchIncremental(context.Background(), cfg, legacy)
+ require.NoError(t, err)
+ require.Len(t, items, 1)
+ items, _, err = conn.FetchIncremental(context.Background(), cfg, cursor)
+ require.NoError(t, err)
+ require.Empty(t, items)
+}
+
+func TestWikiPartialListingKeepsAccessibleShortcut(t *testing.T) {
+ origin := fileNode("origin", "origin.pdf", func(n *core.WikiNode) { n.HasChild = true })
+ shortcut := fileNode("shortcut", "reference.pdf", func(n *core.WikiNode) {
+ n.NodeType = "shortcut"
+ n.OriginNodeID = "origin"
+ n.HasChild = true
+ })
+ server, cfg := fakeFeishuHierarchy([]core.WikiNode{origin, shortcut}, map[string][]core.WikiNode{
+ "shortcut": {fileNode("child", "child.pdf")},
+ }, "origin")
+ defer server.Close()
+ conn := NewConnector(core.RegionFeishu)
+ items, _, err := conn.FetchIncremental(context.Background(), makeConfig(cfg, []string{"space1"}), nil)
+ require.NoError(t, err)
+ var fetched []string
+ for _, item := range items {
+ if item.Metadata["error"] == "" {
+ fetched = append(fetched, item.ExternalID)
+ }
+ }
+ require.Contains(t, fetched, "shortcut")
+ require.Contains(t, fetched, "child", "a failed origin subtree must not suppress the accessible copy")
+}
diff --git a/internal/datasource/connector/feishu/wiki/paths_test.go b/internal/datasource/connector/feishu/wiki/paths_test.go
new file mode 100644
index 000000000..6ff50a847
--- /dev/null
+++ b/internal/datasource/connector/feishu/wiki/paths_test.go
@@ -0,0 +1,282 @@
+package wiki
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// ──────────────────────────────────────────────────────────────────────
+// P1 directory mapping tests: path-qualified FileName, shortcut subtree
+// dedup, move/rename following, anchored against the fake wiki tree below.
+// ──────────────────────────────────────────────────────────────────────
+
+// fakeWikiTree serves a mutable wiki hierarchy: the test can rewrite the tree
+// between sync runs to model moves/renames. All nodes are "file" obj_type so
+// fetchDriveFile uses the node title verbatim as the base file name — the
+// assertions then exercise only the path prefix logic under test.
+type fakeWikiTree struct {
+ top []core.WikiNode
+ children map[string][]core.WikiNode
+ ts *httptest.Server
+ cfg *core.Config
+}
+
+func newFakeWikiTree(t *testing.T, top []core.WikiNode, children map[string][]core.WikiNode) *fakeWikiTree {
+ t.Helper()
+ f := &fakeWikiTree{top: top, children: children}
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, core.TokenResponse{
+ ApiResponse: core.ApiResponse{Code: 0},
+ TenantAccessToken: "fake-token", Expire: 7200,
+ })
+ })
+ mux.HandleFunc("/open-apis/wiki/v2/spaces", func(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, core.WikiSpaceListResponse{
+ ApiResponse: core.ApiResponse{Code: 0},
+ Data: core.WikiSpaceListData{Items: []core.WikiSpace{{SpaceID: "space1", Name: "Test Space"}}},
+ })
+ })
+ mux.HandleFunc("/open-apis/wiki/v2/spaces/space1/nodes", func(w http.ResponseWriter, r *http.Request) {
+ parentToken := r.URL.Query().Get("parent_node_token")
+ nodes := f.top
+ if parentToken != "" {
+ nodes = f.children[parentToken]
+ for i := range nodes {
+ if nodes[i].ParentNodeID == "" {
+ nodes[i].ParentNodeID = parentToken
+ }
+ if nodes[i].SpaceID == "" {
+ nodes[i].SpaceID = "space1"
+ }
+ }
+ }
+ writeJSON(w, core.WikiNodeListResponse{
+ ApiResponse: core.ApiResponse{Code: 0},
+ Data: core.WikiNodeListData{Items: nodes},
+ })
+ })
+ mux.HandleFunc("/open-apis/wiki/v2/spaces/get_node", func(w http.ResponseWriter, r *http.Request) {
+ token := r.URL.Query().Get("token")
+ for _, n := range f.top {
+ if n.NodeToken == token {
+ writeJSON(w, core.WikiNodeInfoResponse{
+ ApiResponse: core.ApiResponse{Code: 0},
+ Data: core.WikiNodeInfoData{Node: n},
+ })
+ return
+ }
+ }
+ for _, group := range f.children {
+ for _, n := range group {
+ if n.NodeToken == token {
+ writeJSON(w, core.WikiNodeInfoResponse{
+ ApiResponse: core.ApiResponse{Code: 0},
+ Data: core.WikiNodeInfoData{Node: n},
+ })
+ return
+ }
+ }
+ }
+ writeJSON(w, core.WikiNodeInfoResponse{ApiResponse: core.ApiResponse{Code: 1663, Msg: "node not found"}})
+ })
+ // Drive download for "file" type nodes.
+ mux.HandleFunc("/open-apis/drive/v1/files/", func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/download") {
+ w.Header().Set("Content-Type", "application/octet-stream")
+ _, _ = w.Write([]byte("fake-file-content"))
+ return
+ }
+ http.NotFound(w, r)
+ })
+
+ f.ts = httptest.NewServer(mux)
+ t.Cleanup(f.ts.Close)
+ f.cfg = &core.Config{AppID: "test-app-id", AppSecret: "test-app-secret", BaseURL: f.ts.URL}
+ return f
+}
+
+func fileNode(token, title string, opts ...func(*core.WikiNode)) core.WikiNode {
+ n := core.WikiNode{
+ NodeToken: token,
+ ObjToken: "obj-" + token,
+ ObjType: "file",
+ NodeType: "origin",
+ Title: title,
+ NodeEditTime: "100",
+ }
+ for _, opt := range opts {
+ opt(&n)
+ }
+ return n
+}
+
+// TestWikiFetchAll_PathQualifiedMultiLevel anchors the multi-level directory
+// mapping: the synced space mirrors as a top-level KB folder named after it,
+// so paths are <空间名>/<目录A>/<目录B>/<文档名>, Chinese directory names kept
+// as-is and "/" inside a directory name sanitised to "_" so it cannot fake an
+// extra nesting level.
+func TestWikiFetchAll_PathQualifiedMultiLevel(t *testing.T) {
+ f := newFakeWikiTree(t,
+ []core.WikiNode{
+ fileNode("nt-dirA", "产品文档", func(n *core.WikiNode) { n.HasChild = true }),
+ fileNode("nt-top", "顶层.pdf"),
+ },
+ map[string][]core.WikiNode{
+ "nt-dirA": {
+ fileNode("nt-dirB", "子/目录", func(n *core.WikiNode) { n.HasChild = true }),
+ },
+ "nt-dirB": {
+ fileNode("nt-leaf", "规格说明.pdf"),
+ },
+ },
+ )
+
+ c := NewConnector(core.RegionFeishu)
+ items, err := c.FetchAll(context.Background(), makeConfig(f.cfg, []string{"space1"}), []string{"space1"})
+ if err != nil {
+ t.Fatalf("FetchAll() error: %v", err)
+ }
+
+ want := map[string]string{
+ // The synced space mirrors as a top-level KB folder ("Test Space" in
+ // the fake tree): every item's prefix starts with the space name,
+ // deeper items then carry the directory path. Base names are
+ // sanitised like directory segments: a "/" in a title must not fake
+ // an extra folder level (nt-dirB), while the directory path prefix
+ // is built from the sanitised folder name (nt-leaf).
+ "nt-dirA": "Test Space/产品文档",
+ "nt-top": "Test Space/顶层.pdf",
+ "nt-dirB": "Test Space/产品文档/子_目录",
+ "nt-leaf": "Test Space/产品文档/子_目录/规格说明.pdf",
+ }
+ got := make(map[string]string, len(items))
+ for _, item := range items {
+ got[item.ExternalID] = item.FileName
+ }
+ if len(got) != len(want) {
+ t.Fatalf("got %d items (%v), want %d", len(got), got, len(want))
+ }
+ for id, wantPath := range want {
+ if got[id] != wantPath {
+ t.Errorf("FileName for %s = %q, want %q", id, got[id], wantPath)
+ }
+ }
+}
+
+// TestWikiFetchAll_ShortcutSubtreeDeduped anchors the shortcut dedup: a
+// shortcut node and its whole subtree are skipped — the origin entity is
+// enumerated at its real location, so the shortcut would duplicate it.
+func TestWikiFetchAll_ShortcutSubtreeDeduped(t *testing.T) {
+ origin := fileNode("nt-origin", "origin.pdf")
+ shortcut := fileNode("nt-shortcut", "origin.pdf", func(n *core.WikiNode) {
+ n.NodeType = "shortcut"
+ n.OriginNodeID = "nt-origin"
+ n.HasChild = true
+ })
+ f := newFakeWikiTree(t,
+ []core.WikiNode{origin, shortcut},
+ map[string][]core.WikiNode{
+ // The client's recursive walk descends into the shortcut (HasChild),
+ // so the listing contains the origin's subtree a second time.
+ "nt-shortcut": {fileNode("nt-under-shortcut", "duplicate.pdf")},
+ },
+ )
+
+ c := NewConnector(core.RegionFeishu)
+ items, cursor, err := c.FetchIncremental(context.Background(), makeConfig(f.cfg, []string{"space1"}), nil)
+ if err != nil {
+ t.Fatalf("FetchIncremental() error: %v", err)
+ }
+
+ if len(items) != 1 {
+ t.Fatalf("expected exactly 1 item (the origin), got %d: %+v", len(items), items)
+ }
+ if items[0].ExternalID != "nt-origin" {
+ t.Errorf("item ExternalID = %q, want nt-origin", items[0].ExternalID)
+ }
+
+ // The cursor must only record the kept node, so the filtered shortcut and
+ // its subtree do not linger as ghosts.
+ var fc core.FeishuCursor
+ b, _ := json.Marshal(cursor.ConnectorCursor)
+ _ = json.Unmarshal(b, &fc)
+ times := fc.SpaceNodeTimes["space1"]
+ if _, ok := times["nt-shortcut"]; ok {
+ t.Error("cursor records the skipped shortcut node")
+ }
+ if _, ok := times["nt-under-shortcut"]; ok {
+ t.Error("cursor records a node under the skipped shortcut subtree")
+ }
+ if _, ok := times["nt-origin"]; !ok {
+ t.Error("cursor missing the origin node")
+ }
+}
+
+// TestWikiFetchIncremental_MoveFollowsNewPath anchors the move/rename story:
+// the external_id is unchanged, and once the node's edit time moves the next
+// sync re-fetches it under the NEW directory path. Ingestion's
+// update=delete+recreate then lands the knowledge row in the new folder_path.
+func TestWikiFetchIncremental_MoveFollowsNewPath(t *testing.T) {
+ doc := fileNode("nt-doc", "文档.pdf", func(n *core.WikiNode) { n.NodeEditTime = "100" })
+ f := newFakeWikiTree(t,
+ []core.WikiNode{
+ fileNode("nt-dirA", "目录A", func(n *core.WikiNode) { n.HasChild = true }),
+ },
+ map[string][]core.WikiNode{"nt-dirA": {doc}},
+ )
+
+ c := NewConnector(core.RegionFeishu)
+ cfg := makeConfig(f.cfg, []string{"space1"})
+
+ items1, cursor, err := c.FetchIncremental(context.Background(), cfg, nil)
+ if err != nil {
+ t.Fatalf("first sync error: %v", err)
+ }
+ if len(items1) != 2 {
+ t.Fatalf("first sync: expected 2 items (dir + doc), got %d: %+v", len(items1), items1)
+ }
+ var docItem *types.FetchedItem
+ for i := range items1 {
+ if items1[i].ExternalID == "nt-doc" {
+ docItem = &items1[i]
+ }
+ }
+ if docItem == nil || docItem.FileName != "Test Space/目录A/文档.pdf" {
+ t.Fatalf("first sync: doc item missing or wrong path: %+v", items1)
+ }
+
+ // Move the doc from 目录A to a new top-level 目录B; the edit time moves so
+ // the incremental fast-path does not skip it.
+ f.top = append(f.top, fileNode("nt-dirB", "目录B", func(n *core.WikiNode) { n.HasChild = true }))
+ f.children = map[string][]core.WikiNode{
+ "nt-dirB": {fileNode("nt-doc", "文档.pdf", func(n *core.WikiNode) { n.NodeEditTime = "200" })},
+ }
+
+ items2, _, err := c.FetchIncremental(context.Background(), cfg, cursor)
+ if err != nil {
+ t.Fatalf("second sync error: %v", err)
+ }
+
+ var moved *types.FetchedItem
+ for i := range items2 {
+ if items2[i].ExternalID == "nt-doc" && !items2[i].IsDeleted {
+ moved = &items2[i]
+ }
+ }
+ if moved == nil {
+ t.Fatalf("moved doc not re-fetched on second sync: %+v", items2)
+ }
+ if moved.FileName != "Test Space/目录B/文档.pdf" {
+ t.Errorf("moved doc FileName = %q, want %q (same external_id, new folder)",
+ moved.FileName, "Test Space/目录B/文档.pdf")
+ }
+}
diff --git a/internal/infrastructure/docparser/image_resolver.go b/internal/infrastructure/docparser/image_resolver.go
index cfbfa24fe..b7c2e67f7 100644
--- a/internal/infrastructure/docparser/image_resolver.go
+++ b/internal/infrastructure/docparser/image_resolver.go
@@ -718,7 +718,7 @@ func (r *ImageResolver) ResolveDataURIImages(
processed := 0
for i := len(matches) - 1; i >= 0; i-- {
- if processed >= maxRemoteImages {
+ if processed >= types.MaxInlineDocumentImages {
break
}
m := matches[i]
diff --git a/internal/infrastructure/docparser/image_resolver_test.go b/internal/infrastructure/docparser/image_resolver_test.go
index a39990ea8..416e11f57 100644
--- a/internal/infrastructure/docparser/image_resolver_test.go
+++ b/internal/infrastructure/docparser/image_resolver_test.go
@@ -18,6 +18,7 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
)
// createTestPNG generates a minimal PNG image with the given dimensions.
@@ -634,3 +635,22 @@ func TestResolveAndStoreSharedMHTMLContract(t *testing.T) {
t.Fatalf("fenced code blank lines changed: %s", out)
}
}
+
+func TestResolveAndStore_ExportImageRefsBeyondInlineBudget(t *testing.T) {
+ data := createTestPNG(200, 150)
+ result := &types.ReadResult{}
+ for i := 0; i < 61; i++ {
+ ref := fmt.Sprintf("image-%d.png", i)
+ result.MarkdownContent += "![image](" + ref + ")\n"
+ result.ImageRefs = append(result.ImageRefs, types.ImageRef{
+ OriginalRef: ref, Filename: ref, ImageData: data, MimeType: "image/png",
+ })
+ }
+ out, images, err := NewImageResolver().ResolveAndStore(context.Background(), result, &captureSaveBytes{}, 1)
+ require.NoError(t, err)
+ require.Len(t, images, 61, "native export ImageRefs must retain all images beyond the inline URI budget")
+ require.NotContains(t, out, "data:image/")
+ for i := 0; i < 61; i++ {
+ require.NotContains(t, out, fmt.Sprintf("](image-%d.png)", i))
+ }
+}
diff --git a/internal/types/datasource.go b/internal/types/datasource.go
index 814b74088..716e36b33 100644
--- a/internal/types/datasource.go
+++ b/internal/types/datasource.go
@@ -228,14 +228,6 @@ type DataSourceConfig struct {
// Connector-specific configuration
Settings map[string]interface{} `json:"settings"`
-
- // MultimodalEnabled mirrors the target knowledge base's VLM/multimodal
- // setting for the current sync run. The service populates it before each fetch
- // and it is never persisted (json:"-") — the KB owns the setting. Connectors
- // use it to decide whether extracting embedded images for OCR is worthwhile:
- // ingesting an image into a KB without VLM is rejected, so image extraction is
- // skipped when this is false.
- MultimodalEnabled bool `json:"-"`
}
// HasCredentials reports whether the credentials map carries any value at
diff --git a/internal/types/docparser.go b/internal/types/docparser.go
index bd780c1cc..3d167791c 100644
--- a/internal/types/docparser.go
+++ b/internal/types/docparser.go
@@ -2,6 +2,11 @@ package types
import "strings"
+// MaxInlineDocumentImages is the number of Markdown data-URI images the parser
+// stores in one pass. Producers must use a file export when a document exceeds
+// this budget, rather than leave unprocessed base64 in searchable content.
+const MaxInlineDocumentImages = 30
+
// ReadRequest is the unified transport-agnostic request for document reading.
// Set FileContent for file mode, URL for URL mode.
type ReadRequest struct {
diff --git a/migrations/sqlite/000040_feishu_deep_adaptation_resync.down.sql b/migrations/sqlite/000040_feishu_deep_adaptation_resync.down.sql
new file mode 100644
index 000000000..479956734
--- /dev/null
+++ b/migrations/sqlite/000040_feishu_deep_adaptation_resync.down.sql
@@ -0,0 +1,7 @@
+-- Migration 000040 down: drop the one-shot resync marker.
+
+UPDATE data_sources
+SET config = json_remove(config, '$.settings.resync_required')
+WHERE deleted_at IS NULL
+ AND type IN ('feishu', 'lark', 'feishu_drive', 'lark_drive')
+ AND json_extract(config, '$.settings.resync_required') IS NOT NULL;
diff --git a/migrations/sqlite/000040_feishu_deep_adaptation_resync.up.sql b/migrations/sqlite/000040_feishu_deep_adaptation_resync.up.sql
new file mode 100644
index 000000000..018601f04
--- /dev/null
+++ b/migrations/sqlite/000040_feishu_deep_adaptation_resync.up.sql
@@ -0,0 +1,19 @@
+-- Migration 000040: feishu deep adaptation — one-shot full-resync marker.
+-- (Postgres twin: versioned/000122_feishu_deep_adaptation_resync.)
+--
+-- Legacy feishu/lark data sources created before the deep-adaptation feature
+-- hold documents ingested through the export path with no knowledge-base
+-- folder paths. This stamps their Settings with a one-shot resync_required
+-- marker; the sync entry upgrades the next run (even a scheduled incremental
+-- one) to a full pass so documents re-ingest with folder paths and
+-- block-level parsing, then clears the marker.
+
+UPDATE data_sources
+SET config = json_set(
+ json_set(config, '$.settings', json(
+ CASE WHEN json_type(config, '$.settings') = 'object'
+ THEN json_extract(config, '$.settings') ELSE '{}' END)),
+ '$.settings.resync_required', json('true'))
+WHERE deleted_at IS NULL
+ AND type IN ('feishu', 'lark', 'feishu_drive', 'lark_drive')
+ AND json_extract(config, '$.settings.resync_required') IS NULL;
diff --git a/migrations/versioned/000122_feishu_deep_adaptation_resync.down.sql b/migrations/versioned/000122_feishu_deep_adaptation_resync.down.sql
new file mode 100644
index 000000000..710282e1a
--- /dev/null
+++ b/migrations/versioned/000122_feishu_deep_adaptation_resync.down.sql
@@ -0,0 +1,7 @@
+-- Migration 000122 down: drop the one-shot resync marker.
+
+UPDATE data_sources
+SET config = config #-'{settings,resync_required}'
+WHERE deleted_at IS NULL
+ AND type IN ('feishu', 'lark', 'feishu_drive', 'lark_drive')
+ AND (config -> 'settings' -> 'resync_required') IS NOT NULL;
diff --git a/migrations/versioned/000122_feishu_deep_adaptation_resync.up.sql b/migrations/versioned/000122_feishu_deep_adaptation_resync.up.sql
new file mode 100644
index 000000000..8901db5cd
--- /dev/null
+++ b/migrations/versioned/000122_feishu_deep_adaptation_resync.up.sql
@@ -0,0 +1,20 @@
+-- Migration 000122: feishu deep adaptation — one-shot full-resync marker.
+--
+-- Legacy feishu/lark data sources created before the deep-adaptation feature
+-- hold documents ingested through the export path with no knowledge-base
+-- folder paths. This stamps their Settings with a one-shot resync_required
+-- marker; the sync entry upgrades the next run (even a scheduled incremental
+-- one) to a full pass so documents re-ingest with folder paths and
+-- block-level parsing, then clears the marker.
+--
+-- Settings is optional; API-created sources may store it as JSON null.
+-- Normalize the parent object before writing its nested marker.
+
+UPDATE data_sources
+SET config = jsonb_set(config, '{settings}',
+ (CASE WHEN jsonb_typeof(config -> 'settings') = 'object'
+ THEN config -> 'settings' ELSE '{}'::jsonb END)
+ || '{"resync_required":true}'::jsonb, true)
+WHERE deleted_at IS NULL
+ AND type IN ('feishu', 'lark', 'feishu_drive', 'lark_drive')
+ AND (config -> 'settings' -> 'resync_required') IS NULL;
diff --git a/website-docs/03-features/10-datasource.md b/website-docs/03-features/10-datasource.md
index f5c359544..66276dd38 100644
--- a/website-docs/03-features/10-datasource.md
+++ b/website-docs/03-features/10-datasource.md
@@ -65,19 +65,76 @@
#### Feishu / Lark(`connector/feishu/wiki/`)
-云盘应用权限、文件夹授权、资源选择和 `FEISHU_DOCX_PARSE_MODE` 取舍见[飞书云盘接入](24-feishu-drive.md)。默认 export 与 blocks 模式的图片、附件语义不同;开启同步删除时会删除当前数据源对应的知识条目。
+云盘应用权限、文件夹授权、资源选择和解析模式取舍见[飞书云盘接入](24-feishu-drive.md)。默认 `blocks` 与 `export` 模式的图片、附件语义见下文;开启同步删除时会删除当前数据源对应的知识条目。
飞书与 Lark(国际版 open.larksuite.com)是部署在两朵隔离云上的同一产品,Wiki/docx/drive API 完全一致,因此**共用同一份连接器代码**,由 `feishu/core/region.go` 中的 `Region` 结构选择云端(`RegionFeishu` / `RegionLark`,分别对应类型 `feishu` / `lark`、API 域名 `open.feishu.cn` / `open.larksuite.com`)。`base_url` 凭据字段可显式覆盖(兼容历史上把 feishu 连接器指向 larksuite 的存量数据源)。
+> **从旧版本升级**:解析模式改为数据源级配置后,升级到本版本有三处行为变化。
+> 1. 环境变量 `FEISHU_DOCX_PARSE_MODE` 已废弃:仅在数据源未配置解析模式时作为回退读取并打印弃用警告,后续版本移除;在 `.env` 中显式设为 `export` 的部署升级后行为不变。
+> 2. 未设置任何解析模式的存量飞书/Lark 数据源,默认解析模式由 `export` 变为 `blocks`。
+> 3. 迁移会给所有存量飞书/Lark 数据源打一次性全量重同步标记:升级后的下一次同步(含计划增量)自动按全量执行,全部文档重新入库并重新计算 embedding/VLM 摘要,产生相应耗时与模型调用开销,完成后标记自动清除。
+
+**应用权限**(飞书/Lark 开放平台 → 企业自建应用 → 权限管理;均为只读权限,开通后需创建并发布新版本才生效)。飞书与 Lark 的权限标识相同,但应用互不通用。
+
+#### 飞书知识库(feishu / lark)所需权限
+
+必选权限:
+
+| 权限 | blocks 模式(默认) | export 模式 | 缺失时的表现 |
+| --- | --- | --- | --- |
+| `wiki:wiki:readonly` | 必选:列举知识库空间与节点树 | 必选 | 加载资源树失败 |
+| `docx:document:readonly` | 必选:blocks API 读取新版文档正文 | 不需要 | docx 文档无法解析 |
+| `drive:drive:readonly` | 必选:下载 docx 内嵌图片/附件、file 类型节点原文件 | 按需:仅同步 file 类型节点时需要 | 内嵌图片/附件或 file 节点下载失败 |
+| `drive:export:readonly` | 按需:sheet/bitable 节点导出 xlsx;blocks 失败或正文为空时的回退导出 | 必选:docx/doc/sheet/bitable 全部走异步导出 | sheet/bitable 节点失败;blocks 回退不可用 |
+
+可选增强权限(仅 blocks 渲染路径使用,缺失时同步不失败、对应能力降级):
+
+| 权限 | 用途 | 缺失时 |
+| --- | --- | --- |
+| `sheets:spreadsheet:readonly` | docx 内嵌电子表格转为 Markdown 表格 | 该块显示「无法读取」占位 |
+| `bitable:app:readonly` | docx 内嵌多维表格转为 Markdown 表格 | 该块显示「无法读取」占位 |
+| `board:whiteboard:node:read` | 画板(含思维导图/流程图)导出为图片内嵌正文 | 占位标记 |
+| `contact:user.base:readonly` | @成员 显示真实姓名 | 降级为「@成员」 |
+| `drive:drive.metadata:readonly` | 正文中的云文档引用回填文档标题 | 保持 URL 形式 |
+
+#### 飞书云盘(feishu_drive / lark_drive)所需权限
+
+不需要 `wiki:wiki:readonly`,其余与知识库连接器同源:
+
+| 权限 | blocks 模式(默认) | export 模式 | 缺失时的表现 |
+| --- | --- | --- | --- |
+| `drive:drive:readonly` | 必选:列举文件夹、下载普通文件、下载 docx 内嵌图片/附件 | 必选:列举文件夹、下载普通文件 | 加载文件夹或同步报 403 |
+| `docx:document:readonly` | 必选:blocks API 读取新版文档正文 | 不需要 | 云文档 docx 无法解析 |
+| `drive:export:readonly` | 按需:表格/多维表格文件导出 xlsx;blocks 回退导出 | 必选:docx/doc/sheet/bitable 全部走异步导出 | 表格类文件失败;blocks 回退不可用 |
+
+可选增强权限与知识库连接器完全相同(见上表),仅 blocks 渲染路径使用。
+
+除上表推荐的只读最小集外,部分接口也接受替代权限(文件夹清单/文件下载可用 `drive:drive`、`space:document:retrieve`、`drive:file:download` 等,素材下载可用 `docs:document.media:download`,导出可用 `docs:document:export`),按最小授权原则不建议开通读写权限。另外,API 权限之外还有一层资源授权:知识库需要知识库管理员授权应用,云盘需要把目标文件夹分享给应用(见[飞书云盘接入](24-feishu-drive.md))。
+
- **认证**(`core/client.go`):`POST /open-apis/auth/v3/tenant_access_token/internal` 换取 tenant_access_token,带互斥锁缓存与过期刷新。
- **资源列举**(`ListResources`):三级懒加载——`parentID==""` 列 Wiki 空间;`parentID==spaceID` 列空间顶层节点;`parentID=="spaceID:nodeToken"` 列该节点子节点。早期版本会预先递归整棵树,大 Wiki 会超时(issue #1672),现在递归只发生在同步时。`ResolveResourceAncestors` 通过 `GetWikiNode` 的 `parent_node_token` 逐级上溯,O(depth) 回显深层勾选。
+- **目录映射**:同步时按 Wiki 节点树 / Drive 文件夹树在知识库内重建同名目录(`knowledges.folder_path`,目录名中的 `/` 等非法字符替换为 `_`)。**选中的同步根本身也镜像为顶层文件夹**——Wiki 空间以其名称建目录(如同步知识库「飞书知识库同步测试」→ 顶层出现 `飞书知识库同步测试/`),Drive 文件夹同理(如同步「测试1」→ 顶层出现 `测试1/`),因此一个知识库同时链接多个飞书数据源时可以一眼区分来源;根名解析失败时退回根不落目录的旧行为,同步不失败。Wiki 侧通过节点时间和目标路径指纹识别改名/移动,祖先目录变化也会触发后代文档重新归档;Drive 侧目录改名/文件移动不改变文件修改时间,增量同步不感知,需手动全量同步刷新目录结构;节点删除时文档跟随删除(彻底删除,不可恢复,可在数据源关闭"同步删除")。Wiki 快捷方式仅在同一次完整列举中包含独立的原节点子树时去重;原节点不在同步范围内或列举不完整时保留快捷方式及其子节点。存量数据源升级后会在下一次同步(含增量)自动按全量执行一次完成目录收敛,无需手动操作。
+- **docx 解析模式**(数据源编辑页 → 解析模式,配置存于数据源级 `settings.parse_mode`,新建默认 `blocks`):旧数据源未显式设置时显示“使用服务器配置”,保存其他设置不会改变其解析方式;也可选择该选项恢复服务器回退配置。有效解析模式改变后,下一次同步(含增量)会重新抓取已有 docx,无需源文档再次修改。
+ - `blocks`(默认)→ blocks API 逐块读取并转为 GFM Markdown(`core/blocks.go`/`markdown.go`),保留代码块语言、LaTeX 公式(`$...$`)、原生表格(**合并单元格拆分为独立单元格并填充左上值**,列对齐随源文档)、任务列表、分栏、高亮块等;文档内嵌的电子表格/多维表格块直接转为文档内 Markdown 表格(合并单元格同样以左上值填充);文档小组件中的时间轴转为 Markdown 列表;覆盖不到的块类型(会话卡片、OKR、议程等无公开内容 API 的少数类型)降级为占位标记,不影响文档其余部分;
+ - `export` → 异步导出 API(`POST /drive/v1/export_tasks`)导出 `.docx` 走通用文档解析。
+ - `doc`(旧版文档)/`sheet`/`bitable` 不受此开关影响,仍走导出通道。
+ - 取舍:**blocks** 快、保留 docx 内 file block 附件、需 `docx:document:readonly`;**export** 慢(异步导出 + docreader 解析)、丢失 docx 内附件、但解析表现与普通 docx 手工上传完全一致。只要正文与附件用默认 blocks 即可;需要与上传流程一致的解析表现时选 export。
+- **内嵌对象**(blocks 模式):
+ - **图片**:下载后存入 WeKnora 存储,Markdown 正文内嵌 WeKnora 持久图片地址;配置了 VLM 的知识库会自动生成 OCR/描述子分块(未配置则仅保留图片,不报错)。**画板**(block 43)经官方 `download_as_image` 接口导出为图片走同一管线,无权限/失败时降级占位(需应用具备 `board:whiteboard:node:read` 权限)。单篇超过 30 个图片/画板块时,正文自动走原生 docx 导出解析,避免超出内联图片预算;已列出的 file block 附件仍单独同步并关联父文档。导出失败会记录失败并在后续同步重试,不会入库带有未处理 base64 的正文。
+ - **文档类附件**(PDF/Markdown/Excel/PPT/Word 等):下载后作为独立知识入库,落在父文档同目录,文件名用附件自身名称;父文档元数据与附件元数据互相记录对方 ID,正文中附件位置以文件名列表展示。同字节文件在多个文档出现时共享同一份知识(去重)。
+ - **电子表格/多维表格块**:转为 GFM 内联表格(非独立文件),检索时保持文档上下文。
+ - **视频**:不存储不解析,正文留占位与飞书原链接。
+- **mention 渲染增强**(blocks 模式,缺权限时同步不失败,仅降级展示):
+ - `mention_user`(@成员):经 contacts API 反查 open_id 显示真实姓名,需 `contact:user.base:readonly`,缺失时降级为「@成员」;
+ - `mention_doc`(云文档引用):经 `POST /drive/v1/metas/batch_query` 批量回填文档标题(≤200/次),需 `drive:drive.metadata:readonly`;无权限(970003)、文档已删(970005)或接口失败时回退为 `[URL](URL)` 形式;
+ - 时间轴等文档小组件块无公开读取 API,渲染为占位注记,不影响文档其余部分。
- **内容抓取**(`fetchNodeContent`)按 `obj_type` 分派:
- - `docx`/`doc` → 异步导出 API(`POST /drive/v1/export_tasks`)导出 `.docx`;
+ - `docx`/`doc` → 按上述解析模式分派;
- `sheet`/`bitable` → 导出 `.xlsx`;
- `file` → drive 原文件下载(PDF/Word/图片等);
- `mindnote`/`slides` → **跳过**(无内容读取 API),并通过 `fetchTally` 统计输出 `discovered/fetched/failed/skipped_unsupported by_type` 摘要日志,解释"发现 13 篇为何只同步了 3 篇"(issue #2136)。
-- **增量逻辑**:游标 `FeishuCursor.SpaceNodeTimes`(`resourceID → nodeToken → editTime`)。变更判定用 `obj_edit_time`(文档内容编辑时间),而**不是** `node_edit_time`(只反映改标题/挪位置)。抓取失败的节点**不推进游标**(保留旧 editTime,下次必然 prev != current 而重试),避免瞬时导出失败导致文档被永久跳过。
-- **FetchStream**:统一全量/增量路径(cursor==nil 即全量),每处理 `FeishuStreamCheckpointInterval = 50` 个节点、或距上次 checkpoint 超过 `FeishuStreamCheckpointMaxInterval = 30s` 就落盘一次游标——后者兜底"少量文档但每篇导出都极慢(被限流)"导致 2 小时超时前从未 checkpoint 的场景。
+- **增量逻辑**:Wiki 游标 `FeishuCursor.SpaceNodeTimes` 保存 `resourceID → nodeToken → 变更键`,由 `obj_edit_time`、`node_edit_time` 的较新值、目标路径指纹以及 docx 的有效解析模式组成,同时识别内容编辑和祖先目录改名/移动;文档源更新时间仍保留内容编辑时间。旧格式游标会刷新一次以升级格式。抓取失败的节点**不推进游标**(保留旧变更键,下次重试),避免瞬时导出失败导致文档被永久跳过。
+- **FetchStream / FetchFullStream**:增量按变更键跳过未修改文档;全量重新抓取全部文档,同时保留旧游标中的删除基线,只有完整列举后才确认删除。中途 checkpoint 保留尚未遍历的旧节点,抓取失败的节点会在后续同步重试。每处理 `FeishuStreamCheckpointInterval = 50` 个节点、或距上次 checkpoint 超过 `FeishuStreamCheckpointMaxInterval = 30s` 就落盘一次游标——后者兜底"少量文档但每篇导出都极慢(被限流)"导致 2 小时超时前从未 checkpoint 的场景。
- **错误分类**(`feishuFailure`):把原始错误归类为稳定 i18n code(`feishu_auth_or_permission` / `feishu_rate_limited` / `feishu_timeout` / `feishu_server_unavailable` / `feishu_api_error`(+code) / `sync_failed`),前端本地化展示;原始 status/body/log_id 只留在服务端日志。
#### GitLab(`connector/gitlab/`)
@@ -247,7 +304,7 @@ flowchart LR
- **防御性取消**:数据源或知识库已被删除时,把 SyncLog 置为 `canceled` 并返回 nil(不再重试)。
- **两条抓取路径**:连接器实现了 `StreamingConnector` 走 `processSyncStreaming`(流式);否则按 `ForceFull || SyncMode==full` 走 `FetchAll`,或带上 `ParseSyncCursor()` 的游标走 `FetchIncremental`(批量)。
-- **流式路径的游标策略**(`streamStartCursor`):用户触发的全量同步在**首次尝试**时丢弃游标全量抓取;Asynq **重试**(attempt > 0)以及所有增量同步都从最后一个 checkpoint 续传。实现了 `FullStreamingConnector` 的连接器(目前为 Confluence)在全量同步时改走 `FetchFullStream`:重新抓取全部条目,同时保留旧游标作为删除对账基线。
+- **流式路径的游标策略**(`streamStartCursor`):用户触发的全量同步在**首次尝试**时丢弃游标全量抓取;Asynq **重试**(attempt > 0)以及所有增量同步都从最后一个 checkpoint 续传。实现了 `FullStreamingConnector` 的连接器(包括 Feishu/Lark Wiki 与云盘、Seafile、Confluence)在全量同步时改走 `FetchFullStream`:重新抓取全部条目,同时保留旧游标作为删除对账基线。
- **入库核心 `applyFetchedItem` → `ingestItem`**:
- `IsDeleted=true` 且 `sync_deletions=true` 时,按租户、知识库、数据源 ID 和 external_id 查找并真实删除对应知识;关闭同步删除则保留已有知识。删除能力还取决于连接器是否提供可靠的删除检测;
- 有 `Content` 字节 → 包装成 `multipart.FileHeader` 走 `KnowledgeService.CreateKnowledgeFromFile`(完整文档解析流水线);只有 `URL` → 走 `CreateKnowledgeFromURL` 由 WeKnora 下载解析;
@@ -391,7 +448,7 @@ type StreamingConnector interface {
}
```
-任务超时后可从最近的 checkpoint 继续处理。Asynq 同步任务超时为 2 小时,流式路径按条目推进,避免缓存全部文件正文。Feishu/Lark(知识库与云盘)、GitLab 和 Confluence 连接器实现了 `StreamingConnector`;Confluence 另实现 `FullStreamingConnector`,全量同步也能对账删除。钉钉目前走 batch `FetchAll`/`FetchIncremental`/`FetchAllFromCursor`,超大知识库建议使用增量模式以免一次装入全部 Markdown。
+任务超时后可从最近的 checkpoint 继续处理。Asynq 同步任务超时为 2 小时,流式路径按条目推进,避免缓存全部文件正文。Feishu/Lark(知识库与云盘)、GitLab 和 Confluence 连接器实现了 `StreamingConnector`;Feishu/Lark、Seafile 和 Confluence 另实现 `FullStreamingConnector`,全量同步也能对账删除。钉钉目前走 batch `FetchAll`/`FetchIncremental`/`FetchAllFromCursor`,超大知识库建议使用增量模式以免一次装入全部 Markdown。
#### ConnectorRegistry:注册与查找
diff --git a/website-docs/03-features/24-feishu-drive.md b/website-docs/03-features/24-feishu-drive.md
index 056d10457..f1e4335d5 100644
--- a/website-docs/03-features/24-feishu-drive.md
+++ b/website-docs/03-features/24-feishu-drive.md
@@ -4,7 +4,19 @@
## 应用身份与文件夹权限
-使用对应区域的企业自建应用 App ID 与 App Secret;飞书与 Lark 的凭据不能混用。应按实际使用的接口开通读取权限:目录列举与文件下载、云文档导出,以及 blocks 模式下的 docx 内容读取。权限名称、可替代权限和申请要求以飞书开放平台的[文件夹列表接口](https://open.feishu.cn/document/server-docs/docs/drive-v1/folder/list)与[导出接口](https://open.feishu.cn/document/server-docs/docs/drive-v1/export_task/create)等接口说明为准。
+使用对应区域的企业自建应用 App ID 与 App Secret;飞书与 Lark 的凭据不能混用。权限在开放平台「权限管理」中开通,均为只读权限,开通后需创建并发布新版本才生效。
+
+必要权限:
+
+| 权限 | blocks 模式(默认) | export 模式 | 缺少时的表现 |
+| --- | --- | --- | --- |
+| `drive:drive:readonly` | 必选:列举文件夹、下载普通文件、下载 docx 内嵌图片/附件 | 必选:列举文件夹、下载普通文件 | 加载文件夹或同步报 403,提示「需先将文件夹分享给应用所在的群」 |
+| `docx:document:readonly` | 必选:blocks API 解析新版文档正文 | 不需要 | 云文档 docx 解析失败 |
+| `drive:export:readonly` | 按需:表格/多维表格文件导出 xlsx;blocks 失败或正文为空时的回退导出 | 必选:docx/doc/sheet/bitable 全部走异步导出 | 表格类文件同步失败;blocks 回退不可用 |
+
+云盘连接器**不需要** `wiki:wiki:readonly`(那是知识库连接器的权限)。
+
+可选增强权限(@成员真实姓名 `contact:user.base:readonly`、云文档引用标题 `drive:drive.metadata:readonly`、画板导出 `board:whiteboard:node:read`、内嵌电子表格/多维表格转 Markdown 表格 `sheets:spreadsheet:readonly` / `bitable:app:readonly`):仅 blocks 渲染路径使用,缺失时同步不失败,仅对应内容降级。知识库连接器的完整权限矩阵见[数据源同步](10-datasource.md)的 Feishu/Lark 小节。
配置权限后发布应用版本,并把目标文件夹授权给应用可访问的范围。若通过应用所在群分享,核对应用、文件夹管理者和群的授权关系。API 权限与文件访问权是两层检查:能取得 tenant access token,不代表能读取任意文件夹。
@@ -17,7 +29,7 @@ WeKnora 内的连接测试验证应用凭据;随后加载资源树才会验证
3. 输入具体文件夹的 `folder_token` 或完整 `/drive/folder/<token>` 链接,加载资源树并选择同步范围。不能留空使用云空间根目录。
4. 选择全量/增量、同步计划、冲突策略与同步删除;保存后先手动同步少量文件,检查日志和解析结果。
-增量同步会对照旧游标与当前文件树:仅在选定资源完整列举成功时,将消失的文件标记为删除;子目录列举失败时暂缓检测。开启同步删除才会据此删除**当前数据源对应的知识条目**,关闭则保留。首次同步或未携带旧游标的全量同步不能据此检测历史删除,删除失败也不能保证靠一次全量同步补齐,应检查同步日志与剩余条目。
+增量同步会对照旧游标与当前文件树:仅在选定资源完整列举成功时,将消失的文件标记为删除;子目录列举失败时暂缓检测。开启同步删除才会据此删除**当前数据源对应的知识条目**,关闭则保留。全量同步(包括升级触发的全量重同步)同样保留旧游标用于删除对账;首次同步没有历史基线,无法检测更早的删除。删除失败时仍应检查同步日志与剩余条目。
文档自身更新还会清理 blocks 模式中已消失的附件子项,这是内容更新的一部分,不受上述源文档同步删除开关控制。
@@ -25,24 +37,16 @@ WeKnora 内的连接测试验证应用凭据;随后加载资源树才会验证
普通文件下载后按文件类型进入解析流程;表格/多维表格导出为 xlsx,文件夹递归遍历,快捷方式解析到目标文件。不支持的云文档类型会跳过,应查看同步日志中的跳过原因。
-新版 docx 有两条路径,由 **app 服务**的 `FEISHU_DOCX_PARSE_MODE` 控制,同时影响 Wiki 与云盘连接器:
+新版 docx 有两条路径,在**知识库设置 → 数据源编辑页 → 解析模式**按数据源选择(存于数据源的 `settings.parse_mode`),默认 `blocks`,同时影响 Wiki 与云盘连接器:
| 模式 | 路径 | 适用与限制 |
| --- | --- | --- |
-| 留空或 `export`(默认) | 异步导出 docx,再进入文档解析 | 图片随父文档解析;导出和解析耗时较长,内嵌 file block 附件不随导出保留 |
-| `blocks` | blocks API 转 Markdown;API 失败或正文为空时回退导出 | 保留可解析附件为独立条目;开启多模态同步时图片作为独立条目,不能假定检索会自动关联回正文 |
-
-需要 blocks 模式时在 `.env` 设置并重建 app:
-
-```dotenv
-FEISHU_DOCX_PARSE_MODE=blocks
-```
+| `blocks`(默认) | blocks API 转 Markdown;API 失败、正文为空或超过 30 个图片/画板块时回退导出 | 图片/画板随父文档入库并建立关联;可解析附件(pdf/office 等)保留为独立条目并与父文档互相关联;内嵌电子表格/多维表格转为文档内 Markdown 表格 |
+| `export` | 异步导出 docx,再进入文档解析 | 图片随父文档解析;导出和解析耗时较长;内嵌 file block 附件不随导出保留;电子表格/多维表格变为 docx 内嵌表格,无法按表格解析 |
-```bash
-docker compose up -d app
-```
+已废弃的环境变量 `FEISHU_DOCX_PARSE_MODE` 仅在数据源未配置解析模式时作为回退读取(打印弃用警告,后续版本移除);在 `.env` 中显式设为 `export` 的部署升级后行为不变。
-修改模式影响之后的抓取,不会把已入库内容自动转换成另一种格式。图片内容能否被检索还取决于对象存储、OCR/多模态处理和索引状态,见[文档解析](03-document-parsing.md)。
+修改有效解析模式后,下一次同步(含增量)会重新抓取已有 docx;仅保存其他设置不会触发模式变化。超过内联图片预算而回退导出时,blocks API 已列出的 file block 附件仍会单独入库并关联父文档;原生导出正文的格式限制与 `export` 模式一致。图片内容能否被检索还取决于对象存储、OCR/多模态处理和索引状态,见[文档解析](03-document-parsing.md)。
## 常见问题
@@ -52,7 +56,7 @@ docker compose up -d app
| 加载文件夹失败 | 使用具体文件夹链接;检查 API 权限及文件夹分享授权 |
| 云文档失败而普通文件正常 | 检查导出权限;blocks 模式另需 docx 读取权限 |
| 同步数少于目录文件数 | 检查不支持类型、子目录授权、失败/跳过统计 |
-| 图片无法随正文召回 | 确认解析模式和多模态状态;blocks 独立图片与 export 内联图片语义不同 |
+| 图片无法随正文召回 | 确认对象存储、OCR/多模态处理与索引状态;两种解析模式的图片均与父文档建立关联 |
| 文档变更后短暂不可检索 | 更新可能删除旧知识并重新入库,等待新版本解析和索引完成 |
实现参考:`internal/datasource/connector/feishu/drive/`、`core/shared.go` 和 `internal/application/service/datasource_service.go`。