File size: 8,921 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { chatApi } from "./chat";

// chat.ts uses both fetch (uploadFile) and the request wrapper (others) — mock both
vi.mock("../request", () => ({ request: vi.fn() }));
vi.mock("../config", () => ({
  getApiUrl: (path: string) => `/api${path}`,
  getApiToken: vi.fn(() => ""),
}));
vi.mock("../authHeaders", () => ({
  buildAuthHeaders: vi.fn(() => ({})),
}));

import { request } from "../request";
import { getApiToken } from "../config";

// ---------------------------------------------------------------------------
// filePreviewUrl — pure function, highest ROI
// ---------------------------------------------------------------------------
describe("chatApi.filePreviewUrl", () => {
  afterEach(() => vi.clearAllMocks());

  it("returns empty string for empty input", () => {
    expect(chatApi.filePreviewUrl("")).toBe("");
  });

  it("returns http URL as-is", () => {
    expect(chatApi.filePreviewUrl("http://cdn.com/img.png")).toBe(
      "http://cdn.com/img.png",
    );
  });

  it("returns https URL as-is", () => {
    expect(chatApi.filePreviewUrl("https://cdn.com/img.png")).toBe(
      "https://cdn.com/img.png",
    );
  });

  it("prepends /api/files/preview/ for relative paths", () => {
    const result = chatApi.filePreviewUrl("img.png");
    expect(result).toBe("/api/files/preview/img.png");
  });

  it("strips leading / from path", () => {
    const result = chatApi.filePreviewUrl("/img.png");
    expect(result).toBe("/api/files/preview/img.png");
  });

  it("appends ?token= param when token is present", () => {
    vi.mocked(getApiToken).mockReturnValue("my-token");
    const result = chatApi.filePreviewUrl("img.png");
    expect(result).toContain("?token=my-token");
  });

  it("URL-encodes token with special characters", () => {
    vi.mocked(getApiToken).mockReturnValue("tok en+1");
    const result = chatApi.filePreviewUrl("img.png");
    expect(result).toContain("token=tok%20en%2B1");
  });

  it("does not append query param when token is empty", () => {
    vi.mocked(getApiToken).mockReturnValue("");
    const result = chatApi.filePreviewUrl("img.png");
    expect(result).not.toContain("?token");
  });
});

// ---------------------------------------------------------------------------
// uploadFile — raw fetch, includes error handling logic
// ---------------------------------------------------------------------------
describe("chatApi.uploadFile", () => {
  afterEach(() => vi.clearAllMocks());

  it("returns url and file_name on successful upload", async () => {
    global.fetch = vi.fn().mockResolvedValue({
      ok: true,
      status: 200,
      json: () =>
        Promise.resolve({ url: "/uploads/img.png", file_name: "img.png" }),
    } as unknown as Response);

    const file = new File(["content"], "img.png", { type: "image/png" });
    const result = await chatApi.uploadFile(file);
    expect(result).toEqual({ url: "/uploads/img.png", file_name: "img.png" });
  });

  it("sends POST to /api/console/upload", async () => {
    global.fetch = vi.fn().mockResolvedValue({
      ok: true,
      json: () => Promise.resolve({ url: "", file_name: "" }),
    } as unknown as Response);

    await chatApi.uploadFile(new File([""], "f.txt"));
    expect(fetch).toHaveBeenCalledWith(
      "/api/console/upload",
      expect.objectContaining({ method: "POST" }),
    );
  });

  it("throws error with status code on upload failure", async () => {
    global.fetch = vi.fn().mockResolvedValue({
      ok: false,
      status: 413,
      statusText: "Payload Too Large",
      text: () => Promise.resolve("File too large"),
    } as unknown as Response);

    await expect(chatApi.uploadFile(new File([""], "big.bin"))).rejects.toThrow(
      "Upload failed: 413 Payload Too Large - File too large",
    );
  });

  it("throws error without dash when upload fails with empty body", async () => {
    global.fetch = vi.fn().mockResolvedValue({
      ok: false,
      status: 500,
      statusText: "Internal Server Error",
      text: () => Promise.resolve(""),
    } as unknown as Response);

    const err = await chatApi
      .uploadFile(new File([""], "f.bin"))
      .catch((e) => e);
    expect(err.message).toBe("Upload failed: 500 Internal Server Error");
  });
});

// ---------------------------------------------------------------------------
// listChats — query string construction
// ---------------------------------------------------------------------------
describe("chatApi.listChats", () => {
  beforeEach(() => vi.mocked(request).mockResolvedValue([]));
  afterEach(() => vi.clearAllMocks());

  it("calls /chats with no params", async () => {
    await chatApi.listChats();
    expect(request).toHaveBeenCalledWith("/chats");
  });

  it("builds query string with user_id", async () => {
    await chatApi.listChats({ user_id: "u1" });
    expect(request).toHaveBeenCalledWith("/chats?user_id=u1");
  });

  it("builds query string with channel", async () => {
    await chatApi.listChats({ channel: "console" });
    expect(request).toHaveBeenCalledWith("/chats?channel=console");
  });

  it("both params appear in query when both are provided", async () => {
    await chatApi.listChats({ user_id: "u1", channel: "dingtalk" });
    expect(request).toHaveBeenCalledWith(expect.stringContaining("user_id=u1"));
    expect(request).toHaveBeenCalledWith(
      expect.stringContaining("channel=dingtalk"),
    );
  });

  it("can exclude PawApp-owned dialogues for the main Chat surface", async () => {
    await chatApi.listChats({
      archived: false,
      include_app_owned: false,
    });
    expect(request).toHaveBeenCalledWith(
      "/chats?archived=false&include_app_owned=false",
    );
  });
});

// ---------------------------------------------------------------------------
// Other methods — verify path and HTTP method
// ---------------------------------------------------------------------------
describe("chatApi CRUD", () => {
  beforeEach(() => vi.mocked(request).mockResolvedValue(undefined));
  afterEach(() => vi.clearAllMocks());

  it("getChat encodes chatId and sends GET", async () => {
    await chatApi.getChat("chat/1");
    expect(request).toHaveBeenCalledWith(
      "/chats/chat%2F1",
      expect.objectContaining({ signal: undefined }),
    );
  });

  it("getChat can exclude PawApp-owned dialogue history", async () => {
    await chatApi.getChat("chat-1", { include_app_owned: false });
    expect(request).toHaveBeenCalledWith(
      "/chats/chat-1?include_app_owned=false",
      expect.objectContaining({ signal: undefined }),
    );
  });

  it("updateChat sends PUT to the correct path", async () => {
    await chatApi.updateChat("chat-1", { name: "New Name" });
    expect(request).toHaveBeenCalledWith(
      "/chats/chat-1",
      expect.objectContaining({ method: "PUT" }),
    );
  });

  it("deleteChat sends DELETE to the correct path", async () => {
    await chatApi.deleteChat("chat-1");
    expect(request).toHaveBeenCalledWith(
      "/chats/chat-1",
      expect.objectContaining({ method: "DELETE" }),
    );
  });

  it("stopChat encodes chatId and appends query param", async () => {
    await chatApi.stopChat("chat/1");
    expect(request).toHaveBeenCalledWith(
      "/console/chat/stop?chat_id=chat%2F1",
      expect.objectContaining({ method: "POST" }),
    );
  });

  it("batchDeleteChats sends POST with list of ids", async () => {
    await chatApi.batchDeleteChats(["id1", "id2"]);
    expect(request).toHaveBeenCalledWith(
      "/chats/batch-delete",
      expect.objectContaining({
        method: "POST",
        body: JSON.stringify(["id1", "id2"]),
      }),
    );
  });

  it("creates and renames chat groups", async () => {
    await chatApi.createGroup("Work");
    expect(request).toHaveBeenCalledWith(
      "/chats/groups",
      expect.objectContaining({
        method: "POST",
        body: JSON.stringify({ name: "Work" }),
      }),
    );

    await chatApi.updateGroup("group/1", { name: "Projects" });
    expect(request).toHaveBeenCalledWith(
      "/chats/groups/group%2F1",
      expect.objectContaining({
        method: "PUT",
        body: JSON.stringify({ name: "Projects" }),
      }),
    );
  });

  it("pins a chat group", async () => {
    await chatApi.updateGroup("group-1", { pinned: true });
    expect(request).toHaveBeenCalledWith(
      "/chats/groups/group-1",
      expect.objectContaining({
        method: "PUT",
        body: JSON.stringify({ pinned: true }),
      }),
    );
  });

  it("persists the complete chat-group order", async () => {
    await chatApi.reorderGroups(["default", "subagents"]);
    expect(request).toHaveBeenCalledWith(
      "/chats/groups/order",
      expect.objectContaining({
        method: "PUT",
        body: JSON.stringify({ group_ids: ["default", "subagents"] }),
      }),
    );
  });
});