Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(settings): Model Storage sagt, welcher Ordner wem gehoert

purple467fbe543309
diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rs
index 4a1d704a..af27d004 100644
--- a/src-tauri/src/commands/download.rs
+++ b/src-tauri/src/commands/download.rs
@@ -1203,6 +1203,48 @@ pub fn detect_model_path(provider: String) -> Result<serde_json::Value, String>
}
}
+/// Where LM Studio keeps its models, and whether LM Studio is on this machine
+/// at all. Reads only: nothing is created.
+///
+/// `detect_model_path` cannot answer this. It is a DOWNLOAD TARGET, so for
+/// Ollama and LM Studio it creates the folder when it is missing, which is
+/// right for a download and wrong for a panel whose whole job is to say
+/// "LM Studio is not installed". Asking it here would create
+/// `~/.lmstudio/models` on a machine that has never seen LM Studio and then
+/// report that folder as evidence of an install.
+///
+/// Installed is answered from the folder first because that is free on every
+/// platform, and only then from `os_paths::lmstudio_installed()`, which knows
+/// the `lms` CLI and the app bundle. A user who has LM Studio but has not
+/// downloaded a model yet is therefore still recognised.
+#[tauri::command]
+pub fn lmstudio_model_dir() -> Result<serde_json::Value, String> {
+ let home = dirs::home_dir().ok_or("Cannot find home directory")?;
+ let found = lmstudio_dir_in(&home);
+ let installed = found.is_some() || crate::os_paths::lmstudio_installed();
+ Ok(serde_json::json!({
+ "installed": installed,
+ "path": found.map(|p| p.to_string_lossy().to_string()),
+ }))
+}
+
+/// The LM Studio models folder under a given home, or None. Creates nothing.
+///
+/// Split out from the command so the "creates nothing" half can be proven
+/// against a throwaway home directory instead of the tester's own.
+///
+/// Same two candidates and the same order as detect_model_path: LM Studio
+/// 0.3.x writes ~/.lmstudio/models on all three platforms, 0.2.x used
+/// ~/.cache/lm-studio/models.
+pub fn lmstudio_dir_in(home: &Path) -> Option<PathBuf> {
+ [
+ home.join(".lmstudio").join("models"),
+ home.join(".cache").join("lm-studio").join("models"),
+ ]
+ .into_iter()
+ .find(|p| p.is_dir())
+}
+
#[allow(non_snake_case)]
#[tauri::command]
pub async fn download_model_to_path(
@@ -1423,6 +1465,39 @@ pub async fn check_model_sizes(
mod tests {
use super::*;
+ #[test]
+ fn the_lm_studio_row_looks_and_never_creates() {
+ // A14: Model Storage has to be able to say "LM Studio is not
+ // installed". detect_model_path cannot answer that, because it is a
+ // download target and calls create_dir_all on the way out, so asking
+ // it would conjure ~/.lmstudio/models on a machine that has never seen
+ // LM Studio and then report that folder as proof of an install.
+ let home = tempfile::tempdir().expect("tempdir");
+ let h = home.path();
+
+ // Nothing there: no answer, and nothing left behind.
+ assert!(lmstudio_dir_in(h).is_none());
+ assert!(!h.join(".lmstudio").exists(), "the look created a folder");
+ assert!(!h.join(".cache").exists(), "the look created a folder");
+
+ // The 0.2.x location alone is still an answer.
+ let legacy = h.join(".cache").join("lm-studio").join("models");
+ fs::create_dir_all(&legacy).expect("legacy dir");
+ assert_eq!(lmstudio_dir_in(h).as_deref(), Some(legacy.as_path()));
+
+ // With both present the modern one wins, same order as detect_model_path.
+ let modern = h.join(".lmstudio").join("models");
+ fs::create_dir_all(&modern).expect("modern dir");
+ assert_eq!(lmstudio_dir_in(h).as_deref(), Some(modern.as_path()));
+
+ // NEGATIVE CONTROL: a FILE named like the folder is not a folder, and
+ // must not be reported as one.
+ let other = tempfile::tempdir().expect("tempdir");
+ fs::create_dir_all(other.path().join(".lmstudio")).expect("parent");
+ fs::write(other.path().join(".lmstudio").join("models"), b"x").expect("file");
+ assert!(lmstudio_dir_in(other.path()).is_none());
+ }
+
#[test]
fn a_full_drive_is_named_before_the_first_byte() {
// Der echte Fall vom 15.08.: 16,3 GB Videomodell, 15,2 GB frei.
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index a91aaa4a..abfd5085 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -270,6 +270,7 @@ fn main() {
commands::download::cancel_download,
commands::download::resume_download,
commands::download::detect_model_path,
+ commands::download::lmstudio_model_dir,
commands::download::check_model_sizes,
commands::download::delete_comfy_model,
// Built-in inference engine (bundled llama-server, P1)
diff --git a/src/api/model-folders.ts b/src/api/model-folders.ts
new file mode 100644
index 00000000..d4cd78a1
--- /dev/null
+++ b/src/api/model-folders.ts
@@ -0,0 +1,28 @@
+/**
+ * Read-only questions about the model folders LU does NOT own.
+ *
+ * Deliberately separate from `detectProviderModelPath` in discover.ts: that
+ * one asks the backend for a DOWNLOAD TARGET and the backend creates the
+ * folder to hand one back. Model Storage asks a different question ("where is
+ * it, and is it there at all") and must not leave a folder behind on a machine
+ * that has no LM Studio.
+ */
+
+import { backendCall } from './backend'
+import type { LmStudioModelDir } from '../lib/model-storage-rows'
+
+/**
+ * LM Studio's models folder, without creating anything.
+ *
+ * Any failure (web build, bridge without the command, older backend) answers
+ * "not installed, no path", which is what the panel should say when it cannot
+ * find out: the row is informational and must never block Settings.
+ */
+export async function lmStudioModelDir(): Promise<LmStudioModelDir> {
+ try {
+ const res = await backendCall<{ installed?: boolean; path?: string | null }>('lmstudio_model_dir')
+ return { installed: res?.installed === true, path: res?.path ?? null }
+ } catch {
+ return { installed: false, path: null }
+ }
+}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index ff0216e7..eaa674fd 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -65,7 +65,12 @@ import { ArrowUpCircle, KeyRound, RefreshCw } from 'lucide-react'
import { CLOUD_BASE } from '../../api/cloud/config'
import { formatBytes } from '../../lib/formatters'
import { syncCustomModelDir, type CustomModelDirResult } from '../../lib/custom-model-dir'
-import { listBundledModels, lastCustomScanDir, type ScannedDir } from '../../api/engine'
+import { listBundledModels, lastCustomScanDir, lastScanDirs, type ScannedDir } from '../../api/engine'
+import { lmStudioModelDir } from '../../api/model-folders'
+import {
+ luEngineFolderPlaceholder, lmStudioFolderNote, lmStudioFolderPath,
+ type LmStudioModelDir,
+} from '../../lib/model-storage-rows'
import { CivitaiApiKeySetting } from './CivitaiApiKeySetting'
// ── User profile picture (Appearance) ───────────────────────────
@@ -270,17 +275,29 @@ export function HfDownloadPathSetting() {
const [draft, setDraft] = useState(override)
const [comfy, setComfy] = useState<CustomModelDirResult | null>(null)
const [scan, setScan] = useState<ScannedDir | null>(null)
+ // The folder LU reads while the field is empty. Row 0 of the listing is the
+ // app's own models dir, which is exactly the folder the LU Engine loads
+ // from, so the empty field can name it instead of saying "(auto-detect)"
+ // and leaving the user to guess.
+ const [autoDir, setAutoDir] = useState('')
useEffect(() => { setDraft(override) }, [override])
// How the GGUF scan itself fared in that folder. A folder too big to finish
// within the budget returns a real but partial list, and the only person who
// can do anything about that is the one who chose the folder.
+ //
+ // Runs with and without an override since 2.6.8: without one there is no
+ // scan verdict to show, but the listing is still the only place the app dir
+ // is known, and the placeholder needs it.
useEffect(() => {
let alive = true
- if (!override) { setScan(null); return }
void listBundledModels()
- .then(() => { if (alive) setScan(lastCustomScanDir()) })
- .catch(() => { if (alive) setScan(null) })
+ .then(() => {
+ if (!alive) return
+ setScan(override ? lastCustomScanDir() : null)
+ setAutoDir(lastScanDirs()[0]?.path ?? '')
+ })
+ .catch(() => { if (alive) { setScan(null); setAutoDir('') } })
return () => { alive = false }
}, [override])
@@ -320,8 +337,9 @@ export function HfDownloadPathSetting() {
return (
<div className="space-y-2 py-1">
+ <p className="text-[0.62rem] font-semibold text-gray-700 dark:text-gray-300">LU Engine folder</p>
<div className="text-[0.6rem] text-gray-500 leading-relaxed">
- Your own model folder. LU downloads GGUFs here, and it also reads this folder: every <code className="font-mono">.gguf</code> in it, up to four levels down, is listed under Installed and can be loaded straight from there. Leave empty to auto-detect from your active provider's models folder (e.g. <code className="font-mono">~/.lmstudio/models</code> for LM Studio). Ollama is unaffected, it manages its own blob store; LU pulls Ollama models via <code className="font-mono">ollama pull</code> regardless of this setting.
+ LU downloads GGUFs here and reads every <code className="font-mono">.gguf</code> in it, up to four levels down. Models here run on the LU Engine.
</div>
<div className="flex items-center gap-2">
<input
@@ -329,8 +347,8 @@ export function HfDownloadPathSetting() {
value={draft}
onChange={(e) => setDraft(e.target.value)}
onBlur={() => apply(draft.trim())}
- placeholder="(auto-detect)"
- aria-label="Your own model folder"
+ placeholder={luEngineFolderPlaceholder(autoDir)}
+ aria-label="LU Engine folder"
className="flex-1 px-2 py-1 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-700 dark:text-gray-300 font-mono focus:outline-none focus:border-white/20"
/>
<button
@@ -431,7 +449,45 @@ function CustomModelDirNote({ result }: { result: CustomModelDirResult }) {
// download them a second time. The backend hard links the GGUF into the app
// models dir, zero copy; Ollama and LM Studio keep working untouched.
-function ImportLocalModels() {
+// ── Model Storage, row 2: LM Studio's folder ────────────────────
+//
+// Read-only on purpose. LU does not own this folder and cannot move it, so a
+// field here would be a lie with a Browse button on it. What the user needs is
+// the answer to "is THIS the folder I was about to set", and that is a path
+// and a sentence about who owns it.
+
+export function LmStudioFolderSetting() {
+ // null = not asked yet. Distinguished from "not installed" so the row never
+ // flashes the wrong verdict for the length of one backend round trip.
+ const [dir, setDir] = useState<LmStudioModelDir | null>(null)
+ useEffect(() => {
+ let alive = true
+ void lmStudioModelDir().then((d) => { if (alive) setDir(d) })
+ return () => { alive = false }
+ }, [])
+
+ const path = lmStudioFolderPath(dir)
+ return (
+ <div className="space-y-1 py-1 border-t border-white/5 mt-2 pt-2">
+ <p className="text-[0.62rem] font-semibold text-gray-700 dark:text-gray-300">LM Studio folder</p>
+ {path && (
+ <code data-testid="lmstudio-folder-path" className="block text-[0.6rem] text-gray-400 font-mono break-all select-text">{path}</code>
+ )}
+ <div data-testid="lmstudio-folder-note" className="text-[0.6rem] text-gray-500 leading-relaxed">
+ {lmStudioFolderNote(dir)}
+ </div>
+ </div>
+ )
+}
+
+// ── Model Storage, row 3: Ollama ────────────────────────────────
+//
+// No path at all, and that is the point of the row. Ollama keeps its models in
+// a content-addressed blob store under names no human picked, so there is
+// nothing to set and nothing worth printing; what there IS is a way to link
+// those blobs into LU, which is the scan below.
+
+export function ImportLocalModels() {
const [candidates, setCandidates] = useState<import('../../api/engine').ImportCandidate[] | null>(null)
const [scanning, setScanning] = useState(false)
const [busyPath, setBusyPath] = useState<string | null>(null)
@@ -468,6 +524,10 @@ function ImportLocalModels() {
return (
<div className="space-y-2 py-1 border-t border-white/5 mt-2 pt-2">
+ <p className="text-[0.62rem] font-semibold text-gray-700 dark:text-gray-300">Ollama</p>
+ <div data-testid="ollama-store-note" className="text-[0.6rem] text-gray-500 leading-relaxed">
+ Ollama keeps its own model store. LU pulls Ollama models with <code className="font-mono">ollama pull</code>; a folder cannot be set here.
+ </div>
<div className="text-[0.6rem] text-gray-500 leading-relaxed">
Already have models in Ollama or LM Studio? Link them into LU without downloading or copying anything. The file stays where it is; both apps keep working.
</div>
@@ -1551,6 +1611,7 @@ export function SettingsPage() {
<Section title="Model Storage">
<HfDownloadPathSetting />
+ <LmStudioFolderSetting />
<ImportLocalModels />
{/* goonerforporn (Discord #bug-reports, 2026-08-28): the store knew
the key, the changelog named it, and no component ever set it.
diff --git a/src/components/settings/__tests__/model-storage-three-rows.test.ts b/src/components/settings/__tests__/model-storage-three-rows.test.ts
new file mode 100644
index 00000000..e257fdd8
--- /dev/null
+++ b/src/components/settings/__tests__/model-storage-three-rows.test.ts
@@ -0,0 +1,164 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * A14 (2.6.8), David: "es muss klar sein, ob der Ordner fuer LM Studio, Ollama
+ * oder die LU Engine gilt."
+ *
+ * Before this, Model Storage was one field labelled "(auto-detect)" over a
+ * paragraph that named all three backends at once. A user setting that field
+ * had no way to tell whose folder he was setting, and the honest answer is
+ * that it is one backend's folder and not the other two's. It is three named
+ * rows now: the field the user owns, the folder LM Studio owns, and Ollama,
+ * which has no folder to set at all.
+ *
+ * Run: npx vitest run src/components/settings/__tests__/model-storage-three-rows.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { createElement } from 'react'
+import { render, screen, cleanup, act } from '@testing-library/react'
+import type { ScannedDir } from '../../../api/engine'
+
+let dirs: ScannedDir[] = []
+let lmstudio: { installed: boolean; path: string | null } = { installed: false, path: null }
+
+vi.mock('../../../api/engine', async () => {
+ const actual = await vi.importActual<typeof import('../../../api/engine')>('../../../api/engine')
+ return {
+ ...actual,
+ listBundledModels: vi.fn(async () => []),
+ lastCustomScanDir: () => null,
+ lastScanDirs: () => dirs,
+ }
+})
+vi.mock('../../../api/model-folders', () => ({
+ lmStudioModelDir: vi.fn(async () => lmstudio),
+}))
+vi.mock('../../../lib/custom-model-dir', () => ({
+ syncCustomModelDir: vi.fn(async () => ({ status: 'ok', folders: [], yaml: '' })),
+}))
+vi.mock('../../../api/backend', () => ({
+ backendCall: vi.fn(async () => null),
+ isTauri: () => true,
+ isMacOS: () => false,
+ openExternal: vi.fn(),
+ secretGet: vi.fn().mockRejectedValue(new Error('no keychain here')),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+}))
+
+const { HfDownloadPathSetting, LmStudioFolderSetting, ImportLocalModels } = await import('../SettingsPage')
+const { useSettingsStore } = await import('../../../stores/settingsStore')
+
+const APP_DIR = '/Users/dev/Library/Application Support/lu/models'
+
+async function settle() {
+ await act(async () => { await Promise.resolve(); await Promise.resolve(); await Promise.resolve() })
+}
+
+beforeEach(() => {
+ dirs = []
+ lmstudio = { installed: false, path: null }
+ useSettingsStore.getState().updateSettings({ hfDownloadPathOverride: '' })
+})
+afterEach(() => {
+ cleanup()
+ useSettingsStore.getState().updateSettings({ hfDownloadPathOverride: '' })
+})
+
+describe('row 1: the folder the user sets belongs to the LU Engine and says so', () => {
+ it('is named LU Engine folder and says what runs from it', async () => {
+ render(createElement(HfDownloadPathSetting))
+ await settle()
+ expect(screen.getByText('LU Engine folder')).toBeTruthy()
+ expect(screen.getByText(/Models here run on the LU Engine/)).toBeTruthy()
+ expect(screen.getByText(/up to four levels down/)).toBeTruthy()
+ })
+
+ it('the empty field names the folder that is being read instead of saying nothing', async () => {
+ dirs = [{ path: APP_DIR, status: 'ok' }]
+ render(createElement(HfDownloadPathSetting))
+ await settle()
+ const field = screen.getByLabelText('LU Engine folder') as HTMLInputElement
+ expect(field.placeholder).toBe(`(auto: ${APP_DIR})`)
+ })
+
+ // NEGATIVE CONTROL: with no folder known there is nothing to name, and the
+ // placeholder must not print "(auto: )" at the user.
+ it('falls back to the old wording when the listing knows no folder', async () => {
+ dirs = []
+ render(createElement(HfDownloadPathSetting))
+ await settle()
+ const field = screen.getByLabelText('LU Engine folder') as HTMLInputElement
+ expect(field.placeholder).toBe('(auto-detect)')
+ })
+
+ // NEGATIVE CONTROL: the sentences that moved to the other two rows are gone
+ // from this one. Leaving them would put the same claim on screen twice and
+ // the row would still not say whose folder it is.
+ it('no longer explains LM Studio and Ollama in the LU Engine row', async () => {
+ render(createElement(HfDownloadPathSetting))
+ await settle()
+ expect(screen.queryByText(/auto-detect from your active provider/)).toBeNull()
+ expect(screen.queryByText(/Ollama is unaffected/)).toBeNull()
+ })
+})
+
+describe('row 2: LM Studio owns its folder and the row is read-only', () => {
+ it('shows the detected path and who manages it', async () => {
+ lmstudio = { installed: true, path: '/Users/dev/.lmstudio/models' }
+ render(createElement(LmStudioFolderSetting))
+ await settle()
+ expect(screen.getByText('LM Studio folder')).toBeTruthy()
+ expect(screen.getByTestId('lmstudio-folder-path').textContent).toBe('/Users/dev/.lmstudio/models')
+ expect(screen.getByTestId('lmstudio-folder-note').textContent).toBe(
+ 'LM Studio manages this folder. LU reads it through LM Studio when LM Studio is your chat provider.',
+ )
+ })
+
+ it('says so plainly when LM Studio is not on the machine', async () => {
+ lmstudio = { installed: false, path: null }
+ render(createElement(LmStudioFolderSetting))
+ await settle()
+ expect(screen.getByTestId('lmstudio-folder-note').textContent).toBe('LM Studio is not installed.')
+ })
+
+ // NEGATIVE CONTROL: installed with no models downloaded yet is a real state.
+ // The row must not invent a path it has not seen.
+ it('prints no path when LM Studio is installed but has no models folder yet', async () => {
+ lmstudio = { installed: true, path: null }
+ render(createElement(LmStudioFolderSetting))
+ await settle()
+ expect(screen.queryByTestId('lmstudio-folder-path')).toBeNull()
+ expect(screen.getByTestId('lmstudio-folder-note').textContent).toContain('LM Studio manages this folder')
+ })
+
+ // NEGATIVE CONTROL: no input, no Browse. LU does not own this folder and a
+ // field here would be a promise it cannot keep.
+ it('offers nothing to edit', async () => {
+ lmstudio = { installed: true, path: '/Users/dev/.lmstudio/models' }
+ const { container } = render(createElement(LmStudioFolderSetting))
+ await settle()
+ expect(container.querySelectorAll('input').length).toBe(0)
+ expect(container.querySelectorAll('button').length).toBe(0)
+ })
+})
+
+describe('row 3: Ollama has no folder, and the row says why', () => {
+ it('names Ollama, names the reason, and keeps the scan button under it', async () => {
+ render(createElement(ImportLocalModels))
+ await settle()
+ expect(screen.getByText('Ollama')).toBeTruthy()
+ expect(screen.getByTestId('ollama-store-note').textContent).toBe(
+ 'Ollama keeps its own model store. LU pulls Ollama models with ollama pull; a folder cannot be set here.',
+ )
+ expect(screen.getByText('Scan for local models')).toBeTruthy()
+ })
+
+ // NEGATIVE CONTROL: a row that says "a folder cannot be set here" must not
+ // then offer a field to set one.
+ it('offers no path field of its own', async () => {
+ const { container } = render(createElement(ImportLocalModels))
+ await settle()
+ expect(container.querySelectorAll('input').length).toBe(0)
+ })
+})
diff --git a/src/lib/__tests__/custom-model-dir-comfy.test.ts b/src/lib/__tests__/custom-model-dir-comfy.test.ts
index 8294a359..fe634fab 100644
--- a/src/lib/__tests__/custom-model-dir-comfy.test.ts
+++ b/src/lib/__tests__/custom-model-dir-comfy.test.ts
@@ -70,9 +70,12 @@ describe('the Model Storage copy tells the truth', () => {
it('says the folder is read, not only written to', () => {
// The shipped sentence started "Custom location for downloaded GGUFs" and
// stopped there, which is why two users concluded the setting was broken
- // rather than one-directional.
- expect(src).toMatch(/it also reads this folder/)
- expect(src).toMatch(/listed under Installed/)
+ // rather than one-directional. A14 shortened the copy again, because the
+ // row is now labelled "LU Engine folder" and the two other backends have
+ // rows of their own, but both halves of the claim have to survive that.
+ expect(src).toMatch(/LU downloads GGUFs here and reads every/)
+ expect(src).toMatch(/up to four levels down/)
+ expect(src).toMatch(/Models here run on the LU Engine/)
})
it('is honest that image and video go through ComfyUI', () => {
diff --git a/src/lib/model-storage-rows.ts b/src/lib/model-storage-rows.ts
new file mode 100644
index 00000000..a4fa4cec
--- /dev/null
+++ b/src/lib/model-storage-rows.ts
@@ -0,0 +1,86 @@
+/**
+ * What Settings, AI Backends, Model Storage says about each of the three
+ * places a local chat model can live.
+ *
+ * A14 (2.6.8), David: the panel held ONE field labelled "(auto-detect)" and a
+ * paragraph that named LM Studio, Ollama and our own downloads in the same
+ * breath. Nothing on screen said which of the three the folder you were about
+ * to pick actually belonged to, and the honest answer is that it belongs to
+ * exactly one of them. So the panel is three rows now, each with a name, a
+ * path and a role, and the rules for what each row prints live here where they
+ * can be read and tested without a browser.
+ */
+
+/** What the backend knows about LM Studio's models folder. */
+export interface LmStudioModelDir {
+ installed: boolean
+ path: string | null
+}
+
+/**
+ * The placeholder in the LU Engine folder field.
+ *
+ * "(auto-detect)" on its own answered the wrong question. The user is not
+ * asking whether the app detects something, he is asking which folder is being
+ * read while the field is empty, and the app knows that folder: it is row 0 of
+ * the last listing, the app's own models dir. So the placeholder names it.
+ */
+export function luEngineFolderPlaceholder(autoDir: string | null | undefined): string {
+ const dir = (autoDir ?? '').trim()
+ return dir ? `(auto: ${dir})` : '(auto-detect)'
+}
+
+/** The role line under the LM Studio row. */
+export function lmStudioFolderNote(dir: LmStudioModelDir | null | undefined): string {
+ if (!dir) return ''
+ if (!dir.installed) return 'LM Studio is not installed.'
+ return 'LM Studio manages this folder. LU reads it through LM Studio when LM Studio is your chat provider.'
+}
+
+/**
+ * The path the LM Studio row prints, or '' when there is none to print.
+ *
+ * Installed with no folder yet is a real state (LM Studio present, no model
+ * downloaded), and it must not print an invented path: this row is read-only
+ * precisely because LU does not own that folder.
+ */
+export function lmStudioFolderPath(dir: LmStudioModelDir | null | undefined): string {
+ return (dir?.path ?? '') || ''
+}
+
+/**
+ * Folders macOS gates behind a consent dialog. The user gets asked once, by
+ * the system, the first time LU walks one of them. Nothing here prevents that
+ * dialog, and nothing may: it is the operating system asking on the user's
+ * behalf. The panel just stops it from arriving as a surprise.
+ *
+ * Matched on the path segment rather than on a home-directory prefix, because
+ * the home directory is spelled differently on a Mac with a relocated home,
+ * and because a folder on an external drive named `Documents` is not one of
+ * these.
+ */
+const MACOS_GATED_FOLDERS = ['desktop', 'documents', 'downloads']
+
+/**
+ * Does macOS ask for access to this folder the first time it is read.
+ *
+ * `platformIsMac` is passed in rather than read here so the rule can be tested
+ * in both directions from one process.
+ */
+export function macOsWillAskForFolder(path: string | null | undefined, platformIsMac: boolean): boolean {
+ if (!platformIsMac) return false
+ const raw = (path ?? '').trim()
+ if (!raw) return false
+ const segments = raw.replace(/\\/g, '/').split('/').filter(Boolean)
+ // Only the folder itself and what lies inside it are gated, and the gate
+ // sits directly under the home directory: /Users/<name>/Documents/... . So
+ // the gated segment is the one right after the user name, never any deeper
+ // segment that merely happens to be called "documents".
+ const home = segments.findIndex((s) => s.toLowerCase() === 'users')
+ const gatedIndex = home >= 0 ? home + 2 : -1
+ if (gatedIndex < 0 || gatedIndex >= segments.length) return false
+ return MACOS_GATED_FOLDERS.includes(segments[gatedIndex].toLowerCase())
+}
+
+/** The one line the panel prints under a gated folder. */
+export const MACOS_FOLDER_ACCESS_NOTE = 'macOS will ask once for access to this folder.'