From 23832fabad7b0a0fac98360a6d12825032f2fc76 Mon Sep 17 00:00:00 2001 From: nullptr-error <104547331+nullptr-error@users.noreply.github.com> Date: Wed, 23 Sep 2026 12:12:08 +0800 Subject: [PATCH] feat(lite): let new chats bind a host project directory (#3554) * feat(lite): let new chats bind a host project directory Unpinned Lite sessions already run on the host sandbox. The new-chat page can now pick an approved project, and the header shows that workspace instead of a full path. * docs(lite): publish the host sandbox note on the site The published docs live in website-docs, so the host backend entry belongs in the sandbox guide. Session creation also stops rewriting project_dir inside the shared API helper. --------- Co-authored-by: hailongzhao --- frontend/src/api/chat/index.ts | 4 +- frontend/src/components/ChatHeader.test.mjs | 13 ++ frontend/src/components/ChatHeader.vue | 29 +++++ frontend/src/i18n/locales/en-US.ts | 4 + frontend/src/i18n/locales/ja-JP.ts | 4 + frontend/src/i18n/locales/ko-KR.ts | 4 + frontend/src/i18n/locales/ru-RU.ts | 4 + frontend/src/i18n/locales/zh-CN.ts | 4 + frontend/src/utils/desktopProjectDir.test.ts | 18 +++ frontend/src/utils/desktopProjectDir.ts | 13 ++ frontend/src/utils/hostWorkspace.test.ts | 58 +++++++++ frontend/src/utils/hostWorkspace.ts | 30 +++++ .../src/views/creatChat/creatChat.test.mjs | 25 ++++ frontend/src/views/creatChat/creatChat.vue | 111 +++++++++++++++++- .../src/views/settings/SandboxSettings.vue | 4 +- website-docs/03-features/22-skills-sandbox.md | 3 +- 16 files changed, 319 insertions(+), 9 deletions(-) create mode 100644 frontend/src/components/ChatHeader.test.mjs create mode 100644 frontend/src/utils/desktopProjectDir.test.ts create mode 100644 frontend/src/utils/desktopProjectDir.ts create mode 100644 frontend/src/utils/hostWorkspace.test.ts create mode 100644 frontend/src/utils/hostWorkspace.ts create mode 100644 frontend/src/views/creatChat/creatChat.test.mjs diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.ts index e28c7464..0eed1e38 100644 --- a/frontend/src/api/chat/index.ts +++ b/frontend/src/api/chat/index.ts @@ -1,8 +1,6 @@ import { get, post, put, del, postChat, getDown } from "../../utils/request"; - - -export async function createSessions(data = {}) { +export async function createSessions(data: Record = {}) { return post("/api/v1/sessions", data); } diff --git a/frontend/src/components/ChatHeader.test.mjs b/frontend/src/components/ChatHeader.test.mjs new file mode 100644 index 00000000..e0870c3b --- /dev/null +++ b/frontend/src/components/ChatHeader.test.mjs @@ -0,0 +1,13 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' + +const source = readFileSync(new URL('./ChatHeader.vue', import.meta.url), 'utf8') + +test('session header shows basename or temporary workspace, never the absolute path', () => { + assert.match(source, /hostWorkspaceHeaderText/) + assert.match(source, /chatHeader\.temporaryWorkspace/) + assert.match(source, /workspaceLabel/) + assert.doesNotMatch(source, /session\?\.host_workspace_dir\b/) + assert.doesNotMatch(source, /\{\{\s*session\.host_workspace_dir/) +}) diff --git a/frontend/src/components/ChatHeader.vue b/frontend/src/components/ChatHeader.vue index d607cdfa..18f9084c 100644 --- a/frontend/src/components/ChatHeader.vue +++ b/frontend/src/components/ChatHeader.vue @@ -26,6 +26,10 @@ {{ displayTitle }} + {{ workspaceLabel }} () const { t } = useI18n() +const deploymentCapabilities = useDeploymentCapabilitiesStore() const busyAction = ref('') const menuVisible = ref(false) const menuMode = ref('menu') @@ -130,6 +138,13 @@ const titleInputRef = ref(null) const displayTitle = computed(() => props.session?.title?.trim() || t('menu.newSession')) const titleTextRef = ref(null) useSessionTitleMotion(titleTextRef, () => props.session?.id, () => displayTitle.value) +const workspaceLabel = computed(() => { + if (!props.session) return '' + if (!shouldRenderHostProjectSettings(deploymentCapabilities.isSupported('settings.sandbox.host'))) { + return '' + } + return hostWorkspaceHeaderText(props.session.host_workspace_dir, t('chatHeader.temporaryWorkspace')) +}) const menuOverlayClass = computed(() => ( menuMode.value === 'menu' ? 'card-more chat-header-menu-popup' : 'card-more chat-header-menu-popup is-confirm' )) @@ -317,6 +332,20 @@ async function submitDeleteSession(): Promise { white-space: nowrap; } +.chat-header__workspace { + flex: 0 1 auto; + min-width: 0; + max-width: 140px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 0 6px; + color: var(--td-text-color-placeholder); + font-size: var(--app-text-xs); + font-weight: 400; + line-height: 20px; +} + .chat-header__pin { flex: 0 0 auto; color: var(--td-text-color-placeholder); diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 4b0c45c0..65eba621 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -226,6 +226,7 @@ export default { deleteSession: 'Delete Conversation', renamePlaceholder: 'Enter a conversation title', unpinSuccess: 'Conversation unpinned', + temporaryWorkspace: 'Temporary workspace', sessionIdCopied: 'Session ID copied', linkCopied: 'Conversation link copied', copyFailed: 'Copy failed. Check your browser clipboard permission.', @@ -2776,6 +2777,9 @@ export default { createChat: { title: 'Hi, I am WeKnora — your knowledge, within reach', newSessionTitle: 'New Session', + openProject: 'Select project', + clearProject: 'Clear', + pickFailed: 'Could not open the selected path', messages: { createFailed: 'Failed to create session', createError: 'Failed to create session, please try again later' diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 8daea381..d2e0e91d 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -226,6 +226,7 @@ export default { deleteSession: '会話を削除', renamePlaceholder: '会話のタイトルを入力してください', unpinSuccess: '会話のピン留めを解除しました', + temporaryWorkspace: '一時ワークスペース', sessionIdCopied: 'セッションIDをコピーしました', linkCopied: '会話リンクをコピーしました', copyFailed: 'コピーに失敗しました。ブラウザのクリップボード権限を確認してください。', @@ -2776,6 +2777,9 @@ export default { createChat: { title: 'こんにちは、WeKnoraです。あなたのナレッジを、すぐそばに', newSessionTitle: '新しいセッション', + openProject: 'プロジェクトを選択', + clearProject: '解除', + pickFailed: '選択したパスを開けませんでした', messages: { createFailed: 'セッションの作成に失敗しました', createError: 'セッションの作成に失敗しました。しばらくしてから再試行してください' diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 842cdb79..cd0016c7 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -4825,6 +4825,9 @@ export default { createChat: { title: '안녕하세요, WeKnora입니다 — 당신의 지식을 손끝에', newSessionTitle: '새 세션', + openProject: '프로젝트 선택', + clearProject: '바인딩 해제', + pickFailed: '선택한 경로를 열 수 없습니다', messages: { createFailed: '세션 생성 실패', createError: '세션 생성 실패, 나중에 다시 시도해주세요' @@ -7368,6 +7371,7 @@ export default { deleteSession: '대화 삭제', renamePlaceholder: '대화 제목을 입력하세요', unpinSuccess: '대화 고정이 해제되었습니다', + temporaryWorkspace: '임시 작업 영역', sessionIdCopied: '세션 ID가 복사되었습니다', linkCopied: '대화 링크가 복사되었습니다', copyFailed: '복사하지 못했습니다. 브라우저 클립보드 권한을 확인하세요.', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index f9295cc0..95819f34 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -4825,6 +4825,9 @@ export default { createChat: { title: 'Привет, я WeKnora — ваши знания всегда под рукой', newSessionTitle: 'Новая сессия', + openProject: 'Выбрать проект', + clearProject: 'Снять привязку', + pickFailed: 'Не удалось открыть выбранный путь', messages: { createFailed: 'Не удалось создать сессию', createError: 'Не удалось создать сессию, попробуйте позже' @@ -7368,6 +7371,7 @@ export default { deleteSession: 'Удалить диалог', renamePlaceholder: 'Введите название диалога', unpinSuccess: 'Диалог откреплён', + temporaryWorkspace: 'Временная рабочая область', sessionIdCopied: 'ID сессии скопирован', linkCopied: 'Ссылка на диалог скопирована', copyFailed: 'Не удалось скопировать. Проверьте разрешение браузера на доступ к буферу обмена.', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index ed04b9d2..a02769eb 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -4827,6 +4827,9 @@ export default { createChat: { title: 'Hi,我是 WeKnora,让你的知识触手可及', newSessionTitle: '新会话', + openProject: '选择项目', + clearProject: '取消绑定', + pickFailed: '无法打开所选路径', messages: { createFailed: '创建会话失败', createError: '创建会话失败,请稍后重试' @@ -7370,6 +7373,7 @@ export default { deleteSession: '删除对话', renamePlaceholder: '输入对话标题', unpinSuccess: '已取消置顶', + temporaryWorkspace: '临时工作区', sessionIdCopied: '会话 ID 已复制', linkCopied: '对话链接已复制', copyFailed: '复制失败,请检查浏览器剪贴板权限', diff --git a/frontend/src/utils/desktopProjectDir.test.ts b/frontend/src/utils/desktopProjectDir.test.ts new file mode 100644 index 00000000..79df1944 --- /dev/null +++ b/frontend/src/utils/desktopProjectDir.test.ts @@ -0,0 +1,18 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' + +const source = readFileSync(new URL('./desktopProjectDir.ts', import.meta.url), 'utf8') + +test('dirFromPickerResponse reads the HTTP envelope', () => { + assert.match(source, /body\?\.data\?\.dir/) + assert.match(source, /typeof dir === 'string'/) +}) + +test('pickHostProjectDir calls the same-process HTTP picker', () => { + assert.match(source, /\/api\/v1\/system\/host-project-dir/) + assert.match(source, /timeout: 0/) + assert.doesNotMatch(source, /window\['go'\]/) + assert.doesNotMatch(source, /window\.go\.main/) + assert.doesNotMatch(source, /EventsEmit/) +}) diff --git a/frontend/src/utils/desktopProjectDir.ts b/frontend/src/utils/desktopProjectDir.ts new file mode 100644 index 00000000..7c647774 --- /dev/null +++ b/frontend/src/utils/desktopProjectDir.ts @@ -0,0 +1,13 @@ +import { post } from '@/utils/request' + +export function dirFromPickerResponse(body: { data?: { dir?: unknown } } | null | undefined): string { + const dir = body?.data?.dir + return typeof dir === 'string' ? dir.trim() : '' +} + +// Lite's SPA is reverse-proxied; Wails JS bindings are not injected. The +// folder picker is a same-process HTTP call that opens the native dialog. +export async function pickHostProjectDir(): Promise { + const res = await post<{ data?: { dir?: unknown } }>('/api/v1/system/host-project-dir', {}, { timeout: 0 }) + return dirFromPickerResponse(res) +} diff --git a/frontend/src/utils/hostWorkspace.test.ts b/frontend/src/utils/hostWorkspace.test.ts new file mode 100644 index 00000000..6a90540c --- /dev/null +++ b/frontend/src/utils/hostWorkspace.test.ts @@ -0,0 +1,58 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { + hostWorkspaceHeaderText, + projectDirBasename, + shouldRenderHostProjectSettings, + withOptionalProjectDir, +} from './hostWorkspace.ts' + +test('host-capability off hides the new-session project picker', () => { + assert.equal(shouldRenderHostProjectSettings(false), false) +}) + +test('host-capability on shows the new-session project picker', () => { + assert.equal(shouldRenderHostProjectSettings(true), true) +}) + +test('createSession payload includes project_dir when a project is selected', () => { + const body = withOptionalProjectDir({ agent_config: { enabled: true } }, '/Users/dev/My Project') + assert.equal(body.project_dir, '/Users/dev/My Project') + assert.equal(body.agent_config.enabled, true) +}) + +test('createSession payload omits project_dir when unbound', () => { + const empty = withOptionalProjectDir({ agent_config: { enabled: true } }, '') + assert.equal(Object.hasOwn(empty, 'project_dir'), false) + + const missing = withOptionalProjectDir({ agent_config: { enabled: true } }) + assert.equal(Object.hasOwn(missing, 'project_dir'), false) + + const whitespace = withOptionalProjectDir({ agent_config: { enabled: true } }, ' ') + assert.equal(Object.hasOwn(whitespace, 'project_dir'), false) + + const stripped = withOptionalProjectDir( + { agent_config: { enabled: true }, project_dir: '' }, + '', + ) + assert.equal(Object.hasOwn(stripped, 'project_dir'), false) +}) + +test('session header shows the project basename, not the absolute path', () => { + assert.equal(projectDirBasename('/Users/dev/My Project'), 'My Project') + assert.equal(projectDirBasename('C:\\Users\\dev\\My Project'), 'My Project') + assert.equal( + hostWorkspaceHeaderText('/Users/dev/My Project', 'Temporary workspace'), + 'My Project', + ) + const label = hostWorkspaceHeaderText('/Users/dev/My Project', '临时工作区') + assert.equal(label.includes('/'), false) + assert.equal(label.includes('\\'), false) + assert.notEqual(label, '/Users/dev/My Project') +}) + +test('session header shows the temporary workspace label when unbound', () => { + assert.equal(hostWorkspaceHeaderText('', '临时工作区'), '临时工作区') + assert.equal(hostWorkspaceHeaderText(undefined, 'Temporary workspace'), 'Temporary workspace') +}) diff --git a/frontend/src/utils/hostWorkspace.ts b/frontend/src/utils/hostWorkspace.ts new file mode 100644 index 00000000..65145a72 --- /dev/null +++ b/frontend/src/utils/hostWorkspace.ts @@ -0,0 +1,30 @@ +export function shouldRenderHostProjectSettings(supported: boolean): boolean { + return supported === true +} + +export function withOptionalProjectDir>( + data: T, + projectDir?: string | null, +): T & { project_dir?: string } { + const trimmed = typeof projectDir === 'string' ? projectDir.trim() : '' + const next: Record = { ...data } + delete next.project_dir + if (trimmed) next.project_dir = trimmed + return next as T & { project_dir?: string } +} + +export function projectDirBasename(dir: string): string { + const trimmed = dir.replace(/[\\/]+$/, '').trim() + if (!trimmed) return dir + const parts = trimmed.split(/[/\\]/).filter(Boolean) + return parts[parts.length - 1] || dir +} + +export function hostWorkspaceHeaderText( + hostWorkspaceDir: string | null | undefined, + temporaryLabel: string, +): string { + const trimmed = hostWorkspaceDir?.trim() ?? '' + if (!trimmed) return temporaryLabel + return projectDirBasename(trimmed) +} diff --git a/frontend/src/views/creatChat/creatChat.test.mjs b/frontend/src/views/creatChat/creatChat.test.mjs new file mode 100644 index 00000000..681e8257 --- /dev/null +++ b/frontend/src/views/creatChat/creatChat.test.mjs @@ -0,0 +1,25 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' + +const source = readFileSync(new URL('./creatChat.vue', import.meta.url), 'utf8') + +test('new-session createSessions includes project_dir only through withOptionalProjectDir', () => { + assert.match(source, /withOptionalProjectDir/) + assert.match(source, /createSessions\(withOptionalProjectDir/) + assert.match(source, /selectedProjectDir/) + assert.match(source, /hostSandboxEnabled/) + assert.doesNotMatch(source, /approvalMode|GetApprovalMode|SetApprovalMode/) +}) + +test('new-session page has a single project button flush above the composer', () => { + assert.match(source, /pickHostProjectDir/) + assert.match(source, /create-chat-composer/) + assert.match(source, /createChat\.openProject/) + assert.doesNotMatch(source, /wailsjs\/go\/main\/App/) + assert.doesNotMatch(source, /PickProjectFile/) + assert.doesNotMatch(source, /createChat\.openFile/) + assert.doesNotMatch(source, /t-select/) + assert.doesNotMatch(source, /project-dir-picker/) +}) + diff --git a/frontend/src/views/creatChat/creatChat.vue b/frontend/src/views/creatChat/creatChat.vue index abddf866..c11fa170 100644 --- a/frontend/src/views/creatChat/creatChat.vue +++ b/frontend/src/views/creatChat/creatChat.vue @@ -43,7 +43,22 @@ - +
+
+ + +
+ +
@@ -59,12 +74,15 @@ import { ref, watch, onMounted, nextTick, computed } from 'vue'; import ContextualGuide from '@/components/ContextualGuide.vue'; import InputField from '@/components/Input-field.vue'; import { createSessions } from "@/api/chat/index"; +import { pickHostProjectDir } from '@/utils/desktopProjectDir'; +import { projectDirBasename, shouldRenderHostProjectSettings, withOptionalProjectDir } from '@/utils/hostWorkspace'; import { getSuggestedQuestions } from "@/api/agent/index"; import type { SuggestedQuestion } from "@/api/agent/index"; import { questionOriginFromSuggestion, type SendMessageOptions } from '@/utils/questionOrigin'; import { useMenuStore } from '@/stores/menu'; import { useSettingsStore } from '@/stores/settings'; import { useUIStore } from '@/stores/ui'; +import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'; import { useRoute, useRouter } from 'vue-router'; import { MessagePlugin } from 'tdesign-vue-next'; import { useI18n } from 'vue-i18n'; @@ -76,9 +94,16 @@ const route = useRoute(); const usemenuStore = useMenuStore(); const settingsStore = useSettingsStore(); const uiStore = useUIStore(); +const deploymentCapabilities = useDeploymentCapabilitiesStore(); const { t } = useI18n(); const { navigateToKnowledgeBaseList } = useKnowledgeBaseCreationNavigation(); +const hostSandboxEnabled = computed(() => + shouldRenderHostProjectSettings(deploymentCapabilities.isSupported('settings.sandbox.host')), +); +const selectedProjectDir = ref(''); +const pickingProjectDir = ref(false); + const showChatContextualGuide = computed(() => { return route.name === 'globalCreatChat' || route.name === 'kbCreatChat'; }); @@ -178,7 +203,9 @@ watch( { deep: true }, ); -onMounted(() => { fetchSuggestedQuestions(); }); +onMounted(() => { + fetchSuggestedQuestions(); +}); const inputFieldRef = ref(); @@ -210,7 +237,7 @@ async function createNewSession(value: string, modelId: string, mentionedItems: }; try { - const res = await createSessions(sessionData); + const res = await createSessions(withOptionalProjectDir(sessionData, selectedProjectDir.value)); if (res.data && res.data.id) { await navigateToSession(res.data.id, value, modelId, mentionedItems, imageFiles, attachmentFiles, options); } else { @@ -244,6 +271,23 @@ const handleKBEditorSuccess = (kbId: string) => { navigateToKnowledgeBaseList(kbId) } +function clearProjectDir() { + selectedProjectDir.value = ''; +} + +async function openProjectDir() { + if (pickingProjectDir.value) return; + pickingProjectDir.value = true; + try { + const picked = await pickHostProjectDir(); + if (picked) selectedProjectDir.value = picked; + } catch (e: any) { + MessagePlugin.error(e?.message || t('createChat.pickFailed')); + } finally { + pickingProjectDir.value = false; + } +} +