An open-source, faster Devin alternative
TypeScript
computer: download files from linked threads and forwards
Igor Zalutski via Computera83d79498e83
diff --git a/computer/src/links.test.ts b/computer/src/links.test.tsindex 100ee4dd..cfc2602b 100644--- a/computer/src/links.test.ts+++ b/computer/src/links.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { linkedBlock } from './links.js';+import { forwarded, linkedBlock, linkedFiles, MAX_LINKED_FILES } from './links.js';describe('linkedBlock', () => {it('frames held context with its own sentence, oldest first (work 112)', () => {@@ -30,3 +30,24 @@ describe('linkedBlock', () => {expect(linkedBlock({ url: 'u', ok: true, where: '#x', messages: [] })).toContain('A Slack thread linked in the message above');});});++describe('linkedFiles', () => {+ const file = (id: string) => ({ id, name: `${id}.png`, mimetype: 'image/png', size: 10, url_private: `https://files.slack.com/${id}` });++ it('downloads the files of shared links and forwards, not refused ones', () => {+ const linked = [+ { url: 'u1', ok: true as const, where: '#a', messages: [{ name: 'Igor', ts: '1', text: 'cc', files: ['F1.png'], slackFiles: [file('F1')] }] },+ { url: 'u2', ok: false as const, reason: 'private' },+ ...forwarded([{ is_share: true, text: 'see', files: [{ ...file('F2'), title: 't' }] }]),+ ];+ expect(linkedFiles(linked).map((f) => f.id)).toEqual(['F2', 'F1']);+ });++ it('keeps the newest files once, up to the cap', () => {+ const messages = Array.from({ length: MAX_LINKED_FILES + 2 }, (_, i) => ({ name: 'a', ts: String(i), text: '', slackFiles: [file(`F${i}`), file('F0')] }));+ const ids = linkedFiles([{ url: 'u', ok: true, where: '#a', messages }]).map((f) => f.id);+ expect(ids).toHaveLength(MAX_LINKED_FILES);+ expect(ids[0]).toBe(`F${MAX_LINKED_FILES + 1}`);+ expect(new Set(ids).size).toBe(ids.length);+ });+});diff --git a/computer/src/links.ts b/computer/src/links.tsindex 1a472a3c..deddbb89 100644--- a/computer/src/links.ts+++ b/computer/src/links.ts@@ -18,7 +18,7 @@import { randomBytes } from 'node:crypto';import type { WebClient } from '@slack/web-api';-import type { ReadThreadRequest } from './protocol.js';+import type { ReadThreadRequest, SlackFile } from './protocol.js';import { decodeSlack } from './slack-text.js';import { errorText } from './log.js';@@ -28,6 +28,8 @@ export interface LinkedMessage {ts: string;text: string;files?: string[];+ /** The same files as Slack gives them, for the runner to download (`linkedFiles`). */+ slackFiles?: SlackFile[];/** The message the link points at, when it is a reply in a thread. */linked?: boolean;/** Replies left out just before this one (a trailing entry with only this set ends the list). */@@ -211,7 +213,7 @@ export function linkResolver() {name: name(m),ts: m.ts,text: cap(decodeSlack(String(m.text ?? '').replace(/<@([UW][A-Z0-9]+)(\|[^>]*)?>/g, (_, id) => `@${dir.get(id)?.name ?? id}`))),- ...(m.files?.length ? { files: m.files.map((f: any) => f.name ?? f.id) } : {}),+ ...(m.files?.length ? { files: m.files.map((f: any) => f.name ?? f.id), slackFiles: m.files.map(slackFile) } : {}),...(link.threadTs && m.ts === link.ts && m.ts !== link.threadTs ? { linked: true } : {}),});@@ -336,7 +338,7 @@ export interface SharedAttachment {ts?: string;text?: string;fallback?: string;- files?: { name?: string; title?: string }[];+ files?: (Partial<SlackFile> & { title?: string })[];}/**@@ -359,12 +361,38 @@ export function forwarded(attachments: SharedAttachment[] | undefined): Linked[]name: a.author_name ?? a.author_subname ?? 'someone',ts: a.ts ?? '',text: cap(decodeSlack(a.text || a.fallback || '')),- ...(a.files?.length ? { files: a.files.map((f) => f.name ?? f.title ?? 'file') } : {}),+ ...(a.files?.length+ ? { files: a.files.map((f) => f.name ?? f.title ?? 'file'), slackFiles: a.files.filter((f) => f.id).map(slackFile) }+ : {}),},],}));}+/** Files a linked thread or forward is downloaded with: at most this many per message. */+export const MAX_LINKED_FILES = 10;++function slackFile(f: any): SlackFile {+ const { id, name, mimetype, size, url_private, url_private_download } = f;+ return { id, name, mimetype, size, url_private, url_private_download };+}++/**+ * The files in linked threads and forwards that were shared with the session,+ * newest first, so a screenshot posted with the link's last message is the one+ * kept: the runner downloads them as it does the message's own files.+ */+export function linkedFiles(linked: Linked[] | undefined): SlackFile[] {+ const seen = new Set<string>();+ const out: SlackFile[] = [];+ for (const l of [...(linked ?? [])].reverse()) {+ if (!l.ok) continue;+ for (const m of [...l.messages].reverse())+ for (const f of m.slackFiles ?? []) if (f.id && !seen.has(f.id) && out.length < MAX_LINKED_FILES) seen.add(f.id), out.push(f);+ }+ return out;+}+/** The message text with each linked thread (or the reason it isn't shared) after it, for the model. */export function withLinked(text: string, linked: Linked[] | undefined): string {const own = defang(text);diff --git a/computer/src/main.ts b/computer/src/main.tsindex fc41f6bd..208c251a 100644--- a/computer/src/main.ts+++ b/computer/src/main.ts@@ -21,7 +21,7 @@ import { panels } from './runner/agents.js';import { ensureWorkdir } from './workspace.js';import { addressed, decodeSlack } from './slack-text.js';import { fetchAttachments, type SlackFile } from './runner/attachments.js';-import { linkResolver, withLinked } from './links.js';+import { linkedFiles, linkResolver, withLinked } from './links.js';import { log } from './log.js';import { decodeActionId, type PermissionMode } from './protocol.js';import { takeTier } from './tiers.js';@@ -177,12 +177,12 @@ const resolveLinks = linkResolver();async function deliver(s: Session, m: Msg, text: string, mentioned = true, midThread = false) {if (text.startsWith('!')) return s.command(text, m.user!);if (s.isBusy) void s.client.reactions.add({ channel: m.channel, timestamp: m.ts, name: 'eyes' }).catch(() => {});- const atts = await fetchAttachments(m.files, s.client.token ?? env.SLACK_BOT_TOKEN, s.info.key);// One machine has no people table: whoever posts is the owner for the link check (work 049).const req = { text, poster: m.user!, owner: m.user!, destination: m.channel };const linked = await resolveLinks(s.client, req);// Mentioned mid-thread: the replies above, so the new session sees what it was asked about.if (midThread) linked.unshift(await resolveLinks.thread(s.client, req, m.thread_ts!, m.ts));+ const atts = await fetchAttachments([...(m.files ?? []), ...linkedFiles(linked)], s.client.token ?? env.SLACK_BOT_TOKEN, s.info.key);await s.send(withLinked(text, linked), m.user!, atts, mentioned);}diff --git a/computer/src/runner/main.ts b/computer/src/runner/main.tsindex 1546c544..5b20a9ab 100644--- a/computer/src/runner/main.ts+++ b/computer/src/runner/main.ts@@ -39,7 +39,7 @@ import { WebClient } from '@slack/web-api';import { Session, type SessionHooks, prompts } from './session.js';import { mayAnswer } from './prompts.js';import { fetchAttachments, interruptDownloads } from './attachments.js';-import { type Linked, withLinked } from '../links.js';+import { type Linked, linkedFiles, withLinked } from '../links.js';import { SessionSecrets, redactingClient } from './session-secrets.js';import { PromptGuard } from './prompt-guard.js';import { codexBin } from '../runner-env.js';@@ -422,8 +422,9 @@ async function handle(m: Delivery, trace?: TraceContext) {if (refused) return void (await s.say(refused), clearFeedback(m.ts));if (!s.isBusy) awaitingOutput.push(m.ts);else if (s.thread.slack) void s.client.reactions.add({ channel: ss.channel!, timestamp: m.ts, name: 'eyes' }).catch(() => {});- const fetching = fetchAttachments(m.files, botToken, ss.key);- const atts = m.files?.length ? turns.timed('attachments', fetching, { count: m.files.length }) : fetching;+ const files = [...(m.files ?? []), ...linkedFiles(m.linked)];+ const fetching = fetchAttachments(files, botToken, ss.key);+ const atts = files.length ? turns.timed('attachments', fetching, { count: files.length }) : fetching;await s.send(withLinked(m.text, m.linked), m.userId, atts, m.mentioned && m.mentionedInline ? 'inline' : m.mentioned, undefined, m.role);// The gateway set the status to `processing` on receipt. A reply that only// answered an open prompt starts no turn, and nothing would clear it.