π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: sync selected shell into the prompt so the model targets the right shell (#17901)
YuTengjing197e30f17082
diff --git a/apps/desktop/src/main/controllers/ShellCommandCtr.ts b/apps/desktop/src/main/controllers/ShellCommandCtr.tsindex 2d764ac8974..cb2f73d98b7 100644--- a/apps/desktop/src/main/controllers/ShellCommandCtr.ts+++ b/apps/desktop/src/main/controllers/ShellCommandCtr.ts@@ -65,7 +65,16 @@ export default class ShellCommandCtr extends ControllerModule {setWindowsShellPreference(mode);logger.info('Windows shell mode updated:', mode);- return this.getShellSettings();+ const settings = await this.getShellSettings();++ // Push the new shell to every renderer so the `{{defaultShell}}` prompt+ // placeholder flips immediately β otherwise the model keeps emitting+ // commands for the previous shell until the app restarts.+ this.app.browserManager.broadcastToAllWindows('appStateUpdated', {+ defaultShell: settings.currentShell.displayName,+ });++ return settings;}@IpcMethod()diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.tsindex 10718a40b2e..3f72d8607c3 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts@@ -1,3 +1,4 @@+import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import { MessagesEngine } from '@lobechat/context-engine';import { type OpenAIChatMessage } from '@lobechat/types';@@ -71,6 +72,24 @@ const createServerVariableGenerators = (params: {// leaking the literal `{{defaultShell}}` token into the prompt.defaultShell: () =>'the platform default shell (PowerShell on Windows, /bin/sh on macOS/Linux)',+ // Same leak-guard for the paired syntax-guidance placeholder; passing+ // undefined yields the shell-agnostic wording.+ shellSyntaxGuidance: () => getShellSyntaxGuidance(undefined),+ // Leak-guards for the device identity/path placeholders in the local-system+ // system role. Real values arrive via `additionalVariables` (device system+ // info) and override these; without a device report, tell the model the+ // value is unknown instead of leaking the literal `{{...}}` token.+ arch: () => 'unknown',+ hostname: () => 'unknown',+ platform: () => 'unknown',+ desktopPath: () => '(not reported)',+ documentsPath: () => '(not reported)',+ downloadsPath: () => '(not reported)',+ homePath: () => '(not reported)',+ musicPath: () => '(not reported)',+ picturesPath: () => '(not reported)',+ userDataPath: () => '(not reported)',+ videosPath: () => '(not reported)',};};diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex bcb397e6ca5..addc88b197d 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -13,7 +13,7 @@ import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agimport { builtinSkills } from '@lobechat/builtin-skills';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { LobeAgentIdentifier, LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';-import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';+import { getShellSyntaxGuidance, LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';@@ -3603,13 +3603,14 @@ export class AiAgentService {if (!systemInfo) return {};const device = onlineDevices.find((d) => d.deviceId === deviceId);log('execAgent: fetched device system info for %s', deviceId);+ // Devices that don't report defaultShell run an older client whose+ // runner still hardcodes cmd.exe on Windows β describe that honestly+ // instead of the new PowerShell default.+ const defaultShell =+ systemInfo.defaultShell ?? (device?.platform === 'win32' ? 'cmd.exe' : '/bin/sh');return {arch: systemInfo.arch,- // Devices that don't report defaultShell run an older client whose- // runner still hardcodes cmd.exe on Windows β describe that honestly- // instead of the new PowerShell default.- defaultShell:- systemInfo.defaultShell ?? (device?.platform === 'win32' ? 'cmd.exe' : '/bin/sh'),+ defaultShell,desktopPath: systemInfo.desktopPath,documentsPath: systemInfo.documentsPath,downloadsPath: systemInfo.downloadsPath,@@ -3618,6 +3619,9 @@ export class AiAgentService {musicPath: systemInfo.musicPath,picturesPath: systemInfo.picturesPath,platform: device?.platform ?? 'unknown',+ // Keep the syntax guidance consistent with the shell named above β+ // the system role references both placeholders in one sentence.+ shellSyntaxGuidance: getShellSyntaxGuidance(defaultShell),userDataPath: systemInfo.userDataPath,videosPath: systemInfo.videosPath,// `workingDirectory` is intentionally NOT taken from the live devicediff --git a/packages/builtin-tool-local-system/src/__tests__/shellSyntaxGuidance.test.ts b/packages/builtin-tool-local-system/src/__tests__/shellSyntaxGuidance.test.tsnew file mode 100644index 00000000000..746c539db9c--- /dev/null+++ b/packages/builtin-tool-local-system/src/__tests__/shellSyntaxGuidance.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { getShellSyntaxGuidance } from '../shellSyntaxGuidance';++describe('getShellSyntaxGuidance', () => {+ it('gives bash guidance for Git Bash and never mentions PowerShell as the target', () => {+ const guidance = getShellSyntaxGuidance('Git Bash');++ expect(guidance).toContain('POSIX/bash');+ expect(guidance).toContain('do NOT use PowerShell');+ });++ it('warns about missing chain operators only for Windows PowerShell 5.1', () => {+ expect(getShellSyntaxGuidance('Windows PowerShell 5.1')).toContain('NOT available');+ expect(getShellSyntaxGuidance('PowerShell 7+ (pwsh)')).toContain('are available');+ });++ it('gives cmd guidance for cmd.exe', () => {+ expect(getShellSyntaxGuidance('cmd.exe')).toContain('cmd.exe syntax');+ });++ it('gives POSIX guidance for /bin/sh', () => {+ expect(getShellSyntaxGuidance('/bin/sh')).toBe('Write POSIX shell syntax.');+ });++ it('falls back to the shell-conditional wording when the shell is unknown', () => {+ for (const value of [undefined, '', 'something-else']) {+ expect(getShellSyntaxGuidance(value)).toContain('When that shell is PowerShell');+ }+ });++ it('matches display names case-insensitively', () => {+ expect(getShellSyntaxGuidance('git bash')).toContain('POSIX/bash');+ });+});diff --git a/packages/builtin-tool-local-system/src/__tests__/systemRole.test.ts b/packages/builtin-tool-local-system/src/__tests__/systemRole.test.tsnew file mode 100644index 00000000000..cba2939c1cd--- /dev/null+++ b/packages/builtin-tool-local-system/src/__tests__/systemRole.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { systemPrompt as genericPrompt } from '../systemRole';+import { systemPrompt as desktopPrompt } from '../systemRole.desktop';++const extractPlaceholders = (template: string): Set<string> =>+ new Set([...template.matchAll(/\{\{(\w+)\}\}/g)].map((match) => match[1]));++describe('systemRole templates', () => {+ /**+ * The generic template is what the server renders for gateway runs; the+ * `.desktop` variant is a client-only vite module swap. Keep the environment+ * facts in sync: a placeholder present only in the desktop variant means+ * gateway prompts silently lose information the local prompt has (this is+ * how gateway runs ended up without the known-locations list, LOBE-12692).+ */+ it('generic template carries every placeholder the desktop variant has', () => {+ const generic = extractPlaceholders(genericPrompt);+ const desktopOnly = [...extractPlaceholders(desktopPrompt)].filter((key) => !generic.has(key));++ expect(desktopOnly).toEqual([]);+ });++ it('both templates pair {{defaultShell}} with {{shellSyntaxGuidance}}', () => {+ for (const template of [genericPrompt, desktopPrompt]) {+ expect(template).toContain('{{defaultShell}}');+ expect(template).toContain('{{shellSyntaxGuidance}}');+ }+ });+});diff --git a/packages/builtin-tool-local-system/src/index.ts b/packages/builtin-tool-local-system/src/index.tsindex 4e1a85f0b0b..aae77ff09ad 100644--- a/packages/builtin-tool-local-system/src/index.ts+++ b/packages/builtin-tool-local-system/src/index.ts@@ -1,5 +1,6 @@export { createPathScopeAudit, pathScopeAudit } from './interventionAudit';export { LocalSystemManifest } from './manifest';+export { getShellSyntaxGuidance } from './shellSyntaxGuidance';export { systemPrompt } from './systemRole';export {type EditLocalFileState,diff --git a/packages/builtin-tool-local-system/src/shellSyntaxGuidance.ts b/packages/builtin-tool-local-system/src/shellSyntaxGuidance.tsnew file mode 100644index 00000000000..3a8ca0301ee--- /dev/null+++ b/packages/builtin-tool-local-system/src/shellSyntaxGuidance.ts@@ -0,0 +1,39 @@+/**+ * Per-shell syntax guidance for the `{{shellSyntaxGuidance}}` placeholder in+ * the local-system system role, so the model only ever sees instructions for+ * the shell `runCommand` actually spawns. The previous prompt always carried+ * the PowerShell 5.1 guidance, which anchored models into emitting PowerShell+ * commands even when the user had selected Git Bash (LOBE-12692).+ *+ * Matching is by the human-readable shell names produced by `getShellInfo()`+ * in `@lobechat/local-file-shell` ("Git Bash", "PowerShell 7+ (pwsh)",+ * "Windows PowerShell 5.1", "cmd.exe", "/bin/sh") β that display name is what+ * both the renderer context and the device system-info report carry. Keep the+ * two in sync when adding a shell.+ */+export const getShellSyntaxGuidance = (defaultShell?: string): string => {+ const shell = defaultShell?.toLowerCase() ?? '';++ if (shell.includes('git bash') || shell.includes('gitbash'))+ return 'Write POSIX/bash syntax (&&, ||, $VAR); do NOT use PowerShell or cmd.exe syntax.';++ // "Windows PowerShell 5.1" must be checked before the generic PowerShell+ // match β it is the only edition without the && / || chain operators.+ if (shell.includes('powershell 5'))+ return "Write Windows PowerShell 5.1-compatible syntax; the &&/|| chain operators are NOT available β use ';' to sequence commands or 'if ($?) { ... }' for conditional chaining.";++ if (shell.includes('pwsh') || shell.includes('powershell'))+ return 'Write PowerShell syntax; the && and || chain operators are available.';++ if (shell.includes('cmd'))+ return 'Write cmd.exe syntax (&& to chain, %VAR% for environment variables); do NOT use PowerShell-only syntax.';++ // `/bin/β¦` covers sh/zsh/fish paths; a bare "sh" substring would also match+ // unrelated words like "shell", so match the path form and named shells only.+ if (shell.includes('/bin/') || shell.includes('bash') || shell.includes('zsh'))+ return 'Write POSIX shell syntax.';++ // Unknown shell (e.g. an older client that reports nothing): keep the old+ // conditional wording rather than guessing a concrete shell.+ return "When that shell is PowerShell, write PowerShell-compatible syntax; on Windows PowerShell 5.1 the &&/|| chain operators are NOT available β use ';' to sequence commands or 'if ($?) { ... }' for conditional chaining.";+};diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.tsindex 5429edc5b66..10317e00ede 100644--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts@@ -78,7 +78,7 @@ You have access to a set of tools to interact with the user's local file system:- 'command': The shell command to execute.- 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.- 'run_in_background' (Optional): Set to true to return immediately after starting the terminal session. The result includes a 'shell_id' for later observation or termination.- The command runs in {{defaultShell}}. When that shell is PowerShell, write PowerShell-compatible syntax; on Windows PowerShell 5.1 the &&/|| chain operators are NOT available β use ';' to sequence commands or 'if ($?) { ... }' for conditional chaining. The returned output reflects the tool's wait window, not necessarily the full command lifetime.+ The command runs in {{defaultShell}}. {{shellSyntaxGuidance}} The returned output reflects the tool's wait window, not necessarily the full command lifetime.- Installing software: do NOT proactively install software on the user's system. Prefer tools that are already installed, or a no-install alternative. If a task genuinely needs a system-level or global install (e.g. \`brew install\`, \`apt\`/\`dnf install\`, \`npm i -g\`, \`pipx\`, a global \`pip install\`), ask the user first and explain why, rather than running the install on your own. Routine project-local dependency installs (e.g. \`npm\`/\`pnpm install\` inside a project, \`pip install\` inside an active virtualenv) are fine β run them as normal.- Result semantics:- 'success' indicates whether the tool call itself succeeded.diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.tsindex b51add1dc2d..ceb2f4fe449 100644--- a/packages/builtin-tool-local-system/src/systemRole.ts+++ b/packages/builtin-tool-local-system/src/systemRole.ts@@ -3,7 +3,17 @@ export const systemPrompt = `You have a Local System tool with capabilities to i<user_context><device name="{{hostname}}" os="{{platform}}" arch="{{arch}}" /><working-directory>{{workingDirectory}}</working-directory>-<home-path>{{homePath}}</home-path>+<known-locations>+Use these paths when the user refers to these common locations by name (e.g., "my desktop", "downloads folder").+- Desktop: {{desktopPath}}+- Documents: {{documentsPath}}+- Downloads: {{downloadsPath}}+- Music: {{musicPath}}+- Pictures: {{picturesPath}}+- Videos: {{videosPath}}+- User Home: {{homePath}}+- App Data: {{userDataPath}} (Use this primarily for plugin-related data or configurations if needed, less for general user files)+</known-locations></user_context><core_capabilities>@@ -67,7 +77,7 @@ You have access to a set of tools to interact with the user's local file system:- 'command': The shell command to execute.- 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.- 'run_in_background' (Optional): Set to true to return immediately after starting the terminal session. The result includes a 'shell_id' for later observation or termination.- The command runs in {{defaultShell}}. When that shell is PowerShell, write PowerShell-compatible syntax; on Windows PowerShell 5.1 the &&/|| chain operators are NOT available β use ';' to sequence commands or 'if ($?) { ... }' for conditional chaining. The returned output reflects the tool's wait window, not necessarily the full command lifetime.+ The command runs in {{defaultShell}}. {{shellSyntaxGuidance}} The returned output reflects the tool's wait window, not necessarily the full command lifetime.- Installing software: do NOT proactively install software on the user's system. Prefer tools that are already installed, or a no-install alternative. If a task genuinely needs a system-level or global install (e.g. \`brew install\`, \`apt\`/\`dnf install\`, \`npm i -g\`, \`pipx\`, a global \`pip install\`), ask the user first and explain why, rather than running the install on your own. Routine project-local dependency installs (e.g. \`npm\`/\`pnpm install\` inside a project, \`pip install\` inside an active virtualenv) are fine β run them as normal.- Result semantics:- 'success' indicates whether the tool call itself succeeded.diff --git a/packages/electron-client-ipc/src/events/system.ts b/packages/electron-client-ipc/src/events/system.tsindex f9e046f6345..ff879dc0fd4 100644--- a/packages/electron-client-ipc/src/events/system.ts+++ b/packages/electron-client-ipc/src/events/system.ts@@ -1,6 +1,12 @@-import type { ThemeAppearance, ThemeMode } from '../types';+import type { ElectronAppState, ThemeAppearance, ThemeMode } from '../types';export interface SystemBroadcastEvents {+ /**+ * Fired when a piece of the app state changes after boot (e.g. the user+ * switches the Windows shell in settings). Carries only the changed fields;+ * the renderer merges them into its app-state copy and the agent context.+ */+ appStateUpdated: (data: Partial<ElectronAppState>) => void;localeChanged: (data: { locale: string }) => void;systemThemeChanged: (data: { themeMode: ThemeAppearance }) => void;themeChanged: (data: { themeMode: ThemeMode }) => void;diff --git a/src/helpers/GlobalAgentContextManager.ts b/src/helpers/GlobalAgentContextManager.tsindex 6791c373201..b848f688a17 100644--- a/src/helpers/GlobalAgentContextManager.ts+++ b/src/helpers/GlobalAgentContextManager.ts@@ -1,4 +1,7 @@export interface LobeGlobalAgentContext {+ /** CPU architecture reported by the desktop main process (e.g. 'arm64', 'x64'). */+ arch?: string;+// Other potential contextcurrentTime?: string;diff --git a/src/helpers/parserPlaceholder/index.ts b/src/helpers/parserPlaceholder/index.tsindex fb47bd44268..a899535f89e 100644--- a/src/helpers/parserPlaceholder/index.ts+++ b/src/helpers/parserPlaceholder/index.ts@@ -1,3 +1,4 @@+import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';import { isDesktop } from '@lobechat/const';import { uuid } from '@lobechat/utils';@@ -164,14 +165,21 @@ export const VARIABLE_GENERATORS = {* | `{{userDataPath}}` | /Users/username/Library/Application Support/LobeChat |* | `{{workingDirectory}}` | /Users/username/Projects/my-project |* | `{{defaultShell}}` | PowerShell 7+ (pwsh) |+ * | `{{shellSyntaxGuidance}}` | Write PowerShell syntax; ... |+ * | `{{arch}}` | arm64 |**/+ arch: () => globalAgentContextManager.getContext().arch ?? '',homePath: () => globalAgentContextManager.getContext().homePath ?? '',// Fallback keeps the surrounding prompt sentence readable when the desktop// context has not (yet) provided the detected shell.defaultShell: () =>globalAgentContextManager.getContext().defaultShell ??'the platform default shell (PowerShell on Windows, /bin/sh on macOS/Linux)',+ // Syntax rules matching the shell above, so the model never sees guidance+ // for a shell it is not running in (see getShellSyntaxGuidance).+ shellSyntaxGuidance: () =>+ getShellSyntaxGuidance(globalAgentContextManager.getContext().defaultShell),desktopPath: () => globalAgentContextManager.getContext().desktopPath ?? '',documentsPath: () => globalAgentContextManager.getContext().documentsPath ?? '',downloadsPath: () => globalAgentContextManager.getContext().downloadsPath ?? '',diff --git a/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx b/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsxnew file mode 100644index 00000000000..41566ed49ca--- /dev/null+++ b/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx@@ -0,0 +1,33 @@+'use client';++import { useWatchBroadcast } from '@lobechat/electron-client-ipc';++import { useElectronStore } from '@/store/electron';++/**+ * Hydrate the electron app state (default shell, user paths, locale) into the+ * electron store and the global agent context at boot, then keep it fresh via+ * the main process's `appStateUpdated` broadcast (e.g. when the user switches+ * the Windows shell in settings).+ *+ * Mounted from `StoreInitialization` on purpose: the previous init call lived+ * in `TitleBar` and was silently dropped in a titlebar refactor (#13059),+ * leaving `{{defaultShell}}` / path placeholders unresolved for months β keep+ * this with the other store initializers so layout changes can't detach it.+ */+const ElectronAppStateSync = () => {+ const [useInitElectronAppState, updateElectronAppState] = useElectronStore((s) => [+ s.useInitElectronAppState,+ s.updateElectronAppState,+ ]);++ useInitElectronAppState();++ useWatchBroadcast('appStateUpdated', (state) => {+ updateElectronAppState(state);+ });++ return null;+};++export default ElectronAppStateSync;diff --git a/src/layout/GlobalProvider/ElectronAppStateSync.tsx b/src/layout/GlobalProvider/ElectronAppStateSync.tsxnew file mode 100644index 00000000000..8c5c16eef5f--- /dev/null+++ b/src/layout/GlobalProvider/ElectronAppStateSync.tsx@@ -0,0 +1,10 @@+'use client';++/**+ * Web no-op. The desktop build swaps in `ElectronAppStateSync.desktop.tsx`,+ * which hydrates the electron app state (shell, user paths) into the store and+ * the global agent context, and keeps them fresh via main-process broadcasts.+ */+const ElectronAppStateSync = () => null;++export default ElectronAppStateSync;diff --git a/src/layout/GlobalProvider/StoreInitialization.tsx b/src/layout/GlobalProvider/StoreInitialization.tsxindex 3e82a4d2727..b67f50c5082 100644--- a/src/layout/GlobalProvider/StoreInitialization.tsx+++ b/src/layout/GlobalProvider/StoreInitialization.tsx@@ -13,6 +13,7 @@ import { serverConfigSelectors } from '@/store/serverConfig/selectors';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';+import ElectronAppStateSync from './ElectronAppStateSync';import { useUserStateRedirect } from './useUserStateRedirect';const DeferredStoreInitialization = lazy(() => import('./DeferredStoreInitialization'));@@ -77,9 +78,12 @@ const StoreInitialization = memo(() => {useStoreUpdater('isMobile', mobile);return (- <Suspense>- <DeferredStoreInitialization isLogin={isLoginOnInit} />- </Suspense>+ <>+ <ElectronAppStateSync />+ <Suspense>+ <DeferredStoreInitialization isLogin={isLoginOnInit} />+ </Suspense>+ </>);});diff --git a/src/store/electron/actions/__tests__/app.test.ts b/src/store/electron/actions/__tests__/app.test.tsnew file mode 100644index 00000000000..e22a38724ad--- /dev/null+++ b/src/store/electron/actions/__tests__/app.test.ts@@ -0,0 +1,68 @@+import { act } from '@testing-library/react';+import { beforeEach, describe, expect, it } from 'vitest';++import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';+import { useElectronStore } from '@/store/electron';++describe('ElectronAppActionImpl', () => {+ beforeEach(() => {+ globalAgentContextManager.setContext({});+ useElectronStore.setState({ appState: {} });+ });++ describe('updateElectronAppState', () => {+ it('merges the update into appState', () => {+ act(() => {+ useElectronStore.getState().updateElectronAppState({ defaultShell: 'Git Bash' });+ });++ expect(useElectronStore.getState().appState.defaultShell).toBe('Git Bash');+ });++ it('syncs defaultShell into the global agent context so {{defaultShell}} flips without a restart', () => {+ // Regression: switching the Windows shell in settings only updated the+ // main process; the prompt placeholder kept describing the old shell+ // until app restart (LOBE-12692).+ act(() => {+ useElectronStore.getState().updateElectronAppState({ defaultShell: 'Git Bash' });+ });++ expect(globalAgentContextManager.getContext().defaultShell).toBe('Git Bash');+ });++ it('syncs arch into the global agent context so {{arch}} renders in the prompt', () => {+ act(() => {+ useElectronStore.getState().updateElectronAppState({ arch: 'arm64' });+ });++ expect(globalAgentContextManager.getContext().arch).toBe('arm64');+ });++ it('syncs user paths into the global agent context', () => {+ act(() => {+ useElectronStore.getState().updateElectronAppState({+ userPath: {+ desktop: '/home/u/Desktop',+ documents: '/home/u/Documents',+ home: '/home/u',+ userData: '/home/u/.config/lobehub',+ },+ });+ });++ const context = globalAgentContextManager.getContext();+ expect(context.homePath).toBe('/home/u');+ expect(context.desktopPath).toBe('/home/u/Desktop');+ });++ it('leaves existing context fields untouched when the update omits them', () => {+ globalAgentContextManager.setContext({ defaultShell: 'PowerShell 7+ (pwsh)' });++ act(() => {+ useElectronStore.getState().updateElectronAppState({ locale: 'en-US' });+ });++ expect(globalAgentContextManager.getContext().defaultShell).toBe('PowerShell 7+ (pwsh)');+ });+ });+});diff --git a/src/store/electron/actions/app.ts b/src/store/electron/actions/app.tsindex 68b43f9c2ad..57514ec6a07 100644--- a/src/store/electron/actions/app.ts+++ b/src/store/electron/actions/app.ts@@ -6,8 +6,6 @@ import { useOnlyFetchOnceSWR } from '@/libs/swr';// Import for type usageimport { electronSystemService } from '@/services/electron/system';import { type StoreSetter } from '@/store/types';-import { type LocaleMode } from '@/types/locale';-import { switchLang } from '@/utils/client/switchLang';import { merge } from '@/utils/merge';import { type ElectronStore } from '../store';@@ -20,6 +18,33 @@ type Setter = StoreSetter<ElectronStore>;export const createElectronAppSlice = (set: Setter, get: () => ElectronStore, _api?: unknown) =>new ElectronAppActionImpl(set, get, _api);+/**+ * Mirror app state into the global agent context so prompt placeholders+ * ({{defaultShell}}, {{homePath}}, ...) always describe the real desktop+ * environment. Every app-state write path (initial fetch and later+ * `appStateUpdated` broadcasts) must go through this β a prompt that+ * disagrees with the actual runCommand shell makes the model emit commands+ * for the wrong shell (e.g. PowerShell syntax into Git Bash).+ */+const syncAppStateToAgentContext = (state: ElectronAppState): void => {+ globalAgentContextManager.updateContext({+ ...(state.arch ? { arch: state.arch } : {}),+ ...(state.defaultShell ? { defaultShell: state.defaultShell } : {}),+ ...(state.userPath+ ? {+ desktopPath: state.userPath.desktop,+ documentsPath: state.userPath.documents,+ downloadsPath: state.userPath.downloads,+ homePath: state.userPath.home,+ musicPath: state.userPath.music,+ picturesPath: state.userPath.pictures,+ userDataPath: state.userPath.userData,+ videosPath: state.userPath.videos,+ }+ : {}),+ });+};+export class ElectronAppActionImpl {readonly #get: () => ElectronStore;readonly #set: Setter;@@ -37,6 +62,7 @@ export class ElectronAppActionImpl {updateElectronAppState = (state: ElectronAppState): void => {const prevState = this.#get().appState;this.#set({ appState: merge(prevState, state) });+ syncAppStateToAgentContext(state);};useInitElectronAppState = (): SWRResponse<ElectronAppState> => {@@ -47,23 +73,10 @@ export class ElectronAppActionImpl {onSuccess: (result) => {this.#set({ appState: result, isAppStateInit: true }, false, 'initElectronAppState');- // Update the global agent context manager with relevant paths- // We typically only need paths in the agent context for now.- globalAgentContextManager.updateContext({- defaultShell: result.defaultShell,- desktopPath: result.userPath!.desktop,- documentsPath: result.userPath!.documents,- downloadsPath: result.userPath!.downloads,- homePath: result.userPath!.home,- musicPath: result.userPath!.music,- picturesPath: result.userPath!.pictures,- userDataPath: result.userPath!.userData,- videosPath: result.userPath!.videos,- });-- // Initialize i18n with the stored locale, falling back to auto detection.- const locale = (result.locale ?? 'auto') as LocaleMode;- switchLang(locale);+ // Locale is intentionally NOT applied here anymore: the SPA boot flow+ // (SPAGlobalProvider's Locale) owns UI language now, and a second+ // switchLang from this once-dead init path would race it.+ syncAppStateToAgentContext(result);},},);