refactor(webui): remove obsolete workspace picker code

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-08 20:33:15 +08:00
1 parent d5dc59ea76
commit 024d181013
17 files changed
+31 -109

No files matched your search

@@ -134,10 +134,9 @@ function WorkspacePickerPath({ path }: { path: string }) {
); );
} }
export function WorkspaceProjectPicker({ isHero, connected = false, disabled, scope, defaultScope, controls, error, onLoadProjects, onResolveProject, onFavoriteProject, onBrowseDirectories, layoutAnchor, onChange }: { export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, controls, error, onLoadProjects, onResolveProject, onFavoriteProject, onBrowseDirectories, layoutAnchor, onChange }: {
layoutAnchor?: HTMLElement | null; layoutAnchor?: HTMLElement | null;
isHero: boolean; isHero: boolean;
connected?: boolean;
disabled?: boolean; disabled?: boolean;
scope: WorkspaceScopePayload | null; scope: WorkspaceScopePayload | null;
defaultScope: WorkspaceScopePayload | null; defaultScope: WorkspaceScopePayload | null;
@@ -182,10 +181,10 @@ export function WorkspaceProjectPicker({ isHero, connected = false, disabled, sc
const errorId = useId(); const errorId = useId();
const currentProjectScope = selectedProjectScope(scope, defaultScope); const currentProjectScope = selectedProjectScope(scope, defaultScope);
const displayedScope = scope ?? defaultScope; const displayedScope = scope ?? defaultScope;
const projectLabel = displayedScope?.project_name || (displayedScope ? projectNameFromPath(displayedScope.project_path) : t("thread.composer.workspace.projectPlaceholder")); const projectLabel = displayedScope ? displayedScope.project_name || projectNameFromPath(displayedScope.project_path) : "";
const visible = isHero && !!defaultScope && !!onChange && controls?.can_change_project !== false; const visible = isHero && !!defaultScope && !!onChange && controls?.can_change_project !== false;
const canBrowse = !!controls?.can_browse_directories && !!onBrowseDirectories; const canBrowse = !!controls?.can_browse_directories && !!onBrowseDirectories;
const directoryCache = useMemo(() => onBrowseDirectories ? createWorkspaceDirectoryCache(onBrowseDirectories) : null, [onBrowseDirectories, connected]); const directoryCache = useMemo(() => onBrowseDirectories ? createWorkspaceDirectoryCache(onBrowseDirectories) : null, [onBrowseDirectories]);
const absoluteDraft = isAbsoluteWorkspacePath(pathDraft); const absoluteDraft = isAbsoluteWorkspacePath(pathDraft);
const requestedPath = absoluteDraft ? pathDraft.trim() : basePath; const requestedPath = absoluteDraft ? pathDraft.trim() : basePath;
const folderQuery = absoluteDraft ? "" : pathDraft.trim(); const folderQuery = absoluteDraft ? "" : pathDraft.trim();
@@ -379,8 +378,8 @@ export function WorkspaceProjectPicker({ isHero, connected = false, disabled, sc
].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path)); ].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path));
const options = useMemo<PickerOption[]>(() => { const options = useMemo<PickerOption[]>(() => {
if (directory && !loading) return directory.entries.map(entry => ({ ...entry, kind: "directory" })); if (directory && !loading) return directory.entries.map(entry => ({ ...entry, kind: "directory" }));
return !canBrowse && absoluteDraft ? [{ name: t("workspace.dialog.usePath"), path: pathDraft.trim(), kind: "manual" }] : []; return !canBrowse && absoluteDraft ? [{ name: projectNameFromPath(pathDraft.trim()), path: pathDraft.trim(), kind: "manual" }] : [];
}, [directory, loading, canBrowse, absoluteDraft, pathDraft, t]); }, [directory, loading, canBrowse, absoluteDraft, pathDraft]);
function openShortcut(project: ProjectDirectory) { function openShortcut(project: ProjectDirectory) {
if (!canBrowse) { void chooseProject(project.path, project.name); return; } if (!canBrowse) { void chooseProject(project.path, project.name); return; }
setBasePath(project.path); setBasePath(project.path);
-2
View File
@@ -2115,7 +2115,6 @@
"workspace": { "workspace": {
"accessAria": "Workspace access mode", "accessAria": "Workspace access mode",
"projectAria": "Choose project", "projectAria": "Choose project",
"projectPlaceholder": "Select project",
"default": "Default Permission", "default": "Default Permission",
"defaultShort": "Default", "defaultShort": "Default",
"full": "Full Access", "full": "Full Access",
@@ -2486,7 +2485,6 @@
"dialog": { "dialog": {
"defaultProject": "Default workspace", "defaultProject": "Default workspace",
"manual": "Paste path", "manual": "Paste path",
"usePath": "Use Path",
"absolutePathRequired": "Enter an absolute folder path on this machine." "absolutePathRequired": "Enter an absolute folder path on this machine."
}, },
"picker": { "picker": {
-2
View File
@@ -1916,7 +1916,6 @@
"workspace": { "workspace": {
"accessAria": "Modo de acceso al espacio de trabajo", "accessAria": "Modo de acceso al espacio de trabajo",
"projectAria": "Elegir proyecto", "projectAria": "Elegir proyecto",
"projectPlaceholder": "Seleccionar proyecto",
"default": "Permiso predeterminado", "default": "Permiso predeterminado",
"defaultShort": "Predeterm.", "defaultShort": "Predeterm.",
"full": "Acceso completo", "full": "Acceso completo",
@@ -2287,7 +2286,6 @@
"dialog": { "dialog": {
"defaultProject": "Espacio de trabajo predeterminado", "defaultProject": "Espacio de trabajo predeterminado",
"manual": "Pegar ruta", "manual": "Pegar ruta",
"usePath": "Usar ruta",
"absolutePathRequired": "Introduce una ruta absoluta de carpeta en esta máquina." "absolutePathRequired": "Introduce una ruta absoluta de carpeta en esta máquina."
}, },
"picker": { "picker": {
-2
View File
@@ -1915,7 +1915,6 @@
"workspace": { "workspace": {
"accessAria": "Mode d’accès à l’espace de travail", "accessAria": "Mode d’accès à l’espace de travail",
"projectAria": "Choisir un projet", "projectAria": "Choisir un projet",
"projectPlaceholder": "Sélectionner un projet",
"default": "Autorisation par défaut", "default": "Autorisation par défaut",
"defaultShort": "Par défaut", "defaultShort": "Par défaut",
"full": "Accès complet", "full": "Accès complet",
@@ -2286,7 +2285,6 @@
"dialog": { "dialog": {
"defaultProject": "Espace de travail par défaut", "defaultProject": "Espace de travail par défaut",
"manual": "Coller un chemin", "manual": "Coller un chemin",
"usePath": "Utiliser le chemin",
"absolutePathRequired": "Saisissez un chemin absolu de dossier sur cette machine." "absolutePathRequired": "Saisissez un chemin absolu de dossier sur cette machine."
}, },
"picker": { "picker": {
-2
View File
@@ -1915,7 +1915,6 @@
"workspace": { "workspace": {
"accessAria": "Mode akses ruang kerja", "accessAria": "Mode akses ruang kerja",
"projectAria": "Pilih proyek", "projectAria": "Pilih proyek",
"projectPlaceholder": "Pilih proyek",
"default": "Izin bawaan", "default": "Izin bawaan",
"defaultShort": "Bawaan", "defaultShort": "Bawaan",
"full": "Akses penuh", "full": "Akses penuh",
@@ -2286,7 +2285,6 @@
"dialog": { "dialog": {
"defaultProject": "Ruang kerja bawaan", "defaultProject": "Ruang kerja bawaan",
"manual": "Tempel path", "manual": "Tempel path",
"usePath": "Gunakan path",
"absolutePathRequired": "Masukkan path folder absolut di mesin ini." "absolutePathRequired": "Masukkan path folder absolut di mesin ini."
}, },
"picker": { "picker": {
-2
View File
@@ -1915,7 +1915,6 @@
"workspace": { "workspace": {
"accessAria": "ワークスペースのアクセスモード", "accessAria": "ワークスペースのアクセスモード",
"projectAria": "プロジェクトを選択", "projectAria": "プロジェクトを選択",
"projectPlaceholder": "プロジェクトを選択",
"default": "既定の権限", "default": "既定の権限",
"defaultShort": "既定", "defaultShort": "既定",
"full": "フルアクセス", "full": "フルアクセス",
@@ -2286,7 +2285,6 @@
"dialog": { "dialog": {
"defaultProject": "既定のワークスペース", "defaultProject": "既定のワークスペース",
"manual": "パスを貼り付け", "manual": "パスを貼り付け",
"usePath": "パスを使用",
"absolutePathRequired": "このマシン上の絶対フォルダーパスを入力してください。" "absolutePathRequired": "このマシン上の絶対フォルダーパスを入力してください。"
}, },
"picker": { "picker": {
-2
View File
@@ -1915,7 +1915,6 @@
"workspace": { "workspace": {
"accessAria": "작업공간 접근 모드", "accessAria": "작업공간 접근 모드",
"projectAria": "프로젝트 선택", "projectAria": "프로젝트 선택",
"projectPlaceholder": "프로젝트 선택",
"default": "기본 권한", "default": "기본 권한",
"defaultShort": "기본", "defaultShort": "기본",
"full": "전체 접근 권한", "full": "전체 접근 권한",
@@ -2286,7 +2285,6 @@
"dialog": { "dialog": {
"defaultProject": "기본 작업공간", "defaultProject": "기본 작업공간",
"manual": "경로 붙여넣기", "manual": "경로 붙여넣기",
"usePath": "경로 사용",
"absolutePathRequired": "이 머신의 절대 폴더 경로를 입력하세요." "absolutePathRequired": "이 머신의 절대 폴더 경로를 입력하세요."
}, },
"picker": { "picker": {
-2
View File
@@ -1929,7 +1929,6 @@
"workspace": { "workspace": {
"accessAria": "Modo de acesso ao espaço de trabalho", "accessAria": "Modo de acesso ao espaço de trabalho",
"projectAria": "Escolher projeto", "projectAria": "Escolher projeto",
"projectPlaceholder": "Selecionar projeto",
"default": "Permissão padrão", "default": "Permissão padrão",
"defaultShort": "Padrão", "defaultShort": "Padrão",
"full": "Acesso total", "full": "Acesso total",
@@ -2300,7 +2299,6 @@
"dialog": { "dialog": {
"defaultProject": "Espaço de trabalho padrão", "defaultProject": "Espaço de trabalho padrão",
"manual": "Colar caminho", "manual": "Colar caminho",
"usePath": "Usar caminho",
"absolutePathRequired": "Informe um caminho absoluto de pasta nesta máquina." "absolutePathRequired": "Informe um caminho absoluto de pasta nesta máquina."
}, },
"picker": { "picker": {
-2
View File
@@ -1915,7 +1915,6 @@
"workspace": { "workspace": {
"accessAria": "Chế độ truy cập không gian làm việc", "accessAria": "Chế độ truy cập không gian làm việc",
"projectAria": "Chọn dự án", "projectAria": "Chọn dự án",
"projectPlaceholder": "Chọn dự án",
"default": "Quyền mặc định", "default": "Quyền mặc định",
"defaultShort": "Mặc định", "defaultShort": "Mặc định",
"full": "Toàn quyền truy cập", "full": "Toàn quyền truy cập",
@@ -2286,7 +2285,6 @@
"dialog": { "dialog": {
"defaultProject": "Không gian làm việc mặc định", "defaultProject": "Không gian làm việc mặc định",
"manual": "Dán đường dẫn", "manual": "Dán đường dẫn",
"usePath": "Dùng đường dẫn",
"absolutePathRequired": "Nhập đường dẫn thư mục tuyệt đối trên máy này." "absolutePathRequired": "Nhập đường dẫn thư mục tuyệt đối trên máy này."
}, },
"picker": { "picker": {
-2
View File
@@ -2115,7 +2115,6 @@
"workspace": { "workspace": {
"accessAria": "工作区访问权限", "accessAria": "工作区访问权限",
"projectAria": "选择项目", "projectAria": "选择项目",
"projectPlaceholder": "选择项目",
"default": "默认权限", "default": "默认权限",
"defaultShort": "默认", "defaultShort": "默认",
"full": "完全访问", "full": "完全访问",
@@ -2486,7 +2485,6 @@
"dialog": { "dialog": {
"defaultProject": "默认工作区", "defaultProject": "默认工作区",
"manual": "粘贴路径", "manual": "粘贴路径",
"usePath": "使用路径",
"absolutePathRequired": "请输入这台机器上的绝对文件夹路径。" "absolutePathRequired": "请输入这台机器上的绝对文件夹路径。"
}, },
"picker": { "picker": {
-2
View File
@@ -1915,7 +1915,6 @@
"workspace": { "workspace": {
"accessAria": "工作區存取模式", "accessAria": "工作區存取模式",
"projectAria": "選擇專案", "projectAria": "選擇專案",
"projectPlaceholder": "選擇專案",
"default": "預設權限", "default": "預設權限",
"defaultShort": "預設", "defaultShort": "預設",
"full": "完整存取權", "full": "完整存取權",
@@ -2286,7 +2285,6 @@
"dialog": { "dialog": {
"defaultProject": "預設工作區", "defaultProject": "預設工作區",
"manual": "貼上路徑", "manual": "貼上路徑",
"usePath": "使用路徑",
"absolutePathRequired": "請輸入這台機器上的絕對資料夾路徑。" "absolutePathRequired": "請輸入這台機器上的絕對資料夾路徑。"
}, },
"picker": { "picker": {
+10 -47
View File
@@ -4,7 +4,6 @@ export interface RuntimeHost {
surface: RuntimeSurface; surface: RuntimeSurface;
capabilities: RuntimeCapabilities; capabilities: RuntimeCapabilities;
socketFactory?: (url: string) => WebSocket; socketFactory?: (url: string) => WebSocket;
pickFolder?: () => Promise<string | null>;
restartEngine?: () => Promise<void>; restartEngine?: () => Promise<void>;
openLogs?: () => Promise<void>; openLogs?: () => Promise<void>;
exportDiagnostics?: () => Promise<string>; exportDiagnostics?: () => Promise<string>;
@@ -26,7 +25,6 @@ interface HostRuntimeInfo {
interface NanobotHostApi { interface NanobotHostApi {
getRuntimeInfo?(): Promise<HostRuntimeInfo>; getRuntimeInfo?(): Promise<HostRuntimeInfo>;
restartEngine?(): Promise<void>; restartEngine?(): Promise<void>;
pickFolder?(): Promise<string | null>;
openLogs?(): Promise<void>; openLogs?(): Promise<void>;
exportDiagnostics?(): Promise<string>; exportDiagnostics?(): Promise<string>;
openSocket?(url: string): Promise<string>; openSocket?(url: string): Promise<string>;
@@ -64,7 +62,7 @@ interface LoopbackHostConfig {
token: string; token: string;
} }
let loopbackHostApi: NanobotHostApi | null = null; let hasLoopbackNativeHost = false;
declare global { declare global {
interface Window { interface Window {
@@ -74,21 +72,21 @@ declare global {
function getHostApi(): NanobotHostApi | null { function getHostApi(): NanobotHostApi | null {
if (typeof window === "undefined") return null; if (typeof window === "undefined") return null;
return window.nanobotHost ?? loopbackHostApi; return window.nanobotHost ?? null;
} }
/** /**
* Install the external native-host bridge advertised in the URL fragment. * Recognize the external native host advertised in the URL fragment.
* *
* Only a loopback port is accepted; callers cannot redirect privileged host * Consume the existing loopback bootstrap parameters so native UI behavior
* actions to an arbitrary origin. The short-lived bridge token is removed * survives refresh. The bridge token is removed from the URL and retained
* from the URL and retained only for the lifetime of this browser tab. * only for the lifetime of this browser tab.
*/ */
export function initializeLoopbackRuntimeHost(): boolean { export function initializeLoopbackRuntimeHost(): boolean {
if (typeof window === "undefined") return false; if (typeof window === "undefined") return false;
const config = consumeLoopbackHostConfig() ?? loadLoopbackHostConfig(); const config = consumeLoopbackHostConfig() ?? loadLoopbackHostConfig();
loopbackHostApi = config ? createLoopbackHostApi(config) : null; hasLoopbackNativeHost = config !== null;
return loopbackHostApi !== null; return hasLoopbackNativeHost;
} }
export function toRuntimeSurface(surface: string | null | undefined): RuntimeSurface { export function toRuntimeSurface(surface: string | null | undefined): RuntimeSurface {
@@ -112,7 +110,6 @@ export function createRuntimeHost(
surface, surface,
capabilities: mergedCapabilities, capabilities: mergedCapabilities,
socketFactory: bridge ? createHostWebSocket : undefined, socketFactory: bridge ? createHostWebSocket : undefined,
pickFolder: api?.pickFolder?.bind(api),
restartEngine: api?.restartEngine?.bind(api), restartEngine: api?.restartEngine?.bind(api),
openLogs: api?.openLogs?.bind(api), openLogs: api?.openLogs?.bind(api),
exportDiagnostics: api?.exportDiagnostics?.bind(api), exportDiagnostics: api?.exportDiagnostics?.bind(api),
@@ -123,14 +120,13 @@ export function getRuntimeHost(
surface?: string | null, surface?: string | null,
capabilities?: Partial<RuntimeCapabilities> | null, capabilities?: Partial<RuntimeCapabilities> | null,
): RuntimeHost { ): RuntimeHost {
const api = getHostApi();
const runtimeSurface = const runtimeSurface =
surface == null ? (api ? "native" : "browser") : toRuntimeSurface(surface); surface == null ? (isNativeRuntime() ? "native" : "browser") : toRuntimeSurface(surface);
return createRuntimeHost(runtimeSurface, capabilities); return createRuntimeHost(runtimeSurface, capabilities);
} }
export function isNativeRuntime(surface?: string | null): boolean { export function isNativeRuntime(surface?: string | null): boolean {
return getHostApi() !== null || toRuntimeSurface(surface) === "native"; return getHostApi() !== null || hasLoopbackNativeHost || toRuntimeSurface(surface) === "native";
} }
export function createHostWebSocket(url: string): WebSocket { export function createHostWebSocket(url: string): WebSocket {
@@ -217,39 +213,6 @@ function validateLoopbackHostConfig(
return { port, token }; return { port, token };
} }
function createLoopbackHostApi(config: LoopbackHostConfig): NanobotHostApi {
return {
async pickFolder(): Promise<string | null> {
let response: Response;
try {
response = await fetch(`http://127.0.0.1:${config.port}/v1/pick-folder`, {
method: "POST",
cache: "no-store",
credentials: "omit",
referrerPolicy: "no-referrer",
headers: { Authorization: `Bearer ${config.token}` },
});
} catch {
throw new Error("Native folder picker is unavailable. Reopen Nanobot and try again.");
}
const body = await response.json().catch(() => null) as {
error?: unknown;
path?: unknown;
} | null;
if (!response.ok) {
const detail = typeof body?.error === "string" ? body.error : `HTTP ${response.status}`;
throw new Error(`Native folder picker failed: ${detail}`);
}
if (body?.path === null) return null;
if (typeof body?.path !== "string" || !body.path) {
throw new Error("Native folder picker returned an invalid path.");
}
return body.path;
},
};
}
class HostWebSocket { class HostWebSocket {
binaryType: BinaryType = "blob"; binaryType: BinaryType = "blob";
onclose: ((this: WebSocket, ev: CloseEvent) => unknown) | null = null; onclose: ((this: WebSocket, ev: CloseEvent) => unknown) | null = null;
-7
View File
@@ -16,13 +16,6 @@ export function projectNameFromPath(path: string): string {
return normalized.split("/").filter(Boolean).pop() || path; return normalized.split("/").filter(Boolean).pop() || path;
} }
export function shortWorkspacePath(path: string): string {
const normalized = path.replace(/\\/g, "/");
const parts = normalized.split("/").filter(Boolean);
if (parts.length <= 3) return path;
return `.../${parts.slice(-3).join("/")}`;
}
export function isAbsoluteWorkspacePath(path: string): boolean { export function isAbsoluteWorkspacePath(path: string): boolean {
const trimmed = path.trim(); const trimmed = path.trim();
return ( return (
+1 -1
View File
@@ -2232,7 +2232,7 @@ describe("App layout", () => {
}); });
it("uses native chrome when the host bridge overrides browser gateway metadata", async () => { it("uses native chrome when the host bridge overrides browser gateway metadata", async () => {
Reflect.set(window, "nanobotHost", { pickFolder: vi.fn() }); Reflect.set(window, "nanobotHost", { getRuntimeInfo: vi.fn() });
vi.mocked(fetchBootstrap).mockResolvedValue({ vi.mocked(fetchBootstrap).mockResolvedValue({
token: "tok", token: "tok",
api_token: "api-tok", api_token: "api-tok",
-1
View File
@@ -205,7 +205,6 @@ const LOCALIZED_WORKSPACE_COPY_KEYS = [
"errors.workspaceScopeRejected.title", "errors.workspaceScopeRejected.title",
"errors.workspaceScopeRejected.body", "errors.workspaceScopeRejected.body",
"workspace.dialog.defaultProject", "workspace.dialog.defaultProject",
"workspace.dialog.usePath",
"workspace.dialog.absolutePathRequired", "workspace.dialog.absolutePathRequired",
]; ];
const LOCALIZED_CHANNEL_SHELL_KEYS = [ const LOCALIZED_CHANNEL_SHELL_KEYS = [
+15 -24
View File
@@ -11,7 +11,6 @@ afterEach(() => {
window.sessionStorage.clear(); window.sessionStorage.clear();
window.history.replaceState(null, "", "/"); window.history.replaceState(null, "", "/");
initializeLoopbackRuntimeHost(); initializeLoopbackRuntimeHost();
vi.unstubAllGlobals();
}); });
describe("runtime host facade", () => { describe("runtime host facade", () => {
@@ -19,21 +18,21 @@ describe("runtime host facade", () => {
const host = getRuntimeHost(); const host = getRuntimeHost();
expect(host.surface).toBe("browser"); expect(host.surface).toBe("browser");
expect(host.pickFolder).toBeUndefined(); expect(host.restartEngine).toBeUndefined();
expect(isNativeRuntime()).toBe(false); expect(isNativeRuntime()).toBe(false);
}); });
it("wraps native host actions behind the runtime facade", async () => { it("wraps native host actions behind the runtime facade", async () => {
const pickFolder = vi.fn(async () => "/tmp/project");
const restartEngine = vi.fn(async () => undefined); const restartEngine = vi.fn(async () => undefined);
const openLogs = vi.fn(async () => undefined);
const exportDiagnostics = vi.fn(async () => "/tmp/diagnostics.txt");
Object.defineProperty(window, "nanobotHost", { Object.defineProperty(window, "nanobotHost", {
configurable: true, configurable: true,
value: { value: {
getRuntimeInfo: vi.fn(), getRuntimeInfo: vi.fn(),
restartEngine, restartEngine,
pickFolder, openLogs,
openLogs: vi.fn(async () => undefined), exportDiagnostics,
exportDiagnostics: vi.fn(async () => "/tmp/diagnostics.txt"),
}, },
}); });
@@ -41,23 +40,20 @@ describe("runtime host facade", () => {
expect(host.surface).toBe("native"); expect(host.surface).toBe("native");
expect(isNativeRuntime()).toBe(true); expect(isNativeRuntime()).toBe(true);
await expect(host.pickFolder?.()).resolves.toBe("/tmp/project");
await host.restartEngine?.(); await host.restartEngine?.();
expect(pickFolder).toHaveBeenCalledTimes(1); await host.openLogs?.();
await expect(host.exportDiagnostics?.()).resolves.toBe("/tmp/diagnostics.txt");
expect(restartEngine).toHaveBeenCalledTimes(1); expect(restartEngine).toHaveBeenCalledTimes(1);
expect(openLogs).toHaveBeenCalledTimes(1);
expect(exportDiagnostics).toHaveBeenCalledTimes(1);
}); });
it("treats server-reported native surface as native for UI labels", () => { it("treats server-reported native surface as native for UI labels", () => {
expect(isNativeRuntime("native")).toBe(true); expect(isNativeRuntime("native")).toBe(true);
}); });
it("installs an authenticated loopback folder picker from the URL fragment", async () => { it("recognizes an external native host across refresh and consumes its URL bootstrap", () => {
const token = "a".repeat(43); const token = "a".repeat(43);
const fetchMock = vi.fn(async () => new Response(
JSON.stringify({ path: "/Users/test/project" }),
{ status: 200, headers: { "Content-Type": "application/json" } },
));
vi.stubGlobal("fetch", fetchMock);
window.history.replaceState( window.history.replaceState(
null, null,
"", "",
@@ -67,18 +63,12 @@ describe("runtime host facade", () => {
expect(initializeLoopbackRuntimeHost()).toBe(true); expect(initializeLoopbackRuntimeHost()).toBe(true);
expect(window.location.hash).toBe("#/new?bootstrapSecret=secret"); expect(window.location.hash).toBe("#/new?bootstrapSecret=secret");
expect(isNativeRuntime()).toBe(true); expect(isNativeRuntime()).toBe(true);
await expect(getRuntimeHost().pickFolder?.()).resolves.toBe("/Users/test/project"); expect(getRuntimeHost().surface).toBe("native");
expect(fetchMock).toHaveBeenCalledWith(
"http://127.0.0.1:43123/v1/pick-folder",
expect.objectContaining({
method: "POST",
headers: { Authorization: `Bearer ${token}` },
}),
);
window.history.replaceState(null, "", "/#/new"); window.history.replaceState(null, "", "/#/new");
expect(initializeLoopbackRuntimeHost()).toBe(true); expect(initializeLoopbackRuntimeHost()).toBe(true);
await expect(getRuntimeHost().pickFolder?.()).resolves.toBe("/Users/test/project"); expect(getRuntimeHost().surface).toBe("native");
expect(isNativeRuntime()).toBe(true);
}); });
it("rejects invalid loopback bridge bootstrap values", () => { it("rejects invalid loopback bridge bootstrap values", () => {
@@ -90,6 +80,7 @@ describe("runtime host facade", () => {
expect(initializeLoopbackRuntimeHost()).toBe(false); expect(initializeLoopbackRuntimeHost()).toBe(false);
expect(window.location.hash).toBe("#/new"); expect(window.location.hash).toBe("#/new");
expect(getRuntimeHost().pickFolder).toBeUndefined(); expect(getRuntimeHost().surface).toBe("browser");
expect(isNativeRuntime()).toBe(false);
}); });
}); });
-3
View File
@@ -1596,7 +1596,6 @@ describe("ThreadComposer", () => {
it("browses and selects the connected host's project in one dialog on a native client", async () => { it("browses and selects the connected host's project in one dialog on a native client", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onWorkspaceScopeChange = vi.fn(); const onWorkspaceScopeChange = vi.fn();
const pickFolder = vi.fn().mockResolvedValue("/Users/test/native-project");
const defaultScope = { const defaultScope = {
project_path: "/Users/test/.nanobot/workspace", project_path: "/Users/test/.nanobot/workspace",
project_name: "workspace", project_name: "workspace",
@@ -1618,7 +1617,6 @@ describe("ThreadComposer", () => {
value: { value: {
getRuntimeInfo: vi.fn(), getRuntimeInfo: vi.fn(),
restartEngine: vi.fn(), restartEngine: vi.fn(),
pickFolder,
openLogs: vi.fn(), openLogs: vi.fn(),
exportDiagnostics: vi.fn(), exportDiagnostics: vi.fn(),
}, },
@@ -1652,7 +1650,6 @@ describe("ThreadComposer", () => {
await user.click(screen.getByRole("button", { name: "Select" })); await user.click(screen.getByRole("button", { name: "Select" }));
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Choose project" })).not.toBeInTheDocument()); await waitFor(() => expect(screen.queryByRole("dialog", { name: "Choose project" })).not.toBeInTheDocument());
expect(onResolveWorkspaceProject).toHaveBeenCalledWith(project.path); expect(onResolveWorkspaceProject).toHaveBeenCalledWith(project.path);
expect(pickFolder).not.toHaveBeenCalled();
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
project_path: project.path, project_path: project.path,
project_name: project.name, project_name: project.name,