JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix: save trusted path for project_dir
ldstyle84620eeaa2795
diff --git a/jiuwenclaw/channels/tui/frontend/src/app-state.ts b/jiuwenclaw/channels/tui/frontend/src/app-state.tsindex 92e2aff572..236ce9e8b6 100644--- a/jiuwenclaw/channels/tui/frontend/src/app-state.ts+++ b/jiuwenclaw/channels/tui/frontend/src/app-state.ts@@ -54,6 +54,8 @@ import {setTrustedDir,removeTrustedDir,clearTrustedDirs,+ setCurrentProjectDir,+ getCurrentProjectDir,} from "./core/tui-trusted-dirs-store.js";import { loadTuiConfig, type StatusLineSetting } from "./core/tui-config-store.js";import { execFile } from "node:child_process";@@ -535,6 +537,8 @@ export class CliPiAppState {setTrustedDir: setTrustedDir,removeTrustedDir: removeTrustedDir,clearTrustedDirs: clearTrustedDirs,+ setCurrentProjectDir: setCurrentProjectDir,+ getCurrentProjectDir: getCurrentProjectDir,getWorkspaceDir: () => getTrustedDirs()[0] || process.cwd(),enterConfigEditor: undefined, // AppScreen injects the real handler when executing slash commands.setInput: this._setInputRef ?? undefined,diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/workspace-dir.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/workspace-dir.tsindex 73a0013738..3717ca2afd 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/workspace-dir.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/workspace-dir.ts@@ -12,7 +12,13 @@ function showAllTrustedPaths(ctx: CommandContext): void {value: "~/.jiuwenswarm/agent/workspace",});- // Show trusted directories+ // Show current project scope (always resolved absolute path)+ items.push({+ label: "project scope",+ value: ctx.getCurrentProjectDir(),+ });++ // Show trusted directories for this project onlyif (trustedDirs.length > 0) {trustedDirs.forEach((dir, index) => {items.push({@@ -28,7 +34,7 @@ function showAllTrustedPaths(ctx: CommandContext): void {}ctx.addItem(- addInfo(ctx.sessionId, "Trusted paths for file operations", "c", {+ addInfo(ctx.sessionId, "Trusted paths for current project", "c", {view: "kv",title: "Trusted Paths",items,@@ -36,33 +42,6 @@ function showAllTrustedPaths(ctx: CommandContext): void {);}-/**- * Ask user for Yes/No confirmation.- * @returns true if user selected Yes, false if No or cancelled- */-async function askYesNo(- ctx: CommandContext,- header: string,- question: string,- yesLabel: string,- noLabel: string,-): Promise<boolean> {- const answers = await ctx.askQuestions(- [- {- header,- question,- options: [{ label: yesLabel }, { label: noLabel }],- },- ],- "local_command",- );- const answer = answers[0];- if (!answer) return false;- const selected = answer.selected_options[0] ?? "";- return selected === yesLabel;-}-export function createWorkspaceCommand(): SlashCommand {return {name: "workspace",@@ -128,65 +107,56 @@ export function createWorkspaceCommand(): SlashCommand {},{name: "set",- description: "Reset trusted dirs and set a single path",+ description: "Switch project scope to a new directory",usage: "/workspace set <path>",kind: CommandKind.BUILT_IN,takesArgs: true,action: async (ctx, args) => {- const directoryPath = args.trim();- if (!directoryPath) {+ const rawPath = args.trim();+ if (!rawPath) {ctx.addItem(addError(ctx.sessionId, "usage: /workspace set <path>"));return;}// Validate path without modifying state- const result = ctx.validateDirPath(directoryPath);+ const result = ctx.validateDirPath(rawPath);if (result === "not_found") {- ctx.addItem(addError(ctx.sessionId, `Path does not exist: ${directoryPath}`));+ ctx.addItem(addError(ctx.sessionId, `Path does not exist: ${rawPath}`));return;}if (result === "invalid") {- ctx.addItem(addError(ctx.sessionId, `Path is not a directory: ${directoryPath}`));+ ctx.addItem(addError(ctx.sessionId, `Path is not a directory: ${rawPath}`));return;}if (result === "no_access") {- ctx.addItem(addError(ctx.sessionId, `Permission denied: cannot access directory ${directoryPath}`));+ ctx.addItem(addError(ctx.sessionId, `Permission denied: cannot access directory ${rawPath}`));return;}- // If trusted dirs already has content, ask for confirmation- const currentDirs = ctx.getTrustedDirs();- if (currentDirs.length > 0) {- const confirmed = await askYesNo(- ctx,- "Confirm Reset",- `This will clear all existing trusted directories and set "${directoryPath}" as the only trusted path.\nCurrent trusted dirs will be removed: ${currentDirs.join(", ")}`,- "Yes, reset and set",- "No, keep current",- );- if (!confirmed) {- ctx.addItem(addInfo(ctx.sessionId, "Operation cancelled. Current trusted dirs unchanged.", "c"));- return;- }- }-- // Execute the set operation- ctx.setTrustedDir(directoryPath);+ // Switch project scope to the new directory (absolute path)+ ctx.setCurrentProjectDir(rawPath);+ // Add the new directory itself as a trusted dir for this project+ ctx.addTrustedDir(rawPath);// Sync to server-side permissionstry {ctx.sendEventOnly("command.add_dir", {- path: directoryPath,+ path: ctx.getCurrentProjectDir(),remember: true});} catch (error) {- // Ignore sync errors, still set locallyconsole.warn("Failed to sync trusted directory to server:", error);}++ const projectDir = ctx.getCurrentProjectDir();+ const finalDirs = ctx.getTrustedDirs();ctx.addItem(- addInfo(ctx.sessionId, `Trusted directory set: ${directoryPath}`, "c", {+ addInfo(ctx.sessionId, `Project scope switched: ${projectDir}`, "c", {view: "kv",title: "Set Trusted Dir",- items: [{ label: "path", value: directoryPath }],+ items: [+ { label: "project scope", value: projectDir },+ ...finalDirs.map((dir, i) => ({ label: `trusted[${i}]`, value: dir })),+ ],}),);},diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.tsindex 614c091c46..722cc1d470 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts@@ -70,13 +70,15 @@ export interface CommandContext {expandToolGroups: (scope: "last" | "all") => void;sessionTitle: string;setSessionTitle: (title: string) => void;- // Trusted directories management (global, not session-specific)+ // Trusted directories management (project-scoped)getTrustedDirs: () => string[];validateDirPath: (path: string) => "valid" | "not_found" | "invalid" | "no_access";addTrustedDir: (path: string) => "added" | "exists" | "not_found" | "invalid" | "no_access";setTrustedDir: (path: string) => "set" | "not_found" | "invalid" | "no_access";removeTrustedDir: (path: string) => boolean;clearTrustedDirs: () => void;+ setCurrentProjectDir: (dir: string) => void;+ getCurrentProjectDir: () => string;// Workspace directory (current working directory)getWorkspaceDir: () => string | undefined;setInput?: (text: string) => void;diff --git a/jiuwenclaw/channels/tui/frontend/src/core/tui-config-store.ts b/jiuwenclaw/channels/tui/frontend/src/core/tui-config-store.tsindex 8d87af5a2e..7dc776df57 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/tui-config-store.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/tui-config-store.ts@@ -16,7 +16,12 @@ export interface StatusLineSetting {export interface TuiConfig {theme?: ThemeName;accentColor?: AccentColorName;- trustedDirs?: string[];+ /**+ * Project-scoped trusted directories.+ * Key = normalized project cwd path, value = list of trusted dir paths for that project.+ * Legacy flat array (string[]) is migrated on first load.+ */+ trustedDirs?: Record<string, string[]> | string[];statusLine?: StatusLineSetting;}diff --git a/jiuwenclaw/channels/tui/frontend/src/core/tui-trusted-dirs-store.ts b/jiuwenclaw/channels/tui/frontend/src/core/tui-trusted-dirs-store.tsindex fbf4aada70..c395dd18ea 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/tui-trusted-dirs-store.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/tui-trusted-dirs-store.ts@@ -5,27 +5,12 @@ import { resolve } from "node:path";import { loadTuiConfig, saveTuiConfig } from "./tui-config-store.js";/**- * Trusted directories storage with persistence via ~/.jiuwenswarm-tui/config.json.- * Managed at CLI startup and via /workspace commands.+ * Trusted directories storage — project-scoped.+ *+ * Each project (identified by its cwd) maintains its own trusted dirs list.+ * Stored in ~/.jiuwenclaw-tui/config.json as `trustedDirs: {projectPath: [dir1, dir2]}`.*/-let _trustedDirs: string[] | null = null;--/**- * Ensure _trustedDirs is loaded from persisted config.- */-function ensureLoaded(): void {- if (_trustedDirs === null) {- const config = loadTuiConfig();- _trustedDirs = Array.isArray(config.trustedDirs) ? [...config.trustedDirs!] : [];- }-}--/**- * Persist current _trustedDirs to config file.- */-function persist(): void {- saveTuiConfig({ trustedDirs: _trustedDirs! });-}+let _trustedDirsByProject: Record<string, string[]> | null = null;/*** Normalize a path for comparison (handle trailing separators, case on Windows)@@ -48,17 +33,100 @@ function normalizePath(path: string): string {}/**- * Get all trusted directories.- * Returns empty array if no dirs set (will use default workspace).- * @returns Array of trusted directory paths (normalized)+ * Migrate legacy flat `trustedDirs: string[]` format to project-scoped format.+ * The first element in the flat array is treated as the project cwd,+ * and the entire list becomes that project's trusted dirs.+ */+function migrateLegacyFormat(config: Record<string, unknown>): Record<string, string[]> {+ const raw = config.trustedDirs;+ if (Array.isArray(raw) && raw.length > 0) {+ // Use the first dir as project cwd, all dirs become that project's list+ const projectCwd = normalizePath(raw[0]);+ const migrated: Record<string, string[]> = {};+ if (projectCwd) {+ const normalizedList = raw.map(d => normalizePath(d)).filter(d => d);+ migrated[projectCwd] = normalizedList;+ }+ // Persist the migrated format immediately+ saveTuiConfig({ trustedDirs: migrated });+ return migrated;+ }+ // Empty array or not an array → empty project-scoped map+ const empty: Record<string, string[]> = {};+ saveTuiConfig({ trustedDirs: empty });+ return empty;+}++/**+ * Ensure _trustedDirsByProject is loaded from persisted config.+ */+function ensureLoaded(): void {+ if (_trustedDirsByProject === null) {+ const config = loadTuiConfig();+ const raw = config.trustedDirs;+ if (Array.isArray(raw)) {+ _trustedDirsByProject = migrateLegacyFormat(config as Record<string, unknown>);+ } else if (raw && typeof raw === "object") {+ _trustedDirsByProject = raw as Record<string, string[]>;+ } else {+ _trustedDirsByProject = {};+ }+ }+}++/**+ * Persist current _trustedDirsByProject to config file.+ */+function persist(): void {+ saveTuiConfig({ trustedDirs: _trustedDirsByProject! });+}++/**+ * Get the project key (normalized cwd) used for scoping.+ * Defaults to process.cwd() but can be overridden.+ */+let _currentProjectDir: string | null = null;++/**+ * Override the project directory used for scoping trusted dirs.+ * The path is normalized to an absolute path.+ * This is a session-level override — not persisted, because on restart+ * the project scope must match the user's actual cwd.+ */+export function setCurrentProjectDir(dir: string): void {+ _currentProjectDir = normalizePath(dir);+}++/**+ * Get the current project scope directory (absolute path).+ */+export function getCurrentProjectDir(): string {+ return getProjectKey();+}++/**+ * Get the current project directory key (normalized absolute path).+ * Priority: in-memory _currentProjectDir > process.cwd()+ */+function getProjectKey(): string {+ if (_currentProjectDir) {+ return _currentProjectDir;+ }+ return normalizePath(process.cwd());+}++/**+ * Get trusted directories for the current project only.+ * Returns empty array if no dirs set for this project.*/export function getTrustedDirs(): string[] {ensureLoaded();- return [..._trustedDirs!];+ const key = getProjectKey();+ return [...(_trustedDirsByProject![key] || [])];}/**- * Add a trusted directory.+ * Add a trusted directory to the current project.* @param path - Directory path to add (must be a folder, not a file)* @returns "added" if added, "exists" if already trusted, "not_found" if path doesn't exist, "invalid" if invalid path or not a directory, "no_access" if permission denied*/@@ -83,10 +151,13 @@ export function addTrustedDir(path: string): "added" | "exists" | "not_found" |if (access !== "valid") {return access;}- if (_trustedDirs!.includes(normalized)) {+ const key = getProjectKey();+ const projectDirs = _trustedDirsByProject![key] || [];+ if (projectDirs.includes(normalized)) {return "exists";}- _trustedDirs!.push(normalized);+ projectDirs.push(normalized);+ _trustedDirsByProject![key] = projectDirs;persist();return "added";}@@ -136,7 +207,7 @@ export function validateDirPath(path: string): "valid" | "not_found" | "invalid"}/**- * Reset trusted dirs and set a single path.+ * Reset trusted dirs for the current project and set a single path.* @param path - Directory path to set as the only trusted dir (must be a folder, not a file)* @returns "set" if set successfully, "not_found" if path doesn't exist, "invalid" if invalid path or not a directory, "no_access" if permission denied*/@@ -161,15 +232,16 @@ export function setTrustedDir(path: string): "set" | "not_found" | "invalid" | "if (access !== "valid") {return access;}- _trustedDirs = [normalized];+ const key = getProjectKey();+ _trustedDirsByProject![key] = [normalized];persist();return "set";}/**- * Remove a trusted directory.+ * Remove a trusted directory from the current project.* @param path - Directory path to remove- * @returns true if removed, false if not found+ * @returns true if removed, false if not found in this project's trusted dirs*/export function removeTrustedDir(path: string): boolean {ensureLoaded();@@ -177,28 +249,36 @@ export function removeTrustedDir(path: string): boolean {if (!normalized) {return false;}- const index = _trustedDirs!.indexOf(normalized);+ const key = getProjectKey();+ const projectDirs = _trustedDirsByProject![key] || [];+ const index = projectDirs.indexOf(normalized);if (index === -1) {return false;}- _trustedDirs!.splice(index, 1);+ projectDirs.splice(index, 1);+ if (projectDirs.length === 0) {+ delete _trustedDirsByProject![key];+ } else {+ _trustedDirsByProject![key] = projectDirs;+ }persist();return true;}/**- * Clear all trusted directories (will use default workspace only).+ * Clear all trusted directories for the current project.*/export function clearTrustedDirs(): void {ensureLoaded();- _trustedDirs = [];+ const key = getProjectKey();+ delete _trustedDirsByProject![key];persist();}/**- * Check if a path is a trusted directory.+ * Check if a path is a trusted directory for the current project.* @param path - Directory path to check- * @returns true if trusted+ * @returns true if trusted for the current project*/export function isTrustedDir(path: string): boolean {ensureLoaded();@@ -206,7 +286,9 @@ export function isTrustedDir(path: string): boolean {if (!normalized) {return false;}- return _trustedDirs!.includes(normalized);+ const key = getProjectKey();+ const projectDirs = _trustedDirsByProject![key] || [];+ return projectDirs.includes(normalized);}/**@@ -214,4 +296,4 @@ export function isTrustedDir(path: string): boolean {*/export function getDefaultWorkspacePath(): string {return resolve(homedir(), ".jiuwenswarm/agent/workspace");-}+}\ No newline at end of filediff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.tsindex cbe6777aa9..eadc7a3037 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts@@ -43,7 +43,7 @@ import type { ConfigItemSchema } from "../core/commands/builtins/config.js";import type { McpListItem, McpListPayload } from "../core/commands/builtins/mcp.js";import { buildModeAutocompleteItems } from "../core/commands/builtins/mode.js";import { isTeamMode } from "../core/modes.js";-import { addTrustedDir, getTrustedDirs, isTrustedDir } from "../core/tui-trusted-dirs-store.js";+import { addTrustedDir, getTrustedDirs, isTrustedDir, setCurrentProjectDir } from "../core/tui-trusted-dirs-store.js";import { handleAppScreenKeyInput } from "./keymap.js";import { buildAppScreenLines } from "./screen-layout.js";import {@@ -549,6 +549,8 @@ export class AppScreen implements Component, Focusable {this.editor.setText(text);});this.state.getInputValueRef(() => this.editor.getText());+ // Initialize project scope from the user's actual cwd+ setCurrentProjectDir(process.cwd());// Initialize startup prompt for workspace trustthis.initStartupPrompt();}diff --git a/jiuwenclaw/common/utils.py b/jiuwenclaw/common/utils.pyindex 068bb30eb2..35585345aa 100644--- a/jiuwenclaw/common/utils.py+++ b/jiuwenclaw/common/utils.py@@ -384,8 +384,21 @@ def _resolve_preferred_language(return "zh"+def _is_interactive() -> bool:+ """Check if stdin is connected to a terminal (interactive mode)."""+ try:+ return sys.stdin.isatty()+ except Exception:+ return False++def prompt_preferred_language() -> Optional[Literal["zh", "en"]]:- """交互询问语言偏好。仅接受明确选项;空输入、不在列表或取消用语 → 返回 None(调用方应终止 init)。"""+ """交互询问语言偏好。仅接受明确选项;空输入、不在列表或取消用语 → 返回 None(调用方应终止 init)。+ 非交互环境(stdin非TTY)默认返回 'zh'。+ """+ if not _is_interactive():+ print("[jiuwenclaw-init] Non-interactive mode: using default language 'zh'")+ return "zh"print()print("[jiuwenswarm-init] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")print("[jiuwenswarm-init] 请选择默认语言 / Choose your default language")@@ -953,13 +966,16 @@ def init_user_workspace()print("[jiuwenswarm-init] WARNING: This will delete all historical configuration and memory information.")print("[jiuwenswarm-init] This action cannot be undone.")- confirmation = input(- "[jiuwenswarm-init] Do you want to confirm reinitialization? (yes/no): "- ).strip().lower()-- if confirmation not in ("yes", "y"):- print("[jiuwenswarm-init] Initialization cancelled. Exiting.")- return "cancelled"+ if _is_interactive():+ confirmation = input(+ "[jiuwenswarm-init] Do you want to confirm reinitialization? (yes/no): "+ ).strip().lower()++ if confirmation not in ("yes", "y"):+ print("[jiuwenswarm-init] Initialization cancelled. Exiting.")+ return "cancelled"+ else:+ print("[jiuwenswarm-init] Non-interactive mode: proceeding with reinitialization.")# Close all log handlers to release file locks before deleting_close_log_handlers()@@ -978,11 +994,14 @@ def init_user_workspace("existing files will be preserved and merged with template.")print("[jiuwenswarm-init] This action cannot be undone.")- confirmation = input("[jiuwenswarm-init] Do you want to continue? (yes/no): ").strip().lower()+ if _is_interactive():+ confirmation = input("[jiuwenswarm-init] Do you want to continue? (yes/no): ").strip().lower()- if confirmation not in ("yes", "y"):- print("[jiuwenswarm-init] Initialization cancelled. Exiting.")- return "cancelled"+ if confirmation not in ("yes", "y"):+ print("[jiuwenswarm-init] Initialization cancelled. Exiting.")+ return "cancelled"+ else:+ print("[jiuwenswarm-init] Non-interactive mode: proceeding with merge initialization.")lang = prompt_preferred_language()if lang is None:diff --git a/tests/system_tests/test_init_workspace.py b/tests/system_tests/test_init_workspace.pyindex 1027961f72..6066b3ee98 100644--- a/tests/system_tests/test_init_workspace.py+++ b/tests/system_tests/test_init_workspace.py@@ -30,7 +30,13 @@ def temp_home() -> Generator[Path, None, None]:@pytest.fixture-def clean_environment(temp_home: Path, monkeypatch: pytest.MonkeyPatch) -> None:+def interactive_mode(monkeypatch: pytest.MonkeyPatch) -> None:+ """Force _is_interactive() to return True so tests hit the interactive branch."""+ monkeypatch.setattr("jiuwenclaw.common.utils._is_interactive", lambda: True)+++def clean_environment(temp_home: Path, monkeypatch: pytest.MonkeyPatch, interactive_mode: None) -> None:"""Set up a clean environment for testing initialization."""# Override HOME to use temporary directorymonkeypatch.setenv("HOME", str(temp_home))@@ -97,7 +103,11 @@ class TestPromptPreferredLanguage:assert result == "zh"@staticmethod- def test_prompt_select_english(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture):+ def test_prompt_select_english(+ monkeypatch: pytest.MonkeyPatch,+ interactive_mode: None,+ capsys: pytest.CaptureFixture,+ ):"""Test prompt_preferred_language with English selection."""from jiuwenclaw.common.utils import prompt_preferred_language@@ -117,7 +127,7 @@ class TestPromptPreferredLanguage:assert result == "zh"@staticmethod- def test_prompt_select_en_alias(monkeypatch: pytest.MonkeyPatch):+ def test_prompt_select_en_alias(monkeypatch: pytest.MonkeyPatch, interactive_mode: None):"""Test prompt_preferred_language with 'en' alias."""from jiuwenclaw.common.utils import prompt_preferred_language@@ -126,7 +136,7 @@ class TestPromptPreferredLanguage:assert result == "en"@staticmethod- def test_prompt_cancel_with_no(monkeypatch: pytest.MonkeyPatch):+ def test_prompt_cancel_with_no(monkeypatch: pytest.MonkeyPatch, interactive_mode: None):"""Test prompt_preferred_language cancellation with 'no'."""from jiuwenclaw.common.utils import prompt_preferred_language@@ -135,7 +145,7 @@ class TestPromptPreferredLanguage:assert result is None@staticmethod- def test_prompt_cancel_with_n(monkeypatch: pytest.MonkeyPatch):+ def test_prompt_cancel_with_n(monkeypatch: pytest.MonkeyPatch, interactive_mode: None):"""Test prompt_preferred_language cancellation with 'n'."""from jiuwenclaw.common.utils import prompt_preferred_language@@ -144,7 +154,7 @@ class TestPromptPreferredLanguage:assert result is None@staticmethod- def test_prompt_cancel_with_q(monkeypatch: pytest.MonkeyPatch):+ def test_prompt_cancel_with_q(monkeypatch: pytest.MonkeyPatch, interactive_mode: None):"""Test prompt_preferred_language cancellation with 'q'."""from jiuwenclaw.common.utils import prompt_preferred_language@@ -153,7 +163,11 @@ class TestPromptPreferredLanguage:assert result is None@staticmethod- def test_prompt_invalid_input_returns_none(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture):+ def test_prompt_invalid_input_returns_none(+ monkeypatch: pytest.MonkeyPatch,+ interactive_mode: None,+ capsys: pytest.CaptureFixture,+ ):"""Test prompt_preferred_language with invalid input."""from jiuwenclaw.common.utils import prompt_preferred_language