feedbackHttpClient.test.ts 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { createServer, type IncomingMessage, type Server } from "node:http";
  3. import { mkdtemp, rm, truncate, writeFile } from "node:fs/promises";
  4. import { release, tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import type {
  7. ApiRequestInit,
  8. ApiClient,
  9. FeedbackDeviceInfo,
  10. FeedbackTicketSeverity,
  11. FeedbackTicketType,
  12. } from "@zcode/shared";
  13. import type { ICredentialService } from "../src/credential/credential.js";
  14. import { FeedbackHttpClient } from "../src/feedback/feedbackHttpClient.js";
  15. import { createFeedbackService } from "../src/feedback/feedbackService.js";
  16. import type { IOAuthService } from "../src/oauth/oauth.js";
  17. import { setDataBaseDir } from "../src/paths.js";
  18. import type { ServiceLogger } from "../src/logger/serviceLogger.js";
  19. import { createNodeApiClient } from "#src/providers/api/nodeApiClient.js";
  20. const REQUEST_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  21. const ONE_GIB_BYTES = 1024 * 1024 * 1024;
  22. async function startTestServer(
  23. handler: Parameters<typeof createServer>[0],
  24. ): Promise<{ server: Server; port: number }> {
  25. const server = createServer(handler);
  26. await new Promise<void>((resolve) => {
  27. server.listen(0, "127.0.0.1", resolve);
  28. });
  29. const address = server.address();
  30. if (!address || typeof address === "string") {
  31. throw new Error("Test server did not bind to a TCP port");
  32. }
  33. return { server, port: address.port };
  34. }
  35. async function closeTestServer(server: Server): Promise<void> {
  36. await new Promise<void>((resolve, reject) => {
  37. server.close((error) => {
  38. if (error) {
  39. reject(error);
  40. return;
  41. }
  42. resolve();
  43. });
  44. });
  45. }
  46. async function readRequestBody(request: IncomingMessage): Promise<Buffer> {
  47. const chunks: Buffer[] = [];
  48. for await (const chunk of request) {
  49. chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  50. }
  51. return Buffer.concat(chunks);
  52. }
  53. function epochSeconds(year: number, month: number, day: number, hour = 0): number {
  54. return Math.floor(Date.UTC(year, month - 1, day, hour, 0, 0) / 1000);
  55. }
  56. function makeCredentialService(
  57. loadValue: (key: string) => string | null = () => null,
  58. ): ICredentialService {
  59. return {
  60. load: vi.fn(async (key: string) => loadValue(key)),
  61. save: vi.fn(async () => {}),
  62. delete: vi.fn(async () => {}),
  63. };
  64. }
  65. function makeOAuthService(): IOAuthService {
  66. return {
  67. getProviders: vi.fn(async () => []),
  68. getActiveProvider: vi.fn(async () => null),
  69. restoreCachedSession: vi.fn(async () => null),
  70. restoreSession: vi.fn(async () => null),
  71. startOAuth: vi.fn(),
  72. handleCallback: vi.fn(),
  73. refreshToken: vi.fn(),
  74. logout: vi.fn(),
  75. logoutAll: vi.fn(),
  76. cancelPending: vi.fn(),
  77. } as unknown as IOAuthService;
  78. }
  79. function makeFetchApiClient(): ApiClient {
  80. return {
  81. request: (input, init) => fetch(input, init),
  82. };
  83. }
  84. function makeClient(
  85. baseUrl = "https://zcode.z.ai/api/v1",
  86. logger?: ServiceLogger,
  87. ): FeedbackHttpClient {
  88. return new FeedbackHttpClient({
  89. baseUrl,
  90. apiClient: makeFetchApiClient(),
  91. getAuthHeaders: async () => ({
  92. Authorization: "Bearer test-jwt",
  93. "X-Device-Mid": "desktop-device-mid-test",
  94. }),
  95. logger,
  96. });
  97. }
  98. describe("FeedbackHttpClient", () => {
  99. afterEach(() => {
  100. vi.unstubAllGlobals();
  101. });
  102. it("sends feedback API requests through the injected zcode api client", async () => {
  103. const createdAt = epochSeconds(2026, 6, 25, 10);
  104. const apiClient: ApiClient = {
  105. request: vi.fn(async () => {
  106. return new Response(
  107. JSON.stringify({
  108. code: 0,
  109. msg: "ok",
  110. data: {
  111. ticket_id: "fbk_1",
  112. device_mid: "desktop-device-mid-test",
  113. status: "submitted",
  114. created_at: createdAt,
  115. },
  116. }),
  117. { status: 200, headers: { "Content-Type": "application/json" } },
  118. );
  119. }),
  120. };
  121. const globalFetch = vi.fn(async () => {
  122. throw new Error("global fetch should not be used for feedback API requests");
  123. });
  124. vi.stubGlobal("fetch", globalFetch);
  125. const client = new FeedbackHttpClient({
  126. baseUrl: "https://zcode.z.ai/api/v1",
  127. getAuthHeaders: async () => ({
  128. Authorization: "Bearer test-jwt",
  129. "X-Device-Mid": "desktop-device-mid-test",
  130. }),
  131. apiClient,
  132. });
  133. await expect(
  134. client.create({
  135. title: "ticket",
  136. description: "desc",
  137. type: "bug",
  138. severity: "P2-中",
  139. locale: "en-US",
  140. device: {
  141. appVersion: "1.2.3",
  142. osPlatform: "darwin",
  143. osVersion: "23.1.0",
  144. },
  145. }),
  146. ).resolves.toMatchObject({ id: "fbk_1" });
  147. expect(apiClient.request).toHaveBeenCalledTimes(1);
  148. expect(globalFetch).not.toHaveBeenCalled();
  149. const [url, init] = vi.mocked(apiClient.request).mock.calls[0];
  150. expect(String(url)).toBe("https://zcode.z.ai/api/v1/feedback/ticket");
  151. const headers = init?.headers as Record<string, string>;
  152. expect(headers.Authorization).toBe("Bearer test-jwt");
  153. expect(headers["X-Device-Mid"]).toBe("desktop-device-mid-test");
  154. expect(headers["Accept-Language"]).toBe("en-US");
  155. expect(headers["x-request-id"]).toMatch(REQUEST_ID_PATTERN);
  156. });
  157. it("creates tickets through the wrapped new feedback API", async () => {
  158. const createdAt = epochSeconds(2026, 6, 25, 10);
  159. const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
  160. const headers = init?.headers as Record<string, string>;
  161. const body = JSON.parse(String(init?.body ?? "{}")) as {
  162. title?: string;
  163. device_mid?: string;
  164. content?: {
  165. description?: string;
  166. category?: FeedbackTicketType;
  167. function?: string;
  168. severity?: FeedbackTicketSeverity;
  169. };
  170. contact?: string;
  171. environment?: Record<string, unknown>;
  172. };
  173. expect(String(url)).toBe("https://zcode.z.ai/api/v1/feedback/ticket");
  174. expect(headers.Authorization).toBe("Bearer test-jwt");
  175. expect(headers["X-Device-Mid"]).toBe("desktop-device-mid-test");
  176. expect(headers["Accept-Language"]).toBe("en-US");
  177. expect(headers["x-request-id"]).toMatch(REQUEST_ID_PATTERN);
  178. expect(body).toMatchObject({
  179. title: "ticket",
  180. device_mid: "desktop-device-mid-test",
  181. content: {
  182. description: "desc",
  183. category: "bug",
  184. severity: "P2-中",
  185. },
  186. contact: "me@example.com",
  187. });
  188. expect(body).not.toHaveProperty("description");
  189. expect(body.environment).toMatchObject({
  190. app_version: "1.2.3",
  191. platform: "darwin-aarch64",
  192. os_category: "darwin",
  193. os_version: "23.1.0",
  194. build_commit_id: "abc123",
  195. agent_framework: "zcode-agent",
  196. });
  197. expect(body.environment).not.toHaveProperty("module");
  198. return new Response(
  199. JSON.stringify({
  200. code: 0,
  201. msg: "ok",
  202. data: {
  203. ticket_id: "fbk_1",
  204. device_mid: "desktop-device-mid-test",
  205. status: "submitted",
  206. created_at: createdAt,
  207. },
  208. }),
  209. { status: 200, headers: { "Content-Type": "application/json" } },
  210. );
  211. });
  212. vi.stubGlobal("fetch", fetchMock);
  213. const device: FeedbackDeviceInfo = {
  214. appVersion: "1.2.3",
  215. buildCommitId: "abc123",
  216. osPlatform: "darwin",
  217. osVersion: "23.1.0",
  218. osArch: "arm64",
  219. agentFramework: "zcode-agent",
  220. };
  221. const ticket = await makeClient().create({
  222. title: "ticket",
  223. description: "desc",
  224. type: "bug",
  225. severity: "P2-中",
  226. contact: "me@example.com",
  227. locale: "en-US",
  228. device,
  229. });
  230. expect(ticket).toMatchObject({
  231. id: "fbk_1",
  232. title: "ticket",
  233. type: "bug",
  234. severity: "P2-中",
  235. status: "已提交",
  236. description: "desc",
  237. device,
  238. attachments: [],
  239. comments: [],
  240. events: [],
  241. });
  242. expect(ticket.created_at).toBe(new Date(createdAt * 1000).toISOString());
  243. expect(ticket.updated_at).toBe(new Date(createdAt * 1000).toISOString());
  244. });
  245. it("lists logged-in tickets from the wrapped server response", async () => {
  246. const createdAt = epochSeconds(2026, 6, 24, 9);
  247. const updatedAt = epochSeconds(2026, 6, 25, 9);
  248. const fetchMock = vi.fn(
  249. async () =>
  250. new Response(
  251. JSON.stringify({
  252. code: 0,
  253. msg: "ok",
  254. data: {
  255. items: [
  256. {
  257. ticket_id: "fbk_2",
  258. device_mid: "fb_device",
  259. title: "closed ticket",
  260. status: "closed",
  261. created_at: createdAt,
  262. updated_at: updatedAt,
  263. },
  264. ],
  265. },
  266. }),
  267. { status: 200, headers: { "Content-Type": "application/json" } },
  268. ),
  269. );
  270. vi.stubGlobal("fetch", fetchMock);
  271. await expect(makeClient().list({ mine: true, limit: 50, offset: 10 })).resolves.toEqual({
  272. total: 1,
  273. items: [
  274. {
  275. id: "fbk_2",
  276. title: "closed ticket",
  277. type: "bug",
  278. status: "已归档",
  279. created_at: new Date(createdAt * 1000).toISOString(),
  280. updated_at: new Date(updatedAt * 1000).toISOString(),
  281. },
  282. ],
  283. });
  284. expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
  285. "https://zcode.z.ai/api/v1/feedback/ticket?limit=50&offset=10",
  286. );
  287. });
  288. it("passes zero list limit to the feedback API", async () => {
  289. const fetchMock = vi.fn(
  290. async () =>
  291. new Response(
  292. JSON.stringify({
  293. code: 0,
  294. msg: "ok",
  295. data: {
  296. items: [],
  297. },
  298. }),
  299. { status: 200, headers: { "Content-Type": "application/json" } },
  300. ),
  301. );
  302. vi.stubGlobal("fetch", fetchMock);
  303. await expect(makeClient().list({ limit: 0 })).resolves.toEqual({
  304. items: [],
  305. total: 0,
  306. });
  307. expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
  308. "https://zcode.z.ai/api/v1/feedback/ticket?limit=0",
  309. );
  310. });
  311. it("maps detail messages into comments for the existing UI contract", async () => {
  312. const createdAt = epochSeconds(2026, 6, 25, 8);
  313. const messageAt = epochSeconds(2026, 6, 25, 9);
  314. const fetchMock = vi.fn(
  315. async () =>
  316. new Response(
  317. JSON.stringify({
  318. code: 0,
  319. msg: "ok",
  320. data: {
  321. ticket_id: "fbk_3",
  322. device_mid: "fb_device",
  323. title: "detail ticket",
  324. status: "submitted",
  325. content: {
  326. description: "detail desc",
  327. category: "usage",
  328. function: "Plugin / MCP",
  329. severity: "P3-低",
  330. },
  331. environment: {
  332. app_version: "1.2.3",
  333. os_category: "darwin",
  334. os_version: "23.1.0",
  335. },
  336. attachments: [
  337. {
  338. attachment_id: "att_1",
  339. file_name: "shot.png",
  340. size: 12,
  341. created_at: createdAt,
  342. },
  343. ],
  344. messages: [
  345. {
  346. message_id: "msg_1",
  347. ticket_id: "fbk_3",
  348. sender_type: "user",
  349. content: { text: "补充信息" },
  350. attachments: [],
  351. created_at: messageAt,
  352. },
  353. ],
  354. created_at: createdAt,
  355. updated_at: messageAt,
  356. },
  357. }),
  358. { status: 200, headers: { "Content-Type": "application/json" } },
  359. ),
  360. );
  361. vi.stubGlobal("fetch", fetchMock);
  362. const ticket = await makeClient().get("fbk_3");
  363. expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
  364. "https://zcode.z.ai/api/v1/feedback/ticket/fbk_3",
  365. );
  366. expect(ticket).toMatchObject({
  367. id: "fbk_3",
  368. title: "detail ticket",
  369. type: "usage",
  370. severity: "P3-低",
  371. status: "已提交",
  372. description: "detail desc",
  373. device: {
  374. appVersion: "1.2.3",
  375. osPlatform: "darwin",
  376. osVersion: "23.1.0",
  377. },
  378. attachments: [{ filename: "shot.png", size: 12, kind: "image" }],
  379. comments: [{ body: "补充信息", is_staff: false }],
  380. });
  381. });
  382. it("posts ticket messages through the new message API", async () => {
  383. const createdAt = epochSeconds(2026, 6, 25, 11);
  384. const logger: ServiceLogger = {
  385. debug: vi.fn(),
  386. info: vi.fn(),
  387. warn: vi.fn(),
  388. error: vi.fn(),
  389. };
  390. const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
  391. const body = JSON.parse(String(init?.body ?? "{}")) as {
  392. content?: { text?: string };
  393. };
  394. expect(String(url)).toBe("https://zcode.z.ai/api/v1/feedback/ticket/fbk_4/message");
  395. expect(body).toEqual({ content: { text: "追加说明" } });
  396. return new Response(
  397. JSON.stringify({
  398. code: 0,
  399. msg: "ok",
  400. data: {
  401. message_id: "msg_2",
  402. ticket_id: "fbk_4",
  403. sender_type: "user",
  404. content: { text: "追加说明" },
  405. attachments: [],
  406. created_at: createdAt,
  407. },
  408. }),
  409. { status: 200, headers: { "Content-Type": "application/json" } },
  410. );
  411. });
  412. vi.stubGlobal("fetch", fetchMock);
  413. await expect(makeClient(undefined, logger).comment("fbk_4", "追加说明")).resolves.toMatchObject(
  414. {
  415. message_id: "msg_2",
  416. body: "追加说明",
  417. is_staff: false,
  418. created_at: new Date(createdAt * 1000).toISOString(),
  419. },
  420. );
  421. expect(logger.info).toHaveBeenCalledWith(
  422. undefined,
  423. "反馈 HTTP 请求开始",
  424. expect.objectContaining({
  425. url: "https://zcode.z.ai/api/v1/feedback/ticket/:ticketId/message",
  426. }),
  427. );
  428. expect(JSON.stringify(vi.mocked(logger.info).mock.calls)).not.toContain("fbk_4");
  429. });
  430. it("retries feedback requests when TLS handshake is reset before reaching backend", async () => {
  431. const fetchMock = vi
  432. .fn()
  433. .mockRejectedValueOnce(
  434. new TypeError("fetch failed", {
  435. cause: Object.assign(
  436. new Error(
  437. "Client network socket disconnected before secure TLS connection was established",
  438. ),
  439. { code: "ECONNRESET" },
  440. ),
  441. }),
  442. )
  443. .mockResolvedValueOnce(
  444. new Response(JSON.stringify({ code: 0, msg: "ok", data: { items: [] } }), {
  445. status: 200,
  446. headers: { "Content-Type": "application/json" },
  447. }),
  448. );
  449. vi.stubGlobal("fetch", fetchMock);
  450. await expect(makeClient().list({ mine: true })).resolves.toEqual({ items: [], total: 0 });
  451. expect(fetchMock).toHaveBeenCalledTimes(2);
  452. });
  453. it("retries feedback requests through repeated transient connection failures", async () => {
  454. const timeoutCause = Object.assign(new AggregateError([], "connection attempts timed out"), {
  455. code: "ETIMEDOUT",
  456. });
  457. const fetchMock = vi
  458. .fn()
  459. .mockRejectedValueOnce(new TypeError("fetch failed", { cause: timeoutCause }))
  460. .mockRejectedValueOnce(new TypeError("fetch failed", { cause: timeoutCause }))
  461. .mockResolvedValueOnce(
  462. new Response(JSON.stringify({ code: 0, msg: "ok", data: { items: [] } }), {
  463. status: 200,
  464. headers: { "Content-Type": "application/json" },
  465. }),
  466. );
  467. vi.stubGlobal("fetch", fetchMock);
  468. await expect(makeClient().list({ mine: true })).resolves.toEqual({ items: [], total: 0 });
  469. expect(fetchMock).toHaveBeenCalledTimes(3);
  470. });
  471. it("retries feedback requests when connection attempts time out as an aggregate fetch failure", async () => {
  472. const timeoutCause = Object.assign(new Error("connect ETIMEDOUT"), { code: "ETIMEDOUT" });
  473. const aggregateCause = new AggregateError([timeoutCause], "connection attempts timed out");
  474. const fetchMock = vi
  475. .fn()
  476. .mockRejectedValueOnce(new TypeError("fetch failed", { cause: aggregateCause }))
  477. .mockResolvedValueOnce(
  478. new Response(JSON.stringify({ code: 0, msg: "ok", data: { items: [] } }), {
  479. status: 200,
  480. headers: { "Content-Type": "application/json" },
  481. }),
  482. );
  483. vi.stubGlobal("fetch", fetchMock);
  484. await expect(makeClient().list({ mine: true })).resolves.toEqual({ items: [], total: 0 });
  485. expect(fetchMock).toHaveBeenCalledTimes(2);
  486. });
  487. it("retries ticket creation when Undici times out before connecting to the feedback API", async () => {
  488. const connectTimeoutCause = Object.assign(
  489. new Error("Connect Timeout Error (attempted address: zcode.z.ai:443, timeout: 10000ms)"),
  490. {
  491. name: "ConnectTimeoutError",
  492. code: "UND_ERR_CONNECT_TIMEOUT",
  493. },
  494. );
  495. const fetchMock = vi
  496. .fn()
  497. .mockRejectedValueOnce(new TypeError("fetch failed", { cause: connectTimeoutCause }))
  498. .mockResolvedValueOnce(
  499. new Response(
  500. JSON.stringify({
  501. code: 0,
  502. msg: "ok",
  503. data: {
  504. ticket_id: "fbk_connect_timeout_retry",
  505. status: "submitted",
  506. created_at: epochSeconds(2026, 7, 15, 8),
  507. },
  508. }),
  509. { status: 200, headers: { "Content-Type": "application/json" } },
  510. ),
  511. );
  512. const client = new FeedbackHttpClient({
  513. baseUrl: "https://zcode.z.ai/api/v1",
  514. apiClient: createNodeApiClient({ fetchImpl: fetchMock as typeof fetch }),
  515. getAuthHeaders: async () => ({ "X-Device-Mid": "desktop-device-mid-test" }),
  516. });
  517. await expect(
  518. client.create({ title: "连接超时", description: "重试后提交成功", type: "bug" }),
  519. ).resolves.toMatchObject({ id: "fbk_connect_timeout_retry" });
  520. expect(fetchMock).toHaveBeenCalledTimes(2);
  521. });
  522. it("does not retry ticket creation when a reset may have happened after the request was sent", async () => {
  523. const fetchMock = vi
  524. .fn()
  525. .mockRejectedValueOnce(
  526. new TypeError("fetch failed", {
  527. cause: Object.assign(new Error("socket hang up"), { code: "ECONNRESET" }),
  528. }),
  529. )
  530. .mockResolvedValueOnce(
  531. new Response(
  532. JSON.stringify({
  533. code: 0,
  534. msg: "ok",
  535. data: {
  536. ticket_id: "fbk_duplicate",
  537. status: "submitted",
  538. created_at: epochSeconds(2026, 7, 15, 8),
  539. },
  540. }),
  541. { status: 200, headers: { "Content-Type": "application/json" } },
  542. ),
  543. );
  544. const client = new FeedbackHttpClient({
  545. baseUrl: "https://zcode.z.ai/api/v1",
  546. apiClient: createNodeApiClient({ fetchImpl: fetchMock as typeof fetch }),
  547. getAuthHeaders: async () => ({ "X-Device-Mid": "desktop-device-mid-test" }),
  548. });
  549. await expect(
  550. client.create({ title: "连接重置", description: "不能重复创建", type: "bug" }),
  551. ).rejects.toThrow("fetch failed");
  552. expect(fetchMock).toHaveBeenCalledTimes(1);
  553. });
  554. it("does not retry ticket creation for a generic ETIMEDOUT after sending the request", async () => {
  555. const fetchMock = vi.fn().mockRejectedValue(
  556. new TypeError("fetch failed", {
  557. cause: Object.assign(new Error("socket timed out while awaiting response"), {
  558. code: "ETIMEDOUT",
  559. }),
  560. }),
  561. );
  562. const client = new FeedbackHttpClient({
  563. baseUrl: "https://zcode.z.ai/api/v1",
  564. apiClient: createNodeApiClient({ fetchImpl: fetchMock as typeof fetch }),
  565. getAuthHeaders: async () => ({ "X-Device-Mid": "desktop-device-mid-test" }),
  566. });
  567. await expect(
  568. client.create({ title: "响应超时", description: "不能重复创建", type: "bug" }),
  569. ).rejects.toThrow("fetch failed");
  570. expect(fetchMock).toHaveBeenCalledTimes(1);
  571. });
  572. it("reports three attempts when an Undici connect timeout remains unavailable", async () => {
  573. const connectTimeoutCause = Object.assign(new Error("Connect Timeout Error"), {
  574. name: "ConnectTimeoutError",
  575. code: "UND_ERR_CONNECT_TIMEOUT",
  576. });
  577. const fetchMock = vi
  578. .fn()
  579. .mockRejectedValue(new TypeError("fetch failed", { cause: connectTimeoutCause }));
  580. const logger: ServiceLogger = {
  581. debug: vi.fn(),
  582. info: vi.fn(),
  583. warn: vi.fn(),
  584. error: vi.fn(),
  585. };
  586. const client = new FeedbackHttpClient({
  587. baseUrl: "https://zcode.z.ai/api/v1",
  588. apiClient: createNodeApiClient({ fetchImpl: fetchMock as typeof fetch }),
  589. getAuthHeaders: async () => ({ "X-Device-Mid": "desktop-device-mid-test" }),
  590. logger,
  591. });
  592. await expect(
  593. client.create({ title: "持续建连超时", description: "三次后失败", type: "bug" }),
  594. ).rejects.toThrow("fetch failed");
  595. expect(fetchMock).toHaveBeenCalledTimes(3);
  596. expect(logger.warn).toHaveBeenCalledWith(
  597. undefined,
  598. "反馈 HTTP 请求网络失败",
  599. expect.objectContaining({
  600. attemptCount: 3,
  601. errorCodes: ["UND_ERR_CONNECT_TIMEOUT"],
  602. url: "https://zcode.z.ai/api/v1/feedback/ticket",
  603. }),
  604. );
  605. });
  606. it("uploads attachments through upload credentials and OSS form post", async () => {
  607. const tempDir = await mkdtemp(join(tmpdir(), "feedback-http-client-"));
  608. const filePath = join(tempDir, "shot.png");
  609. const payload = Buffer.from("image-payload");
  610. await writeFile(filePath, payload);
  611. const credentialBodies: unknown[] = [];
  612. const ossBodies: Buffer[] = [];
  613. const progressEvents: Array<{ uploadedBytes: number; totalBytes: number }> = [];
  614. const logger: ServiceLogger = {
  615. debug: vi.fn(),
  616. info: vi.fn(),
  617. warn: vi.fn(),
  618. error: vi.fn(),
  619. };
  620. const server = await startTestServer((request, response) => {
  621. if (request.url === "/feedback/attachment/upload-credential") {
  622. void readRequestBody(request).then((body) => {
  623. credentialBodies.push(JSON.parse(body.toString("utf8")));
  624. response.setHeader("Content-Type", "application/json");
  625. response.end(
  626. JSON.stringify({
  627. code: 0,
  628. msg: "ok",
  629. data: {
  630. attachment_id: "att_oss",
  631. max_size: 100 * 1024 * 1024,
  632. callback: {
  633. url: "https://zcode.z.ai/api/v1/feedback/attachment/callback",
  634. body: "callback-body",
  635. content_type: "application/json",
  636. },
  637. oss: {
  638. host: `http://127.0.0.1:${server.port}`,
  639. path: "feedback/att_oss/shot.png",
  640. policy: "policy-value",
  641. x_oss_signature: "signature-value",
  642. x_oss_signature_version: "OSS4-HMAC-SHA256",
  643. x_oss_credential: "credential-value",
  644. x_oss_security_token: "security-token",
  645. x_oss_date: "20260625T000000Z",
  646. },
  647. },
  648. }),
  649. );
  650. });
  651. return;
  652. }
  653. if (request.method === "POST" && request.url === "/") {
  654. void readRequestBody(request).then((body) => {
  655. ossBodies.push(body);
  656. response.statusCode = 204;
  657. response.end();
  658. });
  659. return;
  660. }
  661. response.statusCode = 500;
  662. response.end(`unexpected request: ${request.method ?? "GET"} ${request.url ?? "/"}`);
  663. });
  664. try {
  665. const client = makeClient(`http://127.0.0.1:${server.port}`, logger);
  666. const attachment = await client.uploadFile(
  667. "fbk_5",
  668. "image",
  669. filePath,
  670. "shot.png",
  671. "image/png",
  672. {
  673. messageId: "msg_5",
  674. onUploadProgress: (event) => progressEvents.push(event),
  675. },
  676. );
  677. expect(credentialBodies).toEqual([
  678. {
  679. ticket_id: "fbk_5",
  680. message_id: "msg_5",
  681. file_name: "shot.png",
  682. size: payload.byteLength,
  683. },
  684. ]);
  685. expect(logger.info).toHaveBeenCalledWith(
  686. undefined,
  687. "反馈 HTTP 请求开始",
  688. expect.objectContaining({
  689. url: `http://127.0.0.1:${server.port}/feedback/attachment/upload-credential`,
  690. body: expect.objectContaining({
  691. fields: ["file_name", "message_id", "size", "ticket_id"],
  692. hasTicketId: true,
  693. hasMessageId: true,
  694. fileName: { present: true, length: "shot.png".length, extension: ".png" },
  695. size: payload.byteLength,
  696. }),
  697. }),
  698. );
  699. expect(ossBodies).toHaveLength(1);
  700. const multipart = ossBodies[0]!.toString("utf8");
  701. expect(multipart).toContain('name="key"');
  702. expect(multipart).toContain("feedback/att_oss/shot.png");
  703. expect(multipart).toContain('name="policy"');
  704. expect(multipart).toContain("policy-value");
  705. expect(multipart).toContain('name="callback"');
  706. // callback should be base64-encoded JSON with callbackUrl, callbackBody, callbackBodyType
  707. const expectedCallbackJson = JSON.stringify({
  708. callbackUrl: "https://zcode.z.ai/api/v1/feedback/attachment/callback",
  709. callbackBody: "callback-body",
  710. callbackBodyType: "application/json",
  711. });
  712. const expectedCallbackBase64 = Buffer.from(expectedCallbackJson, "utf-8").toString("base64");
  713. expect(multipart).toContain(expectedCallbackBase64);
  714. expect(multipart).toContain('name="file"; filename="shot.png"');
  715. expect(multipart).toContain("image-payload");
  716. expect(progressEvents.at(-1)).toEqual({
  717. uploadedBytes: payload.byteLength,
  718. totalBytes: payload.byteLength,
  719. });
  720. expect(attachment).toMatchObject({
  721. kind: "image",
  722. filename: "shot.png",
  723. size: payload.byteLength,
  724. redacted: false,
  725. content_type: "image/png",
  726. });
  727. } finally {
  728. await closeTestServer(server.server);
  729. await rm(tempDir, { recursive: true, force: true });
  730. }
  731. });
  732. it("requests upload credentials for log attachments at the 1GB client limit", async () => {
  733. const tempDir = await mkdtemp(join(tmpdir(), "feedback-http-client-"));
  734. const filePath = join(tempDir, "one-gib.zip");
  735. await writeFile(filePath, "");
  736. await truncate(filePath, ONE_GIB_BYTES);
  737. const apiClient: ApiClient = {
  738. request: vi.fn(async () => {
  739. return new Response(
  740. JSON.stringify({
  741. code: 0,
  742. msg: "ok",
  743. data: {
  744. attachment_id: "att_one_gib",
  745. max_size: ONE_GIB_BYTES - 1,
  746. },
  747. }),
  748. { status: 200, headers: { "Content-Type": "application/json" } },
  749. );
  750. }),
  751. };
  752. const client = new FeedbackHttpClient({
  753. baseUrl: "https://zcode.z.ai/api/v1",
  754. apiClient,
  755. getAuthHeaders: async () => ({
  756. Authorization: "Bearer test-jwt",
  757. "X-Device-Mid": "desktop-device-mid-test",
  758. }),
  759. });
  760. try {
  761. await expect(
  762. client.uploadFile("fbk_large", "log", filePath, "one-gib.zip", "application/zip"),
  763. ).rejects.toThrow(`Feedback attachment exceeds max size ${ONE_GIB_BYTES - 1}`);
  764. expect(apiClient.request).toHaveBeenCalledTimes(1);
  765. expect(apiClient.request).toHaveBeenCalledWith(
  766. "https://zcode.z.ai/api/v1/feedback/attachment/upload-credential",
  767. expect.objectContaining({
  768. body: JSON.stringify({
  769. ticket_id: "fbk_large",
  770. file_name: "one-gib.zip",
  771. size: ONE_GIB_BYTES,
  772. }),
  773. }),
  774. );
  775. } finally {
  776. await rm(tempDir, { recursive: true, force: true });
  777. }
  778. });
  779. it("rejects log attachments over 1GB before requesting upload credentials", async () => {
  780. const tempDir = await mkdtemp(join(tmpdir(), "feedback-http-client-"));
  781. const filePath = join(tempDir, "too-large.zip");
  782. await writeFile(filePath, "");
  783. await truncate(filePath, ONE_GIB_BYTES + 1);
  784. const apiClient: ApiClient = {
  785. request: vi.fn(async () => {
  786. throw new Error("upload credential should not be requested");
  787. }),
  788. };
  789. const client = new FeedbackHttpClient({
  790. baseUrl: "https://zcode.z.ai/api/v1",
  791. apiClient,
  792. getAuthHeaders: async () => ({
  793. Authorization: "Bearer test-jwt",
  794. "X-Device-Mid": "desktop-device-mid-test",
  795. }),
  796. });
  797. try {
  798. await expect(
  799. client.uploadFile("fbk_large", "log", filePath, "too-large.zip", "application/zip"),
  800. ).rejects.toThrow(`Feedback attachment exceeds max size ${ONE_GIB_BYTES}`);
  801. expect(apiClient.request).not.toHaveBeenCalled();
  802. } finally {
  803. await rm(tempDir, { recursive: true, force: true });
  804. }
  805. });
  806. it("keeps non-log feedback attachments capped at 100MB before requesting upload credentials", async () => {
  807. const tempDir = await mkdtemp(join(tmpdir(), "feedback-http-client-"));
  808. const filePath = join(tempDir, "too-large.png");
  809. await writeFile(filePath, "");
  810. await truncate(filePath, 100 * 1024 * 1024 + 1);
  811. const apiClient: ApiClient = {
  812. request: vi.fn(async () => {
  813. throw new Error("upload credential should not be requested");
  814. }),
  815. };
  816. const client = new FeedbackHttpClient({
  817. baseUrl: "https://zcode.z.ai/api/v1",
  818. apiClient,
  819. getAuthHeaders: async () => ({
  820. Authorization: "Bearer test-jwt",
  821. "X-Device-Mid": "desktop-device-mid-test",
  822. }),
  823. });
  824. try {
  825. await expect(
  826. client.uploadFile("fbk_large", "image", filePath, "too-large.png", "image/png"),
  827. ).rejects.toThrow("Feedback attachment exceeds max size 104857600");
  828. expect(apiClient.request).not.toHaveBeenCalled();
  829. } finally {
  830. await rm(tempDir, { recursive: true, force: true });
  831. }
  832. });
  833. });
  834. describe("createFeedbackService", () => {
  835. afterEach(() => {
  836. setDataBaseDir(null);
  837. vi.unstubAllGlobals();
  838. vi.unstubAllEnvs();
  839. });
  840. it("uses the test ZCode API base by default when ZCODE_ENV=test", async () => {
  841. vi.stubEnv("ZCODE_ENV", "test");
  842. // Bugfix: 开发机 shell 可能导出 ZCODE_BASE_URL / ZCODE_ENDPOINT_ORIGIN(resolver 最高优先级覆盖),
  843. // 会压过 ZCODE_ENV=test 的默认域推断,把「默认 base」用例变成环境敏感;置空恢复封闭性。
  844. vi.stubEnv("ZCODE_BASE_URL", "");
  845. vi.stubEnv("ZCODE_ENDPOINT_ORIGIN", "");
  846. const fetchMock = vi.fn(async (url: string | URL | Request) => {
  847. // Bugfix: feedback 默认 base 已收敛到统一 ZCode endpoint resolver;
  848. // ZCODE_ENV=test 不能继续断言生产域,否则会掩盖测试环境请求边界。
  849. expect(String(url)).toBe("https://zcode.z.ai/api/v1/feedback/ticket");
  850. return new Response(JSON.stringify({ code: 0, msg: "ok", data: { items: [] } }), {
  851. status: 200,
  852. headers: { "Content-Type": "application/json" },
  853. });
  854. });
  855. vi.stubGlobal("fetch", fetchMock);
  856. const service = createFeedbackService({
  857. apiClient: makeFetchApiClient(),
  858. credentialService: makeCredentialService((key) => {
  859. if (key === "zcodejwttoken") return "shared-backend-jwt";
  860. return null;
  861. }),
  862. oauthService: makeOAuthService(),
  863. });
  864. await service.list({ mine: true });
  865. expect(fetchMock).toHaveBeenCalledTimes(1);
  866. });
  867. it("uses the production ZCode API base by default when ZCODE_ENV=production", async () => {
  868. vi.stubEnv("ZCODE_ENV", "production");
  869. // 同上:屏蔽开发机 ambient 覆盖,保持「默认 base」语义封闭
  870. vi.stubEnv("ZCODE_BASE_URL", "");
  871. vi.stubEnv("ZCODE_ENDPOINT_ORIGIN", "");
  872. const fetchMock = vi.fn(async (url: string | URL | Request) => {
  873. expect(String(url)).toBe("https://zcode.z.ai/api/v1/feedback/ticket");
  874. return new Response(JSON.stringify({ code: 0, msg: "ok", data: { items: [] } }), {
  875. status: 200,
  876. headers: { "Content-Type": "application/json" },
  877. });
  878. });
  879. vi.stubGlobal("fetch", fetchMock);
  880. const service = createFeedbackService({
  881. apiClient: makeFetchApiClient(),
  882. credentialService: makeCredentialService((key) => {
  883. if (key === "zcodejwttoken") return "shared-backend-jwt";
  884. return null;
  885. }),
  886. oauthService: makeOAuthService(),
  887. });
  888. await service.list({ mine: true });
  889. expect(fetchMock).toHaveBeenCalledTimes(1);
  890. });
  891. it("keeps explicit feedback API base above environment defaults", async () => {
  892. vi.stubEnv("ZCODE_ENV", "test");
  893. vi.stubEnv("ZCODE_FEEDBACK_API_BASE", "https://feedback-override.example.com/api/v1");
  894. const fetchMock = vi.fn(async (url: string | URL | Request) => {
  895. expect(String(url)).toBe("https://feedback-override.example.com/api/v1/feedback/ticket");
  896. return new Response(JSON.stringify({ code: 0, msg: "ok", data: { items: [] } }), {
  897. status: 200,
  898. headers: { "Content-Type": "application/json" },
  899. });
  900. });
  901. vi.stubGlobal("fetch", fetchMock);
  902. const service = createFeedbackService({
  903. apiClient: makeFetchApiClient(),
  904. credentialService: makeCredentialService((key) => {
  905. if (key === "zcodejwttoken") return "shared-backend-jwt";
  906. return null;
  907. }),
  908. oauthService: makeOAuthService(),
  909. });
  910. await service.list({ mine: true });
  911. expect(fetchMock).toHaveBeenCalledTimes(1);
  912. });
  913. it("uses the host device_mid for anonymous tickets and local ticket storage", async () => {
  914. const tempDir = await mkdtemp(join(tmpdir(), "feedback-service-"));
  915. setDataBaseDir(tempDir);
  916. const createdAt = epochSeconds(2026, 6, 25, 12);
  917. const hostDeviceMid = "desktop-device-mid-001";
  918. const fetchMock = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
  919. const headers = init?.headers as Record<string, string>;
  920. const body = JSON.parse(String(init?.body ?? "{}")) as {
  921. device_mid?: string;
  922. environment?: Record<string, unknown>;
  923. };
  924. expect(headers.Authorization).toBeUndefined();
  925. expect(headers["X-Device-Mid"]).toBe(hostDeviceMid);
  926. expect(headers["X-Feedback-Client-Id"]).toBeUndefined();
  927. expect(body.device_mid).toBe(hostDeviceMid);
  928. expect(body.environment?.app_version).toEqual(expect.any(String));
  929. expect(body.environment?.os_version).toBe(release());
  930. expect(String(body.environment?.os_version ?? "").length).toBeLessThanOrEqual(64);
  931. return new Response(
  932. JSON.stringify({
  933. code: 0,
  934. msg: "ok",
  935. data: {
  936. ticket_id: "fbk_anon",
  937. device_mid: body.device_mid,
  938. status: "submitted",
  939. created_at: createdAt,
  940. },
  941. }),
  942. { status: 200, headers: { "Content-Type": "application/json" } },
  943. );
  944. });
  945. vi.stubGlobal("fetch", fetchMock);
  946. const credentialService = makeCredentialService((key) =>
  947. key === "zcodefeedbackclientid" ? "device_legacy_path_hash" : null,
  948. );
  949. try {
  950. const service = createFeedbackService({
  951. apiClient: makeFetchApiClient(),
  952. apiBaseUrl: "https://zcode.z.ai/api/v1",
  953. getDeviceMid: () => hostDeviceMid,
  954. credentialService,
  955. oauthService: makeOAuthService(),
  956. });
  957. await service.create({ title: "匿名反馈", description: "desc", type: "bug" });
  958. const list = await service.list({ mine: true });
  959. const headers = fetchMock.mock.calls[0]?.[1]?.headers as Record<string, string>;
  960. expect(headers["X-Device-Mid"]).toBe(hostDeviceMid);
  961. expect(credentialService.save).not.toHaveBeenCalled();
  962. expect(list.items).toEqual([
  963. expect.objectContaining({
  964. id: "fbk_anon",
  965. title: "匿名反馈",
  966. type: "bug",
  967. status: "已提交",
  968. }),
  969. ]);
  970. expect(fetchMock).toHaveBeenCalledTimes(1);
  971. } finally {
  972. await rm(tempDir, { recursive: true, force: true });
  973. }
  974. });
  975. it("uses Bearer JWT for logged-in server lists", async () => {
  976. const tempDir = await mkdtemp(join(tmpdir(), "feedback-service-"));
  977. setDataBaseDir(tempDir);
  978. const updatedAt = epochSeconds(2026, 6, 25, 13);
  979. const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
  980. const headers = init?.headers as Record<string, string>;
  981. expect(String(url)).toBe("https://zcode.z.ai/api/v1/feedback/ticket");
  982. expect(headers.Authorization).toBe("Bearer shared-backend-jwt");
  983. expect(headers["X-Device-Mid"]).toBe("desktop-device-mid-222");
  984. expect(headers["X-Feedback-Client-Id"]).toBeUndefined();
  985. return new Response(
  986. JSON.stringify({
  987. code: 0,
  988. msg: "ok",
  989. data: {
  990. items: [
  991. {
  992. ticket_id: "fbk_login",
  993. device_mid: "desktop-device-mid-222",
  994. title: "登录反馈",
  995. status: "closed",
  996. created_at: updatedAt,
  997. updated_at: updatedAt,
  998. },
  999. ],
  1000. },
  1001. }),
  1002. { status: 200, headers: { "Content-Type": "application/json" } },
  1003. );
  1004. });
  1005. vi.stubGlobal("fetch", fetchMock);
  1006. try {
  1007. const service = createFeedbackService({
  1008. apiClient: makeFetchApiClient(),
  1009. apiBaseUrl: "https://zcode.z.ai/api/v1",
  1010. getDeviceMid: () => "desktop-device-mid-222",
  1011. credentialService: makeCredentialService((key) => {
  1012. if (key === "zcodejwttoken") return "shared-backend-jwt";
  1013. return null;
  1014. }),
  1015. oauthService: makeOAuthService(),
  1016. });
  1017. await expect(service.list({ mine: true })).resolves.toEqual({
  1018. total: 1,
  1019. items: [
  1020. expect.objectContaining({
  1021. id: "fbk_login",
  1022. title: "登录反馈",
  1023. status: "已归档",
  1024. }),
  1025. ],
  1026. });
  1027. } finally {
  1028. await rm(tempDir, { recursive: true, force: true });
  1029. }
  1030. });
  1031. it("can abort an active ticket creation request by operation id", async () => {
  1032. const abortErrors: Error[] = [];
  1033. const apiClient: ApiClient = {
  1034. request: vi.fn(
  1035. async (_url: string | URL, init?: ApiRequestInit) =>
  1036. new Promise<Response>((_resolve, reject) => {
  1037. expect(init?.timeoutMs).toBeGreaterThan(0);
  1038. init?.signal?.addEventListener(
  1039. "abort",
  1040. () => {
  1041. const error = new DOMException("The operation was aborted.", "AbortError");
  1042. abortErrors.push(error);
  1043. reject(error);
  1044. },
  1045. { once: true },
  1046. );
  1047. }),
  1048. ),
  1049. };
  1050. const service = createFeedbackService({
  1051. apiClient,
  1052. apiBaseUrl: "https://zcode.z.ai/api/v1",
  1053. getDeviceMid: () => "desktop-device-mid-cancel",
  1054. credentialService: makeCredentialService(),
  1055. oauthService: makeOAuthService(),
  1056. });
  1057. const createPromise = service.create(
  1058. {
  1059. title: "取消创建",
  1060. description: "desc",
  1061. type: "bug",
  1062. },
  1063. { operationId: "feedback-create-cancel-test" },
  1064. );
  1065. await vi.waitFor(() => {
  1066. expect(apiClient.request).toHaveBeenCalledTimes(1);
  1067. });
  1068. await service.cancelCreate("feedback-create-cancel-test");
  1069. await expect(createPromise).rejects.toThrow("The operation was aborted.");
  1070. expect(abortErrors).toHaveLength(1);
  1071. });
  1072. });