Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
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?format=json
371 linespinch 99% · infra-pipeline 1% · review 1%Last change infra-pipeline in version 99, 9 versions changed it
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.
4
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 // As fake-server.ts: never close an idle kept-alive connection, or under load the client can reuse one as it closes
90 // and fail with ECONNRESET (abso 410).
91 issues.keepAliveTimeout = 0;
92 await new Promise<void>((ok) => issues.listen(0, "127.0.0.1", ok));
93 issuesUrl = `http://127.0.0.1:${(issues.address() as AddressInfo).port}`;
94});
95after(async () => {
96 await fake.close();
97 await new Promise((ok) => issues.close(ok));
98 for (const d of dirs) rmSync(d, { recursive: true, force: true, maxRetries: 5 });
99});
101const ENV = (): Record<string, string> => ({
102 AVCS_TOKEN: TOKEN,
103 AVCS_HOOK_FORCE: "1",
104 AVCS_ISSUES_SERVER: issuesUrl,
105 AVCS_SERVERS_FILE: "no-servers.json",
106});
108async function avcs(cwd: string, argv: string[]): Promise<{ exit: number; out: string; json?: unknown }> {
109 const r = await main([...argv, "--json"], { cwd, env: ENV(), write: () => {} });
110 let json: unknown;
111 try {
112 json = JSON.parse(r.stdout);
113 } catch {}
114 return { exit: r.exit, out: r.stdout + r.stderr, json };
117let n = 0;
118async function folder(): Promise<string> {
119 const dir = mkdtempSync(join(tmpdir(), "abso-attach-"));
120 dirs.push(dir);
121 const r = await avcs(dir, ["init", "--server", fake.url, "--project", `attach${++n}`, "--agent", "ann"]);
122 assert.equal(r.exit, 0, r.out);
123 writeFileSync(join(dir, "shot.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]));
124 writeFileSync(join(dir, "after.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 4, 5]));
125 return dir;
128describe("--attach (abso issue 171)", () => {
129 it("uploads each file, then opens the issue carrying their ids", async () => {
130 const dir = await folder();
131 const from = seen.length;
132 const r = await avcs(dir, ["issue", "new", "The page after the fix", "--attach", "shot.png,after.png"]);
133 assert.equal(r.exit, 0, r.out);
134 const calls = seen.slice(from);
135 assert.deepEqual(
136 calls.map((c) => `${c.method} ${c.url.replace(/^\/p\/[^/]+/, "")}`),
137 ["POST /a/ann/attachments", "POST /a/ann/attachments", "POST /a/ann/issue"],
138 );
139 assert.equal(calls[0]!.headers["x-abso-name"], "shot.png");
140 assert.equal(calls[0]!.headers["content-type"], "application/octet-stream");
141 assert.deepEqual([...calls[0]!.body], [0x89, 0x50, 0x4e, 0x47, 1, 2, 3]);
142 const opened = JSON.parse(calls[2]!.body.toString()) as { title: string; attachments: string[] };
143 assert.equal(opened.title, "The page after the fix");
144 assert.equal(opened.attachments.length, 2);
145 assert.deepEqual((r.json as { attachments: string[] }).attachments, opened.attachments);
146 });
148 it("goes on a comment too, and nowhere else", async () => {
149 const dir = await folder();
150 const from = seen.length;
151 const r = await avcs(dir, ["issue", "7", "--comment", "after", "--attach", "shot.png"]);
152 assert.equal(r.exit, 0, r.out);
153 const comment = JSON.parse(seen.at(-1)!.body.toString()) as { text: string; attachments: string[] };
154 assert.equal(comment.text, "after");
155 assert.equal(comment.attachments.length, 1);
156 assert.equal(seen.length - from, 2);
157 const alone = await avcs(dir, ["issue", "7", "--attach", "shot.png"]);
158 assert.equal(alone.exit, 1);
159 assert.match(alone.out, /--attach goes with abso issue new or --comment/);
160 });
162 it("says plainly when the server doesn't take attachments yet, and writes nothing", async () => {
163 const dir = mkdtempSync(join(tmpdir(), "abso-attach-"));
164 dirs.push(dir);
165 const init = await avcs(dir, ["init", "--server", fake.url, "--project", "old", "--agent", "ann"]);
166 assert.equal(init.exit, 0, init.out);
167 writeFileSync(join(dir, "shot.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 1]));
168 const from = seen.length;
169 const r = await avcs(dir, ["issue", "new", "T", "--attach", "shot.png"]);
170 assert.equal(r.exit, 1);
171 assert.match(r.out, /doesn't take attachments yet, so shot.png wasn't sent and nothing was written/);
172 assert.deepEqual(
173 seen.slice(from).map((c) => c.url.replace(/^\/p\/[^/]+/, "")),
174 ["/a/ann/attachments"],
175 "no issue was opened",
176 );
177 });
179 it("sends nothing when a file is missing", async () => {
180 const dir = await folder();
181 const from = seen.length;
182 const r = await avcs(dir, ["issue", "new", "T", "--attach", "shot.png,nope.png"]);
183 assert.equal(r.exit, 1);
184 assert.match(r.out, /--attach nope.png: no such file/);
185 assert.equal(seen.length, from);
186 });
188 it("--save-attachments saves each attachment once, an svg's own file too, outside the folder", async () => {
189 const dir = await folder();
190 const out = mkdtempSync(join(tmpdir(), "abso-saved-"));
191 dirs.push(out);
192 const r = await avcs(dir, ["issue", "8", "--save-attachments", join(out, "images")]);
193 assert.equal(r.exit, 0, r.out);
194 const names = readdirSync(join(out, "images")).sort();
195 assert.deepEqual(names, ["a00000000000b-logo.svg", "a00000000000b-shot_one.png", "a00000000000c-after.png"]);
196 assert.equal(readFileSync(join(out, "images", "a00000000000b-logo.svg"), "utf8"), "a00000000000b/source");
197 assert.equal(readFileSync(join(out, "images", "a00000000000c-after.png"), "utf8"), "a00000000000c");
198 assert.equal((r.json as { files: unknown[] }).files.length, 3);
199 // Into the folder only where abso leaves files out, or they'd be recorded as edits.
200 const inside = await avcs(dir, ["issue", "8", "--save-attachments", "images"]);
201 assert.equal(inside.exit, 1);
202 assert.match(inside.out, /inside this abso folder/);
203 assert.equal((await avcs(dir, ["issue", "8", "--save-attachments", "."])).exit, 1);
204 writeFileSync(join(dir, ".absoignore"), "saved/\n");
205 assert.equal((await avcs(dir, ["issue", "8", "--save-attachments", "saved"])).exit, 0);
206 const mixed = await avcs(dir, ["issue", "8", "--save-attachments", out, "--comment", "x"]);
207 assert.equal(mixed.exit, 1);
208 assert.match(mixed.out, /--save-attachments goes alone/);
209 });
211 it("goes on an ask and on an answer, and not on a withdrawal", async () => {
212 const dir = await folder();
213 let from = seen.length;
214 const asked = await avcs(dir, [
215 "ask",
216 "bob",
217 "Which looks right?",
218 "--issue",
219 "7",
220 "--attach",
221 "shot.png,after.png",
222 ]);
223 assert.equal(asked.exit, 0, asked.out);
224 assert.deepEqual(
225 seen.slice(from).map((c) => `${c.method} ${c.url.replace(/^\/p\/[^/]+/, "")}`),
226 ["POST /a/ann/attachments", "POST /a/ann/attachments", "POST /a/ann/ask"],
227 );
228 const ask = JSON.parse(seen.at(-1)!.body.toString()) as { question: string; attachments: string[] };
229 assert.equal(ask.question, "Which looks right?");
230 assert.equal(ask.attachments.length, 2);
231 assert.deepEqual((asked.json as { attachments: string[] }).attachments, ask.attachments);
232 from = seen.length;
233 const answered = await avcs(dir, ["answer", "9", "This one", "--attach", "after.png"]);
234 assert.equal(answered.exit, 0, answered.out);
235 const answer = JSON.parse(seen.at(-1)!.body.toString()) as { words: string; attachments: string[] };
236 assert.equal(answer.words, "This one");
237 assert.equal(answer.attachments.length, 1);
238 assert.equal(seen.length - from, 2);
239 from = seen.length;
240 const withdrawn = await avcs(dir, ["ask", "--withdraw", "9", "--attach", "shot.png"]);
241 assert.equal(withdrawn.exit, 1);
242 assert.equal(seen.length, from, "nothing was sent");
243 });
245 it("says so when an older Issues server keeps an ask's words but not its files", async () => {
246 const dir = mkdtempSync(join(tmpdir(), "abso-attach-"));
247 dirs.push(dir);
248 const init = await avcs(dir, ["init", "--server", fake.url, "--project", "keepless", "--agent", "ann"]);
249 assert.equal(init.exit, 0, init.out);
250 writeFileSync(join(dir, "shot.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 1]));
251 const asked = await avcs(dir, ["ask", "bob", "Which?", "--attach", "shot.png"]);
252 assert.equal(asked.exit, 0, asked.out);
253 assert.match(asked.out, /didn't keep the file on ask 9: it is older than this client/);
254 const answered = await avcs(dir, ["answer", "9", "This", "--attach", "shot.png"]);
255 assert.match(answered.out, /didn't keep the file on your answer to ask 9/);
256 // A server that keeps them says nothing of the kind.
257 const kept = await avcs(await folder(), ["ask", "bob", "Which?", "--attach", "shot.png"]);
258 assert.doesNotMatch(kept.out, /didn't keep/);
259 });
261 it("--save-attachments takes the files on an issue's asks and answers too", async () => {
262 const dir = await folder();
263 const out = mkdtempSync(join(tmpdir(), "abso-saved-"));
264 dirs.push(out);
265 const r = await avcs(dir, ["issue", "9", "--save-attachments", out]);
266 assert.equal(r.exit, 0, r.out);
267 assert.deepEqual(readdirSync(out).sort(), ["a00000000000d-question.png", "a00000000000e-answer.png"]);
268 });
270 it("an issue's page lists its attachments and each comment's, with links", () => {
271 const page = {
272 issue: {
273 id: 7,
274 title: "T",
275 status: "open",
276 opened: { by: "ann", at: 0 },
277 agent: null,
278 agents: [],
279 blockedBy: [],
280 labels: [],
281 versions: [],
282 waitingOn: [],
283 parent: null,
284 children: 0,
285 updated: 0,
286 closed: null,
287 description: "",
288 lines: null,
289 watchers: [],
290 attachments: [{ id: "a0123456789ab", name: "shot.png", type: "image/png", size: 2048 }],
291 },
292 comments: [
293 {
294 id: 1,
295 by: "bob",
296 kind: "comment",
297 text: "same here",
298 at: 0,
299 attachments: [
300 { id: "a00000000000f", name: "mine.png", type: "image/png", size: 3 * 1024 * 1024 },
301 {
302 id: "a0000000000aa",
303 name: "logo.png",
304 type: "image/png",
305 size: 4096,
306 source: { name: "logo.svg", size: 512 },
307 },
308 ],
309 },
310 ],
311 edits: [],
312 asks: [],
313 claims: [],
314 children: [],
315 } as unknown as IssuePage;
316 const text = issuePage(page, {
317 attachmentUrl: (id: string) => `https://issues.example/p/x/attachments/${id}`,
318 }).join("\n");
319 assert.match(
320 text,
321 /attached a0123456789ab: "shot.png", 2 KB, https:\/\/issues.example\/p\/x\/attachments\/a0123456789ab/,
322 );
323 assert.match(text, /\n {4}attached a00000000000f: "mine.png", 3.0 MB/);
324 // The way in comes before the first link, since an agent's fetch of a link is refused.
325 assert.match(
326 text,
327 /^Issue [^\n]*\n[^\n]*\n3 files are attached below\. To read them: abso issue \d+ --save-attachments <folder> saves every one there, then open the files\. The links are for people signed in on the website\.\n/,
328 );
329 assert.doesNotMatch(
330 issuePage({ ...page, issue: { ...page.issue, attachments: [] }, comments: [] } as unknown as IssuePage).join(
331 "\n",
332 ),
333 /--save-attachments/,
334 );
335 // An SVG is listed as its PNG, with its own file as a download beside it.
336 assert.match(
337 text,
338 /\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/,
339 );
340 // An ask lists its question's files under it, and its answer's under the answer.
341 const file = (id: string, name: string) => ({ id, name, type: "image/png", size: 1024 });
342 const asked = {
343 ...page,
344 asks: [
345 {
346 id: 4,
347 issue: 7,
348 by: "ann",
349 of: "bob",
350 kind: "question",
351 question: "Which?",
352 attachments: [file("a00000000000d", "a.png")],
353 review: false,
354 due: null,
355 recommendation: null,
356 options: [],
357 blocks: [],
358 at: 0,
359 answer: { by: "bob", words: "This", at: 0, attachments: [file("a00000000000e", "b.png")] },
360 seen: null,
361 },
362 ],
363 } as unknown as IssuePage;
364 const asks = issuePage(asked, { attachmentUrl: (id: string) => `https://i.example/${id}` }).join("\n");
365 assert.match(asks, /\n5 files are attached below\./, "an ask's question and answer files count too");
366 assert.match(
367 asks,
368 /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/,
369 );
370 });
371});