Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(agents): persist uploaded profile pictures (#7345)
Eric Hayesbe3ae2fa6b8f
diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsxindex dc0c17e557..76ca2480c0 100644--- a/apps/web/src/features/settings/Agents.test.tsx+++ b/apps/web/src/features/settings/Agents.test.tsx@@ -100,6 +100,11 @@ const agentMocks = vi.hoisted(() => ({isTeamOwner: false,}));+const avatarMocks = vi.hoisted(() => ({ upload: vi.fn() }));+vi.mock('@queries/agents/avatar', () => ({+ useUploadAgentAvatarMutation: () => ({ mutateAsync: avatarMocks.upload }),+}));+vi.mock('@queries/auth/cursor-api-key', () => ({useCursorApiKeyStatusQuery: () => cursorMocks.status,}));@@ -285,6 +290,8 @@ beforeAll(() => {});beforeEach(() => {+ avatarMocks.upload.mockReset();+ avatarMocks.upload.mockResolvedValue('https://static.example/avatar.png');updateSearchParams({ createAgent: undefined });setSearchParams.mockClear();cursorMocks.status.data = {@@ -677,6 +684,111 @@ describe('Agents', () => {expect(screen.queryByText('Other Team Helper')).toBeNull();});+ it('uploads a team agent avatar before saving and retains it when reopened', async () => {+ const originalAvatar = 'https://static.example/original.png';+ const uploadedAvatar = 'https://static.example/avatar.png';+ const existing = {+ bot: {+ id: 'agent-1',+ kind: 'owned',+ owner: { type: 'team', team_id: 'team-1' },+ name: 'Grungus',+ handle: 'grungus',+ has_agent: true,+ avatar_url: originalAvatar,+ },+ instructions: 'Help the team.',+ harness: 'in-memory',+ default_model: Model.sonnet5,+ channel_scope: 'all',+ channel_ids: [],+ };+ agentMocks.query.data = [existing];+ let finishUpload!: (url: string) => void;+ avatarMocks.upload.mockImplementation(+ () =>+ new Promise<string>((resolve) => {+ finishUpload = resolve;+ })+ );+ agentMocks.update.mockImplementation(+ async (params: { avatarUrl: string }) => {+ existing.bot.avatar_url = params.avatarUrl;+ }+ );+ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'Edit Grungus' }));+ const form = screen.getByRole('region', { name: 'Edit agent' });+ const file = new File(['avatar'], 'avatar.png', { type: 'image/png' });+ fireEvent.change(form.querySelector('input[type="file"]')!, {+ target: { files: [file] },+ });+ expect(avatarMocks.upload).toHaveBeenCalledWith(file);+ expect(screen.getByRole('button', { name: 'Save changes' })).toHaveProperty(+ 'disabled',+ true+ );+ expect(screen.getByRole('button', { name: 'Uploading…' })).toHaveProperty(+ 'disabled',+ true+ );+ expect(+ screen.getByRole('img', { name: 'Grungus avatar' }).getAttribute('src')+ ).toBe(originalAvatar);++ finishUpload(uploadedAvatar);+ await waitFor(() =>+ expect(+ screen.getByRole('button', { name: 'Save changes' })+ ).toHaveProperty('disabled', false)+ );+ fireEvent.click(screen.getByRole('button', { name: 'Save changes' }));+ await waitFor(() =>+ expect(agentMocks.update).toHaveBeenCalledWith(+ expect.objectContaining({ avatarUrl: uploadedAvatar, teamId: 'team-1' })+ )+ );+ await waitFor(() =>+ expect(screen.getByRole('button', { name: 'Edit Grungus' })).toBeTruthy()+ );+ fireEvent.click(screen.getByRole('button', { name: 'Edit Grungus' }));+ expect(+ screen.getByRole('img', { name: 'Grungus avatar' }).getAttribute('src')+ ).toBe(uploadedAvatar);+ });++ it('reports avatar upload failures and allows retrying without losing the form', async () => {+ avatarMocks.upload.mockRejectedValueOnce(+ new Error('Failed to upload file')+ );+ render(() => <Agents />);+ fireEvent.click(screen.getByRole('button', { name: 'New agent' }));+ fireEvent.input(screen.getByLabelText('Name'), {+ target: { value: 'Grungus' },+ });+ const input = screen+ .getByRole('region', { name: 'New agent' })+ .querySelector('input[type="file"]')!;+ const file = new File(['avatar'], 'avatar.png', { type: 'image/png' });+ fireEvent.change(input, { target: { files: [file] } });+ await waitFor(() =>+ expect(agentMocks.toastFailure).toHaveBeenCalledWith(+ 'Failed to upload file'+ )+ );+ expect(screen.getByLabelText('Name')).toHaveProperty('value', 'Grungus');+ expect(screen.getByRole('button', { name: 'Upload' })).toHaveProperty(+ 'disabled',+ false+ );+ fireEvent.change(input, { target: { files: [file] } });+ await waitFor(() =>+ expect(+ screen.getByRole('img', { name: 'Grungus avatar' }).getAttribute('src')+ ).toBe('https://static.example/avatar.png')+ );+ });+it('edits and persists an existing agent through the agents API', async () => {agentMocks.query.data = [{diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsxindex d867e4a55f..789cd2ccb7 100644--- a/apps/web/src/features/settings/Agents.tsx+++ b/apps/web/src/features/settings/Agents.tsx@@ -27,6 +27,7 @@ import {useDeleteAgentMutation,useUpdateAgentMutation,} from '@queries/agents/agents';+import { useUploadAgentAvatarMutation } from '@queries/agents/avatar';import {type AgentModelTarget,buildAgentModelTargets,@@ -564,6 +565,9 @@ function AgentEditorPage(props: {const [avatarUrl, setAvatarUrl] = createSignal<string | undefined>(props.agent?.bot.avatar_url ?? undefined);+ const uploadAvatar = useUploadAgentAvatarMutation();+ const [uploadingAvatar, setUploadingAvatar] = createSignal(false);+ const busy = () => props.pending || uploadingAvatar();const [instructions, setInstructions] = createSignal(props.agent?.instructions ?? '');@@ -697,7 +701,7 @@ function AgentEditorPage(props: {let pageContentRef: HTMLDivElement | undefined;const close = () => {- if (!props.pending) props.onClose();+ if (!busy()) props.onClose();};const handleNameInput = (value: string) => {@@ -712,17 +716,23 @@ function AgentEditorPage(props: {setCodingChoice(undefined);};- const handleAvatarInput = (file: File | undefined) => {- if (!file) return;- const reader = new FileReader();- reader.addEventListener('load', () => {- if (typeof reader.result === 'string') setAvatarUrl(reader.result);- });- reader.readAsDataURL(file);+ const handleAvatarInput = async (file: File | undefined) => {+ if (!file || busy()) return;+ setUploadingAvatar(true);+ try {+ setAvatarUrl(await uploadAvatar.mutateAsync(file));+ } catch (error) {+ toast.failure(+ error instanceof Error ? error.message : 'Failed to upload avatar'+ );+ } finally {+ setUploadingAvatar(false);+ if (avatarInputRef) avatarInputRef.value = '';+ }};const canCreate = () =>- !props.pending &&+ !busy() &&name().trim().length > 0 &&tag().trim().length > 0 &&selectedHarness() !== undefined &&@@ -771,12 +781,7 @@ function AgentEditorPage(props: {showTitleInSheetdescription="Give your agent an identity, instructions, and a runtime."actions={- <Button- variant="ghost"- size="sm"- onClick={close}- disabled={props.pending}- >+ <Button variant="ghost" size="sm" onClick={close} disabled={busy()}><ArrowLeftIcon /> Back</Button>}@@ -802,6 +807,7 @@ function AgentEditorPage(props: {<buttontype="button"aria-label="Upload avatar"+ disabled={busy()}class="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-accent"onClick={() => avatarInputRef?.click()}>@@ -830,18 +836,20 @@ function AgentEditorPage(props: {type="file"accept="image/*"class="hidden"+ disabled={busy()}onChange={(event) =>- handleAvatarInput(event.currentTarget.files?.[0])+ void handleAvatarInput(event.currentTarget.files?.[0])}/><Buttontype="button"variant="outline"size="sm"+ disabled={busy()}onClick={() => avatarInputRef?.click()}><UploadIcon />- Upload+ {uploadingAvatar() ? 'Uploading…' : 'Upload'}</Button></div>@@ -1181,7 +1189,7 @@ function AgentEditorPage(props: {variant="ghost"size="sm"onClick={close}- disabled={props.pending}+ disabled={busy()}>Cancel</Button>diff --git a/apps/web/src/lib/core/constant/servers.test.ts b/apps/web/src/lib/core/constant/servers.test.tsnew file mode 100644index 0000000000..91d4965421--- /dev/null+++ b/apps/web/src/lib/core/constant/servers.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';+import { staticFileSizedUrl } from './servers';++describe('staticFileSizedUrl', () => {+ it.each([+ 'data:image/png;base64,aW1hZ2U=',+ 'blob:https://macro.com/avatar-id',+ ])('preserves embedded or local image sources: %s', (url) => {+ expect(staticFileSizedUrl(url, 'small')).toBe(url);+ });++ it('requests a thumbnail for uploaded images', () => {+ expect(+ staticFileSizedUrl('https://static.macro.com/file/avatar-id', 'small')+ ).toBe('https://static.macro.com/file/avatar-id?size=320');+ });+});diff --git a/apps/web/src/lib/core/constant/servers.ts b/apps/web/src/lib/core/constant/servers.tsindex a2c94434f1..1979b967da 100644--- a/apps/web/src/lib/core/constant/servers.ts+++ b/apps/web/src/lib/core/constant/servers.ts@@ -247,5 +247,8 @@ export function staticFileSizedEndpoint(}export function staticFileSizedUrl(url: string, size: StaticFileSize): string {+ // Embedded and local previews are not image-service URLs. A query string+ // changes their contents instead of requesting a resized image.+ if (url.startsWith('data:') || url.startsWith('blob:')) return url;return `${url}?size=${staticFileSizes[size]}`;}diff --git a/apps/web/src/lib/queries/agents/agents.test.tsx b/apps/web/src/lib/queries/agents/agents.test.tsxindex 3fa5765fd8..d02efd09fb 100644--- a/apps/web/src/lib/queries/agents/agents.test.tsx+++ b/apps/web/src/lib/queries/agents/agents.test.tsx@@ -2,6 +2,8 @@* @vitest-environment jsdom*/+import { staticFileIdEndpoint } from '@core/constant/servers';+import { uploadFile } from '@core/util/upload';import { storageServiceClient } from '@service-storage/client';import type { Agent } from '@service-storage/generated/schemas/agent';import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';@@ -29,12 +31,17 @@ vi.mock('@service-storage/client', () => ({},}));+vi.mock('@core/util/upload', () => ({+ uploadFile: vi.fn(),+}));+import {type CreateAgentParams,useCreateAgentMutation,useDeleteAgentMutation,useUpdateAgentMutation,} from './agents';+import { useUploadAgentAvatarMutation } from './avatar';const params: CreateAgentParams = {channelIds: ['channel-new'],@@ -136,26 +143,71 @@ describe('agent channel-bot cache invalidation', () => {deleted: false,});vi.mocked(storageServiceClient.updateAgent).mockResolvedValue(ok(updated));- const invalidateQueries = vi.spyOn(testQueryClient, 'invalidateQueries');+ for (const id of ['channel-old', 'channel-new']) {+ testQueryClient.setQueryData(channelKeys.channelBots(id).queryKey, []);+ }const mutation = renderHook(() => useUpdateAgentMutation());await mutation.mutateAsync({ ...params, agentId: 'agent-1' });- expect(invalidateQueries).toHaveBeenCalledWith({- queryKey: channelKeys.channelBots('channel-old').queryKey,- });- expect(invalidateQueries).toHaveBeenCalledWith({- queryKey: channelKeys.channelBots('channel-new').queryKey,- });- expect(invalidateQueries).toHaveBeenCalledWith({- queryKey: botKeys.list.queryKey,- });+ for (const id of ['channel-old', 'channel-new']) {+ expect(+ testQueryClient.getQueryState(channelKeys.channelBots(id).queryKey)+ ?.isInvalidated+ ).toBe(true);+ }expect(testQueryClient.getQueryData(botKeys.detail(updated.bot.id).queryKey)).toEqual(updated.bot);expect(testQueryClient.getQueryState(profileKey)?.isInvalidated).toBe(true);});+ it('refreshes cached channel and bot profiles when a global team agent changes its avatar', async () => {+ const existing = { ...agent([]), channel_scope: 'all' as const };+ existing.bot.owner = { type: 'team', team_id: 'team-1' };+ const updated = {+ ...existing,+ bot: { ...existing.bot, avatar_url: 'https://static.example/avatar.png' },+ };+ testQueryClient.setQueryData(agentKeys.list.queryKey, [existing]);+ testQueryClient.setQueryData(botKeys.list.queryKey, [existing.bot]);+ testQueryClient.setQueryData(+ botKeys.detail(existing.bot.id).queryKey,+ existing.bot+ );+ testQueryClient.setQueryData(+ channelKeys.channelBots('channel-installed').queryKey,+ [existing.bot]+ );+ vi.mocked(storageServiceClient.updateAgent).mockResolvedValue(ok(updated));+ const mutation = renderHook(() => useUpdateAgentMutation());+ await mutation.mutateAsync({+ ...params,+ agentId: existing.bot.id,+ avatarUrl: updated.bot.avatar_url,+ channelScope: 'all',+ channelIds: [],+ teamId: 'team-1',+ });+ expect(storageServiceClient.updateAgent).toHaveBeenCalledWith(+ expect.objectContaining({ avatar_url: updated.bot.avatar_url })+ );+ expect(testQueryClient.getQueryData(agentKeys.list.queryKey)).toEqual([+ updated,+ ]);+ expect(+ testQueryClient.getQueryData(botKeys.detail(existing.bot.id).queryKey)+ ).toEqual(updated.bot);+ expect(+ testQueryClient.getQueryState(botKeys.list.queryKey)?.isInvalidated+ ).toBe(true);+ expect(+ testQueryClient.getQueryState(+ channelKeys.channelBots('channel-installed').queryKey+ )?.isInvalidated+ ).toBe(true);+ });+it('removes a deleted agent and invalidates its channel bot queries', async () => {const existing = agent(['channel-old']);testQueryClient.setQueryData(agentKeys.list.queryKey, [existing]);@@ -189,3 +241,50 @@ describe('agent channel-bot cache invalidation', () => {});});});++describe('agent avatar uploads', () => {+ it.each(['image/png', 'image/heic'])(+ 'uses the shared image conversion and upload pipeline for %s',+ async (type) => {+ vi.mocked(uploadFile).mockResolvedValue({+ failed: false,+ pending: false,+ destination: 'static',+ id: 'file-id',+ name: 'avatar.png',+ });+ const mutation = renderHook(() => useUploadAgentAvatarMutation());+ // This exceeds the JSON endpoint body limit when encoded as a data URL.+ const file = new File([new Uint8Array(3 * 1024 * 1024)], 'avatar.png', {+ type,+ });+ await expect(mutation.mutateAsync(file)).resolves.toBe(+ staticFileIdEndpoint('file-id')+ );+ expect(uploadFile).toHaveBeenCalledWith(file, 'static');+ }+ );++ it('rejects oversized images before starting an upload', async () => {+ const mutation = renderHook(() => useUploadAgentAvatarMutation());+ const file = new File(+ [new Uint8Array(16 * 1000 * 1000 + 1)],+ 'avatar.png',+ { type: 'image/png' }+ );+ await expect(mutation.mutateAsync(file)).rejects.toThrow('maximum 16 MB');+ expect(uploadFile).not.toHaveBeenCalled();+ });++ it('propagates upload errors without returning an avatar URL', async () => {+ vi.mocked(uploadFile).mockResolvedValue({+ failed: true,+ error: new Error('Failed to upload file'),+ name: 'avatar.png',+ });+ const mutation = renderHook(() => useUploadAgentAvatarMutation());+ await expect(+ mutation.mutateAsync(new File(['avatar'], 'avatar.png'))+ ).rejects.toThrow('Failed to upload file');+ });+});diff --git a/apps/web/src/lib/queries/agents/agents.ts b/apps/web/src/lib/queries/agents/agents.tsindex 7ac4b3a77b..f5fe25b6dd 100644--- a/apps/web/src/lib/queries/agents/agents.ts+++ b/apps/web/src/lib/queries/agents/agents.ts@@ -141,10 +141,6 @@ export function useUpdateAgentMutation() {})),onSuccess: async (updated) => {- const previousChannelIds =- queryClient- .getQueryData<Agent[]>(agentKeys.list.queryKey)- ?.find((agent) => agent.bot.id === updated.bot.id)?.channel_ids ?? [];queryClient.setQueryData<Agent[]>(agentKeys.list.queryKey,(current = []) =>@@ -157,14 +153,15 @@ export function useUpdateAgentMutation() {updated.bot);await Promise.all([- invalidateAgentChannelBots([- ...previousChannelIds,- ...updated.channel_ids,- ]),queryClient.invalidateQueries({ queryKey: botKeys.list.queryKey }),queryClient.invalidateQueries({queryKey: botProfileKeys.detail(updated.bot.id).queryKey,}),+ // Global agents have no selected channel IDs but can still appear in+ // a channel's bot list, which takes precedence in the mention menu.+ queryClient.invalidateQueries({+ queryKey: channelKeys.channelBots._def,+ }),]);},onError: (error) => console.error('failed to update agent', error),diff --git a/apps/web/src/lib/queries/agents/avatar.ts b/apps/web/src/lib/queries/agents/avatar.tsnew file mode 100644index 0000000000..cb657c5294--- /dev/null+++ b/apps/web/src/lib/queries/agents/avatar.ts@@ -0,0 +1,22 @@+import { staticFileIdEndpoint } from '@core/constant/servers';+import { uploadFile } from '@core/util/upload';+import { useMutation } from '@tanstack/solid-query';++const MAX_AVATAR_SIZE = 16 * 1000 * 1000;++/** Store image bytes separately so agent saves contain only a durable URL. */+export function useUploadAgentAvatarMutation() {+ return useMutation(() => ({+ gcTime: 0,+ mutationFn: async (file: File) => {+ if (file.size > MAX_AVATAR_SIZE) {+ throw new Error('Image size too large (maximum 16 MB)');+ }+ // The shared pipeline converts HEIC photos and holds automatic reloads+ // while the image is being uploaded.+ const result = await uploadFile(file, 'static');+ if (result.failed) throw result.error;+ return staticFileIdEndpoint(result.id);+ },+ }));+}diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 7f99c364d5..2d6982c123 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -1714,6 +1714,14 @@ but unconnected app gets a tool result saying so, and the agent's reply renders`Connect <app>` chip that opens Agents → Connections for that app. The same pageis also available as Settings → Connections.+To change an agent's picture, open `Edit <name>`, choose an image with `Upload`,+wait for `Uploading…` to finish, then click `Save changes`. Images up to 16 MB+are uploaded to image storage; Save stays disabled during the upload. A failed+upload shows an error and keeps the previous picture so you can retry. Verify+the picture after reopening settings and after a page reload, then type `@` and+the agent's name in a channel to check its mention-menu picture. Team agents+available in all channels should refresh there without reloading the channel.+With `pipedream-mcp` enabled, Connections (in Agents or Settings) has `Connected` and `Discover`tabs. Connected groups GitHub, Linear, Notion, and Slack tool grants by provider,lists other catalog connections alongside them, and puts custom MCP servers in