refactor(webui): remove obsolete native workspace picker paths

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-08 20:33:15 +08:00
1 parent 024d181013
commit 8a795b428e
32 files changed
+186 -593

No files matched your search

@@ -1064,6 +1064,10 @@ export function ThreadComposer({
isHero
&& !!workspaceDefaultScope
&& !!onWorkspaceScopeChange
&& !!onLoadWorkspaceProjects
&& !!onBrowseWorkspaceDirectories
&& !!onResolveWorkspaceProject
&& !!onFavoriteWorkspaceProject
&& workspaceControls?.can_change_project !== false;
const showProjectPicker = projectPickerAvailable && !workspaceControlsHidden;
@@ -30,8 +30,7 @@ function WorkspaceFavoriteButton({ path, pinned, busy, onToggle }: {
);
}
type PickerOption = ProjectDirectory & { kind: "directory" | "manual" };
type PickerColumn = { path: string; options: PickerOption[]; selectedPath: string | null; hidden: boolean };
type PickerColumn = { path: string; options: ProjectDirectory[]; selectedPath: string | null; hidden: boolean };
function WorkspacePickerTooltip({ label, children }: { label: string; children: ReactElement }) {
return (
@@ -46,9 +45,9 @@ const DIRECTORY_ROW_HEIGHT = 44;
const DIRECTORY_OVERSCAN = 4;
function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children, ...props }: {
options: PickerOption[];
options: ProjectDirectory[];
activeIndex: number | null;
renderOption: (option: PickerOption, index: number) => ReactElement;
renderOption: (option: ProjectDirectory, index: number) => ReactElement;
} & HTMLAttributes<HTMLDivElement>) {
const viewportRef = useRef<HTMLDivElement>(null);
const [firstRow, setFirstRow] = useState(0);
@@ -84,7 +83,7 @@ function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children
<div role="presentation" className="relative" style={{ height: options.length * DIRECTORY_ROW_HEIGHT }}>
{options.slice(start, end).map((option, offset) => {
const index = start + offset;
return <div key={`${option.kind}-${option.path}`} role="presentation" className="absolute inset-x-0" style={{ top: index * DIRECTORY_ROW_HEIGHT }}>
return <div key={option.path} role="presentation" className="absolute inset-x-0" style={{ top: index * DIRECTORY_ROW_HEIGHT }}>
{renderOption(option, index)}
</div>;
})}
@@ -142,10 +141,10 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
defaultScope: WorkspaceScopePayload | null;
controls: WorkspacesPayload["controls"] | null;
error?: string | null;
onResolveProject?: (path: string) => Promise<ProjectDirectory>;
onLoadProjects?: () => Promise<WorkspacesPayload>;
onFavoriteProject?: (path: string, pinned: boolean) => Promise<ProjectDirectory[]>;
onBrowseDirectories?: BrowseWorkspaceDirectories;
onResolveProject: (path: string) => Promise<ProjectDirectory>;
onLoadProjects: () => Promise<WorkspacesPayload>;
onFavoriteProject: (path: string, pinned: boolean) => Promise<ProjectDirectory[]>;
onBrowseDirectories: BrowseWorkspaceDirectories;
onChange?: (scope: WorkspaceScopePayload) => void;
}) {
const { t } = useTranslation();
@@ -183,8 +182,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
const displayedScope = scope ?? defaultScope;
const projectLabel = displayedScope ? displayedScope.project_name || projectNameFromPath(displayedScope.project_path) : "";
const visible = isHero && !!defaultScope && !!onChange && controls?.can_change_project !== false;
const canBrowse = !!controls?.can_browse_directories && !!onBrowseDirectories;
const directoryCache = useMemo(() => onBrowseDirectories ? createWorkspaceDirectoryCache(onBrowseDirectories) : null, [onBrowseDirectories]);
const directoryCache = useMemo(() => createWorkspaceDirectoryCache(onBrowseDirectories), [onBrowseDirectories]);
const absoluteDraft = isAbsoluteWorkspacePath(pathDraft);
const requestedPath = absoluteDraft ? pathDraft.trim() : basePath;
const folderQuery = absoluteDraft ? "" : pathDraft.trim();
@@ -197,15 +195,15 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
setActiveColumn(0);
setHighlightActive(false);
const initialPath = scope?.project_path ?? defaultScope?.project_path ?? "";
setPathDraft(canBrowse ? workspaceDirectoryPrefix(initialPath) : currentProjectScope?.project_path ?? "");
setPathDraft(workspaceDirectoryPrefix(initialPath));
setBasePath(initialPath);
setDirectory(null);
setActiveIndex(0);
setPathError(null);
}, [scope?.project_path, defaultScope?.project_path, open, canBrowse]);
}, [scope?.project_path, defaultScope?.project_path, open]);
useEffect(() => {
if (!open || !onLoadProjects) return;
if (!open) return;
let active = true;
setCatalog(null);
onLoadProjects().then(payload => { if (active) setCatalog(payload); }).catch((err: Error) => { if (active) setPathError(err.message); });
@@ -213,7 +211,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
}, [onLoadProjects, open]);
useEffect(() => {
if (!open || !canBrowse || !directoryCache) return;
if (!open) return;
let active = true;
const apply = (result: WorkspaceDirectoriesPayload) => {
if (!active) return;
@@ -232,7 +230,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
});
}, typing ? 150 : 0);
return () => { active = false; window.clearTimeout(timer); };
}, [open, canBrowse, directoryCache, requestedPath, folderQuery, showHidden, revision, absoluteDraft, pathDraft]);
}, [open, directoryCache, requestedPath, folderQuery, showHidden, revision, absoluteDraft, pathDraft]);
useEffect(() => { if (disabled) setOpen(false); }, [disabled]);
useEffect(() => {
@@ -248,7 +246,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
const ancestorPaths = JSON.stringify(previousColumns.filter(column => column.hidden !== showHidden).map(column => column.path));
useEffect(() => {
if (!open || !canBrowse || !directoryCache) return;
if (!open) return;
const paths: string[] = JSON.parse(ancestorPaths);
if (!paths.length) return;
let active = true;
@@ -257,11 +255,11 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
setPreviousColumns(columns => columns.map(column => {
const result = results.find(result => sameWorkspacePath(column.path, result.path));
if (!result) return column;
return { ...column, hidden: showHidden, options: result.entries.map(entry => ({ ...entry, kind: "directory" as const })) };
return { ...column, hidden: showHidden, options: result.entries };
}));
}).catch((err: Error) => { if (active) setPathError(err.message); });
return () => { active = false; };
}, [open, canBrowse, directoryCache, ancestorPaths, showHidden]);
}, [open, directoryCache, ancestorPaths, showHidden]);
useLayoutEffect(() => {
const viewport = columnsElement;
@@ -309,9 +307,9 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
completionRequest.current += 1;
setPathDraft(value);
const absolute = isAbsoluteWorkspacePath(value);
const cached = directoryCache?.peek(absolute ? value.trim() : basePath, absolute ? "" : value.trim(), showHidden, true);
const cached = directoryCache.peek(absolute ? value.trim() : basePath, absolute ? "" : value.trim(), showHidden, true);
setDirectory(cached ?? null);
setLoading(canBrowse && !cached);
setLoading(!cached);
setDirectoryError(null);
setPathError(null);
setActiveIndex(0);
@@ -328,20 +326,18 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
inputRef.current?.focus();
}
const applyProjectPath = useCallback((path: string, name?: string) => {
const applyProjectPath = useCallback((path: string, name: string) => {
const base = scope ?? defaultScope;
const trimmed = path.trim();
if (!base || !onChange) return;
if (!trimmed || !isAbsoluteWorkspacePath(trimmed)) { setPathError(t("workspace.dialog.absolutePathRequired")); return; }
const accessMode = controls?.can_use_full_access === false && !sameWorkspacePath(trimmed, base.project_path) ? "restricted" : base.access_mode;
onChange({ ...base, project_path: trimmed, project_name: name || projectNameFromPath(trimmed), access_mode: accessMode, restrict_to_workspace: accessMode === "restricted" });
onChange({ ...base, project_path: trimmed, project_name: name, access_mode: accessMode, restrict_to_workspace: accessMode === "restricted" });
setPathError(null);
setOpen(false);
}, [controls?.can_use_full_access, defaultScope, onChange, scope, t]);
}, [controls?.can_use_full_access, defaultScope, onChange, scope]);
const chooseProject = useCallback(async (path: string, name?: string) => {
const chooseProject = useCallback(async (path: string) => {
const session = pickerSession.current;
if (!controls?.can_resolve_project || !onResolveProject) { applyProjectPath(path, name); return; }
setPickingFolder(true); setPathError(null);
try {
const project = await onResolveProject(path);
@@ -349,10 +345,10 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
} catch (err) {
if (session === pickerSession.current) setPathError((err as Error).message);
} finally { setPickingFolder(false); }
}, [applyProjectPath, controls?.can_resolve_project, onResolveProject]);
}, [applyProjectPath, onResolveProject]);
const favorites = catalog?.favorite_projects ?? [];
const canFavorite = !!catalog?.controls.can_manage_favorites && !!onFavoriteProject;
const canFavorite = catalog !== null;
const isFavorite = (path: string) => favorites.some(item => sameWorkspacePath(item.path, path));
function favoriteButton(path: string) {
return canFavorite ? <WorkspaceFavoriteButton path={path} pinned={isFavorite(path)} busy={favoriteBusy || pickingFolder}
@@ -360,7 +356,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
}
const toggleFavorite = async (path: string) => {
if (!onFavoriteProject || favoriteBusy) return;
if (favoriteBusy) return;
const session = pickerSession.current;
setFavoriteBusy(true); setPathError(null);
try {
@@ -373,15 +369,11 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
const recentProjects = [
...(catalog?.recent_projects ?? []),
...(defaultScope ? [{ name: t("workspace.dialog.defaultProject"), path: defaultScope.project_path }] : []),
...(defaultScope ? [{ name: projectNameFromPath(defaultScope.project_path), path: defaultScope.project_path }] : []),
...(currentProjectScope ? [{ name: projectLabel, path: currentProjectScope.project_path }] : []),
].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path));
const options = useMemo<PickerOption[]>(() => {
if (directory && !loading) return directory.entries.map(entry => ({ ...entry, kind: "directory" }));
return !canBrowse && absoluteDraft ? [{ name: projectNameFromPath(pathDraft.trim()), path: pathDraft.trim(), kind: "manual" }] : [];
}, [directory, loading, canBrowse, absoluteDraft, pathDraft]);
const options = useMemo(() => directory && !loading ? directory.entries : [], [directory, loading]);
function openShortcut(project: ProjectDirectory) {
if (!canBrowse) { void chooseProject(project.path, project.name); return; }
setBasePath(project.path);
changeDraft(workspaceDirectoryPrefix(project.path));
setRevision(value => value + 1);
@@ -390,13 +382,12 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
const columns: PickerColumn[] = [...previousColumns, { path: directory?.path ?? requestedPath, options, selectedPath: null, hidden: showHidden }];
const activeOptions = columns[activeColumn]?.options ?? options;
const activeOption = Math.min(activeIndex, Math.max(activeOptions.length - 1, 0));
const selectionPath = canBrowse ? (!loading && directory && !directory.partial ? directory.path : null) : (absoluteDraft ? pathDraft.trim() : scope?.project_path ?? defaultScope?.project_path);
const selectionPath = !loading && directory && !directory.partial ? directory.path : null;
const displayedError = pathError ?? error ?? directoryError;
async function completePath() {
const option = activeOptions[activeOption];
if (option && option.kind !== "manual") { navigate(option.path); return; }
if (!directoryCache || !canBrowse) return;
if (option) { navigate(option.path); return; }
const request = workspacePathCompletionQuery(pathDraft) ?? { path: basePath, query: pathDraft.trim() };
const id = ++completionRequest.current;
const session = pickerSession.current;
@@ -411,10 +402,9 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
if (id === completionRequest.current && session === pickerSession.current) setPathError((err as Error).message);
}
}
function activate(option: PickerOption, columnIndex = activeColumn) {
function activate(option: ProjectDirectory, columnIndex = activeColumn) {
if (pickingFolder) return;
if (canBrowse && option.kind !== "manual") navigate(option.path, columnIndex);
else void chooseProject(option.path, option.kind === "manual" ? undefined : option.name);
navigate(option.path, columnIndex);
}
if (!visible || !defaultScope || !onChange) return null;
@@ -435,7 +425,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
<DialogDescription className="sr-only">{t("workspace.picker.description")}</DialogDescription>
<div className="relative flex shrink-0 items-center border-b border-border/50 px-2 pb-2">
<span className="pointer-events-none absolute left-2 top-0 flex h-10 w-9 items-center justify-center"><Search className="h-4 w-4 text-muted-foreground" /></span>
<Input ref={inputRef} role="combobox" aria-expanded={open} aria-controls={`${optionsId}-${activeColumn}`} aria-activedescendant={activeOptions.length ? `${optionsId}-${activeColumn}-${activeOption}` : undefined} aria-autocomplete="list" aria-busy={loading} value={pathDraft} disabled={disabled || pickingFolder} onChange={event => changeDraft(event.target.value)} placeholder={t("workspace.picker.search")} aria-label={t("workspace.dialog.manual")} aria-invalid={displayedError || directoryError ? true : undefined} aria-describedby={displayedError || directoryError ? errorId : undefined} className="h-10 min-w-0 flex-1 border-0 bg-transparent pl-10 pr-3 text-[14px] shadow-none focus-visible:ring-0" onKeyDown={event => {
<Input ref={inputRef} role="combobox" aria-expanded={open} aria-controls={`${optionsId}-${activeColumn}`} aria-activedescendant={activeOptions.length ? `${optionsId}-${activeColumn}-${activeOption}` : undefined} aria-autocomplete="list" aria-busy={loading} value={pathDraft} disabled={disabled || pickingFolder} onChange={event => changeDraft(event.target.value)} placeholder={t("workspace.picker.search")} aria-label={t("workspace.picker.search")} aria-invalid={displayedError || directoryError ? true : undefined} aria-describedby={displayedError || directoryError ? errorId : undefined} className="h-10 min-w-0 flex-1 border-0 bg-transparent pl-10 pr-3 text-[14px] shadow-none focus-visible:ring-0" onKeyDown={event => {
if (event.nativeEvent.isComposing) return;
if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !event.altKey && activeOptions.length) {
event.preventDefault();
@@ -447,7 +437,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
setHighlightActive(true);
setActiveColumn(activeColumn - 1);
setActiveIndex(Math.max(0, parent.options.findIndex(option => sameWorkspacePath(option.path, parent.selectedPath))));
} else if ((event.key === "Tab" && !event.shiftKey && !!pathDraft.trim() || event.key === "ArrowRight" && !event.shiftKey && event.currentTarget.selectionStart === pathDraft.length && event.currentTarget.selectionEnd === pathDraft.length) && canBrowse) {
} else if (event.key === "Tab" && !event.shiftKey && !!pathDraft.trim() || event.key === "ArrowRight" && !event.shiftKey && event.currentTarget.selectionStart === pathDraft.length && event.currentTarget.selectionEnd === pathDraft.length) {
event.preventDefault(); void completePath();
} else if (event.key === "Enter") {
event.preventDefault();
@@ -486,7 +476,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
className={cn(floatingItemClassName, floatingItemFocusClassName, "flex min-h-11 w-full min-w-0 items-center gap-3 px-3 py-2 text-left hover:bg-foreground/[0.055] dark:hover:bg-white/[0.08] disabled:opacity-50", canFavorite && "pr-12",
sameWorkspacePath(column.selectedPath, option.path) && "bg-primary/10 text-primary font-medium hover:bg-primary/10",
highlightActive && columnIndex === activeColumn && index === activeOption && "ring-1 ring-inset ring-ring")}>
{option.kind === "directory" ? <WorkspacePickerTooltip label={option.path}><span className="min-w-0 flex-1 truncate text-[13px]">{option.name}</span></WorkspacePickerTooltip> : <WorkspacePickerPath path={option.path} />}
<WorkspacePickerTooltip label={option.path}><span className="min-w-0 flex-1 truncate text-[13px]">{option.name}</span></WorkspacePickerTooltip>
{sameWorkspacePath(option.path, scope?.project_path ?? defaultScope.project_path) && <Check className="h-4 w-4 shrink-0 text-muted-foreground" />}
</button>
{favoriteButton(option.path)}
@@ -497,9 +487,9 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
</WorkspaceDirectoryColumn>)}
</div>
</div>
{canBrowse && <div className="flex shrink-0 items-center gap-2 px-2 pt-1">
<div className="flex shrink-0 items-center gap-2 px-2 pt-1">
<label className="flex items-center gap-2 text-[12px] text-muted-foreground"><ToggleButton checked={showHidden} onChange={setShowHidden} label={t("workspace.picker.hidden")} />{t("workspace.picker.hidden")}</label>
</div>}
</div>
</DialogContent>
</Dialog>
</TooltipProvider>
-5
View File
@@ -2482,11 +2482,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "Default workspace",
"manual": "Paste path",
"absolutePathRequired": "Enter an absolute folder path on this machine."
},
"picker": {
"favorites": "Favorites",
"recent": "Recent projects",
-5
View File
@@ -2283,11 +2283,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "Espacio de trabajo predeterminado",
"manual": "Pegar ruta",
"absolutePathRequired": "Introduce una ruta absoluta de carpeta en esta máquina."
},
"picker": {
"favorites": "Favoritos",
"recent": "Proyectos recientes",
-5
View File
@@ -2282,11 +2282,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "Espace de travail par défaut",
"manual": "Coller un chemin",
"absolutePathRequired": "Saisissez un chemin absolu de dossier sur cette machine."
},
"picker": {
"favorites": "Favoris",
"recent": "Projets récents",
-5
View File
@@ -2282,11 +2282,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "Ruang kerja bawaan",
"manual": "Tempel path",
"absolutePathRequired": "Masukkan path folder absolut di mesin ini."
},
"picker": {
"favorites": "Favorit",
"recent": "Proyek terbaru",
-5
View File
@@ -2282,11 +2282,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "既定のワークスペース",
"manual": "パスを貼り付け",
"absolutePathRequired": "このマシン上の絶対フォルダーパスを入力してください。"
},
"picker": {
"favorites": "お気に入り",
"recent": "最近のプロジェクト",
-5
View File
@@ -2282,11 +2282,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "기본 작업공간",
"manual": "경로 붙여넣기",
"absolutePathRequired": "이 머신의 절대 폴더 경로를 입력하세요."
},
"picker": {
"favorites": "즐겨찾기",
"recent": "최근 프로젝트",
-5
View File
@@ -2296,11 +2296,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "Espaço de trabalho padrão",
"manual": "Colar caminho",
"absolutePathRequired": "Informe um caminho absoluto de pasta nesta máquina."
},
"picker": {
"favorites": "Favoritos",
"recent": "Projetos recentes",
-5
View File
@@ -2282,11 +2282,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "Không gian làm việc mặc định",
"manual": "Dán đường dẫn",
"absolutePathRequired": "Nhập đường dẫn thư mục tuyệt đối trên máy này."
},
"picker": {
"favorites": "Yêu thích",
"recent": "Dự án gần đây",
-5
View File
@@ -2482,11 +2482,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "默认工作区",
"manual": "粘贴路径",
"absolutePathRequired": "请输入这台机器上的绝对文件夹路径。"
},
"picker": {
"favorites": "收藏",
"recent": "最近项目",
-5
View File
@@ -2282,11 +2282,6 @@
}
},
"workspace": {
"dialog": {
"defaultProject": "預設工作區",
"manual": "貼上路徑",
"absolutePathRequired": "請輸入這台機器上的絕對資料夾路徑。"
},
"picker": {
"favorites": "收藏",
"recent": "最近專案",
+1 -83
View File
@@ -53,16 +53,6 @@ const HOST_WS_CONNECTING = 0;
const HOST_WS_OPEN = 1;
const HOST_WS_CLOSING = 2;
const HOST_WS_CLOSED = 3;
const LOOPBACK_HOST_PORT_PARAM = "nativeHostPort";
const LOOPBACK_HOST_TOKEN_PARAM = "nativeHostToken";
const LOOPBACK_HOST_STORAGE_KEY = "nanobot-webui.native-host";
interface LoopbackHostConfig {
port: number;
token: string;
}
let hasLoopbackNativeHost = false;
declare global {
interface Window {
@@ -75,20 +65,6 @@ function getHostApi(): NanobotHostApi | null {
return window.nanobotHost ?? null;
}
/**
* Recognize the external native host advertised in the URL fragment.
*
* Consume the existing loopback bootstrap parameters so native UI behavior
* survives refresh. The bridge token is removed from the URL and retained
* only for the lifetime of this browser tab.
*/
export function initializeLoopbackRuntimeHost(): boolean {
if (typeof window === "undefined") return false;
const config = consumeLoopbackHostConfig() ?? loadLoopbackHostConfig();
hasLoopbackNativeHost = config !== null;
return hasLoopbackNativeHost;
}
export function toRuntimeSurface(surface: string | null | undefined): RuntimeSurface {
return surface === "native" ? "native" : "browser";
}
@@ -101,7 +77,6 @@ export function createRuntimeHost(
const mergedCapabilities = {
can_export_diagnostics: false,
can_open_logs: false,
can_pick_folder: false,
can_restart_engine: false,
...(capabilities ?? {}),
};
@@ -126,7 +101,7 @@ export function getRuntimeHost(
}
export function isNativeRuntime(surface?: string | null): boolean {
return getHostApi() !== null || hasLoopbackNativeHost || toRuntimeSurface(surface) === "native";
return getHostApi() !== null || toRuntimeSurface(surface) === "native";
}
export function createHostWebSocket(url: string): WebSocket {
@@ -156,63 +131,6 @@ function getHostSocketBridge(): HostSocketBridge | null {
};
}
function consumeLoopbackHostConfig(): LoopbackHostConfig | null {
const hash = window.location.hash || "";
const queryStart = hash.indexOf("?");
if (queryStart < 0) return null;
const path = hash.slice(0, queryStart) || "#/";
const params = new URLSearchParams(hash.slice(queryStart + 1));
const hasBridgeParams = params.has(LOOPBACK_HOST_PORT_PARAM)
|| params.has(LOOPBACK_HOST_TOKEN_PARAM);
if (!hasBridgeParams) return null;
const config = validateLoopbackHostConfig({
port: Number(params.get(LOOPBACK_HOST_PORT_PARAM)),
token: params.get(LOOPBACK_HOST_TOKEN_PARAM) ?? "",
});
params.delete(LOOPBACK_HOST_PORT_PARAM);
params.delete(LOOPBACK_HOST_TOKEN_PARAM);
const nextQuery = params.toString();
const nextHash = `${path}${nextQuery ? `?${nextQuery}` : ""}`;
window.history.replaceState(
null,
"",
`${window.location.pathname}${window.location.search}${nextHash}`,
);
try {
if (config) {
window.sessionStorage.setItem(LOOPBACK_HOST_STORAGE_KEY, JSON.stringify(config));
} else {
window.sessionStorage.removeItem(LOOPBACK_HOST_STORAGE_KEY);
}
} catch {
// The current page can still use the bridge when session storage is unavailable.
}
return config;
}
function loadLoopbackHostConfig(): LoopbackHostConfig | null {
try {
const raw = window.sessionStorage.getItem(LOOPBACK_HOST_STORAGE_KEY);
if (!raw) return null;
return validateLoopbackHostConfig(JSON.parse(raw) as Partial<LoopbackHostConfig>);
} catch {
return null;
}
}
function validateLoopbackHostConfig(
value: Partial<LoopbackHostConfig>,
): LoopbackHostConfig | null {
const port = Number(value.port);
const token = typeof value.token === "string" ? value.token : "";
if (!Number.isInteger(port) || port < 1 || port > 65_535) return null;
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return null;
return { port, token };
}
class HostWebSocket {
binaryType: BinaryType = "blob";
onclose: ((this: WebSocket, ev: CloseEvent) => unknown) | null = null;
-5
View File
@@ -498,10 +498,6 @@ export interface WorkspacesPayload {
controls: {
can_change_project: boolean;
can_use_full_access: boolean;
can_pick_folder?: boolean;
can_browse_directories?: boolean;
can_resolve_project?: boolean;
can_manage_favorites?: boolean;
};
}
@@ -592,7 +588,6 @@ type SettingsApplyStatus =
export interface RuntimeCapabilities {
can_restart_engine: boolean;
can_pick_folder: boolean;
can_open_logs: boolean;
can_export_diagnostics: boolean;
}
-2
View File
@@ -3,7 +3,6 @@ import ReactDOM from "react-dom/client";
import App from "./App";
import "./globals.css";
import { initializeI18n } from "./i18n";
import { initializeLoopbackRuntimeHost } from "./lib/runtime";
import { initializePairReturn } from "./lib/remote-pair-return";
// `crypto.randomUUID` is only defined in secure contexts (HTTPS or localhost).
@@ -27,7 +26,6 @@ if (!root) throw new Error("root element missing");
initializePairReturn();
window.addEventListener("hashchange", initializePairReturn);
initializeLoopbackRuntimeHost();
async function renderWebui(container: HTMLElement) {
await initializeI18n();
+19 -7
View File
@@ -1141,13 +1141,20 @@ describe("App layout", () => {
it("preserves the first message when the gateway rejects a project", async () => {
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const projectPath = "C:\\missing-project";
const directory = (path: string) => ({
path, parent: null, entries: [], partial: false,
truncated: false, host: "test-host", platform: "Windows",
});
const directoryUrl = (path: string) => `/api/workspaces/directories?${new URLSearchParams({ path, q: "", hidden: "0", partial: "1" })}`;
requestMutationSpy.mockResolvedValue({ path: projectPath, name: "missing-project" });
createChatSpy.mockRejectedValueOnce(
new Error("workspace_scope_rejected:project_path must be an existing directory"),
);
mockFetchRoutes({
"/api/workspaces": {
schema_version: 1,
default_access_mode: "restricted",
default_access_mode: "default",
default_scope: {
project_path: "C:\\workspace",
project_name: "workspace",
@@ -1156,16 +1163,21 @@ describe("App layout", () => {
},
controls: { can_change_project: true, can_use_full_access: true },
},
[directoryUrl("C:\\workspace\\")]: directory("C:\\workspace"),
[directoryUrl(projectPath)]: directory(projectPath),
[directoryUrl(`${projectPath}\\`)]: directory(projectPath),
});
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
fireEvent.click(await screen.findByRole("button", { name: "Switch working directory" }));
fireEvent.change(await screen.findByLabelText("Paste path"), {
target: { value: "C:\\missing-project" },
fireEvent.change(await screen.findByRole("combobox"), {
target: { value: projectPath },
});
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Select" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
const message = screen.getByLabelText("Message input");
fireEvent.change(message, { target: { value: "keep this first message" } });
@@ -1179,10 +1191,10 @@ describe("App layout", () => {
"The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again.",
);
fireEvent.click(projectButton);
const projectPath = await screen.findByLabelText("Paste path");
expect(projectPath).toHaveValue("C:\\missing-project");
expect(projectPath).toHaveAttribute("aria-invalid", "true");
expect(projectPath).toHaveFocus();
const pathInput = await screen.findByRole("combobox");
expect(pathInput).toHaveValue(`${projectPath}\\`);
expect(pathInput).toHaveAttribute("aria-invalid", "true");
expect(pathInput).toHaveFocus();
expect(screen.getByRole("alert")).toHaveTextContent(
"The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again.",
);
-2
View File
@@ -204,8 +204,6 @@ const LOCALIZED_WORKSPACE_COPY_KEYS = [
"thread.composer.workspace.full",
"errors.workspaceScopeRejected.title",
"errors.workspaceScopeRejected.body",
"workspace.dialog.defaultProject",
"workspace.dialog.absolutePathRequired",
];
const LOCALIZED_CHANNEL_SHELL_KEYS = [
"settings.channels.advanced",
-35
View File
@@ -2,15 +2,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
getRuntimeHost,
initializeLoopbackRuntimeHost,
isNativeRuntime,
} from "@/lib/runtime";
afterEach(() => {
Reflect.deleteProperty(window, "nanobotHost");
window.sessionStorage.clear();
window.history.replaceState(null, "", "/");
initializeLoopbackRuntimeHost();
});
describe("runtime host facade", () => {
@@ -52,35 +48,4 @@ describe("runtime host facade", () => {
expect(isNativeRuntime("native")).toBe(true);
});
it("recognizes an external native host across refresh and consumes its URL bootstrap", () => {
const token = "a".repeat(43);
window.history.replaceState(
null,
"",
`/#/new?bootstrapSecret=secret&nativeHostPort=43123&nativeHostToken=${token}`,
);
expect(initializeLoopbackRuntimeHost()).toBe(true);
expect(window.location.hash).toBe("#/new?bootstrapSecret=secret");
expect(isNativeRuntime()).toBe(true);
expect(getRuntimeHost().surface).toBe("native");
window.history.replaceState(null, "", "/#/new");
expect(initializeLoopbackRuntimeHost()).toBe(true);
expect(getRuntimeHost().surface).toBe("native");
expect(isNativeRuntime()).toBe(true);
});
it("rejects invalid loopback bridge bootstrap values", () => {
window.history.replaceState(
null,
"",
"/#/new?nativeHostPort=70000&nativeHostToken=too-short",
);
expect(initializeLoopbackRuntimeHost()).toBe(false);
expect(window.location.hash).toBe("#/new");
expect(getRuntimeHost().surface).toBe("browser");
expect(isNativeRuntime()).toBe(false);
});
});
@@ -335,7 +335,6 @@ describe("Settings capabilities", () => {
runtime_surface: "native" as const,
runtime_capabilities: {
can_restart_engine: true,
can_pick_folder: true,
can_open_logs: true,
can_export_diagnostics: true,
},
+45 -43
View File
@@ -8,6 +8,28 @@ import { encodeImage } from "@/lib/imageEncode";
import { SESSION_DRAG_TYPE } from "@/lib/session-drag";
import type { ChatSummary, CliAppInfo, McpPresetInfo, SlashCommand, WorkspaceScopePayload } from "@/lib/types";
function workspacePickerProps(scope: WorkspaceScopePayload) {
const resolvePath = (path: string) => path.startsWith("~/") ? `/Users/test/${path.slice(2)}` : path;
return {
onLoadWorkspaceProjects: async () => ({
schema_version: 1,
default_access_mode: "default" as const,
default_scope: scope,
recent_projects: [],
favorite_projects: [],
controls: { can_change_project: true, can_use_full_access: true },
}),
onBrowseWorkspaceDirectories: async (path: string) => ({
path: resolvePath(path), parent: null, entries: [], partial: false,
truncated: false, host: "test-host", platform: "Linux",
}),
onResolveWorkspaceProject: async (path: string) => ({
path: resolvePath(path), name: path.replace(/\\/g, "/").split("/").filter(Boolean).pop() || path,
}),
onFavoriteWorkspaceProject: async () => [],
};
}
vi.mock("@/lib/imageEncode", () => ({
encodeImage: vi.fn(async (file: File) => ({
ok: true,
@@ -1467,6 +1489,7 @@ describe("ThreadComposer", () => {
restrict_to_workspace: false,
}}
workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
onWorkspaceScopeChange={onWorkspaceScopeChange}
/>,
@@ -1477,13 +1500,14 @@ describe("ThreadComposer", () => {
expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument();
expect(screen.getByRole("dialog")).toBeInTheDocument();
const input = screen.getByLabelText("Paste path");
const input = screen.getByRole("combobox");
fireEvent.change(input, { target: { value: "relative/project" } });
expect(screen.queryByRole("option", { name: "relative/project" })).not.toBeInTheDocument();
expect(onWorkspaceScopeChange).not.toHaveBeenCalled();
fireEvent.change(input, { target: { value: "/Users/test/project-alpha" } });
fireEvent.click(screen.getByRole("option", { name: "/Users/test/project-alpha" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
await user.click(screen.getByRole("button", { name: "Select" }));
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
project_path: "/Users/test/project-alpha",
@@ -1493,12 +1517,13 @@ describe("ThreadComposer", () => {
}));
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const reopenedInput = await screen.findByLabelText("Paste path");
const reopenedInput = await screen.findByRole("combobox");
fireEvent.change(reopenedInput, { target: { value: "~/Pictures/Photos" } });
fireEvent.click(screen.getByRole("option", { name: "~/Pictures/Photos" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
await user.click(screen.getByRole("button", { name: "Select" }));
expect(onWorkspaceScopeChange).toHaveBeenLastCalledWith(expect.objectContaining({
project_path: "~/Pictures/Photos",
project_path: "/Users/test/Pictures/Photos",
project_name: "Photos",
access_mode: "full",
restrict_to_workspace: false,
@@ -1527,6 +1552,7 @@ describe("ThreadComposer", () => {
variant="hero"
workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
onWorkspaceScopeChange={onWorkspaceScopeChange}
/>,
@@ -1534,9 +1560,10 @@ describe("ThreadComposer", () => {
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
fireEvent.change(await screen.findByLabelText("Paste path"), { target: { value: selectedPath } });
fireEvent.keyDown(screen.getByLabelText("Paste path"), { key: "Enter" });
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: selectedPath }));
fireEvent.change(await screen.findByRole("combobox"), { target: { value: selectedPath } });
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
fireEvent.keyDown(screen.getByRole("combobox"), { key: "Enter" });
await waitFor(() => expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: selectedPath })));
});
it("groups the directory and access beside attachments and hides them with workspace controls", () => {
@@ -1554,6 +1581,7 @@ describe("ThreadComposer", () => {
workspaceControlsHidden={workspaceControlsHidden}
workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
onWorkspaceScopeChange={vi.fn()}
/>
@@ -1576,7 +1604,8 @@ describe("ThreadComposer", () => {
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 }));
const defaultScope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const };
const { container } = render(<ThreadComposer variant="hero" onSend={vi.fn()} workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope} workspaceControls={{ can_change_project: true }} onWorkspaceScopeChange={vi.fn()} />);
workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)} workspaceControls={{ can_change_project: true }} onWorkspaceScopeChange={vi.fn()} />);
const input = screen.getByRole("textbox");
const row = container.querySelector(".thread-composer-workspace-row")!;
const trigger = screen.getByRole("button", { name: "Switch working directory" });
@@ -1629,12 +1658,10 @@ describe("ThreadComposer", () => {
variant="hero"
workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{
can_change_project: true,
can_use_full_access: true,
can_pick_folder: true,
can_browse_directories: true,
can_resolve_project: true,
}}
onBrowseWorkspaceDirectories={onBrowseWorkspaceDirectories}
onResolveWorkspaceProject={onResolveWorkspaceProject}
@@ -1658,7 +1685,7 @@ describe("ThreadComposer", () => {
}));
});
it("selects a restricted project manually when the host lacks directory browsing", async () => {
it("selects an entered host path in Restricted mode when Full Access is unavailable", async () => {
const user = userEvent.setup();
const onWorkspaceScopeChange = vi.fn();
const defaultScope = {
@@ -1674,10 +1701,10 @@ describe("ThreadComposer", () => {
variant="hero"
workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{
can_change_project: true,
can_use_full_access: false,
can_pick_folder: false,
}}
onWorkspaceScopeChange={onWorkspaceScopeChange}
/>,
@@ -1685,12 +1712,13 @@ describe("ThreadComposer", () => {
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(await screen.findByLabelText("Paste path")).toBeInTheDocument();
expect(await screen.findByRole("combobox")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Paste path"), {
fireEvent.change(screen.getByRole("combobox"), {
target: { value: "/srv/nas-project" },
});
fireEvent.click(screen.getByRole("option", { name: "/srv/nas-project" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
await user.click(screen.getByRole("button", { name: "Select" }));
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
project_path: "/srv/nas-project",
@@ -1699,32 +1727,6 @@ describe("ThreadComposer", () => {
}));
});
it("offers manual path entry when the host lacks directory browsing", async () => {
const user = userEvent.setup();
const defaultScope = {
project_path: "/Users/test/.nanobot/workspace",
project_name: "workspace",
access_mode: "full" as const,
restrict_to_workspace: false,
};
render(
<ThreadComposer
onSend={vi.fn()}
placeholder="Ask anything..."
variant="hero"
workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope}
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
onWorkspaceScopeChange={vi.fn()}
/>,
);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument();
expect(screen.getByLabelText("Paste path")).toBeInTheDocument();
});
it("closes the sustained goal through its existing drawer", () => {
const { container, rerender } = render(
+31 -35
View File
@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from "vitest";
import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";
import type { WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types";
import type { BrowseWorkspaceDirectories } from "@/lib/workspace";
import { projectNameFromPath, type BrowseWorkspaceDirectories } from "@/lib/workspace";
const scope = { project_path: "/srv/workspace", access_mode: "restricted" as const };
const catalog: WorkspacesPayload = {
@@ -13,19 +13,28 @@ const catalog: WorkspacesPayload = {
default_scope: scope,
recent_projects: [{ name: "alpha", path: "/srv/alpha" }, { name: "beta", path: "/srv/beta" }],
host: { name: "dev-server", platform: "Linux" },
controls: { can_change_project: true, can_use_full_access: false, can_browse_directories: true },
controls: { can_change_project: true, can_use_full_access: false },
};
const directory: WorkspaceDirectoriesPayload = {
path: "/srv/workspace", parent: "/srv", entries: [{ name: "alpha", path: "/srv/workspace/alpha" }],
truncated: false, host: "dev-server", platform: "Linux",
};
function pickerActions() {
return {
onLoadProjects: vi.fn().mockResolvedValue(catalog),
onBrowseDirectories: vi.fn((path: string) => Promise.resolve({ ...directory, path, entries: [] })),
onResolveProject: vi.fn((path: string) => Promise.resolve({ path, name: projectNameFromPath(path) })),
onFavoriteProject: vi.fn().mockResolvedValue([]),
};
}
describe("Workspace project picker", () => {
it("keeps saved locations separate from directory filtering", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onBrowse = vi.fn().mockResolvedValue(directory);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue(catalog)} onBrowseDirectories={onBrowse} onChange={onChange} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue(catalog)} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const shortcut = await screen.findByRole("button", { name: "/srv/beta" });
await user.clear(screen.getByRole("combobox"));
@@ -52,7 +61,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup();
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
@@ -72,7 +81,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup();
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
@@ -100,7 +109,7 @@ describe("Workspace project picker", () => {
const path = rawPath.replace(/\/$/, "");
return Promise.resolve({ ...directory, path, entries: path === scope.project_path ? entries : [{ name: "child", path: `${path}/child` }] });
});
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const first = await screen.findByRole("option", { name: entries[0].path });
expect(first).toHaveAttribute("aria-setsize", "500");
@@ -124,7 +133,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onBrowse = vi.fn().mockResolvedValue(directory);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await screen.findByRole("option", { name: "/srv/workspace/alpha" });
expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace/", "", false, true);
@@ -138,15 +147,16 @@ describe("Workspace project picker", () => {
await waitFor(() => expect(screen.getByRole("button", { name: "Switch working directory" })).not.toHaveFocus());
});
it("keeps invalid paths editable and validates the project before closing", async () => {
it("keeps the selection editable when project validation fails", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onResolve = vi.fn().mockRejectedValueOnce(new Error("project_path must be an existing directory"))
.mockResolvedValueOnce({ name: "alpha", path: "/srv/alpha" });
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={{ ...catalog.controls, can_resolve_project: true }} onResolveProject={onResolve} onChange={onChange} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onResolveProject={onResolve} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "/srv/missing");
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
await user.keyboard("{Enter}");
expect(await screen.findByRole("alert")).toHaveTextContent("existing directory");
expect(screen.getByRole("combobox")).toHaveValue("/srv/missing");
@@ -154,33 +164,19 @@ describe("Workspace project picker", () => {
expect(onChange).not.toHaveBeenCalled();
await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "/srv/alpha");
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
await user.keyboard("{Enter}");
await waitFor(() => expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" })));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
it("uses manual paths without new requests on a host missing optional capabilities", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onBrowse = vi.fn();
const onResolve = vi.fn();
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={{ can_change_project: true, can_use_full_access: false }} onBrowseDirectories={onBrowse} onResolveProject={onResolve} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
expect(screen.queryByRole("option", { name: "Browse folders…" })).not.toBeInTheDocument();
await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "/srv/alpha");
await user.keyboard("{Enter}");
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" }));
expect(onBrowse).not.toHaveBeenCalled();
expect(onResolve).not.toHaveBeenCalled();
});
it("does not apply a directory response after closing the dialog", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
let finish!: (value: WorkspaceDirectoriesPayload) => void;
const onBrowse = vi.fn(() => new Promise<WorkspaceDirectoriesPayload>((resolve) => { finish = resolve; }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await waitFor(() => expect(onBrowse).toHaveBeenCalled());
await user.keyboard("{Escape}");
@@ -193,7 +189,7 @@ describe("Workspace project picker", () => {
const onChange = vi.fn();
const favorites = [{ name: "beta", path: "/srv/beta" }];
const onFavorite = vi.fn().mockResolvedValueOnce(favorites).mockRejectedValueOnce(new Error("disk full")).mockResolvedValueOnce([]);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue({ ...catalog, controls: { ...catalog.controls, can_manage_favorites: true } })} onFavoriteProject={onFavorite} onChange={onChange} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue(catalog)} onFavoriteProject={onFavorite} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.click(await screen.findByRole("button", { name: "Pin beta" }));
expect(onFavorite).toHaveBeenLastCalledWith("/srv/beta", true);
@@ -213,8 +209,8 @@ describe("Workspace project picker", () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onFavorite = vi.fn().mockResolvedValue([{ name: "alpha", path: "/srv/workspace/alpha" }]);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls}
onLoadProjects={vi.fn().mockResolvedValue({ ...catalog, controls: { ...catalog.controls, can_manage_favorites: true } })}
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls}
onLoadProjects={vi.fn().mockResolvedValue(catalog)}
onBrowseDirectories={vi.fn().mockResolvedValue(directory)} onFavoriteProject={onFavorite} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const option = await screen.findByRole("option", { name: "/srv/workspace/alpha" });
@@ -237,7 +233,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup();
const onChange = vi.fn();
const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: completed, partial: path === draft, entries: path === draft ? [{ name: "alpha", path: completed }] : [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox");
await user.clear(input);
@@ -257,7 +253,7 @@ describe("Workspace project picker", () => {
it("uses one list for partial paths and keyboard completion", async () => {
const user = userEvent.setup();
const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: path === "/srv/al" ? "/srv" : path, parent: "/srv", partial: path === "/srv/al", entries: path === "/srv/al" ? [{ name: "alpha", path: "/srv/alpha" }, { name: "alpine", path: "/srv/alpine" }] : [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox");
await user.clear(input);
@@ -277,7 +273,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup();
let finish!: (value: WorkspaceDirectoriesPayload) => void;
const onBrowse = vi.fn((path: string) => path === "/srv/al" ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; }) : Promise.resolve({ ...directory, entries: [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox");
await user.clear(input);
@@ -295,7 +291,7 @@ describe("Workspace project picker", () => {
const onBrowse = vi.fn<BrowseWorkspaceDirectories>((path: string) => path === "/srv/al"
? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; })
: Promise.resolve({ ...directory, path, entries: [] }));
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox");
await user.clear(input);
@@ -313,7 +309,7 @@ describe("Workspace project picker", () => {
let finishOld!: (value: WorkspaceDirectoriesPayload) => void;
const onBrowse = vi.fn((path: string) => path === "/srv/old/" ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finishOld = resolve; }) : Promise.resolve({ ...directory, path, entries: [{ name: path === "/srv/new/" ? "new-child" : "initial-child", path: `${path.replace(/\/$/, "")}/child` }] }));
const onChange = vi.fn();
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await screen.findByRole("option", { name: "/srv/workspace/child" });
const input = screen.getByRole("combobox");
@@ -336,7 +332,7 @@ describe("Workspace project picker", () => {
it("filters the current directory by name without a second browser view", async () => {
const user = userEvent.setup();
const onBrowse = vi.fn().mockResolvedValue(directory);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await screen.findByRole("option", { name: "/srv/workspace/alpha" });
const input = screen.getByRole("combobox");
@@ -357,7 +353,7 @@ describe("Workspace project picker", () => {
if (showHidden) names.push(".hidden");
return Promise.resolve({ ...directory, path, entries: names.map(name => ({ name, path: `${path}/${name}` })) });
});
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha/child" }));