File size: 5,801 Bytes
4e7644b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
 * Regression tests for cross-agent ownership in the shared session-list CRUD
 * handlers: a delete started under agent A must not mutate the view after the
 * user switches to agent B, while same-agent CRUD keeps working.
 */
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderHook, act, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import React from "react";
import { App } from "antd";
import { MemoryRouter } from "react-router-dom";
import type { ChatSpec } from "../../../../api";
import api from "../../../../api";
import { chatApi } from "../../../../api/modules/chat";
import sessionApi from "../../sessionApi";
import { useAgentStore } from "../../../../stores/agentStore";
import { useSessionListStore } from "../../../../stores/sessionListStore";
import {
  useSessionListData,
  type ExtendedChatSession,
} from "./useSessionListData";

function deferred<T>() {
  let resolve!: (value: T) => void;
  let reject!: (reason?: unknown) => void;
  const promise = new Promise<T>((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}

const A_CHAT = "33333333-aaaa-4aaa-8aaa-333333333333";

const makeSession = (id: string): ExtendedChatSession =>
  ({ id, name: id, messages: [] }) as unknown as ExtendedChatSession;

function wrapper({ children }: { children: ReactNode }) {
  return React.createElement(
    App,
    null,
    React.createElement(MemoryRouter, null, children),
  );
}

function renderListData(sessions: ExtendedChatSession[]) {
  const setSessions = vi.fn();
  const hook = renderHook(
    () =>
      useSessionListData(sessions, setSessions, {
        active: false,
        currentSessionId: A_CHAT,
        onSessionClick: vi.fn(),
      }),
    { wrapper },
  );
  return { hook, setSessions };
}

beforeEach(() => {
  sessionApi.resetForTests();
  useAgentStore.setState({ selectedAgent: "agent-a", lastChatIdByAgent: {} });
  useSessionListStore.setState({
    sessions: [],
    lastUpdated: 0,
    _setLibrarySessions: null,
  });
});

afterEach(() => {
  vi.restoreAllMocks();
  sessionApi.resetForTests();
});

describe("useSessionListData cross-agent ownership", () => {
  it("a delete finishing after an agent switch does not mutate the new view", async () => {
    sessionApi.setActiveAgent("agent-a");
    const onSessionRemoved = vi.fn();
    sessionApi.onSessionRemoved = onSessionRemoved;
    const newChatListener = vi.fn();
    window.addEventListener("qwenpaw:sidebar-new-chat", newChatListener);

    const dDelete = deferred<Awaited<ReturnType<typeof chatApi.deleteChat>>>();
    vi.spyOn(chatApi, "deleteChat").mockReturnValue(dDelete.promise);
    const listSpy = vi.spyOn(api, "listChats").mockResolvedValue([]);

    const { hook, setSessions } = renderListData([makeSession(A_CHAT)]);

    act(() => {
      hook.result.current.handleDelete(A_CHAT);
    });

    // The user switches to agent B while the backend delete is in flight.
    sessionApi.setActiveAgent("agent-b");
    useSessionListStore.setState({ sessions: [makeSession("chat-b")] });

    dDelete.resolve({} as Awaited<ReturnType<typeof chatApi.deleteChat>>);
    await act(async () => {
      await new Promise((res) => setTimeout(res, 0));
    });

    // The late completion must not touch B's view or callbacks.
    expect(onSessionRemoved).not.toHaveBeenCalled();
    expect(setSessions).not.toHaveBeenCalled();
    expect(useSessionListStore.getState().sessions.map((s) => s.id)).toEqual([
      "chat-b",
    ]);
    expect(newChatListener).not.toHaveBeenCalled();
    expect(listSpy).not.toHaveBeenCalled();

    window.removeEventListener("qwenpaw:sidebar-new-chat", newChatListener);
  });

  it("a same-agent delete still refreshes the list and fires callbacks", async () => {
    sessionApi.setActiveAgent("agent-a");
    const onSessionRemoved = vi.fn();
    sessionApi.onSessionRemoved = onSessionRemoved;

    vi.spyOn(chatApi, "deleteChat").mockResolvedValue(
      {} as Awaited<ReturnType<typeof chatApi.deleteChat>>,
    );
    vi.spyOn(api, "listChats").mockResolvedValue([] as ChatSpec[]);

    const { hook, setSessions } = renderListData([makeSession(A_CHAT)]);

    await act(async () => {
      hook.result.current.handleDelete(A_CHAT);
      await new Promise((res) => setTimeout(res, 0));
    });

    expect(onSessionRemoved).toHaveBeenCalledWith(A_CHAT);
    expect(setSessions).toHaveBeenCalled();
  });

  it("updates the backend when a conversation is pinned within its group", async () => {
    sessionApi.setActiveAgent("agent-a");
    const updateSpy = vi
      .spyOn(chatApi, "updateChat")
      .mockResolvedValue({} as Awaited<ReturnType<typeof chatApi.updateChat>>);
    const listSpy = vi
      .spyOn(api, "listChats")
      .mockResolvedValue([] as ChatSpec[]);
    const { hook } = renderListData([makeSession(A_CHAT)]);

    await act(async () => {
      await hook.result.current.handlePinToggle(A_CHAT, true);
    });

    expect(updateSpy).toHaveBeenCalledWith(A_CHAT, { pinned: true });
    expect(listSpy).toHaveBeenCalledOnce();
  });

  it("refetches the list immediately when the selected agent changes", async () => {
    sessionApi.setActiveAgent("agent-a");
    const listSpy = vi.spyOn(api, "listChats").mockResolvedValue([]);
    const setSessions = vi.fn();

    renderHook(
      () =>
        useSessionListData([], setSessions, {
          active: true,
          currentSessionId: undefined,
          onSessionClick: vi.fn(),
        }),
      { wrapper },
    );
    await waitFor(() => expect(listSpy).toHaveBeenCalledTimes(1));

    act(() => {
      useAgentStore.setState({ selectedAgent: "agent-b" });
    });

    await waitFor(() => expect(listSpy).toHaveBeenCalledTimes(2));
  });
});