Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(web-studio): improve resource import options (#3940)
yufengc54f724da22a
diff --git a/web-studio/src/i18n/locales/en/resources.ts b/web-studio/src/i18n/locales/en/resources.tsindex c05c50b3f..c3a011603 100644--- a/web-studio/src/i18n/locales/en/resources.ts+++ b/web-studio/src/i18n/locales/en/resources.ts@@ -100,6 +100,16 @@ const resources = {'targetUri.hint':'Choose where to store this resource. Defaults to viking://resources/.','targetUri.browse': 'Browse',+ destination: {+ parent: 'Parent Directory',+ exact: 'Exact Location',+ parentHint:+ 'The resource name is derived from its source and stored under this parent directory.',+ exactHint:+ 'Writes the resource to this exact URI. TOS imports require this mode.',+ tosHint:+ 'TOS imports must use an exact target URI because the server does not derive a resource name.',+ },advancedOptions: 'Advanced Options',upload: 'Upload File','upload.processing': 'File uploaded, processing...',@@ -128,15 +138,143 @@ const resources = {remote: 'Remote URL',},remoteUrl: 'Remote URL',- 'remoteUrl.placeholder': 'https://github.com/org/repo',+ 'remoteUrl.placeholder': 'Paste a remote resource address','remoteUrl.hint':'HTTP(S) URL, Git repository, or other remote resource address.',+ sourceKind: {+ feishu: 'Feishu / Lark',+ feishuHint:+ 'Supports documents, wiki pages, spreadsheets, and bitable links.',+ git: 'Git Repository',+ gitHint:+ 'Supports public or private Git repositories with an optional branch or commit.',+ remoteFile: 'Remote File',+ remoteFileHint: 'The remote file will be downloaded and parsed.',+ tos: 'TOS',+ tosHint: 'Imports a TOS path through the configured Connector.',+ webFeed: 'Site / Feed',+ webFeedHint: 'Imports content from a Sitemap, RSS, or Atom feed.',+ webPage: 'Web Page',+ webPageHint:+ 'Supports a single page or recursive crawling through same-host links.',+ },+ sourcePicker: {+ title: 'Supported Remote Resource Types',+ hint: 'Every listed type has a server-side import path. Choose one to configure its parameters, or keep auto detection.',+ feishu: 'Feishu / Lark',+ feishuHint: 'Documents, wiki pages, spreadsheets, and bitables',+ feishuExample: 'https://example.feishu.cn/docx/...',+ git: 'Git Repository',+ gitHint: 'Public or private repositories with a branch or commit',+ gitExample: 'https://github.com/org/repo',+ webPage: 'Web Page / Site',+ webPageHint: 'Single pages, crawling, Sitemap, RSS, and Atom',+ webPageExample: 'https://example.com/docs',+ remoteFile: 'Remote File',+ remoteFileHint: 'PDF, Office, Markdown, media files, and more',+ remoteFileExample: 'https://example.com/file.pdf',+ tos: 'TOS',+ tosHint: 'Requires the TOS Connector to be enabled and allowed',+ tosExample: 'tos://bucket/path',+ },+ configurationGuide: {+ title: 'How do I configure this?',+ documentation: 'Open the server configuration guide',+ },+ feishu: {+ auth: {+ title: 'Access Method',+ hint: 'Choose the identity OpenViking uses to access this resource.',+ app: 'Server App Credentials',+ appHint:+ 'Uses FEISHU_APP_ID and FEISHU_APP_SECRET configured on the server.',+ user: 'User Authorization',+ userHint:+ "Uses the current user's Feishu access token for private documents.",+ },+ accessToken: 'Access Token',+ 'accessToken.placeholder': 'u-...',+ 'accessToken.hint':+ 'The token is used only for this import and is not stored.',+ refreshToken: 'Refresh Token',+ 'refreshToken.placeholder': 'r-...',+ 'refreshToken.hint':+ 'Scheduled sync requires a refresh token and the same issuing Feishu app configured on the server.',+ configuration: {+ credentials:+ 'Get the App ID and App Secret from the Feishu Open Platform.',+ server:+ 'Set FEISHU_APP_ID and FEISHU_APP_SECRET on the server, or configure feishu.app_id and feishu.app_secret in ov.conf.',+ restart:+ 'Restart OpenViking so the configuration takes effect; there is no separate enable switch.',+ },+ },+ git: {+ refType: 'Revision',+ branch: 'Branch',+ 'branch.placeholder': 'main',+ commit: 'Commit',+ 'commit.placeholder': 'Full or short commit SHA',+ auth: {+ title: 'Repository Access',+ public: 'Public Repository',+ publicHint: 'Access the repository without credentials.',+ token: 'HTTPS Token',+ tokenHint: 'Uses HTTPS Basic Auth for a private repository.',+ httpsOnly: 'Token authentication only supports HTTPS Git URLs.',+ },+ username: 'Username',+ 'username.placeholder': 'oauth2',+ token: 'Access Token',+ 'token.placeholder': 'Personal Access Token',+ 'token.hint':+ 'Credentials are sent in the request body and stored in private Watch authentication state when scheduled sync is enabled.',+ },+ web: {+ mode: {+ title: 'Import Mode',+ auto: 'Auto Detect',+ autoHint: 'Selects a page or feed based on the URL.',+ single: 'Single Page',+ singleHint: 'Imports only this page without following links.',+ recursive: 'Recursive Crawl',+ recursiveHint: 'Follows same-host links up to the selected depth.',+ site: 'Site / Feed',+ siteHint: 'Discovers a Sitemap, RSS, or Atom feed.',+ },+ depth: 'Crawl Depth',+ maxPages: 'Maximum Pages',+ includePaths: 'Included Path Prefixes',+ 'includePaths.placeholder': '/docs, /en/',+ excludePaths: 'Excluded Path Prefixes',+ 'excludePaths.placeholder': '/changelog, /archive',+ allowExternalLinks: 'Allow external links',+ skipDownloadLinks: 'Skip download links found on pages',+ },watch: {enabled: 'Scheduled Sync',hint: 'Periodically check this remote resource and import its latest content.',+ unsupported: 'Scheduled sync is not available for TOS imports.',+ requiredUnsupported:+ 'This resource type cannot create a scheduled sync. Choose another type.',interval: 'Sync interval (minutes)',intervalHint: 'For example, 60 for hourly or 1440 for daily.',},+ tosOptions: {+ title: 'TOS Import',+ hint: 'Import an object or prefix from a TOS URI.',+ limitations:+ 'The TOS Connector must be enabled and allowed by the server. Imports use an exact destination and do not support scheduled sync or parse-layout options.',+ configuration: {+ service: 'Deploy a Connector service that handles TOS imports.',+ endpoints:+ 'Set connector.enable=true in ov.conf. Set connector.connector to the full doc/add endpoint URL and connector.tracker to the full task/info endpoint URL.',+ allow: 'Add tos to connector.allowed_add_types.',+ restart: 'Restart OpenViking, then import with tos://bucket/path.',+ noDocumentation:+ 'Your Connector deployment provides the service endpoints; Studio does not fill them automatically. A dedicated TOS Connector deployment guide is not currently available.',+ },+ },strict: 'Strict Mode','strict.hint':'When enabled, the server will reject files with unsupported or unrecognized types instead of skipping them silently.',@@ -146,6 +284,26 @@ const resources = {createParent: 'Auto-create Parent Folder','createParent.hint':'When enabled, automatically creates the parent directory if it does not exist.',+ preserveStructure: 'Preserve directory structure',+ 'preserveStructure.serverDefault': 'Use server default',+ 'preserveStructure.preserve': 'Preserve structure',+ 'preserveStructure.flatten': 'Flatten files',+ parseMode: 'Parse Layout',+ 'parseMode.default': 'Default splitting',+ 'parseMode.noSplit': 'One Markdown body per document',+ processingMode: 'Processing Mode',+ 'processingMode.semantic': 'Semantic understanding and vectors',+ 'processingMode.vectorsOnly': 'Vectors only',+ waitForProcessing: 'Wait for processing to finish',+ timeout: 'Wait Timeout (seconds)',+ 'timeout.placeholder': 'No limit when empty',+ sourceName: 'Resource Name',+ 'sourceName.placeholder': 'Optional override for the detected source name',+ tags: 'Retrieval Tags',+ 'tags.placeholder': 'team=docs, env=production',+ tagMode: 'Tag Write Mode',+ 'tagMode.replace': 'Replace',+ 'tagMode.append': 'Append',reason: 'Reason','reason.placeholder': 'Why are you adding this resource?',instruction: 'Instruction',diff --git a/web-studio/src/i18n/locales/zh-CN/resources.ts b/web-studio/src/i18n/locales/zh-CN/resources.tsindex 4cf07ae76..71058dfad 100644--- a/web-studio/src/i18n/locales/zh-CN/resources.ts+++ b/web-studio/src/i18n/locales/zh-CN/resources.ts@@ -95,6 +95,13 @@ const resources = {'targetUri.placeholder': 'viking://resources/','targetUri.hint': '选择资源的存储位置,默认为 viking://resources/。','targetUri.browse': '浏览',+ destination: {+ parent: '父目录',+ exact: '精确位置',+ parentHint: '资源名称由来源自动生成,并保存到该父目录下。',+ exactHint: '将资源写入该精确 URI;TOS 导入必须使用此模式。',+ tosHint: 'TOS 导入必须使用精确目标 URI,因为服务端不会自动生成资源名称。',+ },advancedOptions: '高级选项',upload: '上传文件','upload.processing': '文件已上传,正在处理中...',@@ -123,14 +130,133 @@ const resources = {remote: '远程资源',},remoteUrl: '远程资源地址',- 'remoteUrl.placeholder': 'https://github.com/org/repo',+ 'remoteUrl.placeholder': '粘贴远程资源地址','remoteUrl.hint': 'HTTP(S) 链接、Git 仓库地址或其他远程资源地址。',+ sourceKind: {+ feishu: '飞书 / Lark',+ feishuHint: '支持文档、知识库、电子表格和多维表格链接。',+ git: 'Git 仓库',+ gitHint: '支持公开或私有 Git 仓库,并可指定分支或 Commit。',+ remoteFile: '远程文件',+ remoteFileHint: '将下载并解析该远程文件。',+ tos: 'TOS',+ tosHint: '通过已配置的 Connector 导入 TOS 路径。',+ webFeed: '整站 / 订阅源',+ webFeedHint: '将按 Sitemap、RSS 或 Atom 订阅源导入内容。',+ webPage: '网页',+ webPageHint: '支持导入单页或沿同域链接递归抓取。',+ },+ sourcePicker: {+ title: '支持的远程资源类型',+ hint: '以下类型均有服务端处理链路;选择后可填写对应参数,也可以保持自动识别。',+ feishu: '飞书 / Lark',+ feishuHint: '文档、知识库、电子表格和多维表格',+ feishuExample: 'https://example.feishu.cn/docx/...',+ git: 'Git 仓库',+ gitHint: '公开或私有仓库,可指定分支或 Commit',+ gitExample: 'https://github.com/org/repo',+ webPage: '网页 / 站点',+ webPageHint: '单页、递归抓取、Sitemap、RSS 和 Atom',+ webPageExample: 'https://example.com/docs',+ remoteFile: '远程文件',+ remoteFileHint: 'PDF、Office、Markdown、媒体文件等',+ remoteFileExample: 'https://example.com/file.pdf',+ tos: 'TOS',+ tosHint: '需服务端启用并允许 TOS Connector',+ tosExample: 'tos://bucket/path',+ },+ configurationGuide: {+ title: '如何配置?',+ documentation: '查看服务端配置文档',+ },+ feishu: {+ auth: {+ title: '访问方式',+ hint: '选择 OpenViking 访问该飞书资源时使用的身份。',+ app: '服务端应用凭证',+ appHint: '使用服务端配置的 FEISHU_APP_ID 和 FEISHU_APP_SECRET。',+ user: '用户授权',+ userHint: '使用当前用户的飞书 Access Token 访问私有文档。',+ },+ accessToken: 'Access Token',+ 'accessToken.placeholder': 'u-...',+ 'accessToken.hint': 'Token 仅用于本次导入,不会保存。',+ refreshToken: 'Refresh Token',+ 'refreshToken.placeholder': 'r-...',+ 'refreshToken.hint':+ '定时同步需要 Refresh Token;服务端还需配置签发该 Token 的同一个飞书应用。',+ configuration: {+ credentials: '在飞书开放平台获取应用的 App ID 和 App Secret。',+ server:+ '在服务端设置 FEISHU_APP_ID、FEISHU_APP_SECRET,或写入 ov.conf 的 feishu.app_id、feishu.app_secret。',+ restart: '重启 OpenViking 服务,使配置生效;无需额外开启开关。',+ },+ },+ git: {+ refType: '版本定位',+ branch: '分支',+ 'branch.placeholder': 'main',+ commit: 'Commit',+ 'commit.placeholder': '完整或短 Commit SHA',+ auth: {+ title: '仓库访问方式',+ public: '公开仓库',+ publicHint: '无需凭证,直接访问仓库。',+ token: 'HTTPS Token',+ tokenHint: '通过 HTTPS Basic Auth 访问私有仓库。',+ httpsOnly: 'Token 认证仅支持 HTTPS Git 地址。',+ },+ username: '用户名',+ 'username.placeholder': 'oauth2',+ token: '访问 Token',+ 'token.placeholder': 'Personal Access Token',+ 'token.hint':+ '凭证通过请求体发送;开启定时同步后会保存到 Watch 私有鉴权状态。',+ },+ web: {+ mode: {+ title: '导入方式',+ auto: '自动识别',+ autoHint: '根据地址自动选择单页或订阅源。',+ single: '单页',+ singleHint: '只导入当前页面,不跟随链接。',+ recursive: '递归抓取',+ recursiveHint: '沿同域链接按深度抓取。',+ site: '整站 / 订阅源',+ siteHint: '自动发现 Sitemap、RSS 或 Atom。',+ },+ depth: '抓取深度',+ maxPages: '最大页面数',+ includePaths: '包含路径前缀',+ 'includePaths.placeholder': '/docs, /zh/',+ excludePaths: '排除路径前缀',+ 'excludePaths.placeholder': '/changelog, /archive',+ allowExternalLinks: '允许抓取外部链接',+ skipDownloadLinks: '跳过页面中的下载链接',+ },watch: {enabled: '定时同步',hint: '定期检查该远程资源,并导入最新内容。',+ unsupported: 'TOS 导入暂不支持定时同步。',+ requiredUnsupported: '该资源类型不支持创建定时同步,请选择其他类型。',interval: '同步周期(分钟)',intervalHint: '例如每小时填写 60,每天填写 1440。',},+ tosOptions: {+ title: 'TOS 导入',+ hint: '从 TOS URI 导入对象或目录前缀。',+ limitations:+ '需服务端启用并允许 TOS Connector;导入使用精确目标位置,暂不支持定时同步和解析布局选项。',+ configuration: {+ service: '先部署可处理 TOS 导入的 Connector 服务。',+ endpoints:+ '在 ov.conf 中设置 connector.enable=true;connector.connector 填写完整的 doc/add 接口 URL,connector.tracker 填写完整的 task/info 接口 URL。',+ allow: '将 tos 加入 connector.allowed_add_types。',+ restart: '重启 OpenViking 服务后,再使用 tos://bucket/path 导入。',+ noDocumentation:+ 'Connector 服务地址由部署方提供,Studio 不会自动填写;当前暂无独立的 TOS Connector 部署文档。',+ },+ },strict: '严格模式','strict.hint':'开启时,服务器会拒绝不支持或无法识别类型的文件,而非静默跳过。',@@ -139,6 +265,26 @@ const resources = {'开启时,媒体文件(图片、音频、视频)原样存储。关闭后,媒体文件会先通过 AI 视觉/音频管道提取内容再存储。',createParent: '自动创建父文件夹','createParent.hint': '开启时,若目标父目录不存在则自动创建。',+ preserveStructure: '保留目录结构',+ 'preserveStructure.serverDefault': '使用服务端默认值',+ 'preserveStructure.preserve': '保留目录结构',+ 'preserveStructure.flatten': '平铺文件',+ parseMode: '解析布局',+ 'parseMode.default': '默认拆分',+ 'parseMode.noSplit': '每个文档一个 Markdown 正文',+ processingMode: '处理模式',+ 'processingMode.semantic': '语义理解并生成向量',+ 'processingMode.vectorsOnly': '仅生成向量',+ waitForProcessing: '等待处理完成后返回',+ timeout: '等待超时(秒)',+ 'timeout.placeholder': '不填写则不限制',+ sourceName: '资源名称',+ 'sourceName.placeholder': '可选,覆盖自动识别的来源名称',+ tags: '检索标签',+ 'tags.placeholder': 'team=docs, env=production',+ tagMode: '标签写入方式',+ 'tagMode.replace': '替换',+ 'tagMode.append': '追加',reason: '添加原因','reason.placeholder': '为什么要添加这个资源?',instruction: '处理指令',diff --git a/web-studio/src/lib/watch-interval.ts b/web-studio/src/lib/watch-interval.tsdeleted file mode 100644index 7bb1f5a2e..000000000--- a/web-studio/src/lib/watch-interval.ts+++ /dev/null@@ -1,4 +0,0 @@-export function parsePositiveMinutes(value: number | string): number | null {- const minutes = Number(value)- return Number.isFinite(minutes) && minutes > 0 ? minutes : null-}diff --git a/web-studio/src/routes/resources/-components/add-resource-page.test.tsx b/web-studio/src/routes/resources/-components/add-resource-page.test.tsxindex 4d209de6f..b35ab77d1 100644--- a/web-studio/src/routes/resources/-components/add-resource-page.test.tsx+++ b/web-studio/src/routes/resources/-components/add-resource-page.test.tsx@@ -1,6 +1,12 @@// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { afterEach, describe, expect, it, vi } from 'vitest'@@ -13,7 +19,10 @@ const uploadMocks = vi.hoisted(() => ({}))vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),+ useTranslation: () => ({+ i18n: { resolvedLanguage: 'zh-CN' },+ t: (key: string) => key,+ }),}))vi.mock('../-hooks/use-resource-upload', () => ({@@ -35,6 +44,151 @@ afterEach(() => {})describe('AddResourceForm watch options', () => {+ it('shows supported resource types and switches their parameter forms', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ expect(screen.getByText('sourcePicker.title')).toBeTruthy()+ const remoteUrlInput = screen.getByRole('textbox', { name: 'remoteUrl' })+ expect(remoteUrlInput.getAttribute('placeholder')).toBe(+ 'remoteUrl.placeholder',+ )+ for (const type of ['feishu', 'git', 'webPage', 'remoteFile']) {+ expect(+ screen.getByRole('button', {+ name: new RegExp(`sourcePicker.${type}`),+ }),+ ).toBeTruthy()+ }++ fireEvent.click(screen.getByRole('button', { name: /sourcePicker.feishu/ }))+ expect(remoteUrlInput.getAttribute('placeholder')).toBe(+ 'sourcePicker.feishuExample',+ )+ expect(screen.getByText('sourcePicker.feishuHint')).toBeTruthy()+ expect(screen.getByText('feishu.auth.title')).toBeTruthy()+ fireEvent.click(screen.getByText('configurationGuide.title'))+ expect(screen.getByText('feishu.configuration.server')).toBeTruthy()+ expect(+ screen+ .getByRole('link', { name: /configurationGuide.documentation/ })+ .getAttribute('href'),+ ).toBe('https://docs.openviking.ai/zh/guides/01-configuration#feishu')++ fireEvent.click(screen.getByRole('button', { name: /sourcePicker.feishu/ }))+ expect(screen.queryByText('sourcePicker.feishuHint')).toBeNull()+ fireEvent.click(screen.getByRole('button', { name: /sourcePicker.feishu/ }))++ fireEvent.click(screen.getByRole('button', { name: /sourcePicker.git/ }))+ expect(remoteUrlInput.getAttribute('placeholder')).toBe(+ 'sourcePicker.gitExample',+ )+ expect(screen.getByText('git.refType')).toBeTruthy()++ fireEvent.click(+ screen.getByRole('button', { name: /sourcePicker.webPage/ }),+ )+ expect(remoteUrlInput.getAttribute('placeholder')).toBe(+ 'sourcePicker.webPageExample',+ )+ expect(screen.getByText('web.mode.title')).toBeTruthy()++ expect(+ screen.queryByRole('button', { name: /sourcePicker.tos/ }),+ ).toBeNull()+ expect(+ screen.queryByRole('button', { name: /sourcePicker.connector/ }),+ ).toBeNull()+ })++ it('lets the server validate an address that differs from the selected type', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ fireEvent.click(screen.getByRole('button', { name: /sourcePicker.feishu/ }))+ fireEvent.change(screen.getByRole('textbox', { name: 'remoteUrl' }), {+ target: { value: 'https://github.com/volcengine/OpenViking' },+ })++ const submit = screen.getByRole('button', { name: 'startProcessing' })+ expect(submit.hasAttribute('disabled')).toBe(false)+ fireEvent.click(submit)+ expect(uploadMocks.startRemote).toHaveBeenCalledWith(+ expect.objectContaining({+ url: 'https://github.com/volcengine/OpenViking',+ }),+ )+ })++ it('hides unfinished TOS imports in the watch creation flow', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm+ initialMode="remote"+ initialWatchEnabled+ watchRequired+ />+ </QueryClientProvider>,+ )++ expect(screen.queryByRole('button', { name: 'mode.upload' })).toBeNull()+ expect(+ screen.queryByRole('button', { name: /sourcePicker.tos/ }),+ ).toBeNull()+ expect(screen.queryByText('tosOptions.title')).toBeNull()+ expect(+ screen+ .getByRole('button', { name: 'startProcessing' })+ .hasAttribute('disabled'),+ ).toBe(true)+ })++ it('clears source values when switching resource types', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ fireEvent.click(screen.getByRole('button', { name: /sourcePicker.git/ }))+ const remoteUrlInput = screen.getByRole('textbox', { name: 'remoteUrl' })+ fireEvent.change(remoteUrlInput, {+ target: { value: 'https://github.com/volcengine/OpenViking' },+ })+ fireEvent.change(screen.getByRole('textbox', { name: 'git.branch' }), {+ target: { value: 'feature/docs' },+ })++ fireEvent.click(screen.getByRole('button', { name: /sourcePicker.feishu/ }))+ expect((remoteUrlInput as HTMLInputElement).value).toBe('')++ fireEvent.click(screen.getByRole('button', { name: /sourcePicker.git/ }))+ expect(screen.getByRole('textbox', { name: 'git.branch' }).value).toBe('')+ expect(+ screen+ .getByRole('button', { name: 'git.branch' })+ .getAttribute('aria-pressed'),+ ).toBe('true')+ })+it('submits watch_interval for a watched remote resource', () => {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },@@ -65,4 +219,373 @@ describe('AddResourceForm watch options', () => {url: 'https://github.com/volcengine/OpenViking',})})++ it('submits Feishu user credentials and defers token validation', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" initialWatchEnabled />+ </QueryClientProvider>,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'remoteUrl' }), {+ target: { value: 'https://example.feishu.cn/docx/doc-token' },+ })+ fireEvent.click(screen.getByRole('radio', { name: /feishu.auth.user/ }))+ fireEvent.change(screen.getByLabelText('feishu.accessToken'), {+ target: { value: 'u-token' },+ })++ const submit = screen.getByRole('button', { name: 'startProcessing' })+ expect(submit.hasAttribute('disabled')).toBe(false)+ fireEvent.click(submit)++ expect(uploadMocks.startRemote).toHaveBeenCalledWith({+ commonBody: expect.objectContaining({+ args: {+ feishu_access_token: 'u-token',+ feishu_refresh_token: '',+ },+ watch_interval: 1440,+ }),+ onAccepted: undefined,+ onCompleted: undefined,+ onFailed: undefined,+ url: 'https://example.feishu.cn/docx/doc-token',+ })+ })++ it('submits Git commit and HTTPS credentials', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'remoteUrl' }), {+ target: { value: 'https://github.com/volcengine/OpenViking' },+ })+ const branchButton = screen.getByRole('button', { name: 'git.branch' })+ const commitButton = screen.getByRole('button', { name: 'git.commit' })+ expect(branchButton.getAttribute('aria-pressed')).toBe('true')+ fireEvent.click(commitButton)+ expect(commitButton.getAttribute('aria-pressed')).toBe('true')+ fireEvent.change(screen.getByRole('textbox', { name: 'git.commit' }), {+ target: { value: 'abc123' },+ })+ fireEvent.click(screen.getByRole('radio', { name: /git.auth.token/ }))+ fireEvent.change(screen.getByLabelText('git.username'), {+ target: { value: 'oauth-user' },+ })+ fireEvent.change(screen.getByLabelText('git.token'), {+ target: { value: 'secret-token' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'startProcessing' }))++ expect(uploadMocks.startRemote).toHaveBeenCalledWith({+ commonBody: expect.objectContaining({+ args: {+ auth_config: {+ token: 'secret-token',+ username: 'oauth-user',+ },+ commit: 'abc123',+ },+ }),+ onAccepted: undefined,+ onCompleted: undefined,+ onFailed: undefined,+ url: 'https://github.com/volcengine/OpenViking',+ })+ })++ it('clears HTTPS Git credentials when the source changes to SSH', async () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ const remoteUrlInput = screen.getByRole('textbox', { name: 'remoteUrl' })+ fireEvent.change(remoteUrlInput, {+ target: { value: 'https://github.com/volcengine/OpenViking' },+ })+ fireEvent.click(screen.getByRole('radio', { name: /git.auth.token/ }))+ fireEvent.change(screen.getByLabelText('git.token'), {+ target: { value: 'secret-token' },+ })++ fireEvent.change(remoteUrlInput, {+ target: { value: '[email protected]:volcengine/OpenViking.git' },+ })++ await waitFor(() =>+ expect(+ screen+ .getByRole('radio', { name: /git.auth.public/ })+ .getAttribute('aria-checked'),+ ).toBe('true'),+ )+ fireEvent.click(screen.getByRole('button', { name: 'startProcessing' }))++ expect(uploadMocks.startRemote).toHaveBeenCalledWith({+ commonBody: expect.not.objectContaining({+ args: expect.objectContaining({ auth_config: expect.anything() }),+ }),+ onAccepted: undefined,+ onCompleted: undefined,+ onFailed: undefined,+ url: '[email protected]:volcengine/OpenViking.git',+ })+ })++ it('restores native upload capabilities after detecting TOS', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'remoteUrl' }), {+ target: { value: 'tos://bucket/docs' },+ })+ expect(screen.getByText('destination.tosHint')).toBeTruthy()++ fireEvent.click(screen.getByRole('button', { name: 'mode.upload' }))++ expect(screen.getByText('destination.parentHint')).toBeTruthy()+ expect(screen.queryByText('destination.tosHint')).toBeNull()+ fireEvent.click(screen.getByText('advancedOptions'))+ expect(+ screen.getByRole('checkbox', { name: 'strict' }).hasAttribute('disabled'),+ ).toBe(false)+ })++ it('submits recursive web crawl options', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'remoteUrl' }), {+ target: { value: 'https://example.com/docs' },+ })+ fireEvent.click(screen.getByRole('radio', { name: /web.mode.recursive/ }))+ fireEvent.change(screen.getByLabelText('web.depth'), {+ target: { value: '2' },+ })+ fireEvent.change(screen.getByLabelText('web.maxPages'), {+ target: { value: '25' },+ })+ fireEvent.change(screen.getByLabelText('web.includePaths'), {+ target: { value: '/docs, /zh/' },+ })+ fireEvent.change(screen.getByLabelText('web.excludePaths'), {+ target: { value: '/archive' },+ })+ fireEvent.click(+ screen.getByRole('checkbox', { name: 'web.allowExternalLinks' }),+ )+ fireEvent.click(screen.getByRole('button', { name: 'startProcessing' }))++ expect(uploadMocks.startRemote).toHaveBeenCalledWith({+ commonBody: expect.objectContaining({+ args: {+ allow_external_links: true,+ depth: 2,+ exclude_paths: ['/archive'],+ include_paths: ['/docs', '/zh/'],+ max_pages: 25,+ site: false,+ skip_download_links: true,+ },+ }),+ onAccepted: undefined,+ onCompleted: undefined,+ onFailed: undefined,+ url: 'https://example.com/docs',+ })+ })++ it('forwards server-owned option rules instead of blocking submission', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'remoteUrl' }), {+ target: { value: 'https://example.com/docs' },+ })+ fireEvent.click(screen.getByRole('radio', { name: /web.mode.recursive/ }))+ fireEvent.change(screen.getByLabelText('web.depth'), {+ target: { value: '-1' },+ })+ fireEvent.click(screen.getByText('advancedOptions'))+ fireEvent.change(screen.getByLabelText('tags'), {+ target: { value: 'server decides this format' },+ })+ fireEvent.click(screen.getByRole('checkbox', { name: 'waitForProcessing' }))+ fireEvent.change(screen.getByLabelText('timeout'), {+ target: { value: '-1' },+ })++ const submit = screen.getByRole('button', { name: 'startProcessing' })+ expect(submit.hasAttribute('disabled')).toBe(false)+ fireEvent.click(submit)++ expect(uploadMocks.startRemote).toHaveBeenCalledWith({+ commonBody: expect.objectContaining({+ args: expect.objectContaining({ depth: -1 }),+ tags: ['server decides this format'],+ timeout: -1,+ }),+ onAccepted: undefined,+ onCompleted: undefined,+ onFailed: undefined,+ url: 'https://example.com/docs',+ })+ })++ it('submits only server-supported site and feed options', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'remoteUrl' }), {+ target: { value: 'https://example.com/sitemap.xml' },+ })+ fireEvent.click(screen.getByRole('radio', { name: /web.mode.site/ }))+ fireEvent.change(screen.getByLabelText('web.maxPages'), {+ target: { value: '10' },+ })+ fireEvent.change(screen.getByLabelText('web.includePaths'), {+ target: { value: '/docs/*' },+ })+ fireEvent.change(screen.getByLabelText('web.excludePaths'), {+ target: { value: '/archive/*' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'startProcessing' }))++ expect(uploadMocks.startRemote).toHaveBeenCalledWith({+ commonBody: expect.objectContaining({+ args: {+ max_pages: 10,+ site: true,+ },+ exclude: '/archive/*',+ include: '/docs/*',+ }),+ onAccepted: undefined,+ onCompleted: undefined,+ onFailed: undefined,+ url: 'https://example.com/sitemap.xml',+ })+ })++ it('submits exact destination and common processing options', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" />+ </QueryClientProvider>,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'remoteUrl' }), {+ target: { value: 'https://example.com/guide.pdf' },+ })+ fireEvent.click(screen.getByRole('radio', { name: 'destination.exact' }))+ fireEvent.change(screen.getByLabelText('targetUri'), {+ target: { value: 'viking://resources/guides/guide.pdf' },+ })+ fireEvent.click(screen.getByText('advancedOptions'))+ fireEvent.change(screen.getByLabelText('tags'), {+ target: { value: 'team=docs, env=test' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'startProcessing' }))++ expect(uploadMocks.startRemote).toHaveBeenCalledWith({+ commonBody: expect.objectContaining({+ processing_mode: 'semantic_and_vectors',+ tag_mode: 'replace',+ tags: ['team=docs', 'env=test'],+ to: 'viking://resources/guides/guide.pdf',+ wait: false,+ }),+ onAccepted: undefined,+ onCompleted: undefined,+ onFailed: undefined,+ url: 'https://example.com/guide.pdf',+ })+ expect(+ uploadMocks.startRemote.mock.calls[0]?.[0].commonBody,+ ).not.toHaveProperty('parent')+ expect(+ uploadMocks.startRemote.mock.calls[0]?.[0].commonBody,+ ).not.toHaveProperty('preserve_structure')+ })++ it('submits TOS through the built-in server route', () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ render(+ <QueryClientProvider client={queryClient}>+ <AddResourceForm initialMode="remote" initialWatchEnabled />+ </QueryClientProvider>,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'remoteUrl' }), {+ target: { value: 'tos://bucket/docs' },+ })+ fireEvent.change(screen.getByLabelText('targetUri'), {+ target: { value: 'viking://resources/custom' },+ })+ fireEvent.click(screen.getByRole('button', { name: 'startProcessing' }))++ expect(uploadMocks.startRemote).toHaveBeenCalledWith({+ commonBody: expect.objectContaining({+ add_type: 'tos',+ directly_upload_media: true,+ processing_mode: 'semantic_and_vectors',+ strict: false,+ to: 'viking://resources/custom',+ wait: false,+ }),+ onAccepted: undefined,+ onCompleted: undefined,+ onFailed: undefined,+ url: 'tos://bucket/docs',+ })+ const commonBody = uploadMocks.startRemote.mock.calls[0]?.[0].commonBody+ expect(commonBody).not.toHaveProperty('parent')+ expect(commonBody).not.toHaveProperty('watch_interval')+ expect(commonBody).not.toHaveProperty('args')+ expect(commonBody).not.toHaveProperty('preserve_structure')+ })})diff --git a/web-studio/src/routes/resources/-components/add-resource-page.tsx b/web-studio/src/routes/resources/-components/add-resource-page.tsxindex f60453207..b71ad9986 100644--- a/web-studio/src/routes/resources/-components/add-resource-page.tsx+++ b/web-studio/src/routes/resources/-components/add-resource-page.tsx@@ -1,19 +1,14 @@-import { fileTypeFromBlob } from 'file-type'import {AlertTriangle,CheckCircle2,ChevronRight,- FileIcon,- FolderOpen,Globe,Info,Loader2Icon,Upload,} from 'lucide-react'import { useCallback, useState } from 'react'-import { useDropzone } from 'react-dropzone'import { useTranslation } from 'react-i18next'-import { toast } from 'sonner'import { Button } from '#/components/ui/button'import { Checkbox } from '#/components/ui/checkbox'@@ -24,50 +19,69 @@ import {} from '#/components/ui/collapsible'import { Input } from '#/components/ui/input'import { Label } from '#/components/ui/label'-import { Switch } from '#/components/ui/switch'import { Textarea } from '#/components/ui/textarea'import {Tooltip,TooltipContent,TooltipTrigger,} from '#/components/ui/tooltip'-import { cn } from '#/lib/utils'-import { parsePositiveMinutes } from '#/lib/watch-interval'import { useResourceUpload } from '../-hooks/use-resource-upload'import type { RemoteStartResult } from '../-hooks/use-resource-upload'-import {- MAX_UPLOAD_FILES,- MAX_UPLOAD_FILE_SIZE_BYTES,- formatFileSize,- isBlockedFile,-} from '../-lib/upload'+import { detectRemoteResourceKind } from '../-lib/resource-source'+import type { RemoteResourceTypeSelection } from '../-lib/resource-source'+import { buildResourceImportCommonBody } from '../-lib/resource-import-request'+import { getRemoteResourceCapabilities } from '../-lib/resource-source-strategy'+import type { RemoteSourceOptionState } from '../-lib/resource-source-strategy'import { DirectoryPickerDialog } from './directory-picker-dialog'+import { AdditionalResourceOptions } from './additional-resource-options'+import type { AdditionalResourceOptionsValue } from './additional-resource-options'+import { FeishuResourceOptions } from './feishu-resource-options'+import type { FeishuResourceOptionsValue } from './feishu-resource-options'+import { GitResourceOptions } from './git-resource-options'+import type { GitResourceOptionsValue } from './git-resource-options'+import { RemoteResourceFields } from './remote-resource-fields'+import { ResourceDestinationFields } from './resource-destination-fields'+import type { ResourceDestinationMode } from './resource-destination-fields'+import { TosResourceOptions } from './tos-resource-options'+import { UploadResourceFields } from './upload-resource-fields'+import type { SelectedUploadFile } from './upload-resource-fields'+import { WebResourceOptions } from './web-resource-options'+import type { WebResourceOptionsValue } from './web-resource-options'type Mode = 'upload' | 'remote'-type SelectedUploadFile = {- id: string- file: File- fileType: string | null+const DEFAULT_WEB_OPTIONS: WebResourceOptionsValue = {+ allowExternalLinks: false,+ depth: '1',+ excludePaths: '',+ includePaths: '',+ maxPages: '50',+ mode: 'auto',+ skipDownloadLinks: true,}-function createLocalFileId(): string {- if (- typeof crypto !== 'undefined' &&- typeof crypto.randomUUID === 'function'- ) {- return crypto.randomUUID()- }- return `local-file-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`+const DEFAULT_FEISHU_OPTIONS: FeishuResourceOptionsValue = {+ accessToken: '',+ authMode: 'app',+ refreshToken: '',}-async function detectFileType(file: File): Promise<string | null> {- try {- const result = await fileTypeFromBlob(file)- return result?.mime ?? null- } catch {- return null- }+const DEFAULT_GIT_OPTIONS: GitResourceOptionsValue = {+ authMode: 'public',+ refMode: 'branch',+ refValue: '',+ token: '',+ username: 'oauth2',+}++const DEFAULT_ADDITIONAL_OPTIONS: AdditionalResourceOptionsValue = {+ parseMode: 'default',+ processingMode: 'semantic_and_vectors',+ sourceName: '',+ tagMode: 'replace',+ tags: '',+ timeout: '',+ wait: false,}export function AddResourceForm({@@ -77,6 +91,7 @@ export function AddResourceForm({onCompleted,onFailed,onSubmitted,+ watchRequired = false,}: {initialMode?: ModeinitialWatchEnabled?: boolean@@ -84,15 +99,20 @@ export function AddResourceForm({onCompleted?: () => voidonFailed?: () => voidonSubmitted?: () => void+ watchRequired?: boolean} = {}) {- const { t } = useTranslation('addResource')+ const { i18n, t } = useTranslation('addResource')const { enqueueUploads, startRemote, resetRemote, remoteState } =useResourceUpload()- const [mode, setMode] = useState<Mode>(initialMode)+ const [mode, setMode] = useState<Mode>(watchRequired ? 'remote' : initialMode)const [remoteUrl, setRemoteUrl] = useState('')+ const [remoteResourceType, setRemoteResourceType] =+ useState<RemoteResourceTypeSelection>('auto')const [selectedFiles, setSelectedFiles] = useState<SelectedUploadFile[]>([])const [targetUri, setTargetUri] = useState('viking://resources/')+ const [destinationMode, setDestinationMode] =+ useState<ResourceDestinationMode>('parent')const [strict, setStrict] = useState(false)const [createParent, setCreateParent] = useState(true)const [directlyUploadMedia, setDirectlyUploadMedia] = useState(true)@@ -103,6 +123,15 @@ export function AddResourceForm({const [exclude, setExclude] = useState('')const [watchEnabled, setWatchEnabled] = useState(initialWatchEnabled)const [watchInterval, setWatchInterval] = useState('1440')+ const [feishuOptions, setFeishuOptions] = useState(DEFAULT_FEISHU_OPTIONS)+ const [gitOptions, setGitOptions] = useState(DEFAULT_GIT_OPTIONS)+ const [webOptions, setWebOptions] =+ useState<WebResourceOptionsValue>(DEFAULT_WEB_OPTIONS)+ const [additionalOptions, setAdditionalOptions] =+ useState<AdditionalResourceOptionsValue>(DEFAULT_ADDITIONAL_OPTIONS)+ const feishuConfigurationUrl = i18n.resolvedLanguage?.startsWith('zh')+ ? 'https://docs.openviking.ai/zh/guides/01-configuration#feishu'+ : 'https://docs.openviking.ai/en/guides/01-configuration#feishu'const [advancedOpen, setAdvancedOpen] = useState(false)const [dirPickerOpen, setDirPickerOpen] = useState(false)@@ -111,106 +140,89 @@ export function AddResourceForm({const displayRemoteUrl =remotePhase === 'processing' ? remoteState.remoteUrl : remoteUrlconst skippedFiles = remoteState.skippedFiles-- const addFiles = useCallback(- (files: File[]) => {- void (async () => {- const nextItems: SelectedUploadFile[] = []-- for (const file of files) {- if (isBlockedFile(file.name)) {- toast.error(t('fileBlocked', { name: file.name }), {- duration: 2500,- })- continue- }-- if (file.size > MAX_UPLOAD_FILE_SIZE_BYTES) {- toast.error(- t('fileTooLarge', {- name: file.name,- size: formatFileSize(MAX_UPLOAD_FILE_SIZE_BYTES),- }),- { duration: 2500 },- )- continue- }-- nextItems.push({- id: createLocalFileId(),- file,- fileType: await detectFileType(file),- })- }-- if (nextItems.length === 0) return-- setSelectedFiles((prev) => {- const remainingSlots = Math.max(MAX_UPLOAD_FILES - prev.length, 0)- const kept = nextItems.slice(0, remainingSlots)- if (nextItems.length > remainingSlots) {- toast(t('tooManyFiles', { count: MAX_UPLOAD_FILES }), {- duration: 2500,- })- }- return [...prev, ...kept]- })- })()- },- [t],+ const detectedRemoteResourceKind = detectRemoteResourceKind(remoteUrl)+ const remoteResourceKind =+ remoteResourceType === 'auto'+ ? detectedRemoteResourceKind+ : remoteResourceType+ const sourceCapabilities = getRemoteResourceCapabilities(+ activeMode === 'remote' ? remoteResourceKind : 'unknown',)-- const removeFile = useCallback((id: string) => {- setSelectedFiles((prev) => prev.filter((file) => file.id !== id))- }, [])+ const gitSupportsHttpAuth = remoteUrl+ .trim()+ .toLowerCase()+ .startsWith('https://')+ const effectiveWatchEnabled = watchEnabled && sourceCapabilities.watch+ const effectiveDestinationMode: ResourceDestinationMode =+ sourceCapabilities.exactDestination ? 'to' : destinationMode+ const sourceOptionState: RemoteSourceOptionState = {+ feishu: feishuOptions,+ git: {+ ...gitOptions,+ supportsHttpAuth: gitSupportsHttpAuth,+ },+ watchEnabled: effectiveWatchEnabled,+ web: webOptions,+ }const handleRemoteUrlChange = useCallback((value: string) => {if (remotePhase === 'done') {resetRemote()}+ const nextSupportsHttpAuth = value+ .trim()+ .toLowerCase()+ .startsWith('https://')+ if (gitSupportsHttpAuth && !nextSupportsHttpAuth) {+ setGitOptions((current) => ({+ ...current,+ authMode: 'public',+ token: '',+ }))+ }setRemoteUrl(value)},- [remotePhase, resetRemote],+ [gitSupportsHttpAuth, remotePhase, resetRemote],)- const { getRootProps, getInputProps, isDragActive } = useDropzone({- onDrop: addFiles,- multiple: true,- })+ const resetRemoteSourceFields = useCallback(() => {+ setWatchEnabled(initialWatchEnabled)+ setWatchInterval('1440')+ setFeishuOptions(DEFAULT_FEISHU_OPTIONS)+ setGitOptions(DEFAULT_GIT_OPTIONS)+ setWebOptions(DEFAULT_WEB_OPTIONS)+ }, [initialWatchEnabled])++ const handleRemoteResourceTypeChange = useCallback(+ (value: RemoteResourceTypeSelection) => {+ resetRemote()+ setRemoteUrl('')+ setRemoteResourceType(value)+ resetRemoteSourceFields()+ },+ [resetRemote, resetRemoteSourceFields],+ )- const buildCommonBody = () => {- const body: Record<string, unknown> = {- parent: targetUri.trim() || undefined,+ const buildCommonBody = () =>+ buildResourceImportCommonBody({+ additionalOptions,+ createParent,+ destinationMode,+ directlyUploadMedia,+ exclude,+ ignoreDirs,+ include,+ instruction,+ mode,+ reason,+ remoteResourceKind,+ sourceOptionState,strict,- create_parent: createParent,- telemetry: true,- wait: false,- directly_upload_media: directlyUploadMedia,- }- if (reason.trim()) {- body.reason = reason.trim()- }- if (instruction.trim()) {- body.instruction = instruction.trim()- }- if (mode === 'remote') {- if (watchEnabled) {- const minutes = parsePositiveMinutes(watchInterval)- if (minutes !== null) body.watch_interval = minutes- }- if (ignoreDirs.trim()) {- body.ignore_dirs = ignoreDirs.trim()- }- if (include.trim()) {- body.include = include.trim()- }- if (exclude.trim()) {- body.exclude = exclude.trim()- }- }- return body- }+ targetUri,+ watchEnabled: effectiveWatchEnabled,+ watchInterval,+ })const handleSubmit = () => {if (mode === 'upload') {@@ -240,158 +252,115 @@ export function AddResourceForm({resetRemote()setSelectedFiles([])setRemoteUrl('')- setMode(initialMode)- setWatchEnabled(initialWatchEnabled)- setWatchInterval('1440')+ setRemoteResourceType('auto')+ setMode(watchRequired ? 'remote' : initialMode)+ resetRemoteSourceFields()+ setAdditionalOptions(DEFAULT_ADDITIONAL_OPTIONS)+ setDestinationMode('parent')}- const hasValidWatchInterval =- !watchEnabled || parsePositiveMinutes(watchInterval) !== null+ const hasWatchInterval =+ !effectiveWatchEnabled || Boolean(watchInterval.trim())+ const hasValidDestination =+ !sourceCapabilities.exactDestination ||+ (effectiveDestinationMode === 'to' && !!targetUri.trim())+ const watchRequirementMet =+ !watchRequired ||+ (activeMode === 'remote' &&+ sourceCapabilities.watch &&+ effectiveWatchEnabled &&+ hasWatchInterval)const canSubmit =- activeMode === 'upload'+ hasValidDestination &&+ watchRequirementMet &&+ (activeMode === 'upload'? selectedFiles.length > 0- : !!remoteUrl.trim() && hasValidWatchInterval+ : !!remoteUrl.trim() && hasWatchInterval)return (<div className="flex flex-col gap-6"><div className="space-y-5">- <div className="flex gap-1 rounded-lg bg-muted p-1">- <button- type="button"- className={`flex flex-1 items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors ${- activeMode === 'upload'- ? 'bg-background text-foreground shadow-sm'- : 'text-muted-foreground hover:text-foreground'- }`}- onClick={() => setMode('upload')}- >- <Upload className="size-4" />- {t('mode.upload')}- </button>- <button- type="button"- className={`flex flex-1 items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors ${- activeMode === 'remote'- ? 'bg-background text-foreground shadow-sm'- : 'text-muted-foreground hover:text-foreground'- }`}- onClick={() => setMode('remote')}- >- <Globe className="size-4" />- {t('mode.remote')}- </button>- </div>-- {activeMode === 'upload' ? (- <div className="space-y-3">- <div- {...getRootProps()}- className={cn(- 'relative rounded-lg border-2 border-dashed p-8 text-center transition-colors',- isDragActive- ? 'cursor-pointer border-primary bg-primary/5'- : 'cursor-pointer border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/30',- )}+ {!watchRequired ? (+ <div className="flex gap-1 rounded-lg bg-muted p-1">+ <button+ type="button"+ className={`flex flex-1 items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors ${+ activeMode === 'upload'+ ? 'bg-background text-foreground shadow-sm'+ : 'text-muted-foreground hover:text-foreground'+ }`}+ onClick={() => setMode('upload')}>- <input {...getInputProps()} />- <div className="space-y-2">- <Upload className="mx-auto size-10 text-muted-foreground/60" />- <p className="text-sm font-medium">{t('dropzone.title')}</p>- <p className="text-xs text-muted-foreground">- {t('dropzone.hint')}- </p>- <p className="text-xs text-muted-foreground/70">- {t('dropzone.supportedFormats')}- </p>- </div>- </div>-- {selectedFiles.length > 0 ? (- <div className="overflow-hidden rounded-lg border border-border/60 bg-muted/10">- {selectedFiles.map(({ id, file }) => (- <div- key={id}- className="flex items-center gap-3 border-b border-border/50 px-4 py-3 last:border-b-0"- >- <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted">- <FileIcon className="size-5 text-muted-foreground" />- </div>- <div className="min-w-0 flex-1">- <p className="truncate text-sm font-medium">- {file.name}- </p>- </div>- <div className="shrink-0 text-xs text-muted-foreground">- {formatFileSize(file.size)}- </div>- <Button- type="button"- variant="ghost"- size="sm"- className="shrink-0 text-muted-foreground hover:text-foreground"- onClick={() => removeFile(id)}- >- {t('fileInfo.remove')}- </Button>- </div>- ))}- </div>- ) : null}+ <Upload className="size-4" />+ {t('mode.upload')}+ </button>+ <button+ type="button"+ className={`flex flex-1 items-center justify-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors ${+ activeMode === 'remote'+ ? 'bg-background text-foreground shadow-sm'+ : 'text-muted-foreground hover:text-foreground'+ }`}+ onClick={() => setMode('remote')}+ >+ <Globe className="size-4" />+ {t('mode.remote')}+ </button></div>+ ) : null}++ {activeMode === 'upload' ? (+ <UploadResourceFields+ files={selectedFiles}+ onFilesChange={setSelectedFiles}+ t={t}+ />) : (- <div className="space-y-4">- <div className="space-y-2">- <Label htmlFor="add-resource-remote-url">{t('remoteUrl')}</Label>- <Input- id="add-resource-remote-url"- placeholder={t('remoteUrl.placeholder')}- value={displayRemoteUrl}- onChange={(e) => handleRemoteUrlChange(e.target.value)}+ <RemoteResourceFields+ disabled={remotePhase === 'processing'}+ onResourceTypeChange={handleRemoteResourceTypeChange}+ onUrlChange={handleRemoteUrlChange}+ onWatchEnabledChange={setWatchEnabled}+ onWatchIntervalChange={setWatchInterval}+ resourceKind={remoteResourceKind}+ resourceType={remoteResourceType}+ t={t}+ url={displayRemoteUrl}+ watchEnabled={effectiveWatchEnabled}+ watchInterval={watchInterval}+ watchRequired={watchRequired}+ watchSupported={sourceCapabilities.watch}+ >+ {remoteResourceKind === 'feishu' ? (+ <FeishuResourceOptionsdisabled={remotePhase === 'processing'}+ documentationUrl={feishuConfigurationUrl}+ onChange={setFeishuOptions}+ t={t}+ value={feishuOptions}+ watchEnabled={effectiveWatchEnabled}/>- <p className="text-xs text-muted-foreground">- {t('remoteUrl.hint')}- </p>- </div>-- <div className="rounded-lg border border-border/60 bg-muted/10 p-4">- <div className="flex items-start justify-between gap-4">- <div className="grid gap-1">- <Label htmlFor="add-resource-watch-enabled">- {t('watch.enabled')}- </Label>- <p className="text-xs leading-5 text-muted-foreground">- {t('watch.hint')}- </p>- </div>- <Switch- id="add-resource-watch-enabled"- checked={watchEnabled}- disabled={remotePhase === 'processing'}- onCheckedChange={setWatchEnabled}- />- </div>- {watchEnabled ? (- <div className="mt-4 grid gap-2 border-t border-border/50 pt-4">- <Label htmlFor="add-resource-watch-interval">- {t('watch.interval')}- </Label>- <Input- id="add-resource-watch-interval"- type="number"- min="1"- step="1"- value={watchInterval}- disabled={remotePhase === 'processing'}- onChange={(event) => setWatchInterval(event.target.value)}- />- <p className="text-xs text-muted-foreground">- {t('watch.intervalHint')}- </p>- </div>- ) : null}- </div>- </div>+ ) : null}+ {remoteResourceKind === 'git' ? (+ <GitResourceOptions+ disabled={remotePhase === 'processing'}+ onChange={setGitOptions}+ supportsHttpAuth={gitSupportsHttpAuth}+ t={t}+ value={gitOptions}+ />+ ) : null}+ {remoteResourceKind === 'webPage' ||+ remoteResourceKind === 'webFeed' ? (+ <WebResourceOptions+ disabled={remotePhase === 'processing'}+ onChange={setWebOptions}+ t={t}+ value={webOptions}+ />+ ) : null}+ {remoteResourceKind === 'tos' ? <TosResourceOptions t={t} /> : null}+ </RemoteResourceFields>)}{activeMode === 'remote' && remotePhase === 'processing' ? (@@ -436,29 +405,16 @@ export function AddResourceForm({</div>) : null}- <div className="space-y-2">- <Label htmlFor="add-resource-target">{t('targetUri')}</Label>- <div className="flex gap-2">- <Input- id="add-resource-target"- placeholder={t('targetUri.placeholder')}- value={targetUri}- onChange={(event) => setTargetUri(event.target.value)}- className="flex-1"- />- <Button- type="button"- variant="outline"- size="sm"- className="shrink-0"- onClick={() => setDirPickerOpen(true)}- >- <FolderOpen className="mr-1.5 size-4" />- {t('targetUri.browse')}- </Button>- </div>- <p className="text-xs text-muted-foreground">{t('targetUri.hint')}</p>- </div>+ <ResourceDestinationFields+ disabled={remotePhase === 'processing'}+ exactOnly={sourceCapabilities.exactDestination}+ mode={effectiveDestinationMode}+ onBrowse={() => setDirPickerOpen(true)}+ onModeChange={setDestinationMode}+ onUriChange={setTargetUri}+ t={t}+ uri={targetUri}+ /><Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}><CollapsibleTrigger className="flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground">@@ -472,7 +428,8 @@ export function AddResourceForm({<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center"><Label className="flex items-center gap-2"><Checkbox- checked={strict}+ checked={sourceCapabilities.nativeOptions ? strict : false}+ disabled={!sourceCapabilities.nativeOptions}onCheckedChange={(checked) => setStrict(Boolean(checked))}/><span>{t('strict')}</span>@@ -504,7 +461,12 @@ export function AddResourceForm({</Label><Label className="flex items-center gap-2"><Checkbox- checked={directlyUploadMedia}+ checked={+ sourceCapabilities.nativeOptions+ ? directlyUploadMedia+ : true+ }+ disabled={!sourceCapabilities.nativeOptions}onCheckedChange={(checked) =>setDirectlyUploadMedia(Boolean(checked))}@@ -523,7 +485,16 @@ export function AddResourceForm({</Label></div>- {activeMode === 'remote' ? (+ <AdditionalResourceOptions+ disabled={remotePhase === 'processing'}+ isRemote={activeMode === 'remote'}+ nativeOptions={sourceCapabilities.nativeOptions}+ onChange={setAdditionalOptions}+ t={t}+ value={additionalOptions}+ />++ {activeMode === 'remote' && sourceCapabilities.nativeOptions ? (<div className="space-y-4 border-t border-border/50 pt-4"><div className="space-y-2"><Label htmlFor="add-resource-ignore-dirs">@@ -571,17 +542,19 @@ export function AddResourceForm({/></div>- <div className="space-y-2">- <Label htmlFor="add-resource-instruction">- {t('instruction')}- </Label>- <Textarea- id="add-resource-instruction"- placeholder={t('instruction.placeholder')}- value={instruction}- onChange={(e) => setInstruction(e.target.value)}- />- </div>+ {sourceCapabilities.nativeOptions ? (+ <div className="space-y-2">+ <Label htmlFor="add-resource-instruction">+ {t('instruction')}+ </Label>+ <Textarea+ id="add-resource-instruction"+ placeholder={t('instruction.placeholder')}+ value={instruction}+ onChange={(e) => setInstruction(e.target.value)}+ />+ </div>+ ) : null}</div></CollapsibleContent></Collapsible>diff --git a/web-studio/src/routes/resources/-components/additional-resource-options.tsx b/web-studio/src/routes/resources/-components/additional-resource-options.tsxnew file mode 100644index 000000000..2d33680ae--- /dev/null+++ b/web-studio/src/routes/resources/-components/additional-resource-options.tsx@@ -0,0 +1,228 @@+import type { TFunction } from 'i18next'++import { Checkbox } from '#/components/ui/checkbox'+import { Input } from '#/components/ui/input'+import { Label } from '#/components/ui/label'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '#/components/ui/select'+import type {+ ResourceProcessingMode,+ ResourceTagMode,+} from '../-lib/resource-import-types'++export type ResourceParseMode = 'default' | 'no_split'++export type AdditionalResourceOptionsValue = {+ parseMode: ResourceParseMode+ preserveStructure?: boolean+ processingMode: ResourceProcessingMode+ sourceName: string+ tagMode: ResourceTagMode+ tags: string+ timeout: string+ wait: boolean+}++type AdditionalResourceOptionsProps = {+ disabled: boolean+ isRemote: boolean+ onChange: (value: AdditionalResourceOptionsValue) => void+ t: TFunction<'addResource'>+ value: AdditionalResourceOptionsValue+ nativeOptions?: boolean+}++export function AdditionalResourceOptions({+ disabled,+ isRemote,+ onChange,+ t,+ value,+ nativeOptions = true,+}: AdditionalResourceOptionsProps) {+ const preserveStructureMode =+ value.preserveStructure === undefined+ ? 'server_default'+ : value.preserveStructure+ ? 'preserve'+ : 'flatten'++ return (+ <div className="space-y-4 border-t border-border/50 pt-4">+ <div className="grid gap-3 sm:grid-cols-2">+ <div className="grid gap-2">+ <Label>{t('parseMode')}</Label>+ <Select+ value={value.parseMode}+ onValueChange={(parseMode) =>+ onChange({+ ...value,+ parseMode: parseMode === 'no_split' ? 'no_split' : 'default',+ })+ }+ disabled={disabled || !nativeOptions}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="default">{t('parseMode.default')}</SelectItem>+ <SelectItem value="no_split">{t('parseMode.noSplit')}</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <div className="grid gap-2">+ <Label>{t('processingMode')}</Label>+ <Select+ value={value.processingMode}+ onValueChange={(processingMode) =>+ onChange({+ ...value,+ processingMode:+ processingMode === 'vectors_only'+ ? 'vectors_only'+ : 'semantic_and_vectors',+ })+ }+ disabled={disabled || !nativeOptions}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="semantic_and_vectors">+ {t('processingMode.semantic')}+ </SelectItem>+ <SelectItem value="vectors_only">+ {t('processingMode.vectorsOnly')}+ </SelectItem>+ </SelectContent>+ </Select>+ </div>+ </div>++ <div className="flex flex-wrap gap-x-5 gap-y-3">+ <div className="grid min-w-48 gap-2">+ <Label htmlFor="add-resource-preserve-structure">+ {t('preserveStructure')}+ </Label>+ <Select+ value={preserveStructureMode}+ onValueChange={(mode) =>+ onChange({+ ...value,+ preserveStructure:+ mode === 'server_default' ? undefined : mode === 'preserve',+ })+ }+ disabled={disabled || !nativeOptions}+ >+ <SelectTrigger+ id="add-resource-preserve-structure"+ className="w-full"+ >+ <SelectValue>+ {t(`preserveStructure.${preserveStructureMode}`)}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="server_default">+ {t('preserveStructure.serverDefault')}+ </SelectItem>+ <SelectItem value="preserve">+ {t('preserveStructure.preserve')}+ </SelectItem>+ <SelectItem value="flatten">+ {t('preserveStructure.flatten')}+ </SelectItem>+ </SelectContent>+ </Select>+ </div>+ <Label className="flex items-center gap-2">+ <Checkbox+ checked={value.wait}+ disabled={disabled || !nativeOptions}+ onCheckedChange={(checked) =>+ onChange({ ...value, wait: Boolean(checked) })+ }+ />+ {t('waitForProcessing')}+ </Label>+ </div>++ {value.wait && nativeOptions ? (+ <div className="grid gap-2 sm:max-w-xs">+ <Label htmlFor="add-resource-timeout">{t('timeout')}</Label>+ <Input+ id="add-resource-timeout"+ type="number"+ min="0.1"+ step="0.1"+ value={value.timeout}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, timeout: event.target.value })+ }+ placeholder={t('timeout.placeholder')}+ />+ </div>+ ) : null}++ {isRemote && nativeOptions ? (+ <div className="grid gap-2">+ <Label htmlFor="add-resource-source-name">{t('sourceName')}</Label>+ <Input+ id="add-resource-source-name"+ value={value.sourceName}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, sourceName: event.target.value })+ }+ placeholder={t('sourceName.placeholder')}+ />+ </div>+ ) : null}++ <div className="grid gap-3 sm:grid-cols-[1fr_10rem]">+ <div className="grid gap-2">+ <Label htmlFor="add-resource-tags">{t('tags')}</Label>+ <Input+ id="add-resource-tags"+ value={value.tags}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, tags: event.target.value })+ }+ placeholder={t('tags.placeholder')}+ />+ </div>+ <div className="grid gap-2">+ <Label>{t('tagMode')}</Label>+ <Select+ value={value.tagMode}+ onValueChange={(tagMode) =>+ onChange({+ ...value,+ tagMode: tagMode === 'append' ? 'append' : 'replace',+ })+ }+ disabled={disabled}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="replace">{t('tagMode.replace')}</SelectItem>+ <SelectItem value="append">{t('tagMode.append')}</SelectItem>+ </SelectContent>+ </Select>+ </div>+ </div>+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-components/feishu-resource-options.tsx b/web-studio/src/routes/resources/-components/feishu-resource-options.tsxnew file mode 100644index 000000000..932fe10eb--- /dev/null+++ b/web-studio/src/routes/resources/-components/feishu-resource-options.tsx@@ -0,0 +1,123 @@+import type { TFunction } from 'i18next'++import { Input } from '#/components/ui/input'+import { Label } from '#/components/ui/label'+import { RadioGroup } from '#/components/ui/radio-group'+import { ResourceConfigurationGuide } from './resource-configuration-guide'+import { ResourceOptionRadioCard } from './resource-option-radio-card'++export type FeishuAuthMode = 'app' | 'user'++export type FeishuResourceOptionsValue = {+ accessToken: string+ authMode: FeishuAuthMode+ refreshToken: string+}++type FeishuResourceOptionsProps = {+ disabled: boolean+ documentationUrl: string+ onChange: (value: FeishuResourceOptionsValue) => void+ t: TFunction<'addResource'>+ value: FeishuResourceOptionsValue+ watchEnabled: boolean+}++export function FeishuResourceOptions({+ disabled,+ documentationUrl,+ onChange,+ t,+ value,+ watchEnabled,+}: FeishuResourceOptionsProps) {+ return (+ <div className="space-y-3 rounded-lg border border-border/60 bg-muted/10 p-4">+ <div className="space-y-1">+ <p className="text-sm font-medium">{t('feishu.auth.title')}</p>+ <p className="text-xs text-muted-foreground">{t('feishu.auth.hint')}</p>+ </div>++ <RadioGroup+ value={value.authMode}+ onValueChange={(authMode) =>+ onChange({+ ...value,+ authMode: authMode === 'user' ? 'user' : 'app',+ })+ }+ disabled={disabled}+ className="grid gap-3 sm:grid-cols-2"+ >+ <ResourceOptionRadioCard+ description={t('feishu.auth.appHint')}+ title={t('feishu.auth.app')}+ value="app"+ />+ <ResourceOptionRadioCard+ description={t('feishu.auth.userHint')}+ title={t('feishu.auth.user')}+ value="user"+ />+ </RadioGroup>++ {value.authMode === 'app' ? (+ <ResourceConfigurationGuide+ documentationLabel={t('configurationGuide.documentation')}+ documentationUrl={documentationUrl}+ title={t('configurationGuide.title')}+ >+ <ol className="list-decimal space-y-1 pl-4">+ <li>{t('feishu.configuration.credentials')}</li>+ <li>{t('feishu.configuration.server')}</li>+ <li>{t('feishu.configuration.restart')}</li>+ </ol>+ </ResourceConfigurationGuide>+ ) : null}++ {value.authMode === 'user' ? (+ <div className="grid gap-3 border-t border-border/50 pt-3 sm:grid-cols-2">+ <div className="grid gap-2">+ <Label htmlFor="add-resource-feishu-access-token">+ {t('feishu.accessToken')}+ </Label>+ <Input+ id="add-resource-feishu-access-token"+ type="password"+ autoComplete="off"+ value={value.accessToken}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, accessToken: event.target.value })+ }+ placeholder={t('feishu.accessToken.placeholder')}+ />+ </div>+ {watchEnabled ? (+ <div className="grid gap-2">+ <Label htmlFor="add-resource-feishu-refresh-token">+ {t('feishu.refreshToken')}+ </Label>+ <Input+ id="add-resource-feishu-refresh-token"+ type="password"+ autoComplete="off"+ value={value.refreshToken}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, refreshToken: event.target.value })+ }+ placeholder={t('feishu.refreshToken.placeholder')}+ />+ </div>+ ) : null}+ <p className="text-xs text-muted-foreground sm:col-span-2">+ {watchEnabled+ ? t('feishu.refreshToken.hint')+ : t('feishu.accessToken.hint')}+ </p>+ </div>+ ) : null}+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-components/git-resource-options.tsx b/web-studio/src/routes/resources/-components/git-resource-options.tsxnew file mode 100644index 000000000..a3376ab04--- /dev/null+++ b/web-studio/src/routes/resources/-components/git-resource-options.tsx@@ -0,0 +1,152 @@+import type { TFunction } from 'i18next'++import { Input } from '#/components/ui/input'+import { Label } from '#/components/ui/label'+import { RadioGroup } from '#/components/ui/radio-group'+import { cn } from '#/lib/utils'+import { ResourceOptionRadioCard } from './resource-option-radio-card'++export type GitAuthMode = 'public' | 'token'+export type GitRefMode = 'branch' | 'commit'++export type GitResourceOptionsValue = {+ authMode: GitAuthMode+ refMode: GitRefMode+ refValue: string+ token: string+ username: string+}++const GIT_REF_MODES: GitRefMode[] = ['branch', 'commit']++type GitResourceOptionsProps = {+ disabled: boolean+ onChange: (value: GitResourceOptionsValue) => void+ supportsHttpAuth: boolean+ t: TFunction<'addResource'>+ value: GitResourceOptionsValue+}++export function GitResourceOptions({+ disabled,+ onChange,+ supportsHttpAuth,+ t,+ value,+}: GitResourceOptionsProps) {+ return (+ <div className="space-y-4 rounded-lg border border-border/60 bg-muted/10 p-4">+ <div className="grid gap-3 sm:grid-cols-[10rem_1fr]">+ <div className="grid gap-2">+ <Label>{t('git.refType')}</Label>+ <div+ role="group"+ aria-label={t('git.refType')}+ className="grid h-9 grid-cols-2 gap-1 rounded-md bg-muted p-1"+ >+ {GIT_REF_MODES.map((mode) => (+ <button+ key={mode}+ type="button"+ aria-pressed={value.refMode === mode}+ className={cn(+ 'grid h-full w-full min-w-0 place-items-center rounded px-2 text-xs transition-colors',+ value.refMode === mode && 'bg-background shadow-sm',+ )}+ disabled={disabled}+ onClick={() => onChange({ ...value, refMode: mode })}+ >+ {mode === 'branch' ? t('git.branch') : t('git.commit')}+ </button>+ ))}+ </div>+ </div>+ <div className="grid gap-2">+ <Label htmlFor="add-resource-git-ref">+ {value.refMode === 'branch' ? t('git.branch') : t('git.commit')}+ </Label>+ <Input+ id="add-resource-git-ref"+ value={value.refValue}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, refValue: event.target.value })+ }+ placeholder={+ value.refMode === 'branch'+ ? t('git.branch.placeholder')+ : t('git.commit.placeholder')+ }+ />+ </div>+ </div>++ <div className="space-y-3 border-t border-border/50 pt-3">+ <Label>{t('git.auth.title')}</Label>+ <RadioGroup+ value={value.authMode}+ onValueChange={(authMode) =>+ onChange({+ ...value,+ authMode: authMode === 'token' ? 'token' : 'public',+ })+ }+ disabled={disabled}+ className="grid gap-3 sm:grid-cols-2"+ >+ <ResourceOptionRadioCard+ description={t('git.auth.publicHint')}+ title={t('git.auth.public')}+ value="public"+ />+ <ResourceOptionRadioCard+ description={+ supportsHttpAuth+ ? t('git.auth.tokenHint')+ : t('git.auth.httpsOnly')+ }+ disabled={!supportsHttpAuth}+ title={t('git.auth.token')}+ value="token"+ />+ </RadioGroup>++ {value.authMode === 'token' && supportsHttpAuth ? (+ <div className="grid gap-3 sm:grid-cols-2">+ <div className="grid gap-2">+ <Label htmlFor="add-resource-git-username">+ {t('git.username')}+ </Label>+ <Input+ id="add-resource-git-username"+ value={value.username}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, username: event.target.value })+ }+ placeholder={t('git.username.placeholder')}+ />+ </div>+ <div className="grid gap-2">+ <Label htmlFor="add-resource-git-token">{t('git.token')}</Label>+ <Input+ id="add-resource-git-token"+ type="password"+ autoComplete="off"+ value={value.token}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, token: event.target.value })+ }+ placeholder={t('git.token.placeholder')}+ />+ </div>+ <p className="text-xs text-muted-foreground sm:col-span-2">+ {t('git.token.hint')}+ </p>+ </div>+ ) : null}+ </div>+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-components/remote-resource-descriptors.ts b/web-studio/src/routes/resources/-components/remote-resource-descriptors.tsnew file mode 100644index 000000000..f5857e8fc--- /dev/null+++ b/web-studio/src/routes/resources/-components/remote-resource-descriptors.ts@@ -0,0 +1,62 @@+import type { ComponentType } from 'react'+import { Cloud, FileDown, FileText, GitBranch, Globe2 } from 'lucide-react'++import type {+ RemoteResourceKind,+ RemoteResourceTypeSelection,+} from '../-lib/resource-source'++type SelectableRemoteResourceKind = Exclude<RemoteResourceTypeSelection, 'auto'>++type RemoteResourceDescriptor = {+ exampleKey: `sourcePicker.${SelectableRemoteResourceKind}Example`+ hidden?: boolean+ icon: ComponentType<{ className?: string }>+ type: SelectableRemoteResourceKind+}++export const REMOTE_RESOURCE_DESCRIPTORS: RemoteResourceDescriptor[] = [+ {+ type: 'feishu',+ icon: FileText,+ exampleKey: 'sourcePicker.feishuExample',+ },+ {+ type: 'git',+ icon: GitBranch,+ exampleKey: 'sourcePicker.gitExample',+ },+ {+ type: 'webPage',+ icon: Globe2,+ exampleKey: 'sourcePicker.webPageExample',+ },+ {+ type: 'remoteFile',+ icon: FileDown,+ exampleKey: 'sourcePicker.remoteFileExample',+ },+ {+ type: 'tos',+ hidden: true,+ icon: Cloud,+ exampleKey: 'sourcePicker.tosExample',+ },+]++export const VISIBLE_REMOTE_RESOURCE_DESCRIPTORS =+ REMOTE_RESOURCE_DESCRIPTORS.filter(({ hidden }) => !hidden)++const DESCRIPTOR_BY_TYPE = new Map(+ REMOTE_RESOURCE_DESCRIPTORS.map((descriptor) => [+ descriptor.type,+ descriptor,+ ]),+)++export function getRemoteResourceDescriptor(kind: RemoteResourceKind) {+ const selectableKind = kind === 'webFeed' ? 'webPage' : kind+ return selectableKind === 'unknown'+ ? undefined+ : DESCRIPTOR_BY_TYPE.get(selectableKind)+}diff --git a/web-studio/src/routes/resources/-components/remote-resource-fields.tsx b/web-studio/src/routes/resources/-components/remote-resource-fields.tsxnew file mode 100644index 000000000..42f49c1c8--- /dev/null+++ b/web-studio/src/routes/resources/-components/remote-resource-fields.tsx@@ -0,0 +1,135 @@+import type { ReactNode } from 'react'+import type { TFunction } from 'i18next'++import { Badge } from '#/components/ui/badge'+import { Input } from '#/components/ui/input'+import { Label } from '#/components/ui/label'+import { Switch } from '#/components/ui/switch'+import type {+ RemoteResourceKind,+ RemoteResourceTypeSelection,+} from '../-lib/resource-source'+import { getRemoteResourceDescriptor } from './remote-resource-descriptors'+import { RemoteResourceTypePicker } from './remote-resource-type-picker'++type RemoteResourceFieldsProps = {+ children?: ReactNode+ disabled: boolean+ onUrlChange: (value: string) => void+ onResourceTypeChange: (value: RemoteResourceTypeSelection) => void+ onWatchEnabledChange: (enabled: boolean) => void+ onWatchIntervalChange: (value: string) => void+ resourceKind: RemoteResourceKind+ resourceType: RemoteResourceTypeSelection+ t: TFunction<'addResource'>+ url: string+ watchEnabled: boolean+ watchInterval: string+ watchRequired?: boolean+ watchSupported?: boolean+}++function getRemoteUrlPlaceholder(+ resourceKind: RemoteResourceKind,+ t: TFunction<'addResource'>,+): string {+ const descriptor = getRemoteResourceDescriptor(resourceKind)+ return descriptor ? t(descriptor.exampleKey) : t('remoteUrl.placeholder')+}++export function RemoteResourceFields({+ children,+ disabled,+ onUrlChange,+ onResourceTypeChange,+ onWatchEnabledChange,+ onWatchIntervalChange,+ resourceKind,+ resourceType,+ t,+ url,+ watchEnabled,+ watchInterval,+ watchRequired = false,+ watchSupported = true,+}: RemoteResourceFieldsProps) {+ const remoteUrlPlaceholder = getRemoteUrlPlaceholder(resourceKind, t)++ return (+ <div className="space-y-4">+ <RemoteResourceTypePicker+ disabled={disabled}+ onChange={onResourceTypeChange}+ t={t}+ value={resourceType}+ watchRequired={watchRequired}+ />++ <div className="space-y-2">+ <div className="flex items-center justify-between gap-3">+ <Label htmlFor="add-resource-remote-url">{t('remoteUrl')}</Label>+ {resourceKind !== 'unknown' ? (+ <Badge variant="secondary">{t(`sourceKind.${resourceKind}`)}</Badge>+ ) : null}+ </div>+ <Input+ id="add-resource-remote-url"+ placeholder={remoteUrlPlaceholder}+ value={url}+ onChange={(event) => onUrlChange(event.target.value)}+ disabled={disabled || (watchRequired && !watchSupported)}+ />+ <p className="text-xs text-muted-foreground">+ {resourceKind === 'unknown'+ ? t('remoteUrl.hint')+ : t(`sourceKind.${resourceKind}Hint`)}+ </p>+ </div>++ {children}++ <div className="rounded-lg border border-border/60 bg-muted/10 p-4">+ <div className="flex items-start justify-between gap-4">+ <div className="grid gap-1">+ <Label htmlFor="add-resource-watch-enabled">+ {t('watch.enabled')}+ </Label>+ <p className="text-xs leading-5 text-muted-foreground">+ {watchSupported ? t('watch.hint') : t('watch.unsupported')}+ </p>+ </div>+ <Switch+ id="add-resource-watch-enabled"+ checked={watchSupported && watchEnabled}+ disabled={disabled || !watchSupported || watchRequired}+ onCheckedChange={onWatchEnabledChange}+ />+ </div>+ {watchRequired && !watchSupported ? (+ <p className="mt-3 text-xs text-destructive" role="alert">+ {t('watch.requiredUnsupported')}+ </p>+ ) : null}+ {watchEnabled && watchSupported ? (+ <div className="mt-4 grid gap-2 border-t border-border/50 pt-4">+ <Label htmlFor="add-resource-watch-interval">+ {t('watch.interval')}+ </Label>+ <Input+ id="add-resource-watch-interval"+ type="number"+ min="1"+ step="1"+ value={watchInterval}+ disabled={disabled}+ onChange={(event) => onWatchIntervalChange(event.target.value)}+ />+ <p className="text-xs text-muted-foreground">+ {t('watch.intervalHint')}+ </p>+ </div>+ ) : null}+ </div>+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-components/remote-resource-type-picker.tsx b/web-studio/src/routes/resources/-components/remote-resource-type-picker.tsxnew file mode 100644index 000000000..876085546--- /dev/null+++ b/web-studio/src/routes/resources/-components/remote-resource-type-picker.tsx@@ -0,0 +1,95 @@+import type { TFunction } from 'i18next'++import { cn } from '#/lib/utils'+import { getRemoteResourceCapabilities } from '../-lib/resource-source-strategy'+import type { RemoteResourceTypeSelection } from '../-lib/resource-source'+import {+ getRemoteResourceDescriptor,+ VISIBLE_REMOTE_RESOURCE_DESCRIPTORS,+} from './remote-resource-descriptors'++type RemoteResourceTypePickerProps = {+ disabled: boolean+ onChange: (value: RemoteResourceTypeSelection) => void+ t: TFunction<'addResource'>+ value: RemoteResourceTypeSelection+ watchRequired?: boolean+}++export function RemoteResourceTypePicker({+ disabled,+ onChange,+ t,+ value,+ watchRequired = false,+}: RemoteResourceTypePickerProps) {+ const selectedDescriptor =+ value === 'auto' ? undefined : getRemoteResourceDescriptor(value)++ return (+ <div className="space-y-2.5 rounded-xl border border-border/60 bg-muted/10 p-3">+ <div className="flex min-w-0 items-baseline gap-2">+ <p className="shrink-0 text-sm font-medium">+ {t('sourcePicker.title')}+ </p>+ <p className="truncate text-xs text-muted-foreground">+ {t('sourcePicker.hint')}+ </p>+ </div>++ <div+ role="group"+ aria-label={t('sourcePicker.title')}+ className="grid grid-cols-2 gap-1.5 sm:grid-cols-4"+ >+ {VISIBLE_REMOTE_RESOURCE_DESCRIPTORS.map(({ type, icon: Icon }) => {+ const selected = value === type+ const optionUnavailable =+ watchRequired && !getRemoteResourceCapabilities(type).watch+ return (+ <button+ key={type}+ type="button"+ aria-pressed={selected}+ data-unavailable={optionUnavailable || undefined}+ title={optionUnavailable ? t('watch.unsupported') : undefined}+ className={cn(+ 'group flex min-w-0 items-center justify-center gap-2 rounded-md border px-2.5 py-2 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-50',+ selected+ ? 'border-primary/50 bg-primary/8 shadow-sm'+ : 'border-border/50 bg-background/60 hover:border-border hover:bg-background',+ )}+ disabled={disabled}+ onClick={() => onChange(selected ? 'auto' : type)}+ >+ <span+ className={cn(+ 'flex size-6 shrink-0 items-center justify-center rounded border transition-colors',+ selected+ ? 'border-primary/30 bg-primary/10 text-primary'+ : 'border-border/50 bg-muted/40 text-muted-foreground group-hover:text-foreground',+ )}+ >+ <Icon className="size-3.5" />+ </span>+ <span className="min-w-0 truncate text-xs font-medium">+ {t(`sourcePicker.${type}`)}+ </span>+ </button>+ )+ })}+ </div>++ {selectedDescriptor ? (+ <div className="flex min-h-7 min-w-0 items-center gap-2 rounded-md bg-muted/40 px-2.5 py-1.5 text-xs text-muted-foreground">+ <span className="min-w-0 flex-1 truncate">+ {t(`sourcePicker.${value}Hint`)}+ </span>+ <code className="hidden max-w-[42%] shrink-0 truncate text-[11px] text-muted-foreground/80 sm:block">+ {t(selectedDescriptor.exampleKey)}+ </code>+ </div>+ ) : null}+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-components/resource-configuration-guide.tsx b/web-studio/src/routes/resources/-components/resource-configuration-guide.tsxnew file mode 100644index 000000000..c000b5ecd--- /dev/null+++ b/web-studio/src/routes/resources/-components/resource-configuration-guide.tsx@@ -0,0 +1,39 @@+import { ChevronRight, ExternalLink } from 'lucide-react'+import type { ReactNode } from 'react'++type ResourceConfigurationGuideProps = {+ children: ReactNode+ documentationLabel?: string+ documentationUrl?: string+ title: string+}++export function ResourceConfigurationGuide({+ children,+ documentationLabel,+ documentationUrl,+ title,+}: ResourceConfigurationGuideProps) {+ return (+ <details className="group rounded-md border border-border/50 bg-background/30 px-3 py-2">+ <summary className="flex cursor-pointer list-none items-center gap-1.5 text-xs font-medium text-foreground marker:hidden">+ <ChevronRight className="size-3.5 transition-transform group-open:rotate-90" />+ {title}+ </summary>+ <div className="mt-2 space-y-2 border-t border-border/40 pt-2 text-xs text-muted-foreground">+ {children}+ {documentationUrl && documentationLabel ? (+ <a+ href={documentationUrl}+ target="_blank"+ rel="noreferrer"+ className="inline-flex w-fit items-center gap-1 font-medium text-foreground underline underline-offset-2"+ >+ {documentationLabel}+ <ExternalLink className="size-3" />+ </a>+ ) : null}+ </div>+ </details>+ )+}diff --git a/web-studio/src/routes/resources/-components/resource-destination-fields.tsx b/web-studio/src/routes/resources/-components/resource-destination-fields.tsxnew file mode 100644index 000000000..52fa487d8--- /dev/null+++ b/web-studio/src/routes/resources/-components/resource-destination-fields.tsx@@ -0,0 +1,84 @@+import { FolderOpen } from 'lucide-react'+import type { TFunction } from 'i18next'++import { Button } from '#/components/ui/button'+import { Input } from '#/components/ui/input'+import { Label } from '#/components/ui/label'+import { RadioGroup, RadioGroupItem } from '#/components/ui/radio-group'++export type ResourceDestinationMode = 'parent' | 'to'++type ResourceDestinationFieldsProps = {+ disabled: boolean+ mode: ResourceDestinationMode+ onBrowse: () => void+ onModeChange: (mode: ResourceDestinationMode) => void+ onUriChange: (uri: string) => void+ t: TFunction<'addResource'>+ uri: string+ exactOnly?: boolean+}++export function ResourceDestinationFields({+ disabled,+ mode,+ onBrowse,+ onModeChange,+ onUriChange,+ t,+ uri,+ exactOnly = false,+}: ResourceDestinationFieldsProps) {+ return (+ <div className="space-y-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <Label htmlFor="add-resource-target">{t('targetUri')}</Label>+ <RadioGroup+ value={mode}+ onValueChange={(value) =>+ onModeChange(value === 'to' ? 'to' : 'parent')+ }+ disabled={disabled}+ className="flex gap-3"+ >+ <label className="flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">+ <RadioGroupItem value="parent" disabled={exactOnly} />+ {t('destination.parent')}+ </label>+ <label className="flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground">+ <RadioGroupItem value="to" />+ {t('destination.exact')}+ </label>+ </RadioGroup>+ </div>+ <div className="flex gap-2">+ <Input+ id="add-resource-target"+ placeholder={t('targetUri.placeholder')}+ value={uri}+ disabled={disabled}+ onChange={(event) => onUriChange(event.target.value)}+ className="flex-1"+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="shrink-0"+ disabled={disabled}+ onClick={onBrowse}+ >+ <FolderOpen className="mr-1.5 size-4" />+ {t('targetUri.browse')}+ </Button>+ </div>+ <p className="text-xs text-muted-foreground">+ {exactOnly+ ? t('destination.tosHint')+ : mode === 'parent'+ ? t('destination.parentHint')+ : t('destination.exactHint')}+ </p>+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-components/resource-option-radio-card.tsx b/web-studio/src/routes/resources/-components/resource-option-radio-card.tsxnew file mode 100644index 000000000..a20fe8446--- /dev/null+++ b/web-studio/src/routes/resources/-components/resource-option-radio-card.tsx@@ -0,0 +1,33 @@+import type { ReactNode } from 'react'++import { RadioGroupItem } from '#/components/ui/radio-group'+import { cn } from '#/lib/utils'++type ResourceOptionRadioCardProps = {+ description: ReactNode+ disabled?: boolean+ title: ReactNode+ value: string+}++export function ResourceOptionRadioCard({+ description,+ disabled = false,+ title,+ value,+}: ResourceOptionRadioCardProps) {+ return (+ <label+ className={cn(+ 'flex cursor-pointer items-start gap-3 rounded-md border border-border/50 p-3',+ disabled && 'cursor-not-allowed opacity-60',+ )}+ >+ <RadioGroupItem value={value} disabled={disabled} className="mt-0.5" />+ <span className="grid gap-1">+ <span className="text-sm font-medium">{title}</span>+ <span className="text-xs text-muted-foreground">{description}</span>+ </span>+ </label>+ )+}diff --git a/web-studio/src/routes/resources/-components/tos-resource-options.tsx b/web-studio/src/routes/resources/-components/tos-resource-options.tsxnew file mode 100644index 000000000..f413e9cc8--- /dev/null+++ b/web-studio/src/routes/resources/-components/tos-resource-options.tsx@@ -0,0 +1,28 @@+import type { TFunction } from 'i18next'++import { ResourceConfigurationGuide } from './resource-configuration-guide'++type TosResourceOptionsProps = {+ t: TFunction<'addResource'>+}++export function TosResourceOptions({ t }: TosResourceOptionsProps) {+ return (+ <div className="space-y-2 rounded-lg border border-border/60 bg-muted/10 p-4">+ <p className="text-sm font-medium">{t('tosOptions.title')}</p>+ <p className="text-xs text-muted-foreground">{t('tosOptions.hint')}</p>+ <p className="text-xs text-amber-600 dark:text-amber-400">+ {t('tosOptions.limitations')}+ </p>+ <ResourceConfigurationGuide title={t('configurationGuide.title')}>+ <ol className="list-decimal space-y-1 pl-4">+ <li>{t('tosOptions.configuration.service')}</li>+ <li>{t('tosOptions.configuration.endpoints')}</li>+ <li>{t('tosOptions.configuration.allow')}</li>+ <li>{t('tosOptions.configuration.restart')}</li>+ </ol>+ <p>{t('tosOptions.configuration.noDocumentation')}</p>+ </ResourceConfigurationGuide>+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-components/upload-resource-fields.test.tsx b/web-studio/src/routes/resources/-components/upload-resource-fields.test.tsxnew file mode 100644index 000000000..776b74547--- /dev/null+++ b/web-studio/src/routes/resources/-components/upload-resource-fields.test.tsx@@ -0,0 +1,134 @@+// @vitest-environment jsdom++import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { UploadResourceFields } from './upload-resource-fields'+import type { SelectedUploadFile } from './upload-resource-fields'+import { MAX_UPLOAD_FILES } from '../-lib/upload'++const mocks = vi.hoisted(() => ({+ onDrop: null as ((files: File[]) => void) | null,+ pending: new Map<string, (value: null) => void>(),+ toast: vi.fn(),+}))++vi.mock('file-type', () => ({+ fileTypeFromBlob: (file: File) =>+ new Promise((resolve) => {+ mocks.pending.set(file.name, () => resolve(undefined))+ }),+}))++vi.mock('react-dropzone', () => ({+ useDropzone: ({ onDrop }: { onDrop: (files: File[]) => void }) => {+ mocks.onDrop = onDrop+ return {+ getInputProps: () => ({}),+ getRootProps: () => ({}),+ isDragActive: false,+ }+ },+}))++vi.mock('sonner', () => ({+ toast: Object.assign(mocks.toast, { error: vi.fn() }),+}))++afterEach(() => {+ cleanup()+ mocks.onDrop = null+ mocks.pending.clear()+ vi.clearAllMocks()+})++describe('UploadResourceFields', () => {+ it('appends concurrent drops against the latest selected files', async () => {+ let current: SelectedUploadFile[] = []+ render(+ <UploadResourceFields+ files={[]}+ onFilesChange={(update) => {+ current = typeof update === 'function' ? update(current) : update+ }}+ t={(key) => key}+ />,+ )++ mocks.onDrop?.([new File(['first'], 'first.pdf')])+ mocks.onDrop?.([new File(['second'], 'second.pdf')])+ mocks.pending.get('second.pdf')?.(null)+ await Promise.resolve()+ await Promise.resolve()+ mocks.pending.get('first.pdf')?.(null)+ await Promise.resolve()+ await Promise.resolve()++ expect(current.map(({ file }) => file.name).sort()).toEqual([+ 'first.pdf',+ 'second.pdf',+ ])+ })++ it('reports truncation when concurrent drops exceed the latest limit', async () => {+ let current: SelectedUploadFile[] = Array.from(+ { length: MAX_UPLOAD_FILES - 1 },+ (_, index) => ({+ id: `existing-${index}`,+ file: new File(['existing'], `existing-${index}.pdf`),+ fileType: null,+ }),+ )+ render(+ <UploadResourceFields+ files={current}+ onFilesChange={(update) => {+ current = typeof update === 'function' ? update(current) : update+ }}+ t={(key) => key}+ />,+ )++ mocks.onDrop?.([new File(['first'], 'first.pdf')])+ mocks.onDrop?.([new File(['second'], 'second.pdf')])+ mocks.pending.get('first.pdf')?.(null)+ mocks.pending.get('second.pdf')?.(null)++ await waitFor(() => expect(current).toHaveLength(MAX_UPLOAD_FILES))+ expect(mocks.toast).toHaveBeenCalledWith('tooManyFiles', {+ duration: 2500,+ })+ })++ it('removes from the latest files after an asynchronous append', async () => {+ const existing: SelectedUploadFile = {+ id: 'existing',+ file: new File(['existing'], 'existing.pdf'),+ fileType: null,+ }+ let current = [existing]+ render(+ <UploadResourceFields+ files={current}+ onFilesChange={(update) => {+ current = typeof update === 'function' ? update(current) : update+ }}+ t={(key) => key}+ />,+ )++ mocks.onDrop?.([new File(['new'], 'new.pdf')])+ mocks.pending.get('new.pdf')?.(null)+ await Promise.resolve()+ await Promise.resolve()+ fireEvent.click(screen.getByRole('button', { name: 'fileInfo.remove' }))++ expect(current.map(({ file }) => file.name)).toEqual(['new.pdf'])+ })+})diff --git a/web-studio/src/routes/resources/-components/upload-resource-fields.tsx b/web-studio/src/routes/resources/-components/upload-resource-fields.tsxnew file mode 100644index 000000000..747447893--- /dev/null+++ b/web-studio/src/routes/resources/-components/upload-resource-fields.tsx@@ -0,0 +1,174 @@+import { fileTypeFromBlob } from 'file-type'+import { FileIcon, Upload } from 'lucide-react'+import type { TFunction } from 'i18next'+import { useCallback, useRef } from 'react'+import type { Dispatch, SetStateAction } from 'react'+import { useDropzone } from 'react-dropzone'+import { toast } from 'sonner'++import { Button } from '#/components/ui/button'+import { cn } from '#/lib/utils'+import {+ MAX_UPLOAD_FILES,+ MAX_UPLOAD_FILE_SIZE_BYTES,+ formatFileSize,+ isBlockedFile,+} from '../-lib/upload'++export type SelectedUploadFile = {+ id: string+ file: File+ fileType: string | null+}++type UploadResourceFieldsProps = {+ files: SelectedUploadFile[]+ onFilesChange: Dispatch<SetStateAction<SelectedUploadFile[]>>+ t: TFunction<'addResource'>+}++function createLocalFileId(): string {+ if (+ typeof crypto !== 'undefined' &&+ typeof crypto.randomUUID === 'function'+ ) {+ return crypto.randomUUID()+ }+ return `local-file-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`+}++async function detectFileType(file: File): Promise<string | null> {+ try {+ const result = await fileTypeFromBlob(file)+ return result?.mime ?? null+ } catch {+ return null+ }+}++export function UploadResourceFields({+ files,+ onFilesChange,+ t,+}: UploadResourceFieldsProps) {+ const filesRef = useRef(files)+ filesRef.current = files++ const updateFiles = useCallback(+ (update: (currentFiles: SelectedUploadFile[]) => SelectedUploadFile[]) => {+ const nextFiles = update(filesRef.current)+ filesRef.current = nextFiles+ onFilesChange(nextFiles)+ },+ [onFilesChange],+ )++ const addFiles = useCallback(+ (nextFiles: File[]) => {+ void (async () => {+ const accepted: SelectedUploadFile[] = []++ for (const file of nextFiles) {+ if (isBlockedFile(file.name)) {+ toast.error(t('fileBlocked', { name: file.name }), {+ duration: 2500,+ })+ continue+ }+ if (file.size > MAX_UPLOAD_FILE_SIZE_BYTES) {+ toast.error(+ t('fileTooLarge', {+ name: file.name,+ size: formatFileSize(MAX_UPLOAD_FILE_SIZE_BYTES),+ }),+ { duration: 2500 },+ )+ continue+ }+ accepted.push({+ id: createLocalFileId(),+ file,+ fileType: await detectFileType(file),+ })+ }++ updateFiles((currentFiles) => {+ const remainingSlots = Math.max(+ MAX_UPLOAD_FILES - currentFiles.length,+ 0,+ )+ if (accepted.length > remainingSlots) {+ toast(t('tooManyFiles', { count: MAX_UPLOAD_FILES }), {+ duration: 2500,+ })+ }+ return [...currentFiles, ...accepted.slice(0, remainingSlots)]+ })+ })()+ },+ [t, updateFiles],+ )++ const { getRootProps, getInputProps, isDragActive } = useDropzone({+ onDrop: addFiles,+ multiple: true,+ })++ return (+ <div className="space-y-3">+ <div+ {...getRootProps()}+ className={cn(+ 'relative rounded-lg border-2 border-dashed p-8 text-center transition-colors',+ isDragActive+ ? 'cursor-pointer border-primary bg-primary/5'+ : 'cursor-pointer border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/30',+ )}+ >+ <input {...getInputProps()} />+ <div className="space-y-2">+ <Upload className="mx-auto size-10 text-muted-foreground/60" />+ <p className="text-sm font-medium">{t('dropzone.title')}</p>+ <p className="text-xs text-muted-foreground">{t('dropzone.hint')}</p>+ <p className="text-xs text-muted-foreground/70">+ {t('dropzone.supportedFormats')}+ </p>+ </div>+ </div>++ {files.length ? (+ <div className="overflow-hidden rounded-lg border border-border/60 bg-muted/10">+ {files.map(({ id, file }) => (+ <div+ key={id}+ className="flex items-center gap-3 border-b border-border/50 px-4 py-3 last:border-b-0"+ >+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted">+ <FileIcon className="size-5 text-muted-foreground" />+ </div>+ <p className="min-w-0 flex-1 truncate text-sm font-medium">+ {file.name}+ </p>+ <span className="shrink-0 text-xs text-muted-foreground">+ {formatFileSize(file.size)}+ </span>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="shrink-0 text-muted-foreground hover:text-foreground"+ onClick={() =>+ updateFiles((currentFiles) =>+ currentFiles.filter((item) => item.id !== id),+ )+ }+ >+ {t('fileInfo.remove')}+ </Button>+ </div>+ ))}+ </div>+ ) : null}+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-components/web-resource-options.tsx b/web-studio/src/routes/resources/-components/web-resource-options.tsxnew file mode 100644index 000000000..5b0c520b0--- /dev/null+++ b/web-studio/src/routes/resources/-components/web-resource-options.tsx@@ -0,0 +1,159 @@+import type { TFunction } from 'i18next'++import { Checkbox } from '#/components/ui/checkbox'+import { Input } from '#/components/ui/input'+import { Label } from '#/components/ui/label'+import { RadioGroup } from '#/components/ui/radio-group'+import { Textarea } from '#/components/ui/textarea'+import { ResourceOptionRadioCard } from './resource-option-radio-card'++export type WebImportMode = 'auto' | 'single' | 'recursive' | 'site'++const WEB_IMPORT_MODES: WebImportMode[] = [+ 'auto',+ 'single',+ 'recursive',+ 'site',+]++export type WebResourceOptionsValue = {+ allowExternalLinks: boolean+ depth: string+ excludePaths: string+ includePaths: string+ maxPages: string+ mode: WebImportMode+ skipDownloadLinks: boolean+}++type WebResourceOptionsProps = {+ disabled: boolean+ onChange: (value: WebResourceOptionsValue) => void+ t: TFunction<'addResource'>+ value: WebResourceOptionsValue+}++export function WebResourceOptions({+ disabled,+ onChange,+ t,+ value,+}: WebResourceOptionsProps) {+ const showCrawlLimits = ['recursive', 'site'].includes(value.mode)++ return (+ <div className="space-y-4 rounded-lg border border-border/60 bg-muted/10 p-4">+ <div className="space-y-2">+ <Label>{t('web.mode.title')}</Label>+ <RadioGroup+ value={value.mode}+ onValueChange={(mode) =>+ onChange({ ...value, mode: mode as WebImportMode })+ }+ disabled={disabled}+ className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4"+ >+ {WEB_IMPORT_MODES.map((mode) => (+ <ResourceOptionRadioCard+ key={mode}+ description={t(`web.mode.${mode}Hint`)}+ title={t(`web.mode.${mode}`)}+ value={mode}+ />+ ))}+ </RadioGroup>+ </div>++ {showCrawlLimits ? (+ <div className="grid gap-3 border-t border-border/50 pt-3 sm:grid-cols-2">+ {value.mode === 'recursive' ? (+ <div className="grid gap-2">+ <Label htmlFor="add-resource-web-depth">{t('web.depth')}</Label>+ <Input+ id="add-resource-web-depth"+ type="number"+ min="0"+ step="1"+ value={value.depth}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, depth: event.target.value })+ }+ />+ </div>+ ) : null}+ <div className="grid gap-2">+ <Label htmlFor="add-resource-web-max-pages">+ {t('web.maxPages')}+ </Label>+ <Input+ id="add-resource-web-max-pages"+ type="number"+ min="1"+ step="1"+ value={value.maxPages}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, maxPages: event.target.value })+ }+ />+ </div>+ <div className="grid gap-2">+ <Label htmlFor="add-resource-web-include-paths">+ {t('web.includePaths')}+ </Label>+ <Textarea+ id="add-resource-web-include-paths"+ rows={2}+ value={value.includePaths}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, includePaths: event.target.value })+ }+ placeholder={t('web.includePaths.placeholder')}+ />+ </div>+ <div className="grid gap-2">+ <Label htmlFor="add-resource-web-exclude-paths">+ {t('web.excludePaths')}+ </Label>+ <Textarea+ id="add-resource-web-exclude-paths"+ rows={2}+ value={value.excludePaths}+ disabled={disabled}+ onChange={(event) =>+ onChange({ ...value, excludePaths: event.target.value })+ }+ placeholder={t('web.excludePaths.placeholder')}+ />+ </div>+ {value.mode === 'recursive' ? (+ <div className="flex flex-wrap gap-x-5 gap-y-3 sm:col-span-2">+ <Label className="flex items-center gap-2">+ <Checkbox+ checked={value.allowExternalLinks}+ disabled={disabled}+ onCheckedChange={(checked) =>+ onChange({ ...value, allowExternalLinks: Boolean(checked) })+ }+ />+ {t('web.allowExternalLinks')}+ </Label>+ <Label className="flex items-center gap-2">+ <Checkbox+ checked={value.skipDownloadLinks}+ disabled={disabled}+ onCheckedChange={(checked) =>+ onChange({ ...value, skipDownloadLinks: Boolean(checked) })+ }+ />+ {t('web.skipDownloadLinks')}+ </Label>+ </div>+ ) : null}+ </div>+ ) : null}+ </div>+ )+}diff --git a/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx b/web-studio/src/routes/resources/-hooks/use-resource-upload.tsxindex 6c515555c..ba89bbcb0 100644--- a/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx+++ b/web-studio/src/routes/resources/-hooks/use-resource-upload.tsx@@ -5,7 +5,6 @@ import {getTasks,getOvResult,isOvClientError,- postResources,postResourcesTempUpload,} from '#/lib/ov-client'import { parseUploadError } from '../-lib/upload'@@ -14,10 +13,16 @@ import {mergeServerTasks,normalizeTaskList,} from '../-lib/resource-upload-tasks'+import {+ buildRemoteResourceRequest,+ buildUploadedResourceRequest,+} from '../-lib/resource-import-request'+import { postResourceImport } from '../-lib/resource-import-api'import type {- AddResourceResult,+ ResourceImportCommonBody,+ ResourceImportResult,TempUploadResult,-} from '@ov-server/api/v1/resources'+} from '../-lib/resource-import-types'import type { TaskListResult } from '@ov-server/api/v1/tasks'export type ResourceUploadTaskStatus =@@ -61,7 +66,7 @@ export type UploadBatchItem = {export type UploadBatchParams = {files: UploadBatchItem[]- commonBody: Record<string, unknown>+ commonBody: ResourceImportCommonBody}export type RemoteStartResult = {@@ -71,7 +76,7 @@ export type RemoteStartResult = {export type RemoteStartParams = {url: string- commonBody: Record<string, unknown>+ commonBody: ResourceImportCommonBodyonAccepted?: (result: RemoteStartResult) => voidonCompleted?: () => voidonFailed?: () => void@@ -234,7 +239,7 @@ export function ResourceUploadProvider({async (taskId: string,params: UploadBatchItem,- commonBody: Record<string, unknown>,+ commonBody: ResourceImportCommonBody,) => {try {updateTask(taskId, (task) => ({@@ -274,14 +279,14 @@ export function ResourceUploadProvider({progress: null,}))- const addResult = await getOvResult<AddResourceResult>(- postResources({- body: {- ...commonBody,- temp_file_id: tempFileId,- source_name: params.file.name,- } as Parameters<typeof postResources>[0]['body'],- }),+ const addResult = await getOvResult<ResourceImportResult>(+ postResourceImport(+ buildUploadedResourceRequest(+ tempFileId,+ params.file.name,+ commonBody,+ ),+ ),)if (addResult.status === 'error') {@@ -404,14 +409,11 @@ export function ResourceUploadProvider({void (async () => {try {- const result = await getOvResult<AddResourceResult>(- postResources({- body: {- ...params.commonBody,- path: params.url,- } as Parameters<typeof postResources>[0]['body'],- signal: controller.signal,- }),+ const result = await getOvResult<ResourceImportResult>(+ postResourceImport(+ buildRemoteResourceRequest(params.url, params.commonBody),+ controller.signal,+ ),)if (result.status === 'error') {diff --git a/web-studio/src/routes/resources/-lib/resource-import-api.ts b/web-studio/src/routes/resources/-lib/resource-import-api.tsnew file mode 100644index 000000000..cf135ba51--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-import-api.ts@@ -0,0 +1,18 @@+import { postResources } from '#/lib/ov-client'+import type { ResourceImportRequest } from './resource-import-types'++type GeneratedResourceBody = Parameters<typeof postResources>[0]['body']++/**+ * The checked-in generated client can lag behind Web Studio resource options.+ * Isolate that compatibility boundary here instead of weakening every caller.+ */+export function postResourceImport(+ body: ResourceImportRequest,+ signal?: AbortSignal,+) {+ return postResources({+ body: body as GeneratedResourceBody,+ ...(signal ? { signal } : {}),+ })+}diff --git a/web-studio/src/routes/resources/-lib/resource-import-request.test.ts b/web-studio/src/routes/resources/-lib/resource-import-request.test.tsnew file mode 100644index 000000000..55f554587--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-import-request.test.ts@@ -0,0 +1,199 @@+import { describe, expect, it } from 'vitest'++import {+ buildResourceImportCommonBody,+ buildRemoteResourceRequest,+ buildUploadedResourceRequest,+} from './resource-import-request'+import type { ResourceImportFormState } from './resource-import-request'++const BASE_FORM_STATE: ResourceImportFormState = {+ additionalOptions: {+ parseMode: 'default',+ processingMode: 'semantic_and_vectors',+ sourceName: '',+ tagMode: 'replace',+ tags: '',+ timeout: '',+ wait: false,+ },+ createParent: true,+ destinationMode: 'parent',+ directlyUploadMedia: true,+ exclude: '',+ ignoreDirs: '',+ include: '',+ instruction: '',+ mode: 'remote',+ reason: '',+ remoteResourceKind: 'unknown',+ sourceOptionState: {+ feishu: { accessToken: '', authMode: 'app', refreshToken: '' },+ git: {+ authMode: 'public',+ refMode: 'branch',+ refValue: '',+ supportsHttpAuth: true,+ token: '',+ username: 'oauth2',+ },+ watchEnabled: false,+ web: {+ allowExternalLinks: false,+ depth: '1',+ excludePaths: '',+ includePaths: '',+ maxPages: '50',+ mode: 'auto',+ skipDownloadLinks: true,+ },+ },+ strict: false,+ targetUri: 'viking://resources/',+ watchEnabled: false,+ watchInterval: '1440',+}++describe('resource import request builders', () => {+ it('serializes native form options in one place', () => {+ expect(+ buildResourceImportCommonBody({+ ...BASE_FORM_STATE,+ additionalOptions: {+ ...BASE_FORM_STATE.additionalOptions,+ parseMode: 'no_split',+ preserveStructure: true,+ processingMode: 'vectors_only',+ sourceName: 'docs',+ tagMode: 'append',+ tags: 'team=docs, env=test',+ timeout: '12.5',+ wait: true,+ },+ exclude: '**/dist/**',+ ignoreDirs: '.git,node_modules',+ include: '**/*.md',+ instruction: ' Prefer API docs. ',+ reason: ' Knowledge base ',+ strict: true,+ watchEnabled: true,+ watchInterval: '60',+ }),+ ).toEqual({+ args: { parse_mode: 'no_split' },+ create_parent: true,+ directly_upload_media: true,+ exclude: '**/dist/**',+ ignore_dirs: '.git,node_modules',+ include: '**/*.md',+ instruction: 'Prefer API docs.',+ parent: 'viking://resources/',+ preserve_structure: true,+ processing_mode: 'vectors_only',+ reason: 'Knowledge base',+ source_name: 'docs',+ strict: true,+ tag_mode: 'append',+ tags: ['team=docs', 'env=test'],+ telemetry: true,+ timeout: 12.5,+ wait: true,+ watch_interval: 60,+ })+ })++ it('merges parse mode with source-specific Git options', () => {+ const body = buildResourceImportCommonBody({+ ...BASE_FORM_STATE,+ additionalOptions: {+ ...BASE_FORM_STATE.additionalOptions,+ parseMode: 'no_split',+ },+ remoteResourceKind: 'git',+ sourceOptionState: {+ ...BASE_FORM_STATE.sourceOptionState,+ git: {+ ...BASE_FORM_STATE.sourceOptionState.git,+ refValue: 'main',+ },+ },+ })++ expect(body.args).toEqual({+ branch: 'main',+ parse_mode: 'no_split',+ })+ })++ it('keeps TOS selectable but emits only its supported request fields', () => {+ expect(+ buildResourceImportCommonBody({+ ...BASE_FORM_STATE,+ additionalOptions: {+ ...BASE_FORM_STATE.additionalOptions,+ parseMode: 'no_split',+ processingMode: 'vectors_only',+ wait: true,+ },+ destinationMode: 'parent',+ instruction: 'ignored',+ remoteResourceKind: 'tos',+ strict: true,+ targetUri: ' viking://resources/tos-item ',+ watchEnabled: true,+ }),+ ).toEqual({+ add_type: 'tos',+ create_parent: true,+ directly_upload_media: true,+ processing_mode: 'semantic_and_vectors',+ strict: false,+ telemetry: true,+ to: 'viking://resources/tos-item',+ wait: false,+ })+ })++ it('preserves source-specific remote options', () => {+ expect(+ buildRemoteResourceRequest(' https://example.feishu.cn/docx/doc ', {+ args: {+ feishu_access_token: 'u-token',+ feishu_refresh_token: 'r-token',+ },+ processing_mode: 'vectors_only',+ tags: ['team=docs'],+ tag_mode: 'append',+ to: 'viking://resources/feishu/doc',+ watch_interval: 1440,+ }),+ ).toEqual({+ args: {+ feishu_access_token: 'u-token',+ feishu_refresh_token: 'r-token',+ },+ path: 'https://example.feishu.cn/docx/doc',+ processing_mode: 'vectors_only',+ tags: ['team=docs'],+ tag_mode: 'append',+ to: 'viking://resources/feishu/doc',+ watch_interval: 1440,+ })+ })++ it('removes remote-only scheduling and routing fields from uploads', () => {+ expect(+ buildUploadedResourceRequest(' temp-id ', 'guide.pdf', {+ add_type: 'tos',+ args: { parse_mode: 'no_split' },+ parent: 'viking://resources/docs',+ watch_interval: 60,+ }),+ ).toEqual({+ args: { parse_mode: 'no_split' },+ parent: 'viking://resources/docs',+ source_name: 'guide.pdf',+ temp_file_id: 'temp-id',+ })+ })+})diff --git a/web-studio/src/routes/resources/-lib/resource-import-request.ts b/web-studio/src/routes/resources/-lib/resource-import-request.tsnew file mode 100644index 000000000..9c2c465d0--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-import-request.ts@@ -0,0 +1,149 @@+import type { AdditionalResourceOptionsValue } from '../-components/additional-resource-options'+import type { ResourceDestinationMode } from '../-components/resource-destination-fields'+import { parseResourceTags } from './resource-option-values'+import type { RemoteResourceKind } from './resource-source'+import {+ buildRemoteSourceRequestOptions,+ getRemoteResourceCapabilities,+} from './resource-source-strategy'+import type { RemoteSourceOptionState } from './resource-source-strategy'+import type {+ ResourceImportCommonBody,+ ResourceImportRequest,+} from './resource-import-types'++export type ResourceImportFormState = {+ additionalOptions: AdditionalResourceOptionsValue+ createParent: boolean+ destinationMode: ResourceDestinationMode+ directlyUploadMedia: boolean+ exclude: string+ ignoreDirs: string+ include: string+ instruction: string+ mode: 'remote' | 'upload'+ reason: string+ remoteResourceKind: RemoteResourceKind+ sourceOptionState: RemoteSourceOptionState+ strict: boolean+ targetUri: string+ watchEnabled: boolean+ watchInterval: string+}++export function buildResourceImportCommonBody({+ additionalOptions,+ createParent,+ destinationMode,+ directlyUploadMedia,+ exclude,+ ignoreDirs,+ include,+ instruction,+ mode,+ reason,+ remoteResourceKind,+ sourceOptionState,+ strict,+ targetUri,+ watchEnabled,+ watchInterval,+}: ResourceImportFormState): ResourceImportCommonBody {+ const sourceCapabilities = getRemoteResourceCapabilities(+ mode === 'remote' ? remoteResourceKind : 'unknown',+ )+ const effectiveDestinationMode: ResourceDestinationMode =+ sourceCapabilities.exactDestination ? 'to' : destinationMode+ const tags = parseResourceTags(additionalOptions.tags)+ const body: ResourceImportCommonBody = {+ [effectiveDestinationMode]: targetUri.trim() || undefined,+ strict: sourceCapabilities.nativeOptions ? strict : false,+ create_parent: createParent,+ telemetry: true,+ wait: sourceCapabilities.nativeOptions ? additionalOptions.wait : false,+ ...(sourceCapabilities.nativeOptions &&+ additionalOptions.wait &&+ additionalOptions.timeout.trim()+ ? { timeout: Number(additionalOptions.timeout) }+ : {}),+ directly_upload_media: sourceCapabilities.nativeOptions+ ? directlyUploadMedia+ : true,+ ...(sourceCapabilities.nativeOptions &&+ additionalOptions.preserveStructure !== undefined+ ? { preserve_structure: additionalOptions.preserveStructure }+ : {}),+ processing_mode: sourceCapabilities.nativeOptions+ ? additionalOptions.processingMode+ : 'semantic_and_vectors',+ ...(tags.length ? { tags, tag_mode: additionalOptions.tagMode } : {}),+ ...(mode === 'remote' &&+ sourceCapabilities.nativeOptions &&+ additionalOptions.sourceName.trim()+ ? { source_name: additionalOptions.sourceName.trim() }+ : {}),+ ...(sourceCapabilities.nativeOptions &&+ additionalOptions.parseMode === 'no_split'+ ? { args: { parse_mode: 'no_split' } }+ : {}),+ }++ if (reason.trim()) body.reason = reason.trim()+ if (instruction.trim() && sourceCapabilities.nativeOptions) {+ body.instruction = instruction.trim()+ }+ if (mode !== 'remote') return body++ if (watchEnabled && sourceCapabilities.watch) {+ body.watch_interval = Number(watchInterval)+ }+ if (ignoreDirs.trim() && sourceCapabilities.nativeOptions) {+ body.ignore_dirs = ignoreDirs.trim()+ }+ if (include.trim() && sourceCapabilities.nativeOptions) {+ body.include = include.trim()+ }+ if (exclude.trim() && sourceCapabilities.nativeOptions) {+ body.exclude = exclude.trim()+ }++ const sourceRequestOptions = buildRemoteSourceRequestOptions(+ remoteResourceKind,+ sourceOptionState,+ )+ const { args: sourceArgs, ...sourceOptions } = sourceRequestOptions+ Object.assign(body, sourceOptions)+ const mergedArgs = { ...body.args, ...sourceArgs }+ if (Object.keys(mergedArgs).length > 0) body.args = mergedArgs+ else delete body.args++ return body+}++export function buildRemoteResourceRequest(+ url: string,+ commonBody: ResourceImportCommonBody,+): ResourceImportRequest {+ return {+ ...commonBody,+ path: url.trim(),+ }+}++export function buildUploadedResourceRequest(+ tempFileId: string,+ sourceName: string,+ commonBody: ResourceImportCommonBody,+): ResourceImportRequest {+ const {+ add_type: _addType,+ watch_interval: _watchInterval,+ ...uploadBody+ } = commonBody++ return {+ ...uploadBody,+ source_name: sourceName,+ temp_file_id: tempFileId.trim(),+ }+}diff --git a/web-studio/src/routes/resources/-lib/resource-import-types.ts b/web-studio/src/routes/resources/-lib/resource-import-types.tsnew file mode 100644index 000000000..29f04be2e--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-import-types.ts@@ -0,0 +1,71 @@+export type TempUploadResult = {+ content_type?: string+ file_name?: string+ filename?: string+ size?: number+ temp_file_id: string+}++export type ResourceProcessingMode = 'semantic_and_vectors' | 'vectors_only'++export type ResourceTagMode = 'replace' | 'append'++export type ResourceImportArgs = Record<string, unknown> & {+ allow_external_links?: boolean+ auth_config?: Record<string, unknown>+ branch?: string+ commit?: string+ depth?: number+ exclude_paths?: string[]+ feishu_access_token?: string+ feishu_refresh_token?: string+ include_paths?: string[]+ max_pages?: number+ parse_mode?: 'default' | 'no_split'+ site?: boolean+ skip_download_links?: boolean+}++/**+ * Web Studio resource-import payload. Keep compatibility with the currently+ * deployed API here so feature code does not depend on regenerating a client.+ */+export type ResourceImportRequest = {+ path?: string+ temp_file_id?: string+ add_type?: string+ to?: string+ parent?: string+ create_parent?: boolean+ reason?: string+ instruction?: string+ wait?: boolean+ timeout?: number+ strict?: boolean+ source_name?: string+ ignore_dirs?: string+ include?: string+ exclude?: string+ directly_upload_media?: boolean+ preserve_structure?: boolean+ args?: ResourceImportArgs+ telemetry?: boolean | Record<string, boolean>+ watch_interval?: number+ processing_mode?: ResourceProcessingMode+ tags?: string[]+ tag_mode?: ResourceTagMode+}++export type ResourceImportCommonBody = Omit<+ ResourceImportRequest,+ 'path' | 'temp_file_id'+>++export type ResourceImportResult = {+ errors?: string[]+ message?: string+ root_uri?: string+ status?: 'success' | 'error' | (string & {})+ task_id?: string+ warnings?: string[]+}diff --git a/web-studio/src/routes/resources/-lib/resource-option-values.test.ts b/web-studio/src/routes/resources/-lib/resource-option-values.test.tsnew file mode 100644index 000000000..92d32dab6--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-option-values.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest'++import {+ parseDelimitedValues,+ parseOptionalNumber,+ parseResourceTags,+} from './resource-option-values'++describe('resource option values', () => {+ it('parses comma and newline separated values', () => {+ expect(parseDelimitedValues('/docs, /zh/\n/changelog')).toEqual([+ '/docs',+ '/zh/',+ '/changelog',+ ])+ })++ it('converts optional numeric values without applying server rules', () => {+ expect(parseOptionalNumber('2')).toBe(2)+ expect(parseOptionalNumber('-1')).toBe(-1)+ expect(parseOptionalNumber('1.5')).toBe(1.5)+ expect(parseOptionalNumber('')).toBeUndefined()+ })++ it('normalizes resource tags without duplicating server validation', () => {+ expect(parseResourceTags('team=docs, env=test')).toEqual([+ 'team=docs',+ 'env=test',+ ])+ expect(parseResourceTags('team=docs, invalid')).toEqual([+ 'team=docs',+ 'invalid',+ ])+ })+})diff --git a/web-studio/src/routes/resources/-lib/resource-option-values.ts b/web-studio/src/routes/resources/-lib/resource-option-values.tsnew file mode 100644index 000000000..f3e1b2e04--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-option-values.ts@@ -0,0 +1,16 @@+export function parseDelimitedValues(value: string): string[] {+ return value+ .split(/[\n,]/)+ .map((item) => item.trim())+ .filter(Boolean)+}++export function parseOptionalNumber(value: string): number | undefined {+ const trimmed = value.trim()+ if (!trimmed) return undefined+ return Number(trimmed)+}++export function parseResourceTags(value: string): string[] {+ return Array.from(new Set(parseDelimitedValues(value)))+}diff --git a/web-studio/src/routes/resources/-lib/resource-source-strategy.test.ts b/web-studio/src/routes/resources/-lib/resource-source-strategy.test.tsnew file mode 100644index 000000000..fe715f0f0--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-source-strategy.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from 'vitest'++import {+ buildRemoteSourceRequestOptions,+ getRemoteResourceCapabilities,+} from './resource-source-strategy'+import type { RemoteSourceOptionState } from './resource-source-strategy'++const DEFAULT_STATE: RemoteSourceOptionState = {+ feishu: {+ accessToken: '',+ authMode: 'app',+ refreshToken: '',+ },+ git: {+ authMode: 'public',+ refMode: 'branch',+ refValue: '',+ supportsHttpAuth: false,+ token: '',+ username: 'oauth2',+ },+ watchEnabled: false,+ web: {+ allowExternalLinks: false,+ depth: '1',+ excludePaths: '',+ includePaths: '',+ maxPages: '50',+ mode: 'auto',+ skipDownloadLinks: true,+ },+}++describe('remote resource source strategy', () => {+ it('declares TOS as an exact, connector-only, non-watchable source', () => {+ expect(getRemoteResourceCapabilities('tos')).toEqual({+ exactDestination: true,+ nativeOptions: false,+ watch: false,+ })+ expect(buildRemoteSourceRequestOptions('tos', DEFAULT_STATE)).toEqual({+ add_type: 'tos',+ })+ })++ it('builds watched Feishu user credentials', () => {+ const state: RemoteSourceOptionState = {+ ...DEFAULT_STATE,+ feishu: {+ accessToken: 'u-token',+ authMode: 'user',+ refreshToken: 'r-token',+ },+ watchEnabled: true,+ }++ expect(buildRemoteSourceRequestOptions('feishu', state)).toEqual({+ args: {+ feishu_access_token: 'u-token',+ feishu_refresh_token: 'r-token',+ },+ })+ })++ it('forwards recursive web limits for server validation', () => {+ const state: RemoteSourceOptionState = {+ ...DEFAULT_STATE,+ web: {+ ...DEFAULT_STATE.web,+ depth: '-1',+ mode: 'recursive',+ },+ }++ expect(buildRemoteSourceRequestOptions('webPage', state)).toEqual({+ args: {+ allow_external_links: false,+ depth: -1,+ exclude_paths: undefined,+ include_paths: undefined,+ max_pages: 50,+ site: false,+ skip_download_links: true,+ },+ })+ })++ it('builds site filters as top-level comma-delimited patterns', () => {+ const state: RemoteSourceOptionState = {+ ...DEFAULT_STATE,+ web: {+ ...DEFAULT_STATE.web,+ excludePaths: '/archive\n/private',+ includePaths: '/docs, /zh/',+ mode: 'site',+ },+ }++ expect(buildRemoteSourceRequestOptions('webPage', state)).toEqual({+ args: {+ max_pages: 50,+ site: true,+ },+ exclude: '/archive,/private',+ include: '/docs,/zh/',+ })+ })++ it('does not build token authentication for a non-HTTPS Git source', () => {+ const state: RemoteSourceOptionState = {+ ...DEFAULT_STATE,+ git: {+ ...DEFAULT_STATE.git,+ authMode: 'token',+ token: 'secret-token',+ },+ }++ expect(buildRemoteSourceRequestOptions('git', state)).toEqual({ args: {} })+ })+})diff --git a/web-studio/src/routes/resources/-lib/resource-source-strategy.ts b/web-studio/src/routes/resources/-lib/resource-source-strategy.tsnew file mode 100644index 000000000..5157d132d--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-source-strategy.ts@@ -0,0 +1,170 @@+import type { FeishuAuthMode } from '../-components/feishu-resource-options'+import type {+ GitAuthMode,+ GitRefMode,+} from '../-components/git-resource-options'+import type { WebResourceOptionsValue } from '../-components/web-resource-options'+import {+ parseDelimitedValues,+ parseOptionalNumber,+} from './resource-option-values'+import type { RemoteResourceKind } from './resource-source'+import type { ResourceImportCommonBody } from './resource-import-types'++type RemoteResourceCapabilities = {+ exactDestination: boolean+ nativeOptions: boolean+ watch: boolean+}++type RemoteSourceRequestOptions = Pick<+ ResourceImportCommonBody,+ 'add_type' | 'args' | 'exclude' | 'include'+>++type RemoteSourceStrategy = {+ build: (state: RemoteSourceOptionState) => RemoteSourceRequestOptions+ capabilities: RemoteResourceCapabilities+}++const DEFAULT_CAPABILITIES: RemoteResourceCapabilities = {+ exactDestination: false,+ nativeOptions: true,+ watch: true,+}++const TOS_CAPABILITIES: RemoteResourceCapabilities = {+ exactDestination: true,+ nativeOptions: false,+ watch: false,+}++export type RemoteSourceOptionState = {+ feishu: {+ accessToken: string+ authMode: FeishuAuthMode+ refreshToken: string+ }+ git: {+ authMode: GitAuthMode+ refMode: GitRefMode+ refValue: string+ supportsHttpAuth: boolean+ token: string+ username: string+ }+ watchEnabled: boolean+ web: WebResourceOptionsValue+}++const DEFAULT_STRATEGY: RemoteSourceStrategy = {+ build: () => ({}),+ capabilities: DEFAULT_CAPABILITIES,+}++const FEISHU_STRATEGY: RemoteSourceStrategy = {+ build: (state) =>+ state.feishu.authMode === 'user'+ ? {+ args: {+ feishu_access_token: state.feishu.accessToken.trim(),+ ...(state.watchEnabled+ ? { feishu_refresh_token: state.feishu.refreshToken.trim() }+ : {}),+ },+ }+ : {},+ capabilities: DEFAULT_CAPABILITIES,+}++const GIT_STRATEGY: RemoteSourceStrategy = {+ build: (state) => ({+ args: {+ ...(state.git.refValue.trim()+ ? { [state.git.refMode]: state.git.refValue.trim() }+ : {}),+ ...(state.git.authMode === 'token' && state.git.supportsHttpAuth+ ? {+ auth_config: {+ username: state.git.username.trim() || 'oauth2',+ token: state.git.token.trim(),+ },+ }+ : {}),+ },+ }),+ capabilities: DEFAULT_CAPABILITIES,+}++const WEB_STRATEGY: RemoteSourceStrategy = {+ build: (state) => {+ const includePaths = parseDelimitedValues(state.web.includePaths)+ const excludePaths = parseDelimitedValues(state.web.excludePaths)+ const recursive = state.web.mode === 'recursive'+ const site = state.web.mode === 'site'+ return {+ args: {+ ...(state.web.mode === 'single' ? { site: false, depth: 0 } : {}),+ ...(recursive+ ? {+ site: false,+ depth: parseOptionalNumber(state.web.depth),+ max_pages: parseOptionalNumber(state.web.maxPages),+ include_paths: includePaths.length ? includePaths : undefined,+ exclude_paths: excludePaths.length ? excludePaths : undefined,+ allow_external_links: state.web.allowExternalLinks,+ skip_download_links: state.web.skipDownloadLinks,+ }+ : {}),+ ...(site+ ? {+ site: true,+ max_pages: parseOptionalNumber(state.web.maxPages),+ }+ : {}),+ },+ ...(site && includePaths.length+ ? { include: includePaths.join(',') }+ : {}),+ ...(site && excludePaths.length+ ? { exclude: excludePaths.join(',') }+ : {}),+ }+ },+ capabilities: DEFAULT_CAPABILITIES,+}++const TOS_STRATEGY: RemoteSourceStrategy = {+ build: () => ({ add_type: 'tos' }),+ capabilities: TOS_CAPABILITIES,+}++const REMOTE_SOURCE_STRATEGIES: Record<+ RemoteResourceKind,+ RemoteSourceStrategy+> = {+ unknown: DEFAULT_STRATEGY,+ feishu: FEISHU_STRATEGY,+ git: GIT_STRATEGY,+ webFeed: WEB_STRATEGY,+ webPage: WEB_STRATEGY,+ remoteFile: DEFAULT_STRATEGY,+ tos: TOS_STRATEGY,+}++function getRemoteSourceStrategy(kind: RemoteResourceKind) {+ return REMOTE_SOURCE_STRATEGIES[kind]+}++export function getRemoteResourceCapabilities(+ kind: RemoteResourceKind,+): RemoteResourceCapabilities {+ return getRemoteSourceStrategy(kind).capabilities+}++export function buildRemoteSourceRequestOptions(+ kind: RemoteResourceKind,+ state: RemoteSourceOptionState,+): RemoteSourceRequestOptions {+ return getRemoteSourceStrategy(kind).build(state)+}diff --git a/web-studio/src/routes/resources/-lib/resource-source.test.ts b/web-studio/src/routes/resources/-lib/resource-source.test.tsnew file mode 100644index 000000000..f51efa31d--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-source.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest'++import { detectRemoteResourceKind } from './resource-source'++describe('detectRemoteResourceKind', () => {+ it.each([+ ['https://example.feishu.cn/docx/doxcn123', 'feishu'],+ ['https://open.larksuite.com/wiki/wikcn123', 'feishu'],+ ['https://github.com/volcengine/OpenViking', 'git'],+ ['[email protected]:volcengine/OpenViking.git', 'git'],+ ['https://gitlab.com/group/repo.git', 'git'],+ ['https://git.example.com/group/repo.git', 'git'],+ ['https://dev.azure.com/org/project/_git/repo', 'git'],+ ['https://example.com/sitemap.xml', 'webFeed'],+ ['https://example.com/feed.atom', 'webFeed'],+ ['https://example.com/guide.pdf', 'remoteFile'],+ ['https://example.com/docs/getting-started', 'webPage'],+ ['tos://bucket/docs', 'tos'],+ ['custom://workspace/source', 'unknown'],+ ['', 'unknown'],+ ] as const)('detects %s as %s', (source, expected) => {+ expect(detectRemoteResourceKind(source)).toBe(expected)+ })++ it('does not classify a GitHub blob URL as a repository', () => {+ expect(+ detectRemoteResourceKind(+ 'https://github.com/volcengine/OpenViking/blob/main/README.md',+ ),+ ).toBe('remoteFile')+ })++ it('does not classify an Azure DevOps file browser URL as a repository', () => {+ expect(+ detectRemoteResourceKind(+ 'https://dev.azure.com/org/project/_git/repo?path=/README.md',+ ),+ ).toBe('webPage')+ })+})diff --git a/web-studio/src/routes/resources/-lib/resource-source.ts b/web-studio/src/routes/resources/-lib/resource-source.tsnew file mode 100644index 000000000..62dcf6806--- /dev/null+++ b/web-studio/src/routes/resources/-lib/resource-source.ts@@ -0,0 +1,139 @@+export type RemoteResourceKind =+ | 'unknown'+ | 'feishu'+ | 'git'+ | 'webFeed'+ | 'webPage'+ | 'remoteFile'+ | 'tos'++export type RemoteResourceTypeSelection =+ | 'auto'+ | Exclude<RemoteResourceKind, 'unknown' | 'webFeed'>++const FEISHU_HOST_SUFFIXES = ['feishu.cn', 'larksuite.com', 'larkoffice.com']+const FEISHU_PATH_PREFIXES = ['docx', 'wiki', 'sheets', 'base']+const CODE_HOSTS = new Set([+ 'github.com',+ 'gitlab.com',+ 'bitbucket.org',+ 'codeberg.org',+ 'gitee.com',+ 'gitcode.com',+ 'atomgit.com',+ 'git.sr.ht',+])+const AZURE_DEVOPS_HOSTS = new Set(['dev.azure.com'])+const REMOTE_FILE_EXTENSIONS = new Set([+ 'pdf',+ 'md',+ 'markdown',+ 'txt',+ 'text',+ 'html',+ 'htm',+ 'doc',+ 'docx',+ 'xls',+ 'xlsx',+ 'xlsm',+ 'pptx',+ 'epub',+ 'zip',+ 'jpg',+ 'jpeg',+ 'png',+ 'gif',+ 'webp',+ 'svg',+ 'mp3',+ 'wav',+ 'm4a',+ 'flac',+ 'mp4',+ 'avi',+ 'mov',+ 'mkv',+ 'webm',+])++function hasHostSuffix(host: string, suffix: string): boolean {+ return host === suffix || host.endsWith(`.${suffix}`)+}++function looksLikeFeishuUrl(url: URL): boolean {+ const host = url.hostname.toLowerCase().replace(/\.$/, '')+ const firstPathSegment = url.pathname.split('/').filter(Boolean)[0]+ return (+ FEISHU_HOST_SUFFIXES.some((suffix) => hasHostSuffix(host, suffix)) &&+ FEISHU_PATH_PREFIXES.includes(firstPathSegment)+ )+}++function looksLikeWebFeed(url: URL): boolean {+ const basename = url.pathname+ .toLowerCase()+ .replace(/\/$/, '')+ .split('/')+ .pop()+ if (!basename) return false+ return (+ (basename.startsWith('sitemap') && basename.endsWith('.xml')) ||+ ['feed', 'feed.xml', 'rss', 'rss.xml', 'atom', 'atom.xml'].includes(+ basename,+ ) ||+ basename.endsWith('.rss') ||+ basename.endsWith('.atom')+ )+}++function looksLikeRemoteFile(url: URL): boolean {+ const filename = url.pathname.toLowerCase().split('/').pop() ?? ''+ const extension = filename.includes('.') ? filename.split('.').pop() : ''+ return REMOTE_FILE_EXTENSIONS.has(extension)+}++function looksLikeGitRepository(url: URL): boolean {+ if (['git:', 'ssh:'].includes(url.protocol)) return true+ if (!['http:', 'https:'].includes(url.protocol)) return false++ const parts = url.pathname.split('/').filter(Boolean)+ const host = url.hostname.toLowerCase()+ if (AZURE_DEVOPS_HOSTS.has(host)) {+ return (+ parts.length === 4 && parts[2] === '_git' && !url.searchParams.has('path')+ )+ }+ if (url.pathname.endsWith('.git')) return true+ if (!CODE_HOSTS.has(host)) return false+ if (parts.length < 2) return false+ if (host === 'github.com') {+ return parts.length === 2 || ['tree', 'commit'].includes(parts[2] ?? '')+ }+ return !['blob', 'raw', 'issues', 'pull', 'merge_requests'].some((segment) =>+ parts.includes(segment),+ )+}++export function detectRemoteResourceKind(+ rawSource: string,+): RemoteResourceKind {+ const source = rawSource.trim()+ if (!source) return 'unknown'+ if (source.startsWith('tos://')) return 'tos'+ if (/^git@[^:]+:.+/.test(source)) return 'git'++ let url: URL+ try {+ url = new URL(source)+ } catch {+ return 'unknown'+ }++ if (looksLikeFeishuUrl(url)) return 'feishu'+ if (looksLikeGitRepository(url)) return 'git'+ if (looksLikeWebFeed(url)) return 'webFeed'+ if (looksLikeRemoteFile(url)) return 'remoteFile'+ if (['http:', 'https:'].includes(url.protocol)) return 'webPage'+ return 'unknown'+}diff --git a/web-studio/src/routes/watches/-components/edit-watch-dialog.test.tsx b/web-studio/src/routes/watches/-components/edit-watch-dialog.test.tsxindex 6030c26f6..40a462302 100644--- a/web-studio/src/routes/watches/-components/edit-watch-dialog.test.tsx+++ b/web-studio/src/routes/watches/-components/edit-watch-dialog.test.tsx@@ -75,4 +75,24 @@ describe('EditWatchDialog', () => {),).toEqual({ reason: 'New reason' })})++ it('defers interval range validation to the server', () => {+ const onSubmit = vi.fn()+ render(+ <EditWatchDialog+ watch={watch}+ pending={false}+ onOpenChange={vi.fn()}+ onSubmit={onSubmit}+ />,+ )++ fireEvent.change(+ screen.getByRole('spinbutton', { name: 'editDialog.interval' }),+ { target: { value: '-1' } },+ )+ fireEvent.click(screen.getByRole('button', { name: 'save' }))++ expect(onSubmit).toHaveBeenCalledWith({ watchInterval: -1 })+ })})diff --git a/web-studio/src/routes/watches/-components/edit-watch-dialog.tsx b/web-studio/src/routes/watches/-components/edit-watch-dialog.tsxindex 070272938..3f6c63b05 100644--- a/web-studio/src/routes/watches/-components/edit-watch-dialog.tsx+++ b/web-studio/src/routes/watches/-components/edit-watch-dialog.tsx@@ -12,8 +12,6 @@ import {import { Input } from '#/components/ui/input'import { Label } from '#/components/ui/label'import { Textarea } from '#/components/ui/textarea'-import { parsePositiveMinutes } from '#/lib/watch-interval'-import type { UpdateWatchInput, WatchTask } from '../-lib/api'type EditWatchDialogProps = {@@ -40,7 +38,7 @@ export function EditWatchDialog({setInstruction(watch?.instruction ?? '')}, [watch])- const interval = parsePositiveMinutes(intervalValue)+ const interval = intervalValue.trim() ? Number(intervalValue) : nullconst input = getWatchUpdateInput(watch, interval, reason, instruction)const canSubmit = interval !== null && Object.keys(input).length > 0diff --git a/web-studio/src/routes/watches/route.tsx b/web-studio/src/routes/watches/route.tsxindex 263f623b6..7f489b191 100644--- a/web-studio/src/routes/watches/route.tsx+++ b/web-studio/src/routes/watches/route.tsx@@ -577,6 +577,7 @@ export function WatchManagementPage() {<AddResourceForminitialMode="remote"initialWatchEnabled+ watchRequiredonAccepted={discoverWatch}onCompleted={() => {void refreshWatches()diff --git a/web-studio/types/ov-server/api/v1/resources.ts b/web-studio/types/ov-server/api/v1/resources.tsdeleted file mode 100644index 0136940e6..000000000--- a/web-studio/types/ov-server/api/v1/resources.ts+++ /dev/null@@ -1,16 +0,0 @@-export type TempUploadResult = {- content_type?: string- file_name?: string- filename?: string- size?: number- temp_file_id: string-}--export type AddResourceResult = {- errors?: string[]- message?: string- root_uri?: string- status?: 'success' | 'error' | (string & {})- task_id?: string- warnings?: string[]-}