From e2433b1293fa350d972902cd3676a1aa9a9c9aac Mon Sep 17 00:00:00 2001 From: nullptr-error <104547331+nullptr-error@users.noreply.github.com> Date: Thu, 24 Sep 2026 21:30:34 +0800 Subject: [PATCH] feat(lite): install and run skills on the host (#3661) * fix(desktop): keep Lite signed in with a stable JWT secret Auto-setup fell through to the login form, and a newly generated signing key replaced the HMAC already used for presigned links. Reuse an existing HMAC, fill only a placeholder JWT secret, and clear a sticky auto-setup failure so the desktop window can enter the local account. * fix(desktop): make wails dev start locally and store uploads at home The dev app has no copied config, and the repo env asks for Redis and the Docker path /data/files. Stay on the repo config, use the in-memory stream manager when Redis is unset, write uploads to ~/.weknora/data/files, and allow dragging the top of the window. * feat(lite): install and run skills on the host instead of a remote sandbox Lite has no sandbox image, so skills are stored under ~/.weknora/skills as version directories with a live symlink, and chats execute them in the host Seatbelt. The settings UI no longer asks which sandbox to install into. The base profile opens /tmp, chat commands may use the network, and a failed ready-write rolls the symlink back to the previous version. * fix(ci): align Lite skill checks with the JWT split and lint limits The desktop signing test still expected the session secret to equal the AES key, and the skill settings source test still looked for the old i18n keys. Wrap the lines golangci-lint rejects so the PR checks can pass. * fix(ci): separate multi-line test helpers for gofumpt gofumpt requires a blank line after a multi-line function. The host skill fakes were still packed together, so lint failed on the first one. * fix(lite): address review findings on host skill install - Ask mode denies network again, and /tmp writes open only with a writable root, so nothing runs unapproved. - Lite still reports and accepts the workspace script switch; the Skills page offers to re-enable it when it is off. - The host process refuses symlinks the installer planted before it clears the install cache or reads the env declaration. - An existing signing or AES key stays the signer and is never copied into signing.key; sessions then get their own jwt.key. - Skill env capture writes under the host target on Lite. - Sweep keeps the previous version and skips skills another process holds the lock for. - Terminal and desktop panels never resolve remote sandboxes on Lite. - A detached install stream resubscribes instead of freezing. - Upload migration follows the bundle name and the old relative path. --------- Co-authored-by: hailongzhao Co-authored-by: wizardchen --- cmd/desktop/main.go | 146 ++++++- cmd/desktop/prefs_test.go | 58 +++ cmd/desktop/signing_key.go | 74 +++- cmd/desktop/signing_key_test.go | 43 ++ frontend/src/api/auth/index.ts | 41 +- frontend/src/components/Input-field.vue | 15 +- .../src/components/SandboxSkillsPanel.vue | 40 +- .../src/components/chat/SandboxSidePanel.vue | 3 + .../src/composables/skillInstallProgress.ts | 9 +- .../useConfigSkillInstallProgress.test.ts | 28 ++ .../useConfigSkillInstallProgress.ts | 13 +- .../src/config/deploymentCapabilities.test.ts | 25 +- frontend/src/config/deploymentCapabilities.ts | 20 +- frontend/src/i18n/locales/en-US.ts | 42 ++ frontend/src/i18n/locales/ja-JP.ts | 42 ++ frontend/src/i18n/locales/ko-KR.ts | 42 ++ frontend/src/i18n/locales/ru-RU.ts | 42 ++ frontend/src/i18n/locales/zh-CN.ts | 42 ++ frontend/src/router/index.ts | 43 +- frontend/src/utils/skillTarget.test.ts | 38 ++ frontend/src/utils/skillTarget.ts | 34 ++ frontend/src/views/agent/AgentEditorModal.vue | 45 ++- frontend/src/views/auth/Login.vue | 22 +- .../src/views/settings/EnvVarSettings.vue | 36 +- frontend/src/views/settings/Settings.vue | 19 +- .../src/views/settings/SkillSettings.test.mjs | 4 +- frontend/src/views/settings/SkillSettings.vue | 129 ++++-- frontend/src/views/settings/envVarState.ts | 6 +- internal/agent/skills/manager.go | 17 + internal/agent/skills/shell_environment.go | 29 +- .../agent/skills/shell_environment_test.go | 27 ++ internal/agent/skills/tenant_source.go | 31 +- internal/agent/skills/tenant_source_test.go | 16 + internal/agent/tools/shell_exec.go | 35 ++ internal/agent/tools/shell_exec_test.go | 9 + internal/application/service/agent_service.go | 150 +++++-- .../application/service/agent_service_test.go | 26 ++ .../service/agent_service_user_env_test.go | 8 + .../service/artifact_collector_test.go | 2 +- .../service/host_session_resolver.go | 11 +- .../service/host_session_resolver_test.go | 25 ++ internal/application/service/host_skills.go | 33 ++ .../application/service/host_skills_test.go | 26 ++ .../service/pinned_session_sandbox_test.go | 10 +- .../service/sandbox_desktop_service.go | 1 + .../service/sandbox_terminal_service.go | 7 +- .../service/sandbox_terminal_service_test.go | 2 +- internal/application/service/session.go | 6 +- .../application/service/session_agent_qa.go | 16 +- .../service/session_attachment_staging.go | 2 +- .../service/session_sandbox_pin.go | 4 + .../shared_agent_sandbox_tenant_test.go | 24 +- .../service/tenant_sandbox_resolve.go | 44 ++- .../service/tenant_sandbox_resolve_test.go | 43 ++ .../application/service/tenant_skill_admin.go | 15 +- .../service/tenant_skill_catalog.go | 9 + .../service/tenant_skill_catalog_test.go | 8 +- .../service/tenant_skill_effective.go | 28 ++ .../service/tenant_skill_effective_test.go | 58 +++ .../application/service/tenant_skill_host.go | 361 +++++++++++++++++ .../service/tenant_skill_host_test.go | 369 ++++++++++++++++++ .../service/tenant_skill_install.go | 38 +- .../service/tenant_skill_install_test.go | 1 + .../service/tenant_skill_reaper.go | 9 + .../service/tenant_skill_reaper_test.go | 4 +- .../service/tenant_skill_remove.go | 4 + .../service/tenant_skill_service.go | 6 + .../service/tenant_skill_service_test.go | 2 +- .../service/tenant_skill_source.go | 7 +- internal/application/service/user_env.go | 30 +- internal/application/service/user_env_test.go | 21 +- internal/container/container.go | 2 +- internal/container/sandbox_host.go | 67 +++- internal/container/sandbox_host_test.go | 28 ++ internal/handler/custom_agent.go | 9 + internal/handler/custom_agent_test.go | 18 + internal/handler/deployment_capabilities.go | 10 + .../handler/deployment_capabilities_test.go | 14 + internal/handler/sandbox_config.go | 46 ++- internal/handler/sandbox_config_test.go | 31 ++ internal/handler/sandbox_skill.go | 17 +- internal/handler/sandbox_skill_test.go | 29 +- internal/localsandbox/adapter/adapter.go | 6 +- internal/localsandbox/adapter/install.go | 190 +++++++++ internal/localsandbox/adapter/install_test.go | 96 +++++ internal/localsandbox/aliases.go | 2 + internal/localsandbox/core/policy_builder.go | 63 ++- .../localsandbox/core/policy_builder_test.go | 65 ++- .../localsandbox/seatbelt/backend_test.go | 18 +- internal/localsandbox/seatbelt/compiler.go | 9 + .../localsandbox/seatbelt/compiler_test.go | 14 + internal/localsandbox/service.go | 40 +- internal/localsandbox/service_test.go | 40 ++ internal/localsandbox/skilltree/lock_other.go | 16 + internal/localsandbox/skilltree/lock_unix.go | 47 +++ internal/localsandbox/skilltree/tree.go | 299 ++++++++++++++ internal/localsandbox/skilltree/tree_test.go | 173 ++++++++ internal/router/deployment_capabilities.go | 1 + internal/sandbox/skill_paths.go | 39 +- internal/sandbox/skill_paths_test.go | 51 +++ 100 files changed, 3793 insertions(+), 322 deletions(-) create mode 100644 frontend/src/utils/skillTarget.test.ts create mode 100644 frontend/src/utils/skillTarget.ts create mode 100644 internal/application/service/host_session_resolver_test.go create mode 100644 internal/application/service/host_skills.go create mode 100644 internal/application/service/host_skills_test.go create mode 100644 internal/application/service/tenant_skill_host.go create mode 100644 internal/application/service/tenant_skill_host_test.go create mode 100644 internal/handler/custom_agent_test.go create mode 100644 internal/localsandbox/adapter/install.go create mode 100644 internal/localsandbox/adapter/install_test.go create mode 100644 internal/localsandbox/skilltree/lock_other.go create mode 100644 internal/localsandbox/skilltree/lock_unix.go create mode 100644 internal/localsandbox/skilltree/tree.go create mode 100644 internal/localsandbox/skilltree/tree_test.go diff --git a/cmd/desktop/main.go b/cmd/desktop/main.go index 8efa7f2e..7d9c9b57 100644 --- a/cmd/desktop/main.go +++ b/cmd/desktop/main.go @@ -33,6 +33,7 @@ import ( "github.com/Tencent/WeKnora/internal/handler/session" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/runtime" + "github.com/Tencent/WeKnora/internal/stream" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/joho/godotenv" wailsruntime "github.com/wailsapp/wails/v2/pkg/runtime" @@ -42,7 +43,8 @@ import ( // It bypasses Wails' built-in CSS-variable-based drag detection (which uses // getComputedStyle and has timing/inheritance issues with dynamic SPA content) // and instead uses robust DOM-traversal via el.closest() plus a Y-position -// fallback for the macOS title-bar region on layout containers. The "drag" +// fallback for the top 40px of a layout container, including its children. +// The "drag" // message is sent directly through the WKWebView script-message bridge, // which the native Objective-C handler in WailsContext.m converts to // [NSWindow performWindowDragWithEvent:]. @@ -65,11 +67,12 @@ window.addEventListener('dragstart', function(e){ e.preventDefault(); }, true); -var TITLEBAR_H=38; +var TITLEBAR_H=40; // We specifically look for Wails' inline style attributes injected by Vue, -// and custom drag classes, avoiding generic headers like .section-header -var dragSel='.logo_row,.menu_top,.drag-region,[data-wails-drag],' + +// and custom drag classes, avoiding generic headers like .section-header. +// .chat-topbar is the window top on the conversation page. +var dragSel='.logo_row,.menu_top,.chat-topbar,.drag-region,[data-wails-drag],' + '[style*="--wails-draggable: drag"],[style*="--wails-draggable:drag"]'; var noDragSel='button,a,input,select,textarea,[role="button"],' + @@ -97,11 +100,21 @@ function isLayoutEl(el){ return tag==='BODY'||tag==='HTML'; } +function inTitlebar(el,y){ + if(y>TITLEBAR_H)return false; + var node=el; + while(node&&node instanceof Element){ + if(isLayoutEl(node))return true; + node=node.parentElement; + } + return false; +} + function shouldDrag(el,y){ if(!(el instanceof Element))return false; if(el.closest(noDragSel))return false; if(el.closest(dragSel))return true; - if(y<=TITLEBAR_H&&isLayoutEl(el))return true; + if(inTitlebar(el,y))return true; return false; } @@ -112,8 +125,27 @@ window.addEventListener('mousedown',function(e){ } if(e.button!==0||e.detail!==1)return; if(!shouldDrag(target,e.clientY))return; - e.preventDefault(); - sendDrag(); + // The session title renames on double-click. Wait until the pointer + // actually moves so that click still lands; other top-bar hits drag now. + var defer=target.closest&&target.closest('.chat-header__title'); + if(!defer){ + e.preventDefault(); + sendDrag(); + return; + } + var x=e.clientX,y=e.clientY; + function move(ev){ + if(Math.abs(ev.clientX-x)<4&&Math.abs(ev.clientY-y)<4)return; + cleanup(); + sendDrag(); + } + function up(){cleanup();} + function cleanup(){ + window.removeEventListener('mousemove',move,true); + window.removeEventListener('mouseup',up,true); + } + window.addEventListener('mousemove',move,true); + window.addEventListener('mouseup',up,true); },true); // Intercept external link clicks and window.open so they open in the system browser @@ -162,12 +194,17 @@ func main() { // For macOS .app bundle, the working directory is usually "/" or the MacOS folder. // We need to change the working directory to the Resources folder where our configs are. execPath, errPath := os.Executable() + // A packaged .app keeps config under Contents/Resources. wails dev also + // runs from a .app, but that bundle has no copied config; stay in the + // repo and use config/ there. if errPath == nil && strings.Contains(execPath, ".app/Contents/MacOS") { resPath := filepath.Join(filepath.Dir(filepath.Dir(execPath)), "Resources") - _ = os.Chdir(resPath) - } else if _, err := os.Stat(filepath.Join("config", "config.yaml")); os.IsNotExist(err) { - // wails build 生成绑定时 cwd 多为 cmd/desktop,LoadConfig 默认找 ./config/config.yaml; - // 仓库实际配置在 /config/,向上两级即可。 + if _, err := os.Stat(filepath.Join(resPath, "config", "config.yaml")); err == nil { + _ = os.Chdir(resPath) + } + } + if _, err := os.Stat(filepath.Join("config", "config.yaml")); os.IsNotExist(err) { + // wails dev 的 cwd 是 cmd/desktop。仓库配置在上两级。 repoRoot := filepath.Clean(filepath.Join("..", "..")) if _, err := os.Stat(filepath.Join(repoRoot, "config", "config.yaml")); err == nil { _ = os.Chdir(repoRoot) @@ -176,7 +213,15 @@ func main() { // Load .env explicitly for the desktop app so DB_DRIVER gets loaded _ = godotenv.Load() + // wails dev picks up the repo .env, which may ask for Redis streams + // without REDIS_ADDR. go-redis then dials localhost:6379 and aborts + // startup. Lite has no Redis; keep the in-memory stream manager. + if strings.TrimSpace(os.Getenv("REDIS_ADDR")) == "" && + strings.EqualFold(strings.TrimSpace(os.Getenv("STREAM_MANAGER_TYPE")), stream.TypeRedis) { + _ = os.Setenv("STREAM_MANAGER_TYPE", stream.TypeMemory) + } configureDesktopStorage(execPath) + configureDesktopFileStorage(execPath) logger.ConfigureFromEnv() // Set Gin mode @@ -401,19 +446,90 @@ func configureDesktopStorage(execPath string) { migrateLegacyDesktopData(legacyResourcesDir, targetDataDir) dbPath := resolveDesktopDataPath(os.Getenv("DB_PATH"), filepath.Join("data", "weknora.db"), appSupportDir) - filesPath := resolveDesktopDataPath(os.Getenv("LOCAL_STORAGE_BASE_DIR"), filepath.Join("data", "files"), appSupportDir) if err := os.MkdirAll(filepath.Dir(dbPath), 0o755); err != nil { logger.Warnf(context.Background(), "Failed to create desktop DB directory %s: %v", filepath.Dir(dbPath), err) } - if err := os.MkdirAll(filesPath, 0o755); err != nil { - logger.Warnf(context.Background(), "Failed to create desktop files directory %s: %v", filesPath, err) - } _ = os.Setenv("DB_PATH", dbPath) +} + +// configureDesktopFileStorage points Lite file uploads at ~/.weknora/data/files. +// wails dev is not always inside a packaged .app, so this runs for every +// desktop process. An explicit absolute directory is kept; the Docker default +// /data/files is not writable on macOS and is replaced. Uploads move over from +// wherever the previous build kept them. +func configureDesktopFileStorage(execPath string) { + home, err := os.UserHomeDir() + if err != nil { + logger.Warnf(context.Background(), "Failed to resolve home dir for file storage: %v", err) + return + } + filesPath := desktopLocalFilesDir(home) + raw := strings.TrimSpace(os.Getenv("LOCAL_STORAGE_BASE_DIR")) + if !useDesktopFilesDir(raw) { + return + } + if appSupport, err := defaultMacAppSupportDir(execPath); err == nil { + migrateDesktopFiles(legacyDesktopFilesDir(raw, appSupport), filesPath) + } + if err := os.MkdirAll(filesPath, 0o755); err != nil { + logger.Warnf(context.Background(), "Failed to create desktop files directory %s: %v", filesPath, err) + return + } _ = os.Setenv("LOCAL_STORAGE_BASE_DIR", filesPath) } +func desktopLocalFilesDir(home string) string { + return filepath.Join(home, ".weknora", "data", "files") +} + +func useDesktopFilesDir(raw string) bool { + trimmed := strings.TrimSpace(raw) + if trimmed == "" { + return true + } + cleaned := filepath.Clean(trimmed) + switch cleaned { + case "/data/files", "data/files", filepath.Join(".", "data", "files"): + return true + default: + return !filepath.IsAbs(cleaned) + } +} + +// legacyDesktopFilesDir is where the previous build stored uploads: raw +// resolved under the bundle's Application Support dir, or its data/files +// default when raw is empty or the absolute Docker default. +func legacyDesktopFilesDir(raw, appSupportDir string) string { + if filepath.IsAbs(strings.TrimSpace(raw)) { + raw = "" + } + return resolveDesktopDataPath(raw, filepath.Join("data", "files"), appSupportDir) +} + +func migrateDesktopFiles(oldDir, newDir string) { + if filepath.Clean(oldDir) == filepath.Clean(newDir) { + return + } + info, err := os.Stat(oldDir) + if err != nil || !info.IsDir() { + return + } + if _, err := os.Stat(newDir); err == nil { + logger.Warnf(context.Background(), + "Desktop files already exist at %s; leaving %s in place", newDir, oldDir) + return + } + if err := os.MkdirAll(filepath.Dir(newDir), 0o755); err != nil { + logger.Warnf(context.Background(), "Failed to create %s: %v", filepath.Dir(newDir), err) + return + } + if err := os.Rename(oldDir, newDir); err != nil { + logger.Warnf(context.Background(), "Failed to migrate desktop files from %s to %s: %v", oldDir, newDir, err) + } +} + func defaultMacAppSupportDir(execPath string) (string, error) { homeDir, err := os.UserHomeDir() if err != nil { diff --git a/cmd/desktop/prefs_test.go b/cmd/desktop/prefs_test.go index ee2c2bae..8a4f866f 100644 --- a/cmd/desktop/prefs_test.go +++ b/cmd/desktop/prefs_test.go @@ -7,9 +7,67 @@ import ( "testing" "github.com/Tencent/WeKnora/internal/handler" + "github.com/Tencent/WeKnora/internal/utils" "github.com/stretchr/testify/require" ) +func TestDesktopSigningKeyKeepsExistingAESHMAC(t *testing.T) { + dir := t.TempDir() + aes := "abcdefghijklmnopqrstuvwxyz123456" + t.Setenv("SYSTEM_SIGNING_KEY", "") + t.Setenv("JWT_SECRET", "weknora-jwt-secret") + t.Setenv("SYSTEM_AES_KEY", aes) + require.Equal(t, aes, string(utils.SystemHMACKey())) + require.NoError(t, ensureDesktopSigningKeyInDir(dir)) + require.Equal(t, aes, string(utils.SystemHMACKey())) + _, err := os.Stat(filepath.Join(dir, "signing.key")) + require.True(t, os.IsNotExist(err), "the AES key must not be copied into signing.key") + require.NotEqual(t, aes, os.Getenv("JWT_SECRET")) + require.GreaterOrEqual(t, len(os.Getenv("JWT_SECRET")), 32) +} + +func TestDesktopLocalFilesDir(t *testing.T) { + require.Equal(t, filepath.Join("/Users/dev", ".weknora", "data", "files"), desktopLocalFilesDir("/Users/dev")) +} + +func TestUseDesktopFilesDirReplacesDockerDefault(t *testing.T) { + require.True(t, useDesktopFilesDir("")) + require.True(t, useDesktopFilesDir("/data/files")) + require.True(t, useDesktopFilesDir("./data/files")) + require.False(t, useDesktopFilesDir("/Users/dev/custom-files")) +} + +func TestConfigureDesktopFileStorageUsesHomeWeKnora(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("LOCAL_STORAGE_BASE_DIR", "/data/files") + configureDesktopFileStorage("") + require.Equal(t, filepath.Join(home, ".weknora", "data", "files"), os.Getenv("LOCAL_STORAGE_BASE_DIR")) + info, err := os.Stat(os.Getenv("LOCAL_STORAGE_BASE_DIR")) + require.NoError(t, err) + require.True(t, info.IsDir()) +} + +func TestLegacyDesktopFilesDirFollowsTheOldResolution(t *testing.T) { + appSupport := "/Users/dev/Library/Application Support/WeKnora" + require.Equal(t, filepath.Join(appSupport, "data", "files"), legacyDesktopFilesDir("", appSupport)) + require.Equal(t, filepath.Join(appSupport, "data", "files"), legacyDesktopFilesDir("/data/files", appSupport)) + require.Equal(t, filepath.Join(appSupport, "custom", "files"), legacyDesktopFilesDir("custom/files", appSupport)) +} + +func TestConfigureDesktopFileStorageMigratesFromTheBundleDir(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("LOCAL_STORAGE_BASE_DIR", "custom/files") + old := filepath.Join(home, "Library", "Application Support", "WeKnora", "custom", "files") + require.NoError(t, os.MkdirAll(filepath.Join(old, "1"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(old, "1", "a.txt"), []byte("a"), 0o600)) + + configureDesktopFileStorage("/Applications/WeKnora.app/Contents/MacOS/WeKnora") + + require.FileExists(t, filepath.Join(home, ".weknora", "data", "files", "1", "a.txt")) +} + func TestEnsureDesktopLiteEditionOverridesDefaultStandard(t *testing.T) { old := handler.Edition t.Cleanup(func() { handler.Edition = old }) diff --git a/cmd/desktop/signing_key.go b/cmd/desktop/signing_key.go index a079f7ac..c05f9ee2 100644 --- a/cmd/desktop/signing_key.go +++ b/cmd/desktop/signing_key.go @@ -6,16 +6,17 @@ import ( "fmt" "os" "path/filepath" + "strings" "github.com/Tencent/WeKnora/internal/utils" ) -// ensureDesktopSigningKey persists a signing-only key. It never replaces an -// AES encryption key, so upgrading cannot make stored credentials unreadable. +// ensureDesktopSigningKey persists the desktop signing key and, when no +// explicit secret is configured, a JWT secret. It never replaces an AES +// encryption key, so upgrading cannot make stored credentials unreadable. +// The JWT secret is never that AES key: a leaked session secret must not +// decrypt stored credentials. func ensureDesktopSigningKey() error { - if len(utils.SystemHMACKey()) != 0 { - return nil - } dir, err := os.UserConfigDir() if err != nil { return err @@ -27,6 +28,13 @@ func ensureDesktopSigningKeyInDir(dir string) error { if err := os.MkdirAll(dir, 0o700); err != nil { return err } + // An existing HMAC (an explicit signing key, or the AES key of an older + // install) stays the signer exactly as configured: replacing it would + // invalidate presigned URLs, and copying it into signing.key would leave + // the AES key in a second file. Sessions then get their own secret. + if len(utils.SystemHMACKey()) != 0 { + return ensureDesktopJWTSecret(dir, nil) + } path := filepath.Join(dir, "signing.key") key, err := os.ReadFile(path) if os.IsNotExist(err) { @@ -54,5 +62,59 @@ func ensureDesktopSigningKeyInDir(dir string) error { if len(key) < 32 { return fmt.Errorf("invalid desktop signing key in %s", path) } - return os.Setenv("SYSTEM_SIGNING_KEY", string(key)) + if err := os.Setenv("SYSTEM_SIGNING_KEY", string(key)); err != nil { + return err + } + return ensureDesktopJWTSecret(dir, key) +} + +// ensureDesktopJWTSecret fills JWT_SECRET when it is unset or still a +// placeholder. A signing key this function generated can also sign sessions. +// A nil signingKey means the signer came from the environment (possibly the +// AES key), so sessions get their own persisted secret. +func ensureDesktopJWTSecret(dir string, signingKey []byte) error { + jwtSecret := strings.TrimSpace(os.Getenv("JWT_SECRET")) + if jwtSecret != "" && jwtSecret != "weknora-jwt-secret" && jwtSecret != "CHANGE-ME-jwt-secret" { + return nil + } + secret := string(signingKey) + if signingKey == nil { + var err error + secret, err = desktopJWTSecret(dir) + if err != nil { + return err + } + } + return os.Setenv("JWT_SECRET", secret) +} + +func desktopJWTSecret(dir string) (string, error) { + path := filepath.Join(dir, "jwt.key") + key, err := os.ReadFile(path) + if os.IsNotExist(err) { + bytes := make([]byte, 32) + if _, err := rand.Read(bytes); err != nil { + return "", err + } + key = []byte(base64.RawURLEncoding.EncodeToString(bytes)) + f, createErr := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if os.IsExist(createErr) { + key, err = os.ReadFile(path) + } else if createErr != nil { + return "", createErr + } else { + _, err = f.Write(key) + closeErr := f.Close() + if err == nil { + err = closeErr + } + } + } + if err != nil { + return "", err + } + if len(key) < 32 { + return "", fmt.Errorf("invalid desktop jwt secret in %s", path) + } + return string(key), nil } diff --git a/cmd/desktop/signing_key_test.go b/cmd/desktop/signing_key_test.go index 33a9ba87..368f2bb9 100644 --- a/cmd/desktop/signing_key_test.go +++ b/cmd/desktop/signing_key_test.go @@ -13,13 +13,18 @@ import ( func TestDesktopSigningKeyPersistsWithoutChangingAES(t *testing.T) { dir := t.TempDir() t.Setenv("SYSTEM_SIGNING_KEY", "") + t.Setenv("JWT_SECRET", "") t.Setenv("SYSTEM_AES_KEY", "weknora-system-aes-key-32bytes!!") require.NoError(t, ensureDesktopSigningKeyInDir(dir)) first := string(utils.SystemHMACKey()) + firstJWT := os.Getenv("JWT_SECRET") require.GreaterOrEqual(t, len(first), 32) + require.Equal(t, first, firstJWT) t.Setenv("SYSTEM_SIGNING_KEY", "") + t.Setenv("JWT_SECRET", "") require.NoError(t, ensureDesktopSigningKeyInDir(dir)) require.Equal(t, first, string(utils.SystemHMACKey())) + require.Equal(t, firstJWT, os.Getenv("JWT_SECRET")) require.Equal(t, "weknora-system-aes-key-32bytes!!", os.Getenv("SYSTEM_AES_KEY")) info, err := os.Stat(filepath.Join(dir, "signing.key")) require.NoError(t, err) @@ -27,3 +32,41 @@ func TestDesktopSigningKeyPersistsWithoutChangingAES(t *testing.T) { require.Zero(t, info.Mode().Perm()&0o077) } } + +func TestDesktopJWTSecretIsNotTheAESKey(t *testing.T) { + dir := t.TempDir() + const aes = "0123456789abcdef0123456789abcdef" + t.Setenv("SYSTEM_SIGNING_KEY", "") + t.Setenv("JWT_SECRET", "weknora-jwt-secret") + t.Setenv("SYSTEM_AES_KEY", aes) + + require.NoError(t, ensureDesktopSigningKeyInDir(dir)) + jwt := os.Getenv("JWT_SECRET") + require.GreaterOrEqual(t, len(jwt), 32) + require.NotEqual(t, aes, jwt) + require.Equal(t, aes, string(utils.SystemHMACKey())) + require.Equal(t, aes, os.Getenv("SYSTEM_AES_KEY")) + + t.Setenv("SYSTEM_SIGNING_KEY", "") + t.Setenv("JWT_SECRET", "CHANGE-ME-jwt-secret") + require.NoError(t, ensureDesktopSigningKeyInDir(dir)) + require.Equal(t, jwt, os.Getenv("JWT_SECRET")) + require.Equal(t, aes, string(utils.SystemHMACKey())) + require.Equal(t, aes, os.Getenv("SYSTEM_AES_KEY")) + _, err := os.Stat(filepath.Join(dir, "signing.key")) + require.True(t, os.IsNotExist(err), "the AES key must not be copied into signing.key") +} + +func TestDesktopSigningKeyKeepsAnExplicitKey(t *testing.T) { + dir := t.TempDir() + stale := []byte("stale-file-key-0123456789abcdefgh") + require.NoError(t, os.WriteFile(filepath.Join(dir, "signing.key"), stale, 0o600)) + const explicit = "explicit-24-byte-signkey" + t.Setenv("SYSTEM_SIGNING_KEY", explicit) + t.Setenv("SYSTEM_AES_KEY", "") + t.Setenv("JWT_SECRET", "") + + require.NoError(t, ensureDesktopSigningKeyInDir(dir)) + require.Equal(t, explicit, string(utils.SystemHMACKey())) + require.NotEqual(t, explicit, os.Getenv("JWT_SECRET")) +} diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.ts index 34495c38..2cd3f706 100644 --- a/frontend/src/api/auth/index.ts +++ b/frontend/src/api/auth/index.ts @@ -293,21 +293,34 @@ export async function register(data: RegisterRequest): Promise /** * Lite 版自动初始化(创建默认用户/空间 + 签发令牌) */ -export async function autoSetup(): Promise { - try { - const nativeApp = (window as any).go?.main?.App - if (!nativeApp?.GetAutoSetupToken) return { success: false, message: 'Desktop authentication required' } - const token = await nativeApp.GetAutoSetupToken() - const response = await post('/api/v1/auth/auto-setup', {}, { - headers: { 'X-WeKnora-Desktop-Token': token }, - }) - return response as unknown as LoginResponse - } catch (error: any) { - return { - success: false, - message: error.message || 'Auto-setup unavailable' +let autoSetupPromise: Promise | null = null + +export function autoSetup(): Promise { + if (autoSetupPromise) return autoSetupPromise + + const request = (async () => { + try { + const nativeApp = (window as any).go?.main?.App + if (!nativeApp?.GetAutoSetupToken) return { success: false, message: 'Desktop authentication required' } + const token = await nativeApp.GetAutoSetupToken() + const response = await post('/api/v1/auth/auto-setup', {}, { + headers: { 'X-WeKnora-Desktop-Token': token }, + }) + return response as unknown as LoginResponse + } catch (error: any) { + return { + success: false, + message: error.message || 'Auto-setup unavailable' + } } - } + })() + + autoSetupPromise = request + void request.then( + () => { if (autoSetupPromise === request) autoSetupPromise = null }, + () => { if (autoSetupPromise === request) autoSetupPromise = null }, + ) + return request } /** diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index a25b17de..9152d5b6 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -30,6 +30,8 @@ import { import { type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent'; import { useChatResourcesStore } from '@/stores/chatResources'; import { useEditorResourcesStore } from '@/stores/editorResources'; +import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'; +import { hostSkillsOnly, mentionSkillTargetId } from '@/utils/skillTarget'; import { useI18n } from 'vue-i18n'; import AttachmentUpload, { type AttachmentFile } from './AttachmentUpload.vue'; import { @@ -64,6 +66,7 @@ const orgStore = useOrganizationStore(); const menuStore = useMenuStore(); const chatResources = useChatResourcesStore(); const editorResources = useEditorResourcesStore(); +const deploymentCapabilities = useDeploymentCapabilitiesStore(); const { agents, disabledOwnAgentIds, @@ -1424,9 +1427,17 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) => const skillsMode = agentSkillsSelectionMode.value; if (skillsMode !== 'none') { // The scope makes a shared agent's skills resolve in its owner's - // workspace, where they are actually installed. + // workspace, where they are actually installed. Lite agents store no + // sandbox config id; their skills live on the host target. + await deploymentCapabilities.ensureLoaded(); await editorResources.ensureSkills( - currentAgentConfig.value?.sandbox_config_id, + mentionSkillTargetId( + hostSkillsOnly( + deploymentCapabilities.isSupported('settings.sandbox.remote'), + deploymentCapabilities.isSupported('settings.sandbox.host'), + ), + currentAgentConfig.value?.sandbox_config_id, + ), currentAgentScope.value, ); skillItems = editorResources.skills diff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vue index 347afd4d..faa7fc27 100644 --- a/frontend/src/components/SandboxSkillsPanel.vue +++ b/frontend/src/components/SandboxSkillsPanel.vue @@ -93,8 +93,8 @@ - {{ $t('settings.skills.manageUninstall') }} + {{ hostCopy('settings.skills.manageUninstall', 'manageUninstall') }}
-

{{ $t('settings.sandbox.skillRemoveDone', { name: uninstallingName }) }}

+

{{ hostCopy('settings.sandbox.skillRemoveDone', 'removeDone', { name: uninstallingName }) }}