Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(bots): dedupe bot uploads on content, honour declared vision; isolate tests from the real home (#262)
Salman Qureshi76f2ff101396
diff --git a/DECISIONS.md b/DECISIONS.mdindex ce359741..73f4fb10 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -1,4 +1,3 @@-## ADR-022: Operating a fleet — cost, runs, kill switch- **Context**: ADR-020 and ADR-021 made bot behaviour bounded and legible in the journal, but the owner still had no view of where tokens went, no way to see what a run did without opening JSON files, no single stop, and a dead-letter queue full of pre-ADR-020 misclassified failures with no way to clear it. Onboarding presented the budget as optional.@@ -313,5 +312,5 @@## ADR-031: Bots take files too — attachments ride the job, not the prompt- **Context**: ADR-028 gave the chat route files (#225) and the profile an avatar, but a bot could still only be *told* about a photo: `POST /api/bots/:id/message` read `message` and the durable job carried `{trigger, prompt, fromBot, source}`. The runtime could already read attachments (`withAttachments`, 8 MB image / 15 MB PDF, vision-gated), so the gap was purely the queue: a bot turn has no request, and the job is the only thing that survives a restart.-- **Decision**: The job carries **paths**, not bytes — `attachments?: ChannelAttachment[]` on `BotJob` and `DurableBotJob`, stored as a JSON column (`attachments TEXT`, added by an idempotent `ALTER TABLE` like `run_after`), normalized on read. The route validates and writes the bytes with the same helper the chat route uses (`storeInlineAttachments`), then enqueues; files for a job that is refused (`409`) or a message that never arrives are deleted, so `uploads/` cannot accumulate orphans. `idempotencyKeyFor` now includes the attachment paths: the same caption with two different photos is two jobs, while a retried identical request still dedupes. `runBotTurn` names a caption-less turn `(Attached: names)` — a provider rejects an empty text block — and applies `withAttachments` to the last user message, so a vision model gets image parts and a text-only one gets the existing note.+- **Decision**: The job carries **paths**, not bytes — `attachments?: ChannelAttachment[]` on `BotJob` and `DurableBotJob`, stored as a JSON column (`attachments TEXT`, added by an idempotent `ALTER TABLE` like `run_after`), normalized on read. The route validates and writes the bytes with the same helper the chat route uses (`storeInlineAttachments`), then enqueues; files for a job that is refused (`409`) or a message that never arrives are deleted, so `uploads/` cannot accumulate orphans. `idempotencyKeyFor` now includes a hash of each attachment's bytes (not its path, which is a fresh random name per upload): the same caption with two different photos is two jobs, while a retried identical request still dedupes, and the retry's copies of the files are deleted. `runBotTurn` names a caption-less turn `(Attached: names)` — a provider rejects an empty text block — and applies `withAttachments` to the last user message, so a vision model gets image parts and a text-only one gets the existing note.- **Consequence**: A photo can be handed to a bot exactly like a chat turn, from the phone or a script, and the work survives a restart because the files are on disk and the job references them. Stale paths are harmless: `withAttachments` skips a file that no longer exists rather than failing the turn. Not here: files arriving from *other bots* (bot-to-bot mail carries text), transcription, and any retention sweep for uploads no job references — a disk-hygiene follow-up, not a correctness one.diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 549fd333..68f33729 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -396,7 +396,7 @@ export class BotManager {return this.journalFor(botId);}- enqueue(botId: string, job: { trigger: BotTrigger; prompt: string; fromBot?: string; source?: { channelType: string; channelId: string }; attempts?: number; routineId?: string; attachments?: ChannelAttachment[] }): { jobId: string; accepted: boolean; reasonCode?: string } {+ enqueue(botId: string, job: { trigger: BotTrigger; prompt: string; fromBot?: string; source?: { channelType: string; channelId: string }; attempts?: number; routineId?: string; attachments?: ChannelAttachment[] }): { jobId: string; accepted: boolean; reasonCode?: string; duplicated?: boolean } {const manifest = this.store.get(botId);if (!manifest) return { jobId: '', accepted: false, reasonCode: 'target_unknown' };if (!manifest.enabled || this.disabled.has(botId)) return { jobId: '', accepted: false, reasonCode: 'target_disabled' };@@ -444,7 +444,7 @@ export class BotManager {idempotencyKey: idempotencyKeyFor(botId, job.trigger, job.prompt, job.fromBot, job.attachments),});if (durable.duplicated) {- return { jobId: durable.job.id, accepted: true };+ return { jobId: durable.job.id, accepted: true, duplicated: true };}const id = durable.job.id;queue.push({ id, botId, trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot, source: job.source, createdAt: durable.job.createdAt, attempts: durable.job.attempts, routineId: job.routineId });diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsindex 35ce77e5..46defeac 100644--- a/src/bots/bot-turn.ts+++ b/src/bots/bot-turn.ts@@ -240,7 +240,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {timestamp: Date.now(),metadata: { attachments: files },} as never;- const withFiles = withAttachments(messages, turnMessage, provider.name, provider.getModel());+ const withFiles = withAttachments(messages, turnMessage, provider.name, provider.getModel(), provider.seesImages);messages.splice(0, messages.length, ...withFiles);}diff --git a/src/bots/queue.test.ts b/src/bots/queue.test.tsindex d68ec07a..5c30448f 100644--- a/src/bots/queue.test.ts+++ b/src/bots/queue.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import { mkdtempSync, rmSync } from 'node:fs';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -373,4 +373,30 @@ describe('BotManager durable queue integration', () => {expect(backend.rehydratable()).toHaveLength(1);}});-});\ No newline at end of file+});++describe('idempotencyKeyFor with files', () => {+ let dir = '';+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mercury-idem-')); });+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); });++ const upload = (name: string, bytes: string) => {+ const path = join(dir, name);+ writeFileSync(path, bytes);+ return { kind: 'image' as const, path, mime: 'image/png', name: 'photo.png' };+ };++ it('keys a retried upload on its bytes, not its fresh random path', () => {+ const first = upload('1111-photo.png', 'same pixels');+ const retry = upload('2222-photo.png', 'same pixels');+ expect(idempotencyKeyFor('bot', 'api', 'what is this?', undefined, [retry]))+ .toBe(idempotencyKeyFor('bot', 'api', 'what is this?', undefined, [first]));+ });++ it('still tells two different photos apart', () => {+ const a = upload('a-photo.png', 'cat');+ const b = upload('b-photo.png', 'dog');+ expect(idempotencyKeyFor('bot', 'api', 'what is this?', undefined, [a]))+ .not.toBe(idempotencyKeyFor('bot', 'api', 'what is this?', undefined, [b]));+ });+});diff --git a/src/bots/queue.ts b/src/bots/queue.tsindex 70a04594..6cbfcb20 100644--- a/src/bots/queue.ts+++ b/src/bots/queue.ts@@ -97,8 +97,19 @@ const DLQ_CAP = 100;/*** Two requests that differ only by their files are different jobs: the same caption- * ("what is this?") with two different photos must not collapse into one.+ * ("what is this?") with two different photos must not collapse into one. Files are keyed+ * by their bytes, not their path: every upload gets a fresh random name, so a path would+ * never let a retried request dedupe.*/+/** A file's content hash, or its path when it can't be read (the turn will skip it anyway). */+function fileFingerprint(attachment: ChannelAttachment): string {+ try {+ return createHash('sha256').update(readFileSync(attachment.path)).digest('hex');+ } catch {+ return attachment.path;+ }+}+export function idempotencyKeyFor(botId: string,trigger: BotTrigger,@@ -106,7 +117,7 @@ export function idempotencyKeyFor(fromBot?: string,attachments?: ChannelAttachment[],): string {- const files = (attachments ?? []).map(a => a.path).join(',');+ const files = (attachments ?? []).map(fileFingerprint).join(',');return createHash('sha256').update(`${botId}|${trigger}|${prompt}|${fromBot ?? ''}|${files}`).digest('hex').slice(0, 16);}diff --git a/src/core/commands/chat-command.test.ts b/src/core/commands/chat-command.test.tsindex 8f114091..3e9c3339 100644--- a/src/core/commands/chat-command.test.ts+++ b/src/core/commands/chat-command.test.ts@@ -1,7 +1,25 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { WebChannel } from '../../channels/web.js';import { handleChatCommand } from './chat-command.js';+// A pick is saved to `<mercury home>/permission-mode.json`: without its own home, running+// these tests rewrote the developer's real permission mode to allow-all.+let home = '';+let savedHome: string | undefined;+beforeEach(() => {+ savedHome = process.env.MERCURY_HOME;+ home = mkdtempSync(join(tmpdir(), 'mercury-chat-command-'));+ process.env.MERCURY_HOME = home;+});+afterEach(() => {+ if (savedHome === undefined) delete process.env.MERCURY_HOME;+ else process.env.MERCURY_HOME = savedHome;+ rmSync(home, { recursive: true, force: true });+});+/*** Pickers on the owner's own screens. Since 1.3.1 the default launch attaches* to the runtime, which talks over the web channel — so a picker that wasdiff --git a/src/web/api/bots.test.ts b/src/web/api/bots.test.tsindex abfca232..3e01fd7b 100644--- a/src/web/api/bots.test.ts+++ b/src/web/api/bots.test.ts@@ -1,5 +1,5 @@-import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { existsSync, mkdtempSync, readdirSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { getDefaultConfig } from '../../utils/config.js';@@ -351,11 +351,20 @@ describe('web bots API — avatars', () => {describe('web bots API — files on a bot message', () => {const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');+ let savedHome: string | undefined;beforeEach(() => {+ // Uploads land in `<mercury home>/uploads`: keep them in this test's folder, never the real home.+ savedHome = process.env.MERCURY_HOME;+ process.env.MERCURY_HOME = root;store.create({ id: 'painter', name: 'Painter' });});+ afterEach(() => {+ if (savedHome === undefined) delete process.env.MERCURY_HOME;+ else process.env.MERCURY_HOME = savedHome;+ });+const send = (body: unknown) =>app.request('/api/bots/painter/message', {method: 'POST',@@ -374,6 +383,17 @@ describe('web bots API — files on a bot message', () => {});});+ it('deletes the files of a retry the queue already holds', async () => {+ // The first copy belongs to the queued job; the retry's copy has no job to read it.+ vi.spyOn(manager, 'enqueue').mockReturnValue({ jobId: 'queued', accepted: true, duplicated: true });+ const res = await send({ message: 'what is this?', attachments: [{ name: 'dot.png', data: PNG.toString('base64') }] });++ expect(res.status).toBe(202);+ await expect(jreq(res)).resolves.toMatchObject({ accepted: true, jobId: 'queued' });+ const stored = readdirSync(join(root, 'uploads'), { recursive: true, withFileTypes: true }).filter(e => e.isFile());+ expect(stored).toHaveLength(0);+ });+it('still takes a plain message with no files', async () => {const res = await send({ message: 'check the logs' });expect(res.status).toBe(202);diff --git a/src/web/api/bots.ts b/src/web/api/bots.tsindex f8126872..ff31fae9 100644--- a/src/web/api/bots.ts+++ b/src/web/api/bots.ts@@ -279,6 +279,10 @@ app.post('/api/bots/:id/message', async (c: any) => {for (const a of upload.attachments) rmSync(a.path, { force: true });return c.json({ accepted: false, reasonCode: result.reasonCode }, 409);}+ if (result.duplicated) {+ // A retry of a job already queued: that job holds its own copies of the files.+ for (const a of upload.attachments) rmSync(a.path, { force: true });+ }return c.json({accepted: true,jobId: result.jobId,