Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: choose working folders when creating projects (#13873)

Lee Jacksone468ee3ec468
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index 54dc2d2b307..bde53ca7a6c 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -32,6 +32,7 @@ on:
- 'tests/studio/playwright_data_settings.py'
- 'tests/studio/playwright_keyboard_shortcuts.py'
- 'tests/studio/playwright_find_in_page.py'
+ - 'tests/studio/playwright_project_folders.py'
- 'tests/studio/playwright_tool_activity.py'
- 'tests/studio/playwright_stream_pacing.py'
- 'tests/studio/playwright_code_block_flicker.py'
@@ -74,6 +75,7 @@ on:
- 'tests/studio/playwright_data_settings.py'
- 'tests/studio/playwright_keyboard_shortcuts.py'
- 'tests/studio/playwright_find_in_page.py'
+ - 'tests/studio/playwright_project_folders.py'
- 'tests/studio/playwright_tool_activity.py'
- 'tests/studio/playwright_stream_pacing.py'
- 'tests/studio/playwright_code_block_flicker.py'
@@ -548,6 +550,13 @@ jobs:
PW_BROWSER: chromium
run: python3 tests/studio/playwright_mcp_app_bridge_smoke.py
+ # Project create / edit dialogs with stubbed native IPC and HTTP: lost responses, spent
+ # grants and older backends must leave the saved working folder matching the choice.
+ - name: Browser smoke for project working folders
+ working-directory: ${{ github.workspace }}
+ timeout-minutes: 10
+ run: python3 tests/studio/playwright_project_folders.py --out "$RUNNER_TEMP/project-folders"
+
- name: Icon tooltips follow the pointer between neighbours
working-directory: ${{ github.workspace }}
timeout-minutes: 3
diff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.py
index 1ad3fba8293..9ad0c200a6b 100644
--- a/studio/backend/core/inference/gpu_arbiter.py
+++ b/studio/backend/core/inference/gpu_arbiter.py
@@ -186,6 +186,7 @@ def _commit_swap_kv(unloaded) -> None:
def _evict_diffusion() -> None:
# Unload whichever engine the router has active (diffusers or native sd.cpp).
from core.inference.diffusion_engine_router import get_active_diffusion_engine
+
# A launching upsampler warm start holds the engine's generation slot the unload waits on.
_cancel_prompt_upsampler_warm_start()
get_active_diffusion_engine().unload()
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 11ca2a7ee9f..bdea929e471 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -81,6 +81,7 @@ from storage.studio_db import (
list_chat_threads,
remap_chat_thread_document_ids,
set_chat_project_working_folder,
+ ProjectWorkingFolderConflictError,
sync_chat_messages,
update_chat_project,
update_chat_thread,
@@ -344,6 +345,10 @@ class ChatProjectWorkingFolder(BaseModel):
native_path_lease: str = Field(alias = "nativePathLease", min_length = 1)
+class ChatProjectCreate(ChatProject):
+ nativePathLease: Optional[str] = Field(default = None, min_length = 1)
+
+
class ChatAgentsMd(BaseModel):
text: str = ""
@@ -1284,9 +1289,20 @@ def list_projects(
@router.post("/projects", response_model = ChatProject)
-def save_project(payload: ChatProject, current_subject: str = Depends(get_current_subject)):
+def save_project(payload: ChatProjectCreate, current_subject: str = Depends(get_current_subject)):
+ lease = getattr(payload, "nativePathLease", None)
+ if lease is not None and not is_owner_context():
+ raise HTTPException(status_code = 403, detail = "Only the owner can use a local folder.")
try:
- return ChatProject(**upsert_chat_project(payload.model_dump()))
+ project = payload.model_dump(exclude = {"nativePathLease"})
+ if lease is None:
+ return ChatProject(**upsert_chat_project(project))
+ working_folder = _resolve_project_working_folder(lease)
+ return ChatProject(**upsert_chat_project(project, working_folder = working_folder))
+ except HTTPException:
+ raise
+ except ProjectWorkingFolderConflictError as exc:
+ raise HTTPException(status_code = 409, detail = str(exc)) from exc
except ProjectWorkspaceError as exc:
# A project is the only thing Unsloth writes to Documents, so only this error and only its own path: the same
# upsert also opens the database, which lives elsewhere.
@@ -1299,6 +1315,17 @@ def save_project(payload: ChatProject, current_subject: str = Depends(get_curren
event = "chat_history.create_project_workspace_failed",
log = logger,
) from exc
+ except Exception as exc:
+ if lease is None:
+ raise
+ # The grant is spent: HTTPException keeps CORS so the webview does not resend it (#13131).
+ raise log_and_http_error(
+ exc,
+ 500,
+ "Could not create the project.",
+ event = "chat_history.create_project_with_folder_failed",
+ log = logger,
+ ) from exc
@router.get("/projects/{project_id}", response_model = ChatProject)
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 47eecfb191a..234faf641a0 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -3108,7 +3108,13 @@ def _unretire_project_rag_scope(project_id: str) -> None:
)
-def upsert_chat_project(project: dict) -> dict:
+class ProjectWorkingFolderConflictError(ValueError):
+ pass
+
+
+def upsert_chat_project(
+ project: dict, *, working_folder: Optional[tuple[str, tuple[int, int]]] = None
+) -> dict:
existing = get_chat_project(project["id"])
root_path = existing.get("rootPath") if existing else None
if not root_path:
@@ -3116,6 +3122,15 @@ def upsert_chat_project(project: dict) -> dict:
root_path = _ensure_project_workspace(root_path)
conn = get_connection()
try:
+ if working_folder is not None:
+ # Create-only: an existing project changes its folder via the working-folder route.
+ conn.execute("BEGIN IMMEDIATE")
+ if conn.execute(
+ "SELECT 1 FROM chat_projects WHERE id = ?", (project["id"],)
+ ).fetchone():
+ raise ProjectWorkingFolderConflictError(
+ "This project already exists. Change its working folder from Edit project."
+ )
conn.execute(
"""
INSERT INTO chat_projects
@@ -3139,6 +3154,12 @@ def upsert_chat_project(project: dict) -> dict:
int(project["updatedAt"]),
),
)
+ if working_folder is not None:
+ path, (device, inode) = working_folder
+ conn.execute(
+ "UPDATE chat_projects SET working_folder = ?, working_folder_identity = ? WHERE id = ?",
+ (path, f"{device}:{inode}", project["id"]),
+ )
conn.commit()
saved = get_chat_project(project["id"]) or project
finally:
diff --git a/studio/backend/tests/test_flux3_prompt_upsampler.py b/studio/backend/tests/test_flux3_prompt_upsampler.py
index 177f50a1fb3..ce260dd6b19 100644
--- a/studio/backend/tests/test_flux3_prompt_upsampler.py
+++ b/studio/backend/tests/test_flux3_prompt_upsampler.py
@@ -1502,7 +1502,9 @@ def test_warm_declines_beside_a_render_and_holds_the_slot_while_it_starts(warmab
# While the server starts, the engine's generation slot is held: a render queues behind it.
slot = threading.Lock()
held = []
- monkeypatch.setattr(pup, "_take_render_slot", lambda: (slot.acquire(blocking = False) and slot, ""))
+ monkeypatch.setattr(
+ pup, "_take_render_slot", lambda: (slot.acquire(blocking = False) and slot, "")
+ )
real_spawn = sidecar._spawn_server
monkeypatch.setattr(
sidecar, "_spawn_server", lambda *a: held.append(slot.locked()) or real_spawn(*a)
@@ -1580,7 +1582,6 @@ def test_a_partial_offload_credits_only_its_resident_share(tmp_path):
assert pup._footprint_mib(str(model), None, 8) == 8 + pup._GPU_OVERHEAD_MIB
-
def test_warm_declines_where_it_cannot_be_pinned(warmable, monkeypatch):
sidecar, launched, _memory, model, _mmproj = warmable
monkeypatch.setattr(pup, "_resident_cuda_ordinal", lambda: None)
@@ -1674,7 +1675,8 @@ def test_an_unenhanced_run_does_not_wait_out_a_warm_start(routes, runnable, monk
monkeypatch.setattr(pup, "cancel_warm_start", lambda: cancels.append(True) or False)
monkeypatch.setitem(_sys.modules, "core.inference.flux3_prompt_upsampler", pup)
r = client.post(
- "/api/inference/images/generate", json = {"prompt": "a cat", "steps": 4, "enhance_prompt": False}
+ "/api/inference/images/generate",
+ json = {"prompt": "a cat", "steps": 4, "enhance_prompt": False},
)
assert r.status_code == 200, r.text
assert cancels == [True]
@@ -1711,4 +1713,3 @@ def test_release_route_cancels_a_warm_start_and_stops_an_idle_server(routes, mon
assert r.status_code == 200 and r.json() == {"released": True, "cancelled_warm": True}
# Non-blocking: a request still using the server keeps it.
assert calls == ["cancel", ("unload", False)]
-
diff --git a/studio/backend/tests/test_project_working_folder.py b/studio/backend/tests/test_project_working_folder.py
index 95e608235d5..672f82038fd 100644
--- a/studio/backend/tests/test_project_working_folder.py
+++ b/studio/backend/tests/test_project_working_folder.py
@@ -8,10 +8,16 @@ removes that and nothing else, and a folder that moved or was replaced is never
"""
import os
+import base64
+import hashlib
+import hmac
+import json
import platform
import shutil
+import sqlite3
import stat
import uuid
+import time
from pathlib import Path
from types import SimpleNamespace
@@ -78,6 +84,203 @@ def _identity(path):
return (st.st_dev, st.st_ino)
+def test_create_with_working_folder_saves_identity_and_survives_reload(env):
+ project = {"id": "p2", "name": "Existing repo", "createdAt": 1, "updatedAt": 1}
+ saved = studio_db.upsert_chat_project(
+ project, working_folder = (str(env.repo), _identity(env.repo))
+ )
+ assert saved["workingFolder"] == str(env.repo)
+ assert studio_db.available_project_working_folder(studio_db.get_chat_project("p2")) == str(
+ env.repo
+ )
+ assert env.tools._get_workdir("project-p2") == str(env.repo)
+ assert (env.repo / "main.py").read_text() == "print('hi')\n"
+ studio_db.delete_chat_project("p2")
+ assert (env.repo / "main.py").is_file()
+
+
+def test_create_cannot_change_an_existing_projects_folder(env):
+ with pytest.raises(studio_db.ProjectWorkingFolderConflictError):
+ studio_db.upsert_chat_project(
+ {**env.project, "name": "Unexpected rename"},
+ working_folder = (str(env.repo), _identity(env.repo)),
+ )
+ saved = studio_db.get_chat_project("p1")
+ assert saved["workingFolder"] is None
+ assert saved["name"] == "Repo"
+
+
+def test_failed_folder_save_rolls_back_project_creation(env):
+ conn = studio_db.get_connection()
+ try:
+ conn.execute("""CREATE TRIGGER reject_workspace BEFORE UPDATE OF working_folder
+ ON chat_projects BEGIN SELECT RAISE(ABORT, 'workspace unavailable'); END""")
+ conn.commit()
+ finally:
+ conn.close()
+ with pytest.raises(sqlite3.IntegrityError, match = "workspace unavailable"):
+ studio_db.upsert_chat_project(
+ {"id": "p2", "name": "Repo", "createdAt": 1, "updatedAt": 1},
+ working_folder = (str(env.repo), _identity(env.repo)),
+ )
+ assert studio_db.get_chat_project("p2") is None
+
+
+def test_create_route_requires_a_verified_lease(env, monkeypatch):
+ from routes import chat_history
+ from utils import native_path_leases
+
+ seen = []
+
+ def verify(lease, **checks):
+ seen.append((lease, checks))
+ return _grant(env.repo)
+
+ monkeypatch.setattr(native_path_leases, "verify_native_path_lease", verify)
+ body = chat_history.ChatProjectCreate(
+ id = "p2", name = "Repo", createdAt = 1, updatedAt = 1, nativePathLease = "picked-folder"
+ )
+ saved = chat_history.save_project(body, current_subject = "u")
+ assert saved.workingFolder == str(env.repo)
+ assert seen[0][0] == "picked-folder"
+ assert seen[0][1]["expected_path_type"] == "directory"
+ assert seen[0][1]["operation"] == "link-documents"
+
+
+def test_create_route_rejects_invalid_folder_before_creating_project(env, monkeypatch):
+ from routes import chat_history
+
+ def refuse(lease):
+ raise HTTPException(status_code = 400, detail = "Folder selection expired")
+
+ monkeypatch.setattr(chat_history, "_resolve_project_working_folder", refuse)
+ body = chat_history.ChatProjectCreate(
+ id = "p2", name = "Repo", createdAt = 1, updatedAt = 1, nativePathLease = "expired"
+ )
+ with pytest.raises(HTTPException) as caught:
+ chat_history.save_project(body, current_subject = "u")
+ assert caught.value.status_code == 400
+ assert studio_db.get_chat_project("p2") is None
+
+
+def test_create_failure_after_spending_the_grant_is_an_http_error(env, monkeypatch):
+ from routes import chat_history
+
+ monkeypatch.setattr(
+ chat_history,
+ "_resolve_project_working_folder",
+ lambda lease: (str(env.repo), _identity(env.repo)),
+ )
+
+ def locked(*args, **kwargs):
+ raise sqlite3.OperationalError("database is locked")
+
+ monkeypatch.setattr(chat_history, "upsert_chat_project", locked)
+ body = chat_history.ChatProjectCreate(
+ id = "p2", name = "Repo", createdAt = 1, updatedAt = 1, nativePathLease = "picked"
+ )
+ with pytest.raises(HTTPException) as caught:
+ chat_history.save_project(body, current_subject = "u")
+ assert caught.value.status_code == 500
+ plain = chat_history.ChatProjectCreate(id = "p3", name = "Repo", createdAt = 1, updatedAt = 1)
+ with pytest.raises(sqlite3.OperationalError):
+ chat_history.save_project(plain, current_subject = "u")
+
+
+def test_resolution_failure_after_spending_the_grant_is_an_http_error(env, monkeypatch):
+ from routes import chat_history
+
+ def vanished(lease):
+ raise FileNotFoundError("the folder was removed after its grant was verified")
+
+ monkeypatch.setattr(chat_history, "_resolve_project_working_folder", vanished)
+ body = chat_history.ChatProjectCreate(
+ id = "p2", name = "Repo", createdAt = 1, updatedAt = 1, nativePathLease = "picked"
+ )
+ with pytest.raises(HTTPException) as caught:
+ chat_history.save_project(body, current_subject = "u")
+ assert caught.value.status_code == 500
+ assert studio_db.get_chat_project("p2") is None
+
+
+def test_create_with_local_folder_requires_owner(env, monkeypatch):
+ from routes import chat_history
+
+ monkeypatch.setattr(chat_history, "is_owner_context", lambda: False)
+ body = chat_history.ChatProjectCreate(
+ id = "p2", name = "Repo", createdAt = 1, updatedAt = 1, nativePathLease = "picked"
+ )
+ with pytest.raises(HTTPException) as caught:
+ chat_history.save_project(body, current_subject = "managed-account")
+ assert caught.value.status_code == 403
+ assert studio_db.get_chat_project("p2") is None
+
+
+def test_http_create_consumes_real_signed_grant_and_tools_write_to_selected_folder(
+ env, monkeypatch
+):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+ from routes import chat_history
+ from utils import native_path_leases as leases
+
+ secret = b"workspace-test-key-material-32!!!"
+
+ def b64(value):
+ return base64.urlsafe_b64encode(value).decode().rstrip("=")
+
+ monkeypatch.setenv(leases.LEASE_SECRET_ENV, b64(secret))
+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None)
+ monkeypatch.setattr(leases, "_USED_NONCES", {})
+ now = int(time.time() * 1000)
+ device, inode = _identity(env.repo)
+ payload = {
+ "version": 1,
+ "operation": "link-documents",
+ "canonical_path": str(env.repo),
+ "path_kind": "document-folder",
+ "path_type": "directory",
+ "source_kind": "dialog",
+ "token_id_hash": hashlib.sha256(b"test-picker").hexdigest(),
+ "issued_at_ms": now,
+ "expires_at_ms": now + 120_000,
+ "nonce": os.urandom(16).hex(),
+ "display_label": "repo",
+ "size_bytes": None,
+ "modified_ms": None,
+ "device_id": format(device, "x"),
+ "file_id": format(inode, "x"),
+ }
+ encoded = b64(json.dumps(payload).encode())
+ lease = encoded + "." + b64(hmac.new(secret, encoded.encode(), hashlib.sha256).digest())
+ app = FastAPI()
+ app.include_router(chat_history.router, prefix = "/api/chat")
+ app.dependency_overrides[chat_history.get_current_subject] = lambda: "owner-test"
+ body = {"id": "p2", "name": "Repo", "createdAt": 1, "updatedAt": 1, "nativePathLease": lease}
+ with TestClient(app) as client:
+ response = client.post("/api/chat/projects", json = body)
+ assert response.status_code == 200, response.text
+ assert response.json()["workingFolder"] == str(env.repo)
+ assert "nativePathLease" not in response.json()
+ assert client.post("/api/chat/projects", json = {**body, "id": "p3"}).status_code == 400
+ assert studio_db.get_chat_project("p3") is None
+ assert (
+ client.post(
+ "/api/chat/projects",
+ json = {**body, "id": "p4", "nativePathLease": "forged.signature"},
+ ).status_code
+ == 400
+ )
+ assert studio_db.get_chat_project("p4") is None
+ result = env.tools._python_exec(
+ "from pathlib import Path\nPath('written.txt').write_text('saved')\nprint('done')",
+ session_id = "project-p2",
+ )
+ assert "done" in result, result
+ assert (env.repo / "written.txt").read_text() == "saved"
+ assert not (Path(response.json()["sandboxPath"]) / "written.txt").exists()
+
+
def _use_repo(env):
return studio_db.set_chat_project_working_folder("p1", str(env.repo), _identity(env.repo))
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index d463b301a98..d0bc7070ed2 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -257,8 +257,13 @@ export const BUDGET = {
// 6,837,530 B raw, 2,054,604 -> 2,058,588 B transfer against ffd6c3033, one machine and build, Node 24,
// chunk count unchanged at 96), all in the eager chat chunk the fences render from. Raised to that
// build plus the same 160 B raw / 189 B transfer margin.
- transferBytes: 2_058_777,
- rawBytes: 6_837_690,
+ // Choosing a working folder when creating a project (#13873) adds 1,756 B raw / 719 B transfer (6,837,530 ->
+ // 6,839,286 B raw, 2,058,588 -> 2,059,307 B transfer against 6c3a9e9b3, main's build being its limit less the margin;
+ // one machine and build, Node 24, chunk count unchanged at 96): the picker and the folder reconciliation live in the
+ // create dialog, which the eager sidebar imports. Raised to the measured build plus the same 160 B raw / 189 B
+ // transfer margin.
+ transferBytes: 2_059_496,
+ rawBytes: 6_839_446,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/smoke-project-folders-main.tsx b/studio/frontend/smoke-project-folders-main.tsx
new file mode 100644
index 00000000000..ddfacf8d6d3
--- /dev/null
+++ b/studio/frontend/smoke-project-folders-main.tsx
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Production project dialog, with native IPC and HTTP supplied by the Playwright driver.
+import { createRoot } from "react-dom/client";
+import { useState } from "react";
+import {
+ createMemoryHistory,
+ createRootRoute,
+ createRouter,
+ RouterProvider,
+} from "@tanstack/react-router";
+import { NewProjectDialog } from "@/features/chat/components/new-project-dialog";
+import { EditProjectDialog } from "@/features/chat/components/edit-project-dialog";
+import { getChatProject } from "@/features/chat/api/chat-api";
+import type { ProjectRecord } from "@/features/chat/types";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { Toaster } from "sonner";
+import { setApiBase } from "@/lib/api-base";
+import { initializeLocale } from "@/i18n";
+import "./src/index.css";
+
+setApiBase(Number(location.port));
+initializeLocale();
+function App() {
+ const [open, setOpen] = useState(true);
+ const [created, setCreated] = useState<ProjectRecord | null>(null);
+ const [editing, setEditing] = useState(false);
+ return (
+ <TooltipProvider>
+ <div className="aui-root" style={{ minHeight: "100vh" }}>
+ <NewProjectDialog
+ open={open}
+ onOpenChange={setOpen}
+ onCreated={setCreated}
+ />
+ <p data-testid="created">{created?.id}</p>
+ {created && (
+ <button
+ onClick={async () => {
+ setCreated(await getChatProject(created.id));
+ setEditing(true);
+ }}
+ >
+ Edit project
+ </button>
+ )}
+ <EditProjectDialog
+ project={editing ? created : null}
+ onOpenChange={setEditing}
+ onDelete={() => {
+ setEditing(false);
+ setCreated(null);
+ }}
+ />
+ <Toaster />
+ </div>
+ </TooltipProvider>
+ );
+}
+const root = createRootRoute({ component: App });
+const router = createRouter({
+ routeTree: root,
+ history: createMemoryHistory({ initialEntries: ["/"] }),
+});
+createRoot(document.getElementById("root")!).render(
+ <RouterProvider router={router} />,
+);
diff --git a/studio/frontend/smoke-project-folders.html b/studio/frontend/smoke-project-folders.html
new file mode 100644
index 00000000000..9c4aa16456e
--- /dev/null
+++ b/studio/frontend/smoke-project-folders.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="en" class="dark">
+ <head>
+ <meta charset="UTF-8" />
+ <script src="/crypto-boot.js"></script>
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Project folder review</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/smoke-project-folders-main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 1e0a0432327..a0567a8ba11 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -1378,11 +1378,12 @@ export async function getChatAgentsMd(
export async function saveChatProject(
project: ProjectRecord,
+ nativePathLease?: string,
): Promise<ProjectRecord> {
const response = await authFetch("/api/chat/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify(project),
+ body: JSON.stringify({ ...project, ...(nativePathLease ? { nativePathLease } : {}) }),
});
const saved = await parseJsonOrThrow<ProjectRecord>(response);
notifyChatProjectsUpdated();
diff --git a/studio/frontend/src/features/chat/components/edit-project-dialog.tsx b/studio/frontend/src/features/chat/components/edit-project-dialog.tsx
index 21c1ce458f3..b4c37a2082c 100644
--- a/studio/frontend/src/features/chat/components/edit-project-dialog.tsx
+++ b/studio/frontend/src/features/chat/components/edit-project-dialog.tsx
@@ -13,12 +13,9 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
-import {
- pickNativeDocumentFolder,
- useNativePathLeasesSupported,
-} from "@/features/native-intents";
+import type { NativeDocumentFolderSelection } from "@/features/native-intents";
+import { WorkingFolderPicker } from "./working-folder-picker";
import { LinkedFoldersManager } from "@/features/rag";
-import { isTauri } from "@/lib/api-base";
import { toast } from "@/lib/toast";
import { Folder02Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -35,84 +32,42 @@ import {
newInputImeState,
} from "../utils/composer-preferences";
-function ProjectWorkingFolder({ project }: { project: ProjectRecord }) {
- const leasesSupported = useNativePathLeasesSupported();
+function ProjectWorkingFolder({
+ project,
+ disabled,
+ onPendingChange,
+}: {
+ project: ProjectRecord;
+ disabled: boolean;
+ onPendingChange: (pending: boolean) => void;
+}) {
const [folder, setFolder] = useState(project.workingFolder ?? null);
- // Keyed on the folder so an external change re-seeds.
const seed = `${project.id}\n${project.workingFolder ?? ""}`;
const [seededFor, setSeededFor] = useState(seed);
- const [busy, setBusy] = useState(false);
if (seed !== seededFor) {
setSeededFor(seed);
setFolder(project.workingFolder ?? null);
}
- if (!isTauri || !leasesSupported) return null;
- async function apply(lease: string | null) {
- setBusy(true);
- try {
- const saved = await setChatProjectWorkingFolder(project.id, lease);
- setFolder(saved.workingFolder ?? null);
- } catch (err) {
- toast.error("Could not change the project folder", {
- description: err instanceof Error ? err.message : undefined,
- });
- } finally {
- setBusy(false);
- }
- }
-
- async function choose() {
- if (busy) return;
- try {
- const selected = await pickNativeDocumentFolder();
- if (selected) await apply(selected.token);
- } catch (err) {
- toast.error("Could not open folder", {
- description: err instanceof Error ? err.message : undefined,
- });
- }
+ async function apply(selection: NativeDocumentFolderSelection | null) {
+ const saved = await setChatProjectWorkingFolder(
+ project.id,
+ selection?.token ?? null,
+ );
+ setFolder(saved.workingFolder ?? null);
}
return (
- <div className="flex flex-col gap-1.5">
- <h3 className="text-ui-15 font-medium text-foreground">Working folder</h3>
- <p className="text-ui-13 text-muted-foreground">
- Where code and file tools run for every chat in this project.
- </p>
- <div className="mt-0.5 flex items-center gap-2 rounded-[16px] border border-border px-3 py-2">
- <span
- className="min-w-0 flex-1 truncate text-ui-13 text-foreground"
- title={folder ?? undefined}
- >
- {folder ?? "Studio-managed folder"}
- </span>
- {folder && (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- disabled={busy}
- onClick={() => void apply(null)}
- >
- Use managed folder
- </Button>
- )}
- <Button
- type="button"
- variant="outline"
- size="sm"
- disabled={busy}
- onClick={() => void choose()}
- >
- {folder ? "Change…" : "Choose folder…"}
- </Button>
- </div>
- </div>
+ <WorkingFolderPicker
+ value={folder}
+ onChange={apply}
+ disabled={disabled}
+ onPendingChange={onPendingChange}
+ />
);
}
-/** Name, instructions and linked folders for one project. Opened from the folder row's "Edit".
+/** Name, instructions, working folder and source folders for one project.
* Deleting hands back to the caller, which owns the confirmation. */
export function EditProjectDialog({
project,
@@ -127,6 +82,7 @@ export function EditProjectDialog({
const [name, setName] = useState(project?.name ?? "");
const [instructions, setInstructions] = useState(project?.instructions ?? "");
const [busy, setBusy] = useState(false);
+ const [folderBusy, setFolderBusy] = useState(false);
const nameImeRef = useRef(newInputImeState());
const nameImeHandlers = {
onFocus: () => inputImeHandlers(nameImeRef.current).onFocus(),
@@ -144,6 +100,7 @@ export function EditProjectDialog({
setName(project?.name ?? "");
setInstructions(project?.instructions ?? "");
setBusy(false);
+ setFolderBusy(false);
}
if (!project) return null;
@@ -158,12 +115,12 @@ export function EditProjectDialog({
const dirty = nameChanged || instructionsChanged;
function close() {
- if (busy) return;
+ if (busy || folderBusy) return;
onOpenChange(false);
}
async function save() {
- if (busy || !trimmedName) return;
+ if (busy || folderBusy || !trimmedName) return;
if (!dirty) {
onOpenChange(false);
return;
@@ -215,8 +172,8 @@ export function EditProjectDialog({
<DialogHeader>
<DialogTitle className="text-ui-21">Edit project</DialogTitle>
<DialogDescription className="sr-only">
- Rename this project, set the instructions its chats follow, and manage the local
- folders it indexes.
+ Rename this project, set instructions, choose its working folder,
+ and manage source folders for document search.
</DialogDescription>
</DialogHeader>
{/* The same name field the create dialog uses. */}
@@ -230,7 +187,10 @@ export function EditProjectDialog({
</span>
{/* The rule that separates the icon from the field. The container drops its border in
dark mode, where --border goes with it, so the rule carries its own tint there. */}
- <span aria-hidden="true" className="my-3 w-px bg-border dark:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))]" />
+ <span
+ aria-hidden="true"
+ className="my-3 w-px bg-border dark:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))]"
+ />
<input
value={name}
onChange={(e) => setName(e.target.value)}
@@ -251,7 +211,7 @@ export function EditProjectDialog({
}
}}
autoFocus={true}
- disabled={busy}
+ disabled={busy || folderBusy}
maxLength={120}
placeholder="Project name"
aria-label="Project name"
@@ -272,20 +232,26 @@ export function EditProjectDialog({
id="edit-project-instructions"
value={instructions}
onChange={(e) => setInstructions(e.target.value)}
- disabled={busy}
+ disabled={busy || folderBusy}
rows={4}
placeholder="How should the model answer in this project?"
className="mt-0.5 resize-none rounded-[16px]"
/>
</div>
- <ProjectWorkingFolder project={project} />
+ <ProjectWorkingFolder
+ key={project.id}
+ project={project}
+ disabled={busy}
+ onPendingChange={setFolderBusy}
+ />
{/* The Sources tab's own manager, so a folder linked here is linked there. */}
<div className="flex flex-col gap-1.5">
<h3 className="text-ui-15 font-medium text-foreground">
Source folders
</h3>
<p className="text-ui-13 text-muted-foreground">
- Indexed and kept in sync, for every chat in this project to search.
+ Keep supported documents in sync for chats to search. Linking does
+ not grant access to edit the original files.
</p>
<div className="mt-0.5">
<LinkedFoldersManager
@@ -298,7 +264,7 @@ export function EditProjectDialog({
<Button
type="button"
variant="destructive"
- disabled={busy}
+ disabled={busy || folderBusy}
onClick={() => {
onOpenChange(false);
onDelete(project);
@@ -310,7 +276,7 @@ export function EditProjectDialog({
<Button
type="button"
variant="ghost"
- disabled={busy}
+ disabled={busy || folderBusy}
onClick={close}
>
Cancel
@@ -318,7 +284,7 @@ export function EditProjectDialog({
<Button
type="button"
onClick={() => void save()}
- disabled={busy || !trimmedName}
+ disabled={busy || folderBusy || !trimmedName}
>
{busy ? "Saving…" : "Save"}
</Button>
diff --git a/studio/frontend/src/features/chat/components/new-project-dialog.tsx b/studio/frontend/src/features/chat/components/new-project-dialog.tsx
index b844ce63c0f..8975a71d058 100644
--- a/studio/frontend/src/features/chat/components/new-project-dialog.tsx
+++ b/studio/frontend/src/features/chat/components/new-project-dialog.tsx
@@ -5,6 +5,8 @@ import { useNavigate } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
+import type { NativeDocumentFolderSelection } from "@/features/native-intents";
+import { WorkingFolderPicker } from "./working-folder-picker";
import {
Dialog,
DialogContent,
@@ -26,6 +28,11 @@ import { toast } from "@/lib/toast";
import { Folder02Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ getChatProject,
+ notifyChatProjectsUpdated,
+ setChatProjectWorkingFolder,
+} from "../api/chat-api";
import { createChatProject } from "../hooks/use-chat-projects";
import { useChatRuntimeStore } from "../stores/chat-runtime-store";
import type { ProjectRecord } from "../types";
@@ -63,6 +70,13 @@ export function NewProjectDialog({
const [staged, setStaged] = useState<StagedSource[]>([]);
const [folders, setFolders] = useState<StagedFolder[]>([]);
const [busy, setBusy] = useState(false);
+ const [workingFolder, setWorkingFolder] =
+ useState<NativeDocumentFolderSelection | null>(null);
+ const [pickingWorkingFolder, setPickingWorkingFolder] = useState(false);
+ const [needsReselect, setNeedsReselect] = useState(false);
+ const [createdProject, setCreatedProject] = useState<ProjectRecord | null>(
+ null,
+ );
// A desktop drop reaches `staged` only once its native registration settles. Creating before
// then would upload without the files the user just dropped.
const [stagingDrop, setStagingDrop] = useState(false);
@@ -80,6 +94,11 @@ export function NewProjectDialog({
// Uploads outlive this component, so a slow one must not yank the user to the new project after
// they have navigated away.
const mounted = useRef(true);
+ // One id per draft, so a retried create lands on the same project instead of a second one.
+ const projectId = useRef(crypto.randomUUID());
+ // Single-use grants plus lost responses: reconcile each submit against what was sent vs confirmed.
+ const sentLeases = useRef(new Set<string>());
+ const appliedLease = useRef<string | null>(null);
useEffect(() => {
// Set on setup, not just cleared on cleanup: StrictMode replays setup/cleanup/setup, which would
// otherwise leave this false forever.
@@ -95,25 +114,58 @@ export function NewProjectDialog({
setFolders([]);
setStagingDrop(false);
setPickingFolder(false);
+ setWorkingFolder(null);
+ setPickingWorkingFolder(false);
+ setNeedsReselect(false);
+ setCreatedProject(null);
+ projectId.current = crypto.randomUUID();
+ sentLeases.current = new Set();
+ appliedLease.current = null;
}
// Every close path routes through here: callers keep this mounted, so a draft left behind would
// resurface, and upload, on the next project.
function close() {
- if (busy) return;
+ if (busy || pickingWorkingFolder) return;
reset();
onOpenChange(false);
}
async function commitCreate() {
const trimmed = name.trim();
- if (!trimmed || busy || stagingDrop || pickingFolder) return;
+ if (
+ !trimmed ||
+ busy ||
+ stagingDrop ||
+ pickingFolder ||
+ pickingWorkingFolder ||
+ needsReselect
+ )
+ return;
setBusy(true);
// Sidebar callers keep this mounted across routes, so unmounting alone cannot tell whether the
// user has moved on during a slow upload.
const origin = currentRoute();
+ let project = createdProject;
+ const token = workingFolder?.token ?? null;
try {
- const project = await createChatProject(trimmed);
+ if (!project) {
+ if (token) sentLeases.current.add(token);
+ project = await createChatProject(trimmed, token ?? undefined, projectId.current);
+ if (token && project.workingFolder) appliedLease.current = token;
+ setCreatedProject(project);
+ }
+ // A backend predating create-time folders ignores the lease, leaving it unspent.
+ if (token && appliedLease.current !== token) {
+ sentLeases.current.add(token);
+ project = await setChatProjectWorkingFolder(project.id, token);
+ appliedLease.current = token;
+ setCreatedProject(project);
+ } else if (!token && project.workingFolder) {
+ project = await setChatProjectWorkingFolder(project.id, null);
+ appliedLease.current = null;
+ setCreatedProject(project);
+ }
// Upload before closing so the Sources panel lists them on first fetch.
// Folders first: their leases expire in minutes, and uploads can be slow.
await linkStagedFolders(project.id, folders);
@@ -132,6 +184,20 @@ export function NewProjectDialog({
runtime.setActiveProjectId(project.id);
navigate({ to: "/chat", search: { project: project.id } });
} catch (err) {
+ // A replay 400s on a grant its lost first attempt already spent: re-read what was saved.
+ if (token && appliedLease.current !== token) {
+ const saved = await getChatProject(projectId.current).catch(() => null);
+ if (saved) {
+ project = saved;
+ setCreatedProject(saved);
+ notifyChatProjectsUpdated();
+ // With one grant ever sent, a saved folder can only be this one.
+ if (saved.workingFolder && sentLeases.current.size === 1) {
+ appliedLease.current = token;
+ }
+ }
+ if (appliedLease.current !== token) setNeedsReselect(true);
+ }
toast.error("Failed to create project", {
description: err instanceof Error ? err.message : undefined,
});
@@ -182,13 +248,23 @@ export function NewProjectDialog({
}
}}
autoFocus={true}
- disabled={busy}
+ disabled={busy || !!createdProject}
maxLength={120}
placeholder="Project name"
aria-label="Project name"
className="min-w-0 flex-1 bg-transparent py-4 pr-4 pl-2.5 text-base outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"
/>
</div>
+ <WorkingFolderPicker
+ value={workingFolder?.displayName ?? null}
+ onChange={(value) => {
+ setWorkingFolder(value);
+ setNeedsReselect(false);
+ }}
+ disabled={busy || (!!createdProject && !needsReselect)}
+ needsReselect={needsReselect}
+ onPendingChange={setPickingWorkingFolder}
+ />
<ProjectSourceDropzone
staged={staged}
onChange={setStaged}
@@ -202,19 +278,33 @@ export function NewProjectDialog({
onPendingChange={setPickingFolder}
/>
<DialogFooter className="flex-wrap gap-2 sm:justify-end">
- <Button type="button" variant="ghost" disabled={busy} onClick={close}>
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={busy || pickingWorkingFolder}
+ onClick={close}
+ >
Cancel
</Button>
<Button
type="button"
onClick={() => void commitCreate()}
- disabled={!name.trim() || busy || stagingDrop || pickingFolder}
+ disabled={
+ !name.trim() ||
+ busy ||
+ stagingDrop ||
+ pickingFolder ||
+ pickingWorkingFolder ||
+ needsReselect
+ }
>
{busy
? "Creating…"
- : stagingDrop || pickingFolder
- ? "Adding sources…"
- : submitLabel}
+ : pickingWorkingFolder
+ ? "Choosing folder…"
+ : stagingDrop || pickingFolder
+ ? "Adding sources…"
+ : submitLabel}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/studio/frontend/src/features/chat/components/working-folder-picker.tsx b/studio/frontend/src/features/chat/components/working-folder-picker.tsx
new file mode 100644
index 00000000000..0b32f4959e2
--- /dev/null
+++ b/studio/frontend/src/features/chat/components/working-folder-picker.tsx
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Button } from "@/components/ui/button";
+import { useIsAccountOwner } from "@/features/auth";
+import {
+ type NativeDocumentFolderSelection,
+ pickNativeDocumentFolder,
+ useNativePathLeasesSupported,
+} from "@/features/native-intents";
+import { isTauri } from "@/lib/api-base";
+import { toast } from "@/lib/toast";
+import { useEffect, useRef, useState } from "react";
+
+export function WorkingFolderPicker({
+ value,
+ onChange,
+ disabled,
+ needsReselect = false,
+ onPendingChange,
+}: {
+ value: string | null;
+ onChange: (
+ value: NativeDocumentFolderSelection | null,
+ ) => void | Promise<void>;
+ disabled?: boolean;
+ needsReselect?: boolean;
+ onPendingChange?: (pending: boolean) => void;
+}) {
+ const isOwner = useIsAccountOwner();
+ const supported = useNativePathLeasesSupported();
+ const mounted = useRef(true);
+ const pending = useRef(false);
+ const [picking, setPicking] = useState(false);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+ const available = isTauri && supported && isOwner;
+
+ async function change(choose: boolean) {
+ if ((choose && !available) || disabled || pending.current) return;
+ pending.current = true;
+ setPicking(true);
+ onPendingChange?.(true);
+ try {
+ const selected = choose ? await pickNativeDocumentFolder() : null;
+ if (mounted.current && (!choose || selected)) await onChange(selected);
+ } catch (error) {
+ if (mounted.current) {
+ toast.error("Could not change the working folder", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ }
+ } finally {
+ pending.current = false;
+ if (mounted.current) {
+ setPicking(false);
+ onPendingChange?.(false);
+ }
+ }
+ }
+
+ return (
+ <section className="min-w-0 space-y-2" aria-label="Working folder">
+ <h3 className="text-ui-15 font-medium text-foreground">Working folder</h3>
+ <p className="text-ui-13 text-muted-foreground">
+ Where code and file tools run for every chat in this project.
+ </p>
+ <div className="flex min-w-0 items-center gap-2 rounded-[16px] border border-border px-3 py-2">
+ <span
+ className="min-w-0 flex-1 truncate text-sm"
+ title={value ?? undefined}
+ >
+ {value ?? "Studio-managed folder"}
+ </span>
+ {value && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={disabled || picking}
+ onClick={() => void change(false)}
+ >
+ Use managed folder
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={!available || disabled || picking}
+ onClick={() => void change(true)}
+ >
+ {picking ? "Choosing…" : value ? "Change…" : "Choose folder…"}
+ </Button>
+ </div>
+ {(needsReselect || !available) && (
+ <p
+ className="text-ui-11 text-muted-foreground"
+ role={needsReselect ? "alert" : undefined}
+ >
+ {needsReselect
+ ? "Choose the folder again to retry, or use the managed folder."
+ : !isTauri
+ ? "Choose an existing folder in Unsloth Desktop, or use the managed folder."
+ : !isOwner
+ ? "Only the owner can choose a local working folder."
+ : "Folder selection is unavailable with this connection."}
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-projects.ts b/studio/frontend/src/features/chat/hooks/use-chat-projects.ts
index b009bf000ab..40a53653611 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-projects.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-projects.ts
@@ -149,8 +149,12 @@ export function useChatProjects(): {
return { projects, isLoading, hasLoaded };
}
-export async function createChatProject(name: string): Promise<ProjectRecord> {
- return createStoredChatProject(name);
+export async function createChatProject(
+ name: string,
+ nativePathLease?: string,
+ id?: string,
+): Promise<ProjectRecord> {
+ return createStoredChatProject(name, nativePathLease, id);
}
export async function renameChatProject(
diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
index 117d8ecffa3..a151811af8a 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -1021,6 +1021,8 @@ export async function getStoredChatProject(
export async function createStoredChatProject(
name: string,
+ nativePathLease?: string,
+ id: string = crypto.randomUUID(),
): Promise<ProjectRecord> {
const trimmed = name.trim();
if (!trimmed) {
@@ -1028,13 +1030,13 @@ export async function createStoredChatProject(
}
const now = Date.now();
return saveChatProject({
- id: crypto.randomUUID(),
+ id,
name: trimmed,
instructions: "",
archived: false,
createdAt: now,
updatedAt: now,
- });
+ }, nativePathLease);
}
export async function updateStoredChatProject(
diff --git a/studio/frontend/src/features/rag/components/linked-folders-manager.tsx b/studio/frontend/src/features/rag/components/linked-folders-manager.tsx
index 57c12f16324..de9829d612e 100644
--- a/studio/frontend/src/features/rag/components/linked-folders-manager.tsx
+++ b/studio/frontend/src/features/rag/components/linked-folders-manager.tsx
@@ -22,6 +22,8 @@ import {
import { Progress } from "@/components/ui/progress";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
+import { isTauri } from "@/lib/api-base";
+import { SOURCE_FOLDER_DESCRIPTION, sourceFolderUnavailableMessage } from "./source-folder-copy";
import { RefreshGlyph } from "@/lib/refresh-icon";
import { FolderAddIcon, FolderSyncIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -220,7 +222,7 @@ export function LinkedFoldersManager({
>
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>Unlink folder and remove files?</AlertDialogTitle>
+ <AlertDialogTitle>Unlink folder and remove indexed documents?</AlertDialogTitle>
<AlertDialogDescription>
This will unlink &quot;{removeIndexFolder?.name}&quot; and remove all
documents it manages from the index. The files on disk will not be
@@ -325,7 +327,7 @@ export function LinkedFoldersManager({
title={
manager.desktopSupported
? "Choose a local folder"
- : "Requires the managed desktop backend"
+ : sourceFolderUnavailableMessage(isTauri)
}
className={cn(
rowClass,
@@ -349,8 +351,8 @@ export function LinkedFoldersManager({
native folder picker, and the rows already linked keep syncing regardless. */}
{!manager.desktopSupported ? (
<p className="px-1 text-ui-11 text-muted-foreground">
- Linking a folder needs the managed desktop backend. Folders already
- linked stay synced.
+ {sourceFolderUnavailableMessage(isTauri)} Existing source folders
+ continue to sync.
</p>
) : null}
{removeIndexConfirm}
@@ -363,12 +365,12 @@ export function LinkedFoldersManager({
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h3 className="text-sm font-medium text-foreground">
- Linked local folders
+ Source folders
</h3>
<p className="text-xs leading-snug text-muted-foreground">
{manager.desktopSupported
- ? "Keep supported documents indexed as this folder changes."
- : "Existing linked folders stay synced; linking requires the managed desktop backend."}
+ ? SOURCE_FOLDER_DESCRIPTION
+ : `${sourceFolderUnavailableMessage(isTauri)} Existing source folders continue to sync.`}
</p>
</div>
{scope ? (
@@ -382,7 +384,7 @@ export function LinkedFoldersManager({
title={
manager.desktopSupported
? "Choose a local folder"
- : "Requires the managed desktop backend"
+ : sourceFolderUnavailableMessage(isTauri)
}
>
{manager.mutating ? (
@@ -390,7 +392,7 @@ export function LinkedFoldersManager({
) : (
<HugeiconsIcon icon={FolderSyncIcon} strokeWidth={1.75} className="size-3.5" />
)}
- Link folder
+ Add folder
</Button>
) : null}
</div>
@@ -401,7 +403,7 @@ export function LinkedFoldersManager({
</div>
) : manager.folders.length === 0 ? (
<div className="rounded-xl border border-dashed px-4 py-5 text-center text-xs text-muted-foreground">
- No linked folders.
+ No source folders.
</div>
) : (
<ul className="flex flex-col gap-1.5">
diff --git a/studio/frontend/src/features/rag/components/project-folder-picker.tsx b/studio/frontend/src/features/rag/components/project-folder-picker.tsx
index b49de9b4551..12a3ff65466 100644
--- a/studio/frontend/src/features/rag/components/project-folder-picker.tsx
+++ b/studio/frontend/src/features/rag/components/project-folder-picker.tsx
@@ -24,6 +24,7 @@ import {
useState,
} from "react";
import { FOLDER_CARD_CLASS, FOLDER_ROW_CLASS } from "./linked-folders-manager";
+import { SOURCE_FOLDER_DESCRIPTION, sourceFolderUnavailableMessage } from "./source-folder-copy";
import { EXPIRY_GRACE_MS } from "./staged-source";
import {
isFolderExpired,
@@ -99,7 +100,7 @@ export function ProjectFolderPicker({
return (
<div className="space-y-2.5">
- <p className="text-ui-15 font-medium text-foreground">Linked folders</p>
+ <p className="text-ui-15 font-medium text-foreground">Source folders</p>
<div className={FOLDER_CARD_CLASS}>
{folders.map((folder) => (
<div key={folder.token} className={FOLDER_ROW_CLASS}>
@@ -136,7 +137,7 @@ export function ProjectFolderPicker({
title={
supported
? "Choose a local folder"
- : "Requires the managed desktop backend"
+ : sourceFolderUnavailableMessage(isTauri)
}
className={cn(
FOLDER_ROW_CLASS,
@@ -157,8 +158,8 @@ export function ProjectFolderPicker({
</div>
<p className="px-1 text-ui-11 text-muted-foreground">
{supported
- ? "Indexed and kept in sync, for every chat in this project to search."
- : "Linking a folder needs the managed desktop backend."}
+ ? SOURCE_FOLDER_DESCRIPTION
+ : sourceFolderUnavailableMessage(isTauri)}
</p>
</div>
);
diff --git a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
index 1d355e3f974..185295a45b8 100644
--- a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
+++ b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
@@ -394,7 +394,7 @@ export function ProjectSourceDropzone({
className="size-6 text-muted-foreground"
/>
<span className="text-sm text-muted-foreground">
- Add files every chat in this project can read
+ Add documents for chats in this project to search
</span>
</button>
) : (
diff --git a/studio/frontend/src/features/rag/components/source-folder-copy.ts b/studio/frontend/src/features/rag/components/source-folder-copy.ts
new file mode 100644
index 00000000000..f17a2c16fec
--- /dev/null
+++ b/studio/frontend/src/features/rag/components/source-folder-copy.ts
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export const SOURCE_FOLDER_DESCRIPTION =
+ "Keep supported documents in sync for chats to search. Linking does not grant access to edit the original files.";
+
+export function sourceFolderUnavailableMessage(isDesktop: boolean): string {
+ return isDesktop
+ ? "Folder selection is unavailable with this connection. You can still upload documents."
+ : "Open Unsloth Desktop to add a source folder. You can still upload documents.";
+}
diff --git a/studio/frontend/tests/edit-project-dialog.test.ts b/studio/frontend/tests/edit-project-dialog.test.ts
index f958296f345..11bdf175a57 100644
--- a/studio/frontend/tests/edit-project-dialog.test.ts
+++ b/studio/frontend/tests/edit-project-dialog.test.ts
@@ -92,8 +92,8 @@ test("name and instructions are saved as separate writes", () => {
// Nothing edited is not a write at all, just a close.
assert.match(DIALOG, /if \(!dirty\) \{\n\s*onOpenChange\(false\);/);
// An empty name is not a rename: it would leave the folder row with nothing to show.
- assert.match(DIALOG, /if \(busy \|\| !trimmedName\) return;/);
- assert.match(DIALOG, /disabled=\{busy \|\| !trimmedName\}/);
+ assert.match(DIALOG, /if \(busy \|\| folderBusy \|\| !trimmedName\) return;/);
+ assert.match(DIALOG, /disabled=\{busy \|\| folderBusy \|\| !trimmedName\}/);
});
// The draft is the open project's. Reseeding on id keeps the last project's text from being saved
@@ -104,7 +104,7 @@ test("the draft follows whichever project is open", () => {
/if \(\(project\?\.id \?\? null\) !== seededFor\) \{\n\s*setSeededFor\(project\?\.id \?\? null\);\n\s*setName\(project\?\.name \?\? ""\);\n\s*setInstructions\(project\?\.instructions \?\? ""\);/,
);
// And a save in flight cannot be escaped out from under.
- assert.match(DIALOG, /function close\(\) \{\n\s*if \(busy\) return;/);
+ assert.match(DIALOG, /function close\(\) \{\n\s*if \(busy \|\| folderBusy\) return;/);
});
// Enter commits the name field; the instructions box needs its newlines, so the chord commits
@@ -129,6 +129,6 @@ test("the dialog commits on Enter and on the chord", () => {
test("delete is a destructive button, and the caller still confirms it", () => {
assert.match(
DIALOG,
- /<Button\n\s*type="button"\n\s*variant="destructive"\n\s*disabled=\{busy\}\n\s*onClick=\{\(\) => \{\n\s*onOpenChange\(false\);\n\s*onDelete\(project\);/,
+ /<Button\n\s*type="button"\n\s*variant="destructive"\n\s*disabled=\{busy \|\| folderBusy\}\n\s*onClick=\{\(\) => \{\n\s*onOpenChange\(false\);\n\s*onDelete\(project\);/,
);
});
diff --git a/studio/frontend/tests/linked-folders-lease-gate.test.ts b/studio/frontend/tests/linked-folders-lease-gate.test.ts
index 329f9f997f7..d917926c0b3 100644
--- a/studio/frontend/tests/linked-folders-lease-gate.test.ts
+++ b/studio/frontend/tests/linked-folders-lease-gate.test.ts
@@ -54,16 +54,8 @@ test("link() refuses without the capability, not just the button", () => {
);
});
-test("the unsupported branch names the managed backend, not the desktop app", () => {
- // The old copy told a desktop user to use the desktop app they were already in.
- assert.ok(
- !MANAGER.includes("link new folders in the desktop app"),
- "the unsupported copy must not tell a desktop user to use the desktop app",
- );
- assert.ok(
- MANAGER.includes("managed desktop backend"),
- "the unsupported copy and tooltip should name the managed backend",
- );
+test("the unsupported branch distinguishes desktop connections from browser clients", () => {
+ assert.ok(MANAGER.includes("sourceFolderUnavailableMessage(isTauri)"));
});
test("the capability is read from /api/health and only latches on true", () => {
diff --git a/studio/frontend/tests/new-project-working-folder.test.ts b/studio/frontend/tests/new-project-working-folder.test.ts
new file mode 100644
index 00000000000..c3443231afe
--- /dev/null
+++ b/studio/frontend/tests/new-project-working-folder.test.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Grants are single-use and Desktop authFetch replays after network errors; behaviour is driven
+// end to end by tests/studio/playwright_project_folders.py, these pin the shape.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readSrcAsync } from "./helpers/kit.ts";
+
+const DIALOG = await readSrcAsync(
+ "features/chat/components/new-project-dialog.tsx",
+);
+const BODY = DIALOG.slice(DIALOG.indexOf("async function commitCreate()"));
+const TRY = BODY.slice(0, BODY.indexOf("} catch (err) {"));
+const CATCH = BODY.slice(BODY.indexOf("} catch (err) {"));
+
+test("a retried create reuses the draft's project id", () => {
+ assert.match(DIALOG, /const projectId = useRef\(crypto\.randomUUID\(\)\);/);
+ assert.match(TRY, /createChatProject\(trimmed, token \?\? undefined, projectId\.current\)/);
+ assert.match(DIALOG, /projectId\.current = crypto\.randomUUID\(\);/);
+});
+
+test("every submit reconciles the saved folder with the current choice", () => {
+ const create = TRY.indexOf("await createChatProject(");
+ const put = TRY.indexOf("await setChatProjectWorkingFolder(project.id, token)");
+ const clear = TRY.indexOf("await setChatProjectWorkingFolder(project.id, null)");
+ const links = TRY.indexOf("await linkStagedFolders(project.id, folders)");
+ assert.ok(create > 0 && create < put && put < clear && clear < links);
+ // Outside the `if (!project)` create branch, so a reused project is reconciled too.
+ assert.match(TRY, /\}\n\s*\/\/[^\n]*\n\s*if \(token && appliedLease\.current !== token\) \{/);
+ assert.match(TRY, /\} else if \(!token && project\.workingFolder\) \{/);
+ assert.match(TRY, /if \(token && project\.workingFolder\) appliedLease\.current = token;/);
+});
+
+test("a failure re-reads the project and trusts its folder only when one grant was ever sent", () => {
+ const read = CATCH.indexOf("await getChatProject(projectId.current)");
+ const reselect = CATCH.indexOf("setNeedsReselect(true)");
+ assert.ok(read > 0 && read < reselect);
+ assert.ok(CATCH.indexOf("notifyChatProjectsUpdated()") < reselect, "an adopted project is published");
+ assert.match(CATCH, /saved\.workingFolder && sentLeases\.current\.size === 1/);
+ assert.match(CATCH, /if \(appliedLease\.current !== token\) setNeedsReselect\(true\);/);
+ assert.match(DIALOG, /sentLeases\.current = new Set\(\);\n\s*appliedLease\.current = null;/);
+});
+
+test("a failed folder save re-enables the picker", () => {
+ assert.match(
+ DIALOG,
+ /disabled=\{busy \|\| \(!!createdProject && !needsReselect\)\}\n\s*needsReselect=\{needsReselect\}/,
+ );
+});
diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.json
index 9276e6fcaee..b8cbd170074 100644
--- a/studio/frontend/tsconfig.app.json
+++ b/studio/frontend/tsconfig.app.json
@@ -31,6 +31,7 @@
"include": [
"src",
"smoke-ansi-main.tsx",
+ "smoke-project-folders-main.tsx",
"smoke-composer-icons-main.tsx",
"smoke-tooltip-switch-main.tsx",
"smoke-titlebar-blur-main.tsx",
diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rs
index 27b3a20d5d2..f95f1416e5c 100644
--- a/studio/src-tauri/src/native_intents.rs
+++ b/studio/src-tauri/src/native_intents.rs
@@ -530,7 +530,7 @@ pub async fn pick_native_document_folder(
let (tx, rx) = tokio::sync::oneshot::channel();
app.dialog()
.file()
- .set_title("Link a document folder")
+ .set_title("Choose a local folder")
.pick_folder(move |path| {
let _ = tx.send(path);
});
diff --git a/tests/studio/playwright_project_folders.py b/tests/studio/playwright_project_folders.py
new file mode 100644
index 00000000000..f03b3ffcbbe
--- /dev/null
+++ b/tests/studio/playwright_project_folders.py
@@ -0,0 +1,489 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Drive real project dialogs with stubbed native IPC and HTTP.
+
+Starts its own vite server unless --base-url names a running frontend. --before-url
+optionally captures the same dialog from a second frontend. No model, real native
+picker, or host filesystem grant is involved.
+"""
+
+import asyncio
+import argparse
+import json
+import os
+import sys
+from pathlib import Path
+from playwright.async_api import async_playwright, expect
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import start_vite, stop_process, wait_for_smoke_page # noqa: E402
+
+parser = argparse.ArgumentParser(description = __doc__)
+parser.add_argument("--base-url")
+parser.add_argument("--before-url")
+parser.add_argument("--out", type = Path, default = Path("work/project-folders-review"))
+ARGS = parser.parse_args()
+OUT = ARGS.out.resolve()
+
+
+async def scene(
+ browser,
+ label,
+ base_url,
+ mode,
+ *,
+ exercise = False,
+ reject = False,
+ cancel = False,
+ reset = False,
+ pending = False,
+ narrow = False,
+ legacy = False,
+ lost = False,
+ lost_put = False,
+):
+ context = await browser.new_context(
+ viewport = {"width": 390, "height": 750} if narrow else {"width": 1100, "height": 950},
+ device_scale_factor = 1,
+ )
+ await context.add_init_script("""
+ localStorage.setItem('unsloth_auth_token', 'review.'+btoa(JSON.stringify({sub:'unsloth', role:'owner'}))+'.review');
+ window.__picks = 0;
+ """)
+ await context.add_init_script(
+ f"window.__cancelPick={str(cancel).lower()}; window.__delayPick={str(pending).lower()};"
+ )
+ if mode == "guest":
+ await context.add_init_script("""
+ localStorage.setItem('unsloth_auth_token', 'review.'+btoa(JSON.stringify({sub:'member',role:'member'}))+'.review');
+ """)
+ if mode != "browser":
+ await context.add_init_script("""
+ window.__TAURI_INTERNALS__ = {
+ metadata: {currentWindow:{label:'main'}, currentWebview:{label:'main'}},
+ transformCallback: () => 1, unregisterCallback: () => {},
+ invoke: async (command) => {
+ if(command === 'native_path_leases_usable') return true;
+ if(command === 'pick_native_document_folder') {
+ window.__picks++;
+ if(window.__delayPick) return new Promise(resolve => {window.__resolvePick=resolve;});
+ if(window.__cancelPick) return null;
+ return {token:'native-grant-'+window.__picks, displayName:'Existing project', expiresAtMs:Date.now()+120000};
+ }
+ if(command.endsWith('scale_factor')) return 1;
+ if(command.endsWith('listen')) return 1;
+ return null;
+ }
+ };
+ """)
+ requests = []
+ folder_requests = []
+ stored = {}
+ failures = int(reject)
+ spent = set()
+
+ async def api(route):
+ nonlocal failures
+ req = route.request
+ path = req.url.split("/api/", 1)[-1]
+ if path == "health":
+ return await route.fulfill(
+ json = {"native_path_leases_supported": mode in ("desktop", "guest")}
+ )
+ if path == "chat/projects" and req.method == "POST":
+ data = req.post_data_json
+ requests.append(data)
+ if data.get("nativePathLease") in spent:
+ return await route.fulfill(status = 400, json = {"detail": "Grant already used"})
+ if failures:
+ failures -= 1
+ return await route.fulfill(status = 400, json = {"detail": "Folder selection expired"})
+ # An older backend ignores the lease field.
+ granted = data.get("nativePathLease") and not legacy
+ if granted:
+ spent.add(data["nativePathLease"])
+ stored.update(
+ {**data, "workingFolder": "/review/existing-project" if granted else None}
+ )
+ if lost and len(requests) == 1:
+ # Committed, but the response never arrives.
+ return await route.abort("connectionreset")
+ return await route.fulfill(json = stored)
+ if path.endswith("/working-folder"):
+ folder_requests.append(
+ {"method": req.method, "body": req.post_data_json if req.method == "PUT" else None}
+ )
+ put_lease = (
+ (req.post_data_json or {}).get("nativePathLease") if req.method == "PUT" else None
+ )
+ if put_lease in spent:
+ return await route.fulfill(status = 400, json = {"detail": "Grant already used"})
+ if put_lease and lost_put:
+ spent.add(put_lease)
+ stored["workingFolder"] = "/review/alternate-project"
+ return await route.abort("connectionreset")
+ if await page.evaluate("Boolean(window.__rejectUpdate)"):
+ await page.evaluate("window.__rejectUpdate=false")
+ return await route.fulfill(status = 400, json = {"detail": "Folder selection expired"})
+ if await page.evaluate("Boolean(window.__delayUpdate)"):
+ await page.wait_for_function("!window.__delayUpdate")
+ stored["workingFolder"] = "/review/alternate-project" if req.method == "PUT" else None
+ return await route.fulfill(json = stored)
+ if path.startswith("chat/projects/") and req.method == "GET":
+ if path.split("/")[2] != stored.get("id"):
+ return await route.fulfill(status = 404, json = {"detail": "Project not found"})
+ return await route.fulfill(json = stored)
+ return await route.fulfill(json = {})
+
+ await context.route(f"{base_url}/api/**", api)
+ page = await context.new_page()
+ errors = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ page.on("pageerror", lambda error: print("PAGE ERROR", label, str(error), flush = True))
+ print("SCENE", label, flush = True)
+ await page.goto(f"{base_url}/smoke-project-folders.html")
+ dialog = page.get_by_role("dialog")
+ await expect(dialog).to_be_visible(timeout = 90000)
+ await page.get_by_label("Project name", exact = True).fill("My project")
+ observations = {
+ "workingFolderControls": await dialog.get_by_role(
+ "button", name = "Choose folder…", exact = True
+ ).count(),
+ "sourceFolderLabels": await dialog.get_by_text("Source folders", exact = True).count(),
+ "technicalBackendCopy": "managed desktop backend" in await dialog.inner_text(),
+ }
+ await page.evaluate("document.fonts.ready")
+ await page.screenshot(path = str(OUT / f"{label}.png"), animations = "disabled")
+ await dialog.screenshot(path = str(OUT / f"{label}-dialog.png"), animations = "disabled")
+ if exercise:
+ if mode == "desktop":
+ choose = dialog.get_by_role("button", name = "Choose folder…", exact = True)
+ await expect(choose).to_be_enabled()
+ await choose.click()
+ if pending:
+ await expect(
+ dialog.get_by_role("button", name = "Choosing folder…", exact = True)
+ ).to_be_disabled()
+ await page.keyboard.press("Escape")
+ await expect(dialog).to_be_visible()
+ # The button flips before the native pick is invoked.
+ await page.wait_for_function("typeof window.__resolvePick === 'function'")
+ await page.evaluate("window.__resolvePick(null)")
+ if cancel or pending:
+ await expect(
+ dialog.get_by_text("Studio-managed folder", exact = True)
+ ).to_be_visible()
+ await expect(choose).to_be_enabled()
+ else:
+ await expect(dialog.get_by_text("Existing project", exact = True)).to_be_visible()
+ if reset:
+ await dialog.get_by_role("button", name = "Use managed folder", exact = True).click()
+ await expect(
+ dialog.get_by_text("Studio-managed folder", exact = True)
+ ).to_be_visible()
+ if narrow:
+ assert await page.evaluate("document.documentElement.scrollWidth <= innerWidth")
+ await page.screenshot(path = str(OUT / f"{label}-selected.png"), animations = "disabled")
+ await dialog.screenshot(
+ path = str(OUT / f"{label}-selected-dialog.png"), animations = "disabled"
+ )
+ await dialog.get_by_role("button", name = "Create project", exact = True).click()
+ if reject:
+ await expect(dialog.get_by_role("alert")).to_contain_text("Choose the folder again")
+ assert len(requests) == 1
+ await expect(
+ dialog.get_by_role("button", name = "Create project", exact = True)
+ ).to_be_disabled()
+ await page.screenshot(path = str(OUT / f"{label}-expired.png"), animations = "disabled")
+ await dialog.get_by_role("button", name = "Change…", exact = True).click()
+ await dialog.get_by_role("button", name = "Create project", exact = True).click()
+ if not (lost or lost_put):
+ await expect(page.get_by_test_id("created")).not_to_be_empty()
+ if cancel or pending or reset:
+ assert "nativePathLease" not in requests[-1]
+ else:
+ assert requests[-1]["nativePathLease"].startswith("native-grant-")
+ assert requests[-1]["name"] == "My project"
+ if lost:
+ await expect(dialog.get_by_role("alert")).to_have_count(0)
+ await dialog.get_by_role("button", name = "Create project", exact = True).click()
+ await expect(page.get_by_test_id("created")).to_have_text(requests[0]["id"])
+ assert {r["id"] for r in requests} == {requests[0]["id"]}
+ assert not folder_requests
+ if lost_put:
+ await expect(dialog.get_by_role("alert")).to_have_count(0)
+ await dialog.get_by_role("button", name = "Create project", exact = True).click()
+ await expect(page.get_by_test_id("created")).to_have_text(requests[0]["id"])
+ assert len(requests) == 1
+ assert [r["method"] for r in folder_requests] == ["PUT", "PUT"]
+ if legacy and not lost_put:
+ assert folder_requests == [
+ {"method": "PUT", "body": {"nativePathLease": requests[-1]["nativePathLease"]}}
+ ]
+ if label == "after-desktop":
+ await page.get_by_role("button", name = "Edit project", exact = True).click()
+ await expect(
+ dialog.get_by_text("/review/existing-project", exact = True)
+ ).to_be_visible()
+ await expect(
+ dialog.get_by_text(
+ "Where code and file tools run for every chat in this project.", exact = True
+ )
+ ).to_be_visible()
+ await page.evaluate("window.__cancelPick=true")
+ await dialog.get_by_role("button", name = "Change…", exact = True).click()
+ await expect(
+ dialog.get_by_role("button", name = "Change…", exact = True)
+ ).to_be_enabled()
+ assert not folder_requests
+ await page.evaluate("window.__cancelPick=false; window.__rejectUpdate=true")
+ await dialog.get_by_role("button", name = "Change…", exact = True).click()
+ await expect(
+ page.get_by_text("Could not change the working folder", exact = True)
+ ).to_be_visible()
+ await expect(
+ dialog.get_by_text("/review/existing-project", exact = True)
+ ).to_be_visible()
+ await page.evaluate("window.__delayUpdate=true")
+ await dialog.get_by_role("button", name = "Change…", exact = True).click()
+ await expect(dialog.get_by_role("button", name = "Save", exact = True)).to_be_disabled()
+ await expect(
+ dialog.get_by_role("button", name = "Cancel", exact = True)
+ ).to_be_disabled()
+ await expect(
+ dialog.get_by_role("button", name = "Delete project", exact = True)
+ ).to_be_disabled()
+ await page.keyboard.press("Escape")
+ await expect(dialog).to_be_visible()
+ await page.evaluate("window.__delayUpdate=false")
+ await expect(
+ dialog.get_by_text("/review/alternate-project", exact = True)
+ ).to_be_visible()
+ await dialog.screenshot(
+ path = str(OUT / "after-edit-selected-dialog.png"), animations = "disabled"
+ )
+ await dialog.get_by_role("button", name = "Cancel", exact = True).click()
+ await page.get_by_role("button", name = "Edit project", exact = True).click()
+ await expect(
+ dialog.get_by_text("/review/alternate-project", exact = True)
+ ).to_be_visible()
+ await dialog.get_by_role("button", name = "Use managed folder", exact = True).click()
+ await expect(
+ dialog.get_by_text("Studio-managed folder", exact = True)
+ ).to_be_visible()
+ await dialog.get_by_role("button", name = "Cancel", exact = True).click()
+ await page.get_by_role("button", name = "Edit project", exact = True).click()
+ await expect(
+ dialog.get_by_text("Studio-managed folder", exact = True)
+ ).to_be_visible()
+ assert [r["method"] for r in folder_requests] == ["PUT", "PUT", "DELETE"]
+ else:
+ if mode in ("unsupported", "guest"):
+ await expect(
+ dialog.get_by_role("button", name = "Choose folder…", exact = True)
+ ).to_be_disabled()
+ await dialog.get_by_role("button", name = "Create project", exact = True).click()
+ await expect(page.get_by_test_id("created")).not_to_be_empty()
+ assert "nativePathLease" not in requests[-1]
+ assert not errors, errors
+ facts = {
+ "mode": mode,
+ "requests": requests,
+ "folderRequests": folder_requests,
+ "pageErrors": errors,
+ "rejectedGrant": reject,
+ "cancelledPicker": cancel,
+ "resetToDefault": reset,
+ "pendingPicker": pending,
+ "narrowViewport": narrow,
+ "olderBackend": legacy,
+ "lostResponse": lost,
+ "lostFolderResponse": lost_put,
+ **observations,
+ }
+ await context.close()
+ return facts
+
+
+async def ambiguous_create(browser, label, base_url, choice):
+ """A lease-carrying create commits but its response and the recovery read are both lost."""
+ context = await browser.new_context(viewport = {"width": 1100, "height": 950})
+ await context.add_init_script("""
+ localStorage.setItem('unsloth_auth_token', 'review.'+btoa(JSON.stringify({sub:'unsloth', role:'owner'}))+'.review');
+ window.__picks = 0; window.__failGet = false;
+ window.__TAURI_INTERNALS__ = {
+ metadata: {currentWindow:{label:'main'}, currentWebview:{label:'main'}},
+ transformCallback: () => 1, unregisterCallback: () => {},
+ invoke: async (command) => {
+ if(command === 'native_path_leases_usable') return true;
+ if(command === 'pick_native_document_folder') {
+ window.__picks++;
+ return {token:'native-grant-'+window.__picks, displayName:'Folder '+window.__picks, expiresAtMs:Date.now()+120000};
+ }
+ if(command.endsWith('scale_factor')) return 1;
+ if(command.endsWith('listen')) return 1;
+ return null;
+ }
+ };
+ """)
+ posts, folder_requests, spent, stored = [], [], set(), {}
+
+ def grant(lease):
+ # The backend spends a grant before anything else can fail.
+ if lease in spent:
+ return False
+ spent.add(lease)
+ return True
+
+ async def api(route):
+ req = route.request
+ path = req.url.split("/api/", 1)[-1]
+ if path == "health":
+ return await route.fulfill(json = {"native_path_leases_supported": True})
+ if path == "chat/projects" and req.method == "POST":
+ data = req.post_data_json
+ posts.append(data)
+ lease = data.get("nativePathLease")
+ if lease and not grant(lease):
+ return await route.fulfill(status = 400, json = {"detail": "Grant already used"})
+ if lease and stored:
+ return await route.fulfill(
+ status = 409, json = {"detail": "This project already exists."}
+ )
+ folder = "/review/" + lease if lease else stored.get("workingFolder")
+ stored.update({**data, "workingFolder": folder})
+ if len(posts) == 1:
+ return await route.abort("connectionreset")
+ return await route.fulfill(json = stored)
+ if path.endswith("/working-folder"):
+ body = req.post_data_json if req.method == "PUT" else None
+ folder_requests.append({"method": req.method, "body": body})
+ if body and not grant(body["nativePathLease"]):
+ return await route.fulfill(status = 400, json = {"detail": "Grant already used"})
+ stored["workingFolder"] = "/review/" + body["nativePathLease"] if body else None
+ return await route.fulfill(json = stored)
+ if path.startswith("chat/projects/") and req.method == "GET":
+ if await page.evaluate("window.__failGet"):
+ return await route.abort("connectionreset")
+ if path.split("/")[2] != stored.get("id"):
+ return await route.fulfill(status = 404, json = {"detail": "Project not found"})
+ return await route.fulfill(json = stored)
+ return await route.fulfill(json = {})
+
+ await context.route(f"{base_url}/api/**", api)
+ page = await context.new_page()
+ errors = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ print("SCENE", label, flush = True)
+ await page.goto(f"{base_url}/smoke-project-folders.html")
+ dialog = page.get_by_role("dialog")
+ await expect(dialog).to_be_visible(timeout = 90000)
+ await page.get_by_label("Project name", exact = True).fill("My project")
+ create = dialog.get_by_role("button", name = "Create project", exact = True)
+ await dialog.get_by_role("button", name = "Choose folder…", exact = True).click()
+ await page.evaluate("window.__failGet = true")
+ await create.click()
+ await expect(dialog.get_by_role("alert")).to_contain_text(
+ "Choose the folder again", timeout = 60000
+ )
+ await page.evaluate("window.__failGet = false")
+ if choice == "managed":
+ await dialog.get_by_role("button", name = "Use managed folder", exact = True).click()
+ await create.click()
+ await expect(page.get_by_test_id("created")).to_have_text(posts[0]["id"])
+ assert [r["method"] for r in folder_requests] == ["DELETE"]
+ assert stored["workingFolder"] is None
+ else:
+ await dialog.get_by_role("button", name = "Change…", exact = True).click()
+ await create.click()
+ # The second grant was spent on the conflict, and the saved folder is the first one.
+ await expect(dialog.get_by_role("alert")).to_contain_text("Choose the folder again")
+ await dialog.get_by_role("button", name = "Change…", exact = True).click()
+ await create.click()
+ await expect(page.get_by_test_id("created")).to_have_text(posts[0]["id"])
+ assert folder_requests == [{"method": "PUT", "body": {"nativePathLease": "native-grant-3"}}]
+ assert stored["workingFolder"] == "/review/native-grant-3"
+ assert {p["id"] for p in posts} == {posts[0]["id"]}
+ assert not errors, errors
+ await context.close()
+ return {"posts": posts, "folderRequests": folder_requests, "saved": stored.get("workingFolder")}
+
+
+async def main():
+ OUT.mkdir(parents = True, exist_ok = True)
+ async with async_playwright() as p:
+ browser = await p.chromium.launch(headless = True)
+ facts = {}
+ if ARGS.before_url:
+ facts["before-browser"] = await scene(
+ browser, "before-browser", ARGS.before_url, "browser"
+ )
+ facts["after-browser"] = await scene(
+ browser, "after-browser", ARGS.base_url, "browser", exercise = True
+ )
+ facts["after-desktop-unavailable"] = await scene(
+ browser, "after-desktop-unavailable", ARGS.base_url, "unsupported", exercise = True
+ )
+ facts["after-desktop"] = await scene(
+ browser, "after-desktop", ARGS.base_url, "desktop", exercise = True
+ )
+ facts["after-retry"] = await scene(
+ browser, "after-retry", ARGS.base_url, "desktop", exercise = True, reject = True
+ )
+ facts["after-picker-cancel"] = await scene(
+ browser, "after-picker-cancel", ARGS.base_url, "desktop", exercise = True, cancel = True
+ )
+ facts["after-use-default"] = await scene(
+ browser, "after-use-default", ARGS.base_url, "desktop", exercise = True, reset = True
+ )
+ facts["after-picker-pending"] = await scene(
+ browser, "after-picker-pending", ARGS.base_url, "desktop", exercise = True, pending = True
+ )
+ facts["after-managed-account"] = await scene(
+ browser, "after-managed-account", ARGS.base_url, "guest", exercise = True
+ )
+ facts["after-older-backend"] = await scene(
+ browser, "after-older-backend", ARGS.base_url, "desktop", exercise = True, legacy = True
+ )
+ facts["after-lost-response"] = await scene(
+ browser, "after-lost-response", ARGS.base_url, "desktop", exercise = True, lost = True
+ )
+ facts["after-older-backend-lost-put"] = await scene(
+ browser,
+ "after-older-backend-lost-put",
+ ARGS.base_url,
+ "desktop",
+ exercise = True,
+ legacy = True,
+ lost_put = True,
+ )
+ facts["after-ambiguous-then-other"] = await ambiguous_create(
+ browser, "after-ambiguous-then-other", ARGS.base_url, "other"
+ )
+ facts["after-ambiguous-then-managed"] = await ambiguous_create(
+ browser, "after-ambiguous-then-managed", ARGS.base_url, "managed"
+ )
+ facts["after-narrow"] = await scene(
+ browser, "after-narrow", ARGS.base_url, "desktop", exercise = True, narrow = True
+ )
+ await browser.close()
+ (OUT / "facts.json").write_text(json.dumps(facts, indent = 2), encoding = "utf-8")
+ print(json.dumps({"scenes": len(facts), "output": str(OUT)}, indent = 2))
+
+
+if ARGS.base_url:
+ asyncio.run(main())
+else:
+ port = int(os.environ.get("SMOKE_PORT", "5433"))
+ ARGS.base_url = f"http://127.0.0.1:{port}"
+ server = start_vite(port)
+ try:
+ wait_for_smoke_page(
+ f"{ARGS.base_url}/smoke-project-folders.html",
+ "smoke-project-folders-main.tsx",
+ proc = server,
+ )
+ asyncio.run(main())
+ finally:
+ stop_process(server)