An open-source, faster Devin alternative
TypeScript
Web messages post into Slack as you; cleaner Slack messages on the web (#1060)
opencomputer-app[bot]08f4b0fd50b4
diff --git a/computer/src/provision.ts b/computer/src/provision.tsindex 09eee973..3993ace1 100644--- a/computer/src/provision.ts+++ b/computer/src/provision.ts@@ -33,6 +33,8 @@ export const SCOPES = ['im:read','im:write','chat:write',+ // Posts a person's web messages into their thread under their own name and photo (runner/api/api.ts echo).+ 'chat:write.customize','files:read','files:write','reactions:write',diff --git a/computer/src/runner/api/api.test.ts b/computer/src/runner/api/api.test.tsindex f83e598d..81c7d057 100644--- a/computer/src/runner/api/api.test.ts+++ b/computer/src/runner/api/api.test.ts@@ -26,13 +26,13 @@ afterEach(async () => {});/** `before`: what the journal holds when the runner attaches (it then resumes, as attachApi does). */-async function world(before?: (log: Awaited<ReturnType<typeof openLog>>) => void) {+async function world(before?: (log: Awaited<ReturnType<typeof openLog>>) => void, o: { scopes?: string[] } = {}) {vi.resetModules();vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'performance'], now: new Date('2026-10-26T00:00:00Z') });const T = await import('./testing.js');const { SessionApi } = await import('./api.js');const rec: unknown[] = [];- const t = T.fakeSession(rec);+ const t = T.fakeSession(rec, o);const tmp = tempSession();const log = await openLog(tmp.file, tmp.sessionId);before?.(log);@@ -91,6 +91,21 @@ describe('SessionApi', () => {expect(posts().filter((t) => t.includes('from slack'))).toEqual([]);});+ it("the owner's message from the web posts under their own Slack name and photo when the app may; without the scope, quoted", async () => {+ const posted = async (scopes: string[], who: typeof ANN_CTX) => {+ const w = await world(undefined, { scopes });+ result(await w.call('turns.send', { input: 'ship <it>' }, { ...who, actor: { ...who.actor, via: 'dashboard' as const } }));+ return w.rec.filter((r) => (r as { slack?: string }).slack === 'chat.postMessage').map((r) => (r as { args: object }).args);+ };+ expect(await posted(['chat:write', 'chat:write.customize'], ANN_CTX)).toEqual([+ expect.objectContaining({ text: 'ship <it>', username: 'name-U1', icon_url: 'https://img/U1' }),+ ]);+ expect(await posted(['chat:write', 'chat:write.customize'], BOB)).toEqual([expect.objectContaining({ text: '*Bob* from the web:\n> ship <it>' })]);+ const [plain] = await posted(['chat:write'], ANN_CTX);+ expect(plain).not.toHaveProperty('username');+ expect(plain).toMatchObject({ text: expect.stringContaining('from the web:\n> ship <it>') });+ });+it('one idempotency key gives one turn', async () => {const w = await world();const ctx = { ...ANN_CTX, idempotencyKey: 'k-1' };diff --git a/computer/src/runner/api/api.ts b/computer/src/runner/api/api.tsindex 6aae61ef..c37e71f5 100644--- a/computer/src/runner/api/api.ts+++ b/computer/src/runner/api/api.ts@@ -22,8 +22,9 @@// (asks.ts, prompts.ts); a stop of a subagent is the panel's Stop button;// - Slack sees what it saw before, plus the words: a message into a Slack// session from anywhere else (the dashboard, the CLI, the API) is posted-// into its thread, quoted under its sender's name, before the session takes-// it, so the thread reads as the whole conversation. Nothing else here posts+// into its thread before the session takes it, so the thread reads as the+// whole conversation: the owner's own words under their Slack name and photo+// when the app has `chat:write.customize`, anyone else's quoted under their name. Nothing else here posts// to it beyond what the session's own commands (a model switch) say.import { log } from '../../log.js';@@ -66,16 +67,22 @@ const fail = (code: string, message: string, status: number, extra: Record<strinerror: apiError(code, message, status, { retryable: status >= 500, ...extra }),});const actorOf = (a: ApiActor): Actor => ({ ...a, name: a.name ?? a.id });+/** A person's name for the API: their own, else their git author name without the " via Computer" commits carry. */+export const personName = (p: Person): string => p.name ?? p.gitName.replace(/ via Computer$/, '');/** Longest echo of a message into Slack; the rest is cut. */export const ECHO_MAX = 3_000;const VIA: Record<string, string> = { dashboard: 'the web', opc: 'the CLI', api: 'the API' };+/** A message from outside Slack as posted under its sender's own name: the words, cut, mentions inert. */+export function echoPlain(text: string): string {+ const cut = text.length > ECHO_MAX ? `${text.slice(0, ECHO_MAX)}…` : text;+ return cut.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+}+/** A message from outside Slack as its thread shows it: the sender, where from, and the words quoted (mentions inert). */export function echoText(text: string, actor: Actor): string {- const cut = text.length > ECHO_MAX ? `${text.slice(0, ECHO_MAX)}…` : text;- const safe = cut.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');- const quoted = safe.split('\n').map((l) => `> ${l}`).join('\n');+ const quoted = echoPlain(text).split('\n').map((l) => `> ${l}`).join('\n');return `*${actor.name}* from ${VIA[actor.via] ?? actor.via}:\n${quoted}`;}@@ -147,7 +154,7 @@ export class SessionApi implements Writer {/** A Slack user as the API names people: the owner by their member id, anyone else by their Slack id. */private slackActor(u: string | undefined): Actor {const owner = this.o.owner;- if (!u || u === owner.slackUserId) return { id: owner.userId ?? owner.slackUserId ?? 'owner', name: owner.name ?? owner.gitName, via: 'slack', client: null };+ if (!u || u === owner.slackUserId) return { id: owner.userId ?? owner.slackUserId ?? 'owner', name: personName(owner), via: 'slack', client: null };return { id: u, name: u, via: 'slack', client: null };}@@ -228,9 +235,12 @@ export class SessionApi implements Writer {return this.sent(d.turnId, 'queued');}- /** A message from outside Slack, into a Slack session's thread (never throws: `say` logs Slack's refusals). */+ /** A message from outside Slack, into a Slack session's thread (never throws: `say` logs Slack's refusals). The owner's+ * own words post under their Slack name and photo when the app may (`chat:write.customize`); anyone else's, quoted. */private async echo(text: string, actor: Actor) {if (actor.via === 'slack' || !this.session.thread.slack) return;+ const { owner } = this.o;+ if (owner.slackUserId && actor.id === owner.userId && (await this.session.thread.sayAs(owner.slackUserId, echoPlain(text)))) return;await this.session.thread.say(echoText(text, actor));}diff --git a/computer/src/runner/api/attach.ts b/computer/src/runner/api/attach.tsindex de95ca15..c6474079 100644--- a/computer/src/runner/api/attach.ts+++ b/computer/src/runner/api/attach.ts@@ -8,7 +8,7 @@ import { SessionLog } from '../../api/session-log.js';import { createdOf } from '../../api/created.js';import type { Person, RunnerApi, SessionSpec } from '../../protocol.js';import type { Session } from '../session.js';-import { SessionApi, type SessionApiOptions } from './api.js';+import { personName, SessionApi, type SessionApiOptions } from './api.js';import type { Telemetry } from '../../telemetry/emitter.js';import { apiWriteEvent } from './write-events.js';@@ -35,7 +35,7 @@ export async function attachApi(created: o.spec && createdOf(o.spec),seed: {sessionId: spec.sessionId,- owner: { id: owner.userId ?? owner.slackUserId ?? 'owner', name: owner.name ?? owner.gitName, email: owner.email ?? null },+ owner: { id: owner.userId ?? owner.slackUserId ?? 'owner', name: personName(owner), email: owner.email ?? null },},});const api = new SessionApi(log, session, { ...o, onWrite: o.onWrite ?? (o.telemetry && apiWriteEvent(o.telemetry)) });diff --git a/computer/src/runner/api/surface.ts b/computer/src/runner/api/surface.tsindex 39eec206..46071bc2 100644--- a/computer/src/runner/api/surface.ts+++ b/computer/src/runner/api/surface.ts@@ -35,6 +35,8 @@ export interface Surface extends Names {/** A subagents panel; `stop` stops one subagent. */panel(stop: (taskId: string) => Promise<void>): AgentsPanel;say(text: string): Promise<void>;+ /** `text` under Slack user `id`'s name and photo; false (nothing posted) when Slack won't. */+ sayAs(id: string, text: string): Promise<boolean>;post(text: string, blocks: KnownBlock[]): Promise<string>;update(ts: string, text: string, blocks: KnownBlock[], what?: string): Promise<void>;delete(ts: string, what?: string): Promise<void>;@@ -93,6 +95,9 @@ export class NullSurface implements Surface {return new AgentsPanel(this.client, this.target, stop);}async say() {}+ async sayAs() {+ return false;+ }async post() {return '';}diff --git a/computer/src/runner/api/testing.ts b/computer/src/runner/api/testing.tsindex 20a542f3..e64a3d2d 100644--- a/computer/src/runner/api/testing.ts+++ b/computer/src/runner/api/testing.ts@@ -18,10 +18,12 @@ export type Rec = unknown[];export interface SetupOptions {kind?: 'thread' | 'channel';fresh?: boolean;+ /** The bot token's scopes, as `auth.test` reports them. */+ scopes?: string[];}/** A Slack client that logs every call and answers like Slack does, with counter timestamps. */-function slack(rec: Rec) {+function slack(rec: Rec, scopes = ['chat:write']) {let n = 0;const node = (names: string[]): unknown =>new Proxy(() => {}, {@@ -29,7 +31,8 @@ function slack(rec: Rec) {apply: async (_, __, [args]) => {const method = names.join('.');rec.push({ slack: method, args });- if (method === 'users.info') return { ok: true, user: { profile: { display_name: `name-${args.user}` } } };+ if (method === 'users.info') return { ok: true, user: { profile: { display_name: `name-${args.user}`, image_192: `https://img/${args.user}` } } };+ if (method === 'auth.test') return { ok: true, response_metadata: { scopes } };if (method === 'conversations.info') return { ok: true, channel: { name: 'eng' } };if (method === 'files.getUploadURLExternal') return { ok: true, upload_url: 'https://upload.invalid', file_id: 'F1' };return { ok: true, ts: `1.${++n}` };@@ -108,7 +111,7 @@ export function fakeSession(rec: Rec, o: SetupOptions = {}) {mode: 'default' as const,...(o.fresh ? {} : { sdkSessionId: 'sdk-0' }),};- const sess = new Session(info, slack(rec), () => rec.push({ persist: { mode: sess.info.mode, sdk: sess.info.sdkSessionId ?? null } }), {+ const sess = new Session(info, slack(rec, o.scopes), () => rec.push({ persist: { mode: sess.info.mode, sdk: sess.info.sdkSessionId ?? null } }), {busy: (b) => void rec.push({ busy: b }),}, kind);/** Let the session run: fake time forward in steps, real immediates (Effect's scheduler) in between. */diff --git a/computer/src/runner/thread.ts b/computer/src/runner/thread.tsindex e713ac53..254eea73 100644--- a/computer/src/runner/thread.ts+++ b/computer/src/runner/thread.ts@@ -42,7 +42,9 @@ export interface ContextBarItem {export class SlackThread implements Names {private warned = new Set<string>();- private static names = new Map<string, { name?: string; at: number }>();+ private static names = new Map<string, { name?: string; image?: string; at: number }>();+ /** Whether the app may post under another name and photo (`chat:write.customize`), asked once per process. */+ private static customize?: Promise<boolean>;private channelName?: string;constructor(@@ -199,14 +201,34 @@ export class SlackThread implements Names {/** A person's display name (falling back to real name), cached for the process; misses for ten minutes. */async nameOf(id: string): Promise<string | undefined> {+ return (await this.profileOf(id))?.name;+ }++ /** A person's display name and photo, cached as `nameOf` says. */+ private async profileOf(id: string): Promise<{ name?: string; image?: string } | undefined> {const c = SlackThread.names.get(id);- if (c && (c.name || Date.now() - c.at < MISS_TTL_MS)) return c.name;+ if (c && (c.name || Date.now() - c.at < MISS_TTL_MS)) return c;const r = await within(() => this.client.users.info({ user: id })).catch((e) => this.warn('users.info', e));const u = r?.user;const name = u?.profile?.display_name || u?.real_name || u?.name || undefined;+ const image = u?.profile?.image_192 || u?.profile?.image_72 || undefined;// A timeout or error is tried again next message; only Slack's answer is cached.- if (r) SlackThread.names.set(id, { name, at: Date.now() });- return name;+ if (r) SlackThread.names.set(id, { name, image, at: Date.now() });+ return { name, image };+ }++ /** `text` posted under Slack user `id`'s name and photo, as Devin does; false (nothing posted) when the app lacks `chat:write.customize` or Slack can't name them. */+ async sayAs(id: string, text: string): Promise<boolean> {+ SlackThread.customize ??= within(() => this.client.auth.test())+ .then((r) => !!r?.response_metadata?.scopes?.includes('chat:write.customize'))+ .catch((e) => (this.warn('auth.test', e), false));+ if (!(await SlackThread.customize)) return false;+ const p = await this.profileOf(id);+ if (!p?.name) return false;+ return this.client.chat+ .postMessage({ channel: this.info.channel, ...this.thread, text, username: p.name, ...(p.image ? { icon_url: p.image } : {}) })+ .then(() => true)+ .catch((e) => (this.warn('say', e), false));}/** The conversation by name (`#eng`, `a DM`), looked up once per session; a failure is retried next time. */diff --git a/web/src/managed-agents/computer-sessions/Session.tsx b/web/src/managed-agents/computer-sessions/Session.tsxindex d9628f06..795e59de 100644--- a/web/src/managed-agents/computer-sessions/Session.tsx+++ b/web/src/managed-agents/computer-sessions/Session.tsx@@ -263,6 +263,9 @@ function Header({ id }: { id: string }) {)}+/** Where a message came from, beside its author's name; the web's own messages say nothing. */+const VIA: Record<string, string> = { slack: 'Slack', opc: 'CLI', api: 'API' }+// Members' emails by member id (`usr_…`). The computer derives that id from the// user id: the WorkOS id when there is one, else a hash (`memberId` in managed-agents).async function memberEmails(@@ -327,7 +330,7 @@ function Item({{item.author || email ? (<span className="text-muted-foreground text-xs">{item.author ?? email}- {item.via && item.via !== 'dashboard' ? ` via ${item.via}` : ''}+ {item.via && VIA[item.via] ? ` · ${VIA[item.via]}` : ''}</span>) : null}<div className="bg-secondary rounded-2xl rounded-br-md px-3.5 py-2 text-sm whitespace-pre-wrap">diff --git a/web/src/managed-agents/computer-sessions/transcript.test.ts b/web/src/managed-agents/computer-sessions/transcript.test.tsindex 7e77220a..339fcd47 100644--- a/web/src/managed-agents/computer-sessions/transcript.test.ts+++ b/web/src/managed-agents/computer-sessions/transcript.test.ts@@ -18,6 +18,24 @@ const ev = (})describe('buildTranscript', () => {+ it('shows a Slack message\'s words without the computer\'s header, and its sender without " via Computer"', () => {+ const [item] = buildTranscript([+ {+ ...ev('message.received', {+ input:+ '[Slack: from Mo (<@U1>) in #dev, mentions you]\nhello\n[Slack: from Mo (<@U1>) in #dev, does not mention you]\nand more',+ }),+ actor: { id: 'U1', name: 'Mo via Computer', via: 'slack' },+ },+ ])+ expect(item).toMatchObject({+ kind: 'user',+ text: 'hello\nand more',+ author: 'Mo',+ via: 'slack',+ })+ })+it('folds tool calls between messages into one work step', () => {const items = buildTranscript([ev('message.received', { input: 'Fix the test' }),diff --git a/web/src/managed-agents/computer-sessions/transcript.ts b/web/src/managed-agents/computer-sessions/transcript.tsindex b3dc0e07..ba55ab03 100644--- a/web/src/managed-agents/computer-sessions/transcript.ts+++ b/web/src/managed-agents/computer-sessions/transcript.ts@@ -37,6 +37,10 @@ export type TranscriptItem =const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)+/** A Slack message's words without the `[Slack: from … in #eng, mentions you]` line the computer puts above each for the model. */+export const withoutSlackHeader = (text: string | null): string | null =>+ text && text.replace(/^\[Slack: from [^\n]*\]\n?/gm, '').trim()+export function buildTranscript(events: SessionEvent[]): TranscriptItem[] {const items: TranscriptItem[] = []let work: Extract<TranscriptItem, { kind: 'work' }> | null = null@@ -67,17 +71,16 @@ export function buildTranscript(events: SessionEvent[]): TranscriptItem[] {switch (e.type) {case 'message.received': {closeWork()- const text = str(d.input)+ const text = withoutSlackHeader(str(d.input))+ // Journals before the computer stopped using the git author name carry " via Computer".+ const name = e.actor?.name?.replace(/ via Computer$/, '')if (text)items.push({kind: 'user',key: e.id,text,// The computer falls back to the member id (`usr_…`) when there is no name: not worth showing.- author:- e.actor?.name && e.actor.name !== e.actor.id- ? e.actor.name- : null,+ author: name && e.actor?.name !== e.actor?.id ? name : null,authorId: e.actor?.id ?? null,via: e.actor?.via ?? null,at: e.createdAt,