Skip to content

Open-source, local-first AI agent for real work.

2.6 KB
Raw Blame
// @vitest-environment jsdom
import { renderHook } from "@testing-library/react";
import { createStore, Provider } from "jotai";
import type { ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { browserUrlByWorkspaceAtom, linkOpenTargetAtom, type LinkOpenTarget } from "@shared/store/atoms";
import { useRendererMarkdownModel } from "./useRendererMarkdownModel";

vi.mock("./useMarkdownHost", () => ({ useMarkdownHost: () => undefined }));

/** 交给系统打开的网址,按顺序记录:断言整段序列,多开一次也会被发现。 */
const openedExternally: string[] = [];
async function openExternal(url: string): Promise<undefined> {
	openedExternally.push(url);
	return undefined;
}

function setup(preference: LinkOpenTarget, cwd: string | null = "/repo") {
	const store = createStore();
	store.set(linkOpenTargetAtom, preference);
	const wrapper = ({ children }: { children: ReactNode }) => <Provider store={store}>{children}</Provider>;
	const { result } = renderHook(() => useRendererMarkdownModel(cwd), { wrapper });
	return { store, onOpenUrl: result.current.onOpenUrl };
}

describe("useRendererMarkdownModel link routing", () => {
	beforeEach(() => {
		openedExternally.length = 0;
		Object.defineProperty(window, "vetta", { configurable: true, value: { shell: { openExternal } } });
	});

	it("opens in the workspace browser by default and in the system browser as the alternate", () => {
		const { store, onOpenUrl } = setup("builtin");
		onOpenUrl("https://example.test/a");
		expect(store.get(browserUrlByWorkspaceAtom).get("/repo")).toBe("https://example.test/a");
		expect(openedExternally).toEqual([]);
		onOpenUrl("https://example.test/b", { alternate: true });
		expect(openedExternally).toEqual(["https://example.test/b"]);
	});

	it("opens in the system browser when the user prefers it, and in Vetta as the alternate", () => {
		const { store, onOpenUrl } = setup("system");
		onOpenUrl("https://example.test/a");
		expect(openedExternally).toEqual(["https://example.test/a"]);
		onOpenUrl("https://example.test/b", { alternate: true });
		expect(store.get(browserUrlByWorkspaceAtom).get("/repo")).toBe("https://example.test/b");
		expect(openedExternally).toEqual(["https://example.test/a"]);
	});

	it("falls back to the system for mail links and when no workspace can host the browser", () => {
		setup("builtin").onOpenUrl("mailto:[email protected]");
		expect(openedExternally).toEqual(["mailto:[email protected]"]);
		setup("builtin", null).onOpenUrl("https://example.test/c");
		expect(openedExternally).toEqual(["mailto:[email protected]", "https://example.test/c"]);
	});
});