File size: 5,042 Bytes
1a6d0d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import { MantineProvider } from "@mantine/core";
import { act, cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import {
  afterEach,
  beforeEach,
  describe,
  expect,
  it,
  type Mock,
  vi,
} from "vitest";
import AiModelDownloadAllowanceContent from "@/components/AiResponse/AiModelDownloadAllowanceContent";
import { saveLlmResponseForQuery } from "./history";
import {
  getSettings,
  getTextGenerationState,
  listenToSettingsChanges,
  queryPubSub,
  settingsPubSub,
  updateTextGenerationState,
} from "./pubSub";
import { defaultSettings } from "./settings";
import { searchAndRespond } from "./textGeneration";
import { generateTextWithWllama } from "./textGenerationWithWllama";

const observedListeners = vi.hoisted(
  () =>
    [] as {
      callback: Mock<Parameters<typeof listenToSettingsChanges>[0]>;
      unsubscribe: Mock<() => void>;
    }[],
);

vi.mock("./pubSub", async (importOriginal) => {
  const actual = await importOriginal<typeof import("./pubSub")>();
  return {
    ...actual,
    listenToSettingsChanges: vi.fn(
      (...args: Parameters<typeof actual.listenToSettingsChanges>) => {
        const callback = vi.fn(args[0]);
        const unsubscribe = vi.fn(actual.listenToSettingsChanges(callback));
        observedListeners.push({ callback, unsubscribe });
        return unsubscribe;
      },
    ),
  };
});

vi.mock("./history", () => ({
  getCurrentSearchRunId: vi.fn(() => "permission-test"),
  saveLlmResponseForQuery: vi.fn().mockResolvedValue(undefined),
  updateSearchResults: vi.fn().mockResolvedValue(undefined),
}));

vi.mock("./search", () => ({
  searchText: vi.fn().mockResolvedValue({
    results: [["Fixture", "Search result", "https://example.com"]],
    stale: false,
  }),
  searchImages: vi.fn().mockResolvedValue({ results: [], stale: false }),
}));

vi.mock("./textGenerationWithWllama", () => ({
  generateTextWithWllama: vi.fn().mockResolvedValue(undefined),
  generateChatWithWllama: vi.fn(),
}));

describe("model-download permission lifecycle", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    observedListeners.length = 0;
    settingsPubSub[0]({
      ...defaultSettings,
      inferenceType: "browser",
      enableAiResponse: true,
      enableImageSearch: false,
      enablePageContentFetch: false,
    });
    queryPubSub[0]("Permission test");
    updateTextGenerationState("idle");
  });

  afterEach(() => {
    cleanup();
    for (const { unsubscribe } of observedListeners) unsubscribe();
  });

  it("continues without subscribing when downloads are already allowed", async () => {
    settingsPubSub[0]({ ...getSettings(), allowAiModelDownload: true });

    await searchAndRespond();

    expect(listenToSettingsChanges).not.toHaveBeenCalled();
    expect(generateTextWithWllama).toHaveBeenCalledOnce();
    expect(getTextGenerationState()).toBe("completed");
  });

  it("unsubscribes before continuing after the user allows a download", async () => {
    const generation = searchAndRespond();
    const { callback, unsubscribe } = observedListeners[0];
    render(
      <MantineProvider>
        <AiModelDownloadAllowanceContent />
      </MantineProvider>,
    );

    expect(getTextGenerationState()).toBe("awaitingModelDownloadAllowance");
    expect(generateTextWithWllama).not.toHaveBeenCalled();
    act(() => settingsPubSub[0]({ ...getSettings(), searchResultsLimit: 7 }));
    expect(unsubscribe).not.toHaveBeenCalled();
    expect(generateTextWithWllama).not.toHaveBeenCalled();

    await userEvent.click(
      screen.getByRole("button", { name: "Allow download" }),
    );
    await generation;

    expect(unsubscribe).toHaveBeenCalledOnce();
    expect(unsubscribe.mock.invocationCallOrder[0]).toBeLessThan(
      vi.mocked(generateTextWithWllama).mock.invocationCallOrder[0],
    );
    expect(generateTextWithWllama).toHaveBeenCalledOnce();
    expect(saveLlmResponseForQuery).toHaveBeenCalledOnce();
    expect(getTextGenerationState()).toBe("completed");
    const calls = callback.mock.calls.length;
    act(() => settingsPubSub[0]({ ...getSettings(), searchResultsLimit: 8 }));
    expect(callback).toHaveBeenCalledTimes(calls);
  });

  it("removes each completed wait across repeated permission requests", async () => {
    for (let attempt = 0; attempt < 3; attempt++) {
      settingsPubSub[0]({ ...getSettings(), allowAiModelDownload: false });
      const generation = searchAndRespond();
      expect(getTextGenerationState()).toBe("awaitingModelDownloadAllowance");
      settingsPubSub[0]({ ...getSettings(), allowAiModelDownload: true });
      await generation;
      expect(observedListeners[attempt].unsubscribe).toHaveBeenCalledOnce();
    }

    settingsPubSub[0]({ ...getSettings(), searchResultsLimit: 9 });
    for (const { callback, unsubscribe } of observedListeners) {
      expect(callback).toHaveBeenCalledOnce();
      expect(unsubscribe).toHaveBeenCalledOnce();
    }
    expect(generateTextWithWllama).toHaveBeenCalledTimes(3);
  });
});