- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/test/attach.test.ts?version=41&format=json
356 linespinch 100% · review 1%Last change pinch in version 35, 6 versions changed it
You're reading version 41. The newest is 318, and 3 versions since then changed this file.
1// --attach (abso issue 171): images go up to the Issues Worker before the
2// write that carries them, and the issue's page lists them. The Issues server
3// here is a stand-in that keeps what it was sent.
5import assert from "node:assert/strict";
6import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7import { createServer, type Server } from "node:http";
8import type { AddressInfo } from "node:net";
9import { tmpdir } from "node:os";
10import { join } from "node:path";
11import { after, before, describe, it } from "node:test";
12import { issuePage } from "../src/issues.ts";
13import type { IssuePage } from "../src/issues-wire.ts";
14import { main } from "../src/main.ts";
15import { type Fake, startFake } from "./fake-server.ts";
17const TOKEN = "test-token-not-secret";
18let fake: Fake;
19let issues: Server;
20let issuesUrl: string;
21const seen: { method: string; url: string; headers: Record<string, string | string[] | undefined>; body: Buffer }[] =
22 [];
23const dirs: string[] = [];
25before(async () => {
26 fake = await startFake(0, TOKEN);
27 issues = createServer((req, res) => {
28 const parts: Buffer[] = [];
29 req.on("data", (c: Buffer) => parts.push(c));
30 req.on("end", () => {
31 const body = Buffer.concat(parts);
32 seen.push({ method: req.method!, url: req.url!, headers: req.headers, body });
33 const json = (o: unknown) => res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(o));
34 // A server from before attachments: it reads every POST body as JSON.
35 if (req.url!.includes("/p/old") && req.url!.endsWith("/attachments"))
36 return res.writeHead(400, { "content-type": "application/json" }).end('{"error":"the body is JSON"}');
37 if (req.url!.endsWith("/attachments"))
38 return json({
39 id: `a${String(seen.length).padStart(12, "0")}`,
40 name: "x",
41 type: "image/png",
42 size: body.length,
43 });
44 if (req.url!.endsWith("/issue")) return json({ id: 7 });
45 if (/\/issue\/\d+\/comment$/.test(req.url!)) return json({ id: 3 });
46 // An older Issues server keeps no files on asks: it answers without them (project "keepless").
47 const older = req.url!.includes("/p/keepless/");
48 if (req.url!.endsWith("/ask")) {
49 const sent = (JSON.parse(body.toString()) as { attachments?: string[] }).attachments;
50 return json({ id: 9, ...(sent && !older ? { attachments: sent } : {}) });
51 }
52 if (/\/answer\/\d+$/.test(req.url!)) {
53 const sent = (JSON.parse(body.toString()) as { attachments?: string[] }).attachments ?? [];
54 const files = older ? [] : sent.map((id) => ({ id, name: "x", type: "image/png", size: 1 }));
55 return json({ ask: { by: "bob", answer: { by: "ann", words: "w", at: 0, attachments: files } } });
56 }
57 // Issue 9's ask carries a file on its question and one on its answer.
58 if (req.method === "GET" && /\/issue\/9$/.test(req.url!))
59 return json({
60 issue: { id: 9 },
61 comments: [],
62 edits: [],
63 asks: [
64 {
65 attachments: [{ id: "a00000000000d", name: "question.png", type: "image/png", size: 13 }],
66 answer: { attachments: [{ id: "a00000000000e", name: "answer.png", type: "image/png", size: 13 }] },
67 },
68 ],
69 claims: [],
70 children: [],
71 });
72 // Issue 8 carries an svg-drawn image on itself and again on a comment, plus one more on the comment.
73 const logo = { id: "a00000000000b", name: "../shot one.png", type: "image/png", size: 13 };
74 if (req.method === "GET" && /\/issue\/8$/.test(req.url!))
75 return json({
76 issue: { id: 8, attachments: [{ ...logo, source: { name: "logo.svg", size: 20 } }] },
77 comments: [{ attachments: [logo, { id: "a00000000000c", name: "after.png", type: "image/png", size: 13 }] }],
78 edits: [],
79 asks: [],
80 claims: [],
81 children: [],
82 });
83 const served = /\/attachments\/(a[0-9a-f]{12})(\/source)?$/.exec(req.url!);
84 if (req.method === "GET" && served)
85 return res.writeHead(200, { "content-type": "image/png" }).end(`${served[1]}${served[2] ?? ""}`);
86 res.writeHead(404).end("{}");
87 });
88 });
89 await new Promise<void>((ok) => issues.listen(0, "127.0.0.1", ok));
90 issuesUrl = `http://127.0.0.1:${(issues.address() as AddressInfo).port}`;
91});
92after(async () => {
93 await fake.close();
94 await new Promise((ok) => issues.close(ok));
95 for (const d of dirs) rmSync(d, { recursive: true, force: true, maxRetries: 5 });
96});
98const ENV = (): Record<string, string> => ({
99 AVCS_TOKEN: TOKEN,
100 AVCS_HOOK_FORCE: "1",
101 AVCS_ISSUES_SERVER: issuesUrl,
102 AVCS_SERVERS_FILE: "no-servers.json",
103});
105async function avcs(cwd: string, argv: string[]): Promise<{ exit: number; out: string; json?: unknown }> {
106 const r = await main([...argv, "--json"], { cwd, env: ENV(), write: () => {} });
107 let json: unknown;
108 try {
109 json = JSON.parse(r.stdout);
110 } catch {}
111 return { exit: r.exit, out: r.stdout + r.stderr, json };
112}
114let n = 0;
115async function folder(): Promise<string> {
116 const dir = mkdtempSync(join(tmpdir(), "abso-attach-"));
117 dirs.push(dir);
118 const r = await avcs(dir, ["init", "--server", fake.url, "--project", `attach${++n}`, "--agent", "ann"]);
119 assert.equal(r.exit, 0, r.out);
120 writeFileSync(join(dir, "shot.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]));
121 writeFileSync(join(dir, "after.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 4, 5]));
122 return dir;
123}
125describe("--attach (abso issue 171)", () => {
126 it("uploads each file, then opens the issue carrying their ids", async () => {
127 const dir = await folder();
128 const from = seen.length;
129 const r = await avcs(dir, ["issue", "new", "The page after the fix", "--attach", "shot.png,after.png"]);
130 assert.equal(r.exit, 0, r.out);
131 const calls = seen.slice(from);
132 assert.deepEqual(
133 calls.map((c) => `${c.method} ${c.url.replace(/^\/p\/[^/]+/, "")}`),
134 ["POST /a/ann/attachments", "POST /a/ann/attachments", "POST /a/ann/issue"],
135 );
136 assert.equal(calls[0]!.headers["x-avcs-name"], "shot.png");
137 assert.equal(calls[0]!.headers["content-type"], "application/octet-stream");
138 assert.deepEqual([...calls[0]!.body], [0x89, 0x50, 0x4e, 0x47, 1, 2, 3]);
139 const opened = JSON.parse(calls[2]!.body.toString()) as { title: string; attachments: string[] };
140 assert.equal(opened.title, "The page after the fix");
141 assert.equal(opened.attachments.length, 2);
142 assert.deepEqual((r.json as { attachments: string[] }).attachments, opened.attachments);
143 });
145 it("goes on a comment too, and nowhere else", async () => {
146 const dir = await folder();
147 const from = seen.length;
148 const r = await avcs(dir, ["issue", "7", "--comment", "after", "--attach", "shot.png"]);
149 assert.equal(r.exit, 0, r.out);
150 const comment = JSON.parse(seen.at(-1)!.body.toString()) as { text: string; attachments: string[] };
151 assert.equal(comment.text, "after");
152 assert.equal(comment.attachments.length, 1);
153 assert.equal(seen.length - from, 2);
154 const alone = await avcs(dir, ["issue", "7", "--attach", "shot.png"]);
155 assert.equal(alone.exit, 1);
156 assert.match(alone.out, /--attach goes with abso issue new or --comment/);
157 });
159 it("says plainly when the server doesn't take attachments yet, and writes nothing", async () => {
160 const dir = mkdtempSync(join(tmpdir(), "abso-attach-"));
161 dirs.push(dir);
162 const init = await avcs(dir, ["init", "--server", fake.url, "--project", "old", "--agent", "ann"]);
163 assert.equal(init.exit, 0, init.out);
164 writeFileSync(join(dir, "shot.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 1]));
165 const from = seen.length;
166 const r = await avcs(dir, ["issue", "new", "T", "--attach", "shot.png"]);
167 assert.equal(r.exit, 1);
168 assert.match(r.out, /doesn't take attachments yet, so shot.png wasn't sent and nothing was written/);
169 assert.deepEqual(
170 seen.slice(from).map((c) => c.url.replace(/^\/p\/[^/]+/, "")),
171 ["/a/ann/attachments"],
172 "no issue was opened",
173 );
174 });
176 it("sends nothing when a file is missing", async () => {
177 const dir = await folder();
178 const from = seen.length;
179 const r = await avcs(dir, ["issue", "new", "T", "--attach", "shot.png,nope.png"]);
180 assert.equal(r.exit, 1);
181 assert.match(r.out, /--attach nope.png: no such file/);
182 assert.equal(seen.length, from);
183 });
185 it("--save-attachments saves each attachment once, an svg's own file too, outside the folder", async () => {
186 const dir = await folder();
187 const out = mkdtempSync(join(tmpdir(), "abso-saved-"));
188 dirs.push(out);
189 const r = await avcs(dir, ["issue", "8", "--save-attachments", join(out, "images")]);
190 assert.equal(r.exit, 0, r.out);
191 const names = readdirSync(join(out, "images")).sort();
192 assert.deepEqual(names, ["a00000000000b-logo.svg", "a00000000000b-shot_one.png", "a00000000000c-after.png"]);
193 assert.equal(readFileSync(join(out, "images", "a00000000000b-logo.svg"), "utf8"), "a00000000000b/source");
194 assert.equal(readFileSync(join(out, "images", "a00000000000c-after.png"), "utf8"), "a00000000000c");
195 assert.equal((r.json as { files: unknown[] }).files.length, 3);
196 // Into the folder only where abso leaves files out, or they'd be recorded as edits.
197 const inside = await avcs(dir, ["issue", "8", "--save-attachments", "images"]);
198 assert.equal(inside.exit, 1);
199 assert.match(inside.out, /inside this abso folder/);
200 assert.equal((await avcs(dir, ["issue", "8", "--save-attachments", "."])).exit, 1);
201 writeFileSync(join(dir, ".absoignore"), "saved/\n");
202 assert.equal((await avcs(dir, ["issue", "8", "--save-attachments", "saved"])).exit, 0);
203 const mixed = await avcs(dir, ["issue", "8", "--save-attachments", out, "--comment", "x"]);
204 assert.equal(mixed.exit, 1);
205 assert.match(mixed.out, /--save-attachments goes alone/);
206 });
208 it("goes on an ask and on an answer, and not on a withdrawal", async () => {
209 const dir = await folder();
210 let from = seen.length;
211 const asked = await avcs(dir, [
212 "ask",
213 "bob",
214 "Which looks right?",
215 "--issue",
216 "7",
217 "--attach",
218 "shot.png,after.png",
219 ]);
220 assert.equal(asked.exit, 0, asked.out);
221 assert.deepEqual(
222 seen.slice(from).map((c) => `${c.method} ${c.url.replace(/^\/p\/[^/]+/, "")}`),
223 ["POST /a/ann/attachments", "POST /a/ann/attachments", "POST /a/ann/ask"],
224 );
225 const ask = JSON.parse(seen.at(-1)!.body.toString()) as { question: string; attachments: string[] };
226 assert.equal(ask.question, "Which looks right?");
227 assert.equal(ask.attachments.length, 2);
228 assert.deepEqual((asked.json as { attachments: string[] }).attachments, ask.attachments);
229 from = seen.length;
230 const answered = await avcs(dir, ["answer", "9", "This one", "--attach", "after.png"]);
231 assert.equal(answered.exit, 0, answered.out);
232 const answer = JSON.parse(seen.at(-1)!.body.toString()) as { words: string; attachments: string[] };
233 assert.equal(answer.words, "This one");
234 assert.equal(answer.attachments.length, 1);
235 assert.equal(seen.length - from, 2);
236 from = seen.length;
237 const withdrawn = await avcs(dir, ["ask", "--withdraw", "9", "--attach", "shot.png"]);
238 assert.equal(withdrawn.exit, 1);
239 assert.equal(seen.length, from, "nothing was sent");
240 });
242 it("says so when an older Issues server keeps an ask's words but not its files", async () => {
243 const dir = mkdtempSync(join(tmpdir(), "abso-attach-"));
244 dirs.push(dir);
245 const init = await avcs(dir, ["init", "--server", fake.url, "--project", "keepless", "--agent", "ann"]);
246 assert.equal(init.exit, 0, init.out);
247 writeFileSync(join(dir, "shot.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 1]));
248 const asked = await avcs(dir, ["ask", "bob", "Which?", "--attach", "shot.png"]);
249 assert.equal(asked.exit, 0, asked.out);
250 assert.match(asked.out, /didn't keep the file on ask 9: it is older than this client/);
251 const answered = await avcs(dir, ["answer", "9", "This", "--attach", "shot.png"]);
252 assert.match(answered.out, /didn't keep the file on your answer to ask 9/);
253 // A server that keeps them says nothing of the kind.
254 const kept = await avcs(await folder(), ["ask", "bob", "Which?", "--attach", "shot.png"]);
255 assert.doesNotMatch(kept.out, /didn't keep/);
256 });
258 it("--save-attachments takes the files on an issue's asks and answers too", async () => {
259 const dir = await folder();
260 const out = mkdtempSync(join(tmpdir(), "abso-saved-"));
261 dirs.push(out);
262 const r = await avcs(dir, ["issue", "9", "--save-attachments", out]);
263 assert.equal(r.exit, 0, r.out);
264 assert.deepEqual(readdirSync(out).sort(), ["a00000000000d-question.png", "a00000000000e-answer.png"]);
265 });
267 it("an issue's page lists its attachments and each comment's, with links", () => {
268 const page = {
269 issue: {
270 id: 7,
271 title: "T",
272 status: "open",
273 opened: { by: "ann", at: 0 },
274 agent: null,
275 agents: [],
276 blockedBy: [],
277 labels: [],
278 versions: [],
279 waitingOn: [],
280 parent: null,
281 children: 0,
282 updated: 0,
283 closed: null,
284 description: "",
285 lines: null,
286 watchers: [],
287 attachments: [{ id: "a0123456789ab", name: "shot.png", type: "image/png", size: 2048 }],
288 },
289 comments: [
290 {
291 id: 1,
292 by: "bob",
293 kind: "comment",
294 text: "same here",
295 at: 0,
296 attachments: [
297 { id: "a00000000000f", name: "mine.png", type: "image/png", size: 3 * 1024 * 1024 },
298 {
299 id: "a0000000000aa",
300 name: "logo.png",
301 type: "image/png",
302 size: 4096,
303 source: { name: "logo.svg", size: 512 },
304 },
305 ],
306 },
307 ],
308 edits: [],
309 asks: [],
310 claims: [],
311 children: [],
312 } as unknown as IssuePage;
313 const text = issuePage(page, {
314 attachmentUrl: (id: string) => `https://issues.example/p/x/attachments/${id}`,
315 }).join("\n");
316 assert.match(
317 text,
318 /attached a0123456789ab: "shot.png", 2 KB, https:\/\/issues.example\/p\/x\/attachments\/a0123456789ab/,
319 );
320 assert.match(text, /\n {4}attached a00000000000f: "mine.png", 3.0 MB/);
321 // An SVG is listed as its PNG, with its own file as a download beside it.
322 assert.match(
323 text,
324 /\n {4}attached a0000000000aa: "logo.png", 4 KB, \S+\/a0000000000aa\n {6}drawn from "logo.svg", 512 B, https:\/\/issues.example\/p\/x\/attachments\/a0000000000aa\/source/,
325 );
326 // An ask lists its question's files under it, and its answer's under the answer.
327 const file = (id: string, name: string) => ({ id, name, type: "image/png", size: 1024 });
328 const asked = {
329 ...page,
330 asks: [
331 {
332 id: 4,
333 issue: 7,
334 by: "ann",
335 of: "bob",
336 kind: "question",
337 question: "Which?",
338 attachments: [file("a00000000000d", "a.png")],
339 review: false,
340 due: null,
341 recommendation: null,
342 options: [],
343 blocks: [],
344 at: 0,
345 answer: { by: "bob", words: "This", at: 0, attachments: [file("a00000000000e", "b.png")] },
346 seen: null,
347 },
348 ],
349 } as unknown as IssuePage;
350 const asks = issuePage(asked, { attachmentUrl: (id: string) => `https://i.example/${id}` }).join("\n");
351 assert.match(
352 asks,
353 /ask 4: .*"Which\?"\n {4}attached a00000000000d: "a.png", 1 KB, https:\/\/i.example\/a00000000000d\n {4}answer: "This"\n {6}attached a00000000000e: "b.png", 1 KB/,
354 );
355 });
356});