import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { mkdtemp, readFile, mkdir, rm } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { ATTACHMENT_DIRECTORY, attachmentFileName, base64Size, wishInput, type Actor, type Project, } from '@wishforge/contracts'; import { BASELINE_BUNDLE, bundlePrompt } from '@wishforge/agent'; import { ControlPlane } from '../apps/api/src/domain/control-plane.js'; import { writeAttachments } from '../apps/worker/src/executor.js'; import { MemoryStore } from './helpers/memory-store.js'; // A wish may carry screenshots, designs and logs for the agent to look at. const env = { NODE_ENV: 'test', WF_DISPATCH_TENANTS: 'demo', WF_GIT_SERVICE_URL: 'http://127.0.0.1:4504', WF_GIT_ADMIN_TOKEN: 'git-admin-token-for-tests-only-0001', }; const owner: Actor = { tenantId: 'demo', userId: 'owner', role: 'owner', kind: 'human' }; const worker: Actor = { ...owner, userId: 'worker', kind: 'worker' }; const png = Buffer.from('89504e470d0a1a0a0000000d49484452', 'hex').toString('base64'); let store: MemoryStore; let project: Project; beforeEach(async () => { vi.stubGlobal('fetch', async (input: string | URL, init: RequestInit) => { const body = JSON.parse(String(init.body)); if (new URL(String(input)).pathname === '/repos') return Response.json({ repositoryUrl: `https://git.test/git/${body.tenantId}/${body.projectId}.git`, initialCommit: 'a'.repeat(40), defaultBranch: 'main', }); return Response.json({ token: 'payload.signature', expiresAt: new Date(Date.now() + 900_000).toISOString() }); }); store = new MemoryStore(); store.seed('demo'); project = await new ControlPlane(store, env).createProject(owner, { name: 'Todo App' }); }); afterEach(() => vi.unstubAllGlobals()); describe('wish attachments', () => { it('keeps the files apart from the run, lists them on it, and gives the bytes to the executor only', async () => { const control = new ControlPlane(store, env); const { run_id } = await control.submit( owner, project.id, { goal: 'Make the login page look like the design', acceptanceCriteria: ['Matches the screenshot'], attachments: [ { name: 'design.png', mediaType: 'image/png', data: png }, { name: 'notes.txt', mediaType: 'text/plain', data: Buffer.from('左对齐').toString('base64') }, ], }, 'attachments-0001', ); const run = await control.run(owner, run_id); expect(run.attachments).toEqual([ { id: expect.any(String), name: 'design.png', mediaType: 'image/png', size: 16 }, { id: expect.any(String), name: 'notes.txt', mediaType: 'text/plain', size: 9 }, ]); expect(JSON.stringify(run)).not.toContain(png); const events = await control.events(owner, run_id); expect(events[0]!.message).toContain('2 个附件'); const file = await control.attachment(owner, run_id, run.attachments![0]!.id); expect(Buffer.from(file.data, 'base64').toString('hex')).toBe('89504e470d0a1a0a0000000d49484452'); await expect(control.attachment(owner, run_id, 'missing')).rejects.toMatchObject({ code: 'NOT_FOUND' }); const forWorker = await control.context(worker, run_id); expect(forWorker.attachments.map(item => item.name)).toEqual(['design.png', 'notes.txt']); expect(forWorker.attachments[0]!.data).toBe(png); expect((await control.context(owner, run_id)).attachments).toEqual([]); }); it('refuses files beyond the limits', async () => { const control = new ControlPlane(store, env); const big = Buffer.alloc(4 * 1024 * 1024).toString('base64'); await expect( control.submit( owner, project.id, { goal: 'Too much to look at', acceptanceCriteria: ['n/a'], attachments: [1, 2, 3].map(n => ({ name: `${n}.bin`, data: big })), }, 'attachments-0002', ), ).rejects.toMatchObject({ code: 'ATTACHMENTS_TOO_LARGE' }); expect(() => wishInput.parse({ goal: 'x', acceptanceCriteria: ['y'], attachments: Array.from({ length: 9 }, () => ({ name: 'a.png', data: png })), }), ).toThrow(); expect(() => wishInput.parse({ goal: 'x', acceptanceCriteria: ['y'], attachments: [{ name: 'a', data: 'not base64!' }] }), ).toThrow(); }); it('names files safely and counts base64 bytes', () => { expect(attachmentFileName(0, '../../etc/passwd')).toBe('01-passwd'); expect(attachmentFileName(2, '.env')).toBe('03-env'); expect(attachmentFileName(9, '登录页 截图(1).png')).toBe('10-登录页 截图_1_.png'); expect(attachmentFileName(0, '')).toBe('01-file'); expect(base64Size(Buffer.from('abcd').toString('base64'))).toBe(4); expect(base64Size(Buffer.from('abcde').toString('base64'))).toBe(5); }); it('writes the files into an ignored workspace directory and points the prompt at them', async () => { const workspace = await mkdtemp(path.join(os.tmpdir(), 'wf-attach-')); try { await mkdir(path.join(workspace, '.git', 'info'), { recursive: true }); const files = [{ id: 'a', name: 'design.png', mediaType: 'image/png', data: png }]; const written = await writeAttachments(workspace, files); // A second round (a repair, a resume) writes them again without repeating the ignore rule. await writeAttachments(workspace, files); expect(written).toEqual([ { path: `${ATTACHMENT_DIRECTORY}/01-design.png`, name: 'design.png', mediaType: 'image/png' }, ]); expect((await readFile(path.join(workspace, written[0]!.path))).toString('base64')).toBe(png); expect(await readFile(path.join(workspace, '.git', 'info', 'exclude'), 'utf8')).toBe( `/${ATTACHMENT_DIRECTORY}/\n`, ); const prompt = bundlePrompt(BASELINE_BUNDLE, { goal: 'Match the design', acceptanceCriteria: ['Looks right'], repairCount: 0, attachments: written, }); expect(prompt).toContain(`- ${ATTACHMENT_DIRECTORY}/01-design.png (image/png; uploaded as "design.png")`); expect(prompt).toContain('view images with your file reading tool'); expect(bundlePrompt(BASELINE_BUNDLE, { goal: 'x', acceptanceCriteria: ['y'], repairCount: 0 })).not.toContain( ATTACHMENT_DIRECTORY, ); } finally { await rm(workspace, { recursive: true, force: true }); } }); });