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 <hailongzhao@tencent.com>
main
nullptr-error 2026-09-23 12:12:08 +08:00 committed by GitHub
parent 06ae6bcf04
commit 23832fabad
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 319 additions and 9 deletions

View File

@ -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<string, unknown> = {}) {
return post("/api/v1/sessions", data);
}

View File

@ -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/)
})

View File

@ -26,6 +26,10 @@
<t-icon v-if="session?.is_pinned" name="pin" size="12px" class="chat-header__pin" />
<span ref="titleTextRef" class="chat-header__title-text">{{ displayTitle }}</span>
</h1>
<span
v-if="!titleEditing && workspaceLabel"
class="chat-header__workspace"
>{{ workspaceLabel }}</span>
<t-popup
v-if="!titleEditing"
v-model:visible="menuVisible"
@ -104,6 +108,8 @@ import {
import { normalizeSessionTitleDraft, SESSION_TITLE_MAX_LENGTH } from './sessionTitleEdit'
import { buildSessionMarkdown, collectAllSessionMessages } from '@/utils/sessionMarkdown'
import { useSessionTitleMotion } from '@/composables/useSessionTitleMotion'
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
import { hostWorkspaceHeaderText, shouldRenderHostProjectSettings } from '@/utils/hostWorkspace'
interface ChatHeaderSession {
id: string
@ -111,6 +117,7 @@ interface ChatHeaderSession {
description?: string
tenant_id?: number | string
is_pinned?: boolean
host_workspace_dir?: string
}
type MenuMode = 'menu' | 'delete'
@ -120,6 +127,7 @@ const props = defineProps<{
}>()
const { t } = useI18n()
const deploymentCapabilities = useDeploymentCapabilitiesStore()
const busyAction = ref('')
const menuVisible = ref(false)
const menuMode = ref<MenuMode>('menu')
@ -130,6 +138,13 @@ const titleInputRef = ref<HTMLInputElement | null>(null)
const displayTitle = computed(() => props.session?.title?.trim() || t('menu.newSession'))
const titleTextRef = ref<HTMLElement | null>(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<void> {
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);

View File

@ -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'

View File

@ -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: 'セッションの作成に失敗しました。しばらくしてから再試行してください'

View File

@ -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: '복사하지 못했습니다. 브라우저 클립보드 권한을 확인하세요.',

View File

@ -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: 'Не удалось скопировать. Проверьте разрешение браузера на доступ к буферу обмена.',

View File

@ -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: '复制失败,请检查浏览器剪贴板权限',

View File

@ -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/)
})

View File

@ -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<string> {
const res = await post<{ data?: { dir?: unknown } }>('/api/v1/system/host-project-dir', {}, { timeout: 0 })
return dirFromPickerResponse(res)
}

View File

@ -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')
})

View File

@ -0,0 +1,30 @@
export function shouldRenderHostProjectSettings(supported: boolean): boolean {
return supported === true
}
export function withOptionalProjectDir<T extends Record<string, unknown>>(
data: T,
projectDir?: string | null,
): T & { project_dir?: string } {
const trimmed = typeof projectDir === 'string' ? projectDir.trim() : ''
const next: Record<string, unknown> = { ...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)
}

View File

@ -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/)
})

View File

@ -43,7 +43,22 @@
</div>
</transition>
</div>
<InputField ref="inputFieldRef" @send-msg="sendMsg"></InputField>
<div class="create-chat-composer">
<div v-if="hostSandboxEnabled" class="project-dir-bar">
<button type="button" class="project-dir-bar__btn"
:class="{ 'is-bound': !!selectedProjectDir, 'is-picking': pickingProjectDir }"
:disabled="pickingProjectDir" :title="selectedProjectDir || $t('createChat.openProject')"
@click="openProjectDir">
<t-icon :name="pickingProjectDir ? 'loading' : 'folder'" />
<span class="project-dir-bar__name">{{
selectedProjectDir ? projectDirBasename(selectedProjectDir) : $t('createChat.openProject')
}}</span>
</button>
<button v-if="selectedProjectDir" type="button" class="project-dir-bar__clear"
:aria-label="$t('createChat.clearProject')" @click="clearProjectDir">×</button>
</div>
<InputField ref="inputFieldRef" @send-msg="sendMsg"></InputField>
</div>
</div>
</div>
@ -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;
}
}
</script>
<style lang="less" scoped>
.dialogue-wrap {
@ -268,6 +312,67 @@ const handleKBEditorSuccess = (kbId: string) => {
}
}
.create-chat-composer {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 8px;
width: 100%;
}
.project-dir-bar {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
max-width: 960px;
padding: 0;
box-sizing: border-box;
}
.project-dir-bar__btn {
display: inline-flex;
align-items: center;
gap: 6px;
max-width: 100%;
height: 28px;
padding: 0 10px;
border: 0.5px solid var(--td-component-border);
border-radius: var(--app-radius-md);
background: var(--td-bg-color-container);
color: var(--td-text-color-secondary);
font-size: var(--app-text-sm);
cursor: pointer;
}
.project-dir-bar__btn.is-bound {
color: var(--td-text-color-primary);
}
.project-dir-bar__btn.is-picking,
.project-dir-bar__btn:disabled {
cursor: default;
opacity: 0.75;
}
.project-dir-bar__name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.project-dir-bar__clear {
flex: 0 0 auto;
border: none;
background: transparent;
padding: 0 4px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-base);
line-height: 1;
cursor: pointer;
}
.dialogue-title {
display: flex;
color: var(--td-text-color-primary);

View File

@ -569,8 +569,8 @@ async function forceRemove(record: SandboxConfigRecord) {
await removeRecord(record, true)
}
onMounted(() => {
void deploymentCapabilities.ensureLoaded()
onMounted(async () => {
await deploymentCapabilities.ensureLoaded()
load()
})
</script>

View File

@ -57,8 +57,9 @@
| Docker | 镜像;可选 daemon 地址、TLS 证书目录、CPU/内存/PID 限制、网络模式、runtime、空闲 TTL | 一个会话一个长驻容器 |
| CubeSandbox | 控制面地址、数据面代理、沙箱域名、模板;按集群配置 API Key | 会话级远端沙箱 |
| E2B | API Key、模板;自托管时补 API 地址、沙箱域名和数据面代理 | E2B Cloud 或 E2B 兼容控制面 |
| host | 不用填写。仅 Lite 桌面版,当前仅 macOS | 未选远程沙箱时,在用户选定的本机目录内执行,越界由操作系统拦截 |
`local` 宿主机进程后端已移除。桌面客户端另有基于操作系统隔离的 `host` 后端,不属于上述空间命名配置。当前配置的完整字段见[沙箱与技能 API](../04-api/02-api-sandbox-skills.md)。
`local` 宿主机进程后端已移除:它在本机裸跑,没有任何隔离。Lite 的 `host` 不属于上述空间命名配置,也不是 `local` 的替代项。`host` 由操作系统强制隔离,工作区是真实主机路径,没有 `/workspace`。用户在新对话页选择项目;不选则使用自动会话目录。配了 Docker、E2B 或 Cube 的智能体仍走远程沙箱。当前配置的完整字段见[沙箱与技能 API](../04-api/02-api-sandbox-skills.md)。
Docker 后端默认关闭。系统管理员在「系统设置 → 网络安全」启用,或用 `WEKNORA_SANDBOX_DOCKER_ENABLED=true` 作为未落库时的回退。本机连接还需要把实际 Docker socket 挂给 app;这授予 app 控制宿主机 Docker 的能力。远端 TCP daemon 要配置 TLS 证书目录,其中包括 `ca.pem`、`cert.pem`、`key.pem`。Docker 网络仅接受 `bridge` 或 `none`,可选 `runsc` 等已安装 OCI runtime。