Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(ai): save generated images to static file service (#7335)

Eric Hayes67239a797265
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index ce8647fc96..8775709d84 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -6720,113 +6720,39 @@
"crates/workspace-hack"
],
"image_generation": [
- "crates/activity",
"crates/agent",
- "crates/agent_fold",
- "crates/agent_runtime_protocol",
- "crates/ai_billing",
"crates/ai_toolset",
"crates/ai_usage",
- "crates/analytics_client",
"crates/attachment",
- "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
- "crates/broadcast",
- "crates/calendar_events",
- "crates/channel_sender",
- "crates/channels",
- "crates/comms_db_client",
- "crates/connection",
- "crates/connection_gateway_client",
- "crates/connection_gateway_models",
- "crates/contacts",
"crates/cowlike",
- "crates/crm",
- "crates/database_env_vars",
"crates/document_sub_type",
- "crates/documents",
- "crates/email",
- "crates/email_utils",
- "crates/embedding",
- "crates/entity_access",
- "crates/entity_access_db_utils",
- "crates/entity_access_management",
- "crates/entity_mutation",
- "crates/entity_registry/entity_registry",
- "crates/entity_registry/entity_registry_db_utils",
- "crates/entity_registry/shared_entity_registry",
- "crates/filter_ast",
- "crates/foreign_entity",
- "crates/frecency",
"crates/genai_telemetry",
- "crates/generic_email_domains",
- "crates/google_token",
"crates/harness_id",
"crates/harness_token",
"crates/image_generation",
- "crates/initiative",
- "crates/invite_email",
- "crates/item_filters",
- "crates/kafka_util",
- "crates/last_online_tracker",
- "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
- "crates/macro_db_client",
- "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
- "crates/macro_event_broker",
- "crates/macro_event_topics",
- "crates/macro_service_urls",
- "crates/macro_sync_service_jwt",
- "crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
- "crates/mention_utils",
- "crates/messages",
"crates/model",
"crates/model-entity",
"crates/model-error-response",
"crates/model_file_type",
- "crates/model_notifications",
"crates/model_owner",
"crates/model_user",
- "crates/models_ai_projection",
"crates/models_bulk_upload",
- "crates/models_dcs",
- "crates/models_email",
- "crates/models_entity_access_management",
- "crates/models_opensearch",
"crates/models_pagination",
"crates/models_permissions",
- "crates/models_properties",
"crates/models_sfs",
- "crates/models_team",
"crates/non_empty",
- "crates/notification",
- "crates/notification_state",
"crates/prompt",
- "crates/properties",
- "crates/rate_limit",
"crates/remote_env_var",
- "crates/roles_and_permissions",
- "crates/s3_key",
- "crates/secretsmanager_client",
- "crates/share_permission_db_utils",
- "crates/sqs_client",
- "crates/sqs_worker",
"crates/static_file_service_client",
- "crates/sync_service",
- "crates/sync_service_client",
- "crates/system_properties",
- "crates/system_skills",
- "crates/task_dedup",
- "crates/teams",
- "crates/unfurl",
- "crates/user_quota",
"crates/workspace-hack"
],
"image_optimizer": [
diff --git a/Cargo.lock b/Cargo.lock
index c972723477..606bb7d630 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -936,6 +936,7 @@ dependencies = [
"sqlx",
"sqs_client",
"static_file",
+ "static_file_service_client",
"strum 0.27.2",
"sync_service_client",
"system_properties",
@@ -9438,19 +9439,17 @@ dependencies = [
"attachment",
"base64 0.22.1",
"bot_id",
- "documents",
- "entity_access",
"macro_user_id",
"model",
"model-entity",
"model_owner",
- "models_permissions",
"non_empty",
"reqwest 0.13.4",
"rootcause",
"schemars 1.2.1",
"serde",
"serde_json",
+ "static_file_service_client",
"thiserror 2.0.18",
"tokio",
"tracing",
diff --git a/apps/docs/AI/mcp/tools/generate-image.mdx b/apps/docs/AI/mcp/tools/generate-image.mdx
index 7b7d7df796..cfcfeaf338 100644
--- a/apps/docs/AI/mcp/tools/generate-image.mdx
+++ b/apps/docs/AI/mcp/tools/generate-image.mdx
@@ -1,18 +1,16 @@
---
title: GenerateImage
-description: "Generate or edit an image with Google's Nano Banana image model and save the result as a new image document in Macro. Use for pictures, illustrations, diagram concepts, logo ideas, mockups, or edits based on reference photos. When the user supplies photos or asks to modify an existing image, pass them in referenceImages; describing a photo in the prompt alone does not send it to the image model. Describe the subject, style, composition, lighting, and any text to render; only the prompt is required. Refer to reference images by their order (image 1, image 2, image 3) when explaining how to use them. Returns the new document ID to cite inline. Generation takes several seconds."
+description: "Generate or edit an image with Google's Nano Banana image model and save the result in static file service. Use for pictures, illustrations, diagram concepts, logo ideas, mockups, or edits based on reference photos. When the user supplies photos or asks to modify an existing image, pass them in referenceImages; describing a photo in the prompt alone does not send it to the image model. Describe the subject, style, composition, lighting, and any text to render; only the prompt is required. Refer to reference images by their order (image 1, image 2, image 3) when explaining how to use them. Returns the static file ID and image URL. The tool displays the image inline in chat. In channel messages without tool cards, embed the returned URL as a Markdown image. Do not cite it as a document. Generation takes several seconds."
---
# GenerateImage
-Generate or edit an image with Google's Nano Banana image model and save the result as a new image document in Macro. Use for pictures, illustrations, diagram concepts, logo ideas, mockups, or edits based on reference photos. When the user supplies photos or asks to modify an existing image, pass them in referenceImages; describing a photo in the prompt alone does not send it to the image model. Describe the subject, style, composition, lighting, and any text to render; only the prompt is required. Refer to reference images by their order (image 1, image 2, image 3) when explaining how to use them. Returns the new document ID to cite inline. Generation takes several seconds.
+Generate or edit an image with Google's Nano Banana image model and save the result in static file service. Use for pictures, illustrations, diagram concepts, logo ideas, mockups, or edits based on reference photos. When the user supplies photos or asks to modify an existing image, pass them in referenceImages; describing a photo in the prompt alone does not send it to the image model. Describe the subject, style, composition, lighting, and any text to render; only the prompt is required. Refer to reference images by their order (image 1, image 2, image 3) when explaining how to use them. Returns the static file ID and image URL. The tool displays the image inline in chat. In channel messages without tool cards, embed the returned URL as a Markdown image. Do not cite it as a document. Generation takes several seconds.
## Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `prompt` | string | Yes | Detailed description of the image to generate: subject, style (photo, illustration, flat vector...), composition, colours, mood, and any text that must appear. |
-| `fileName` | string | No | Optional short descriptive name for the saved image, for example `sunset-lighthouse`. The file extension is added from the generated format. No directory path. Omit to name the image after the prompt. |
| `aspectRatio` | `"square"` \| `"landscape"` \| `"portrait"` \| `"widescreen"` \| `"tall"` | No | Shape of the image. Omit for the model default (square). `widescreen` (16:9) suits banners and slides, `tall` (9:16) suits phone screens and stories. |
-| `projectId` | string | No | Optional destination project (folder) ID. Requires edit access. Omit to save to the user's top-level files. |
-| `referenceImages` | ImageReferenceInput[] | No | Up to three reference photos, in the order used by the prompt. Use type document with a Macro image document ID, or type staticFile with the UUID from /file/<id> in an uploaded attachment's source URL. Use the actual IDs supplied in the conversation or by tools; do not invent IDs. Omit for text-only generation. |
+| `referenceImages` | ImageReferenceInput[] | No | Up to three reference photos, in the order used by the prompt. Use type document with a Macro image document ID, or type staticFile with the UUID from /file/<id> in an uploaded attachment's source URL or the staticFileId of a previous generation. Use the actual IDs supplied in the conversation or by tools; do not invent IDs. Omit for text-only generation. |
diff --git a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
index 35d24b2fd5..6d5f0d3c5f 100644
--- a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
@@ -11,6 +11,7 @@ import {
hasToolRenderer,
RenderTool,
} from '@core/component/AI/component/tool/handler';
+import { parseLegacyGeneratedImage } from '@core/component/AI/component/tool/legacy-generated-image';
import ReadIcon from '@phosphor/file-text.svg';
import GlobeIcon from '@phosphor/globe.svg';
import ListIcon from '@phosphor/list-bullets.svg';
@@ -45,6 +46,9 @@ export function MacroToolCall(props: {
json: props.detail.output,
}).unwrapOr(undefined)
);
+ const legacyImage = createMemo(() =>
+ parseLegacyGeneratedImage(props.common.label, props.detail.output)
+ );
const call = createMemo(() =>
deserializeToolCall({
id: props.common.id,
@@ -106,7 +110,7 @@ export function MacroToolCall(props: {
props.common.trailing == null &&
!failure() &&
call() !== undefined &&
- response() !== undefined &&
+ (response() !== undefined || legacyImage() !== undefined) &&
hasToolRenderer(props.common.label);
return (
diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx
index 43858ccc9d..4dd2bfa1c1 100644
--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx
@@ -1226,16 +1226,29 @@ describe('ToolCallPart result summaries', () => {
});
describe('generated image dispatch', () => {
- it.each(['native', 'mcp'] as const)(
- 'uses the image result renderer for %s calls outside group chrome',
- (kind) => {
+ it.each([
+ ['native', 'staticFile'],
+ ['mcp', 'staticFile'],
+ ['native', 'document'],
+ ['mcp', 'document'],
+ ] as const)(
+ 'uses the image result renderer for %s calls with %s images outside group chrome',
+ (kind, storage) => {
const input = { prompt: 'A frog under a leaf' };
- const output = {
- documentId: '01a0eecf-1162-7bea-9ba9-925769372a8a',
- fileName: 'frog.png',
- mimeType: 'image/png',
- sizeBytes: 132421,
- };
+ const output =
+ storage === 'document'
+ ? {
+ documentId: '01a0eecf-1162-7bea-9ba9-925769372a8a',
+ fileName: 'frog.png',
+ mimeType: 'image/png',
+ sizeBytes: 132421,
+ }
+ : {
+ staticFileId: '01a0eecf-1162-7bea-9ba9-925769372a8a',
+ url: 'https://static.example/file/01a0eecf-1162-7bea-9ba9-925769372a8a',
+ mimeType: 'image/png',
+ sizeBytes: 132421,
+ };
const part: ToolUsePart = {
kind: 'tool_use',
id: 'image-call',
diff --git a/apps/web/src/lib/core/component/AI/component/tool/GenerateImage.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/GenerateImage.test.tsx
index 709643abdb..8c0897adf4 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/GenerateImage.test.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/GenerateImage.test.tsx
@@ -1,49 +1,12 @@
import { cleanup, fireEvent, render } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it } from 'vitest';
import { generateImageHandler } from './GenerateImage';
import { ToolErrorContext } from './ToolRenderer';
-const preview = vi.hoisted(() => ({
- isSuccess: true,
- isError: false,
- url: 'https://storage.example/frog.png',
- dataReads: 0,
-}));
-
-vi.mock('@queries/storage/binary-document', () => ({
- useBinaryDocumentQuery: () => ({
- get isSuccess() {
- return preview.isSuccess;
- },
- get isError() {
- return preview.isError;
- },
- get data() {
- preview.dataReads += 1;
- if (!preview.isSuccess) throw new Error('Pending data read');
- return preview.url;
- },
- }),
-}));
-
-const splits = vi.hoisted(() => ({
- activate: vi.fn(),
- insertSplit: vi.fn(),
- replaceOrInsertSplit: vi.fn(),
-}));
-
-vi.mock('@components/app/split-layout/layout', () => ({
- useSplitLayout: () => splits,
-}));
-
-vi.mock('@core/mobile/isTouchDevice', () => ({
- isTouchDevice: () => false,
-}));
-
const result = {
- documentId: 'image-id',
- fileName: 'frog.png',
+ staticFileId: 'image-id',
+ url: 'https://static.example/file/image-id',
mimeType: 'image/png',
sizeBytes: 132421,
note: 'A frog under a leaf.',
@@ -60,7 +23,7 @@ function imageTool(
tool={{
id: 'call-1',
name: 'GenerateImage',
- data: { prompt: 'A frog under a leaf', fileName: 'frog' },
+ data: { prompt: 'A frog under a leaf' },
}}
response={
response
@@ -78,55 +41,16 @@ function imageTool(
}
afterEach(cleanup);
-beforeEach(() => {
- preview.isSuccess = true;
- preview.isError = false;
- preview.dataReads = 0;
- splits.activate.mockClear();
- splits.insertSplit.mockReset().mockReturnValue({ activate: splits.activate });
- splits.replaceOrInsertSplit
- .mockReset()
- .mockReturnValue({ activate: splits.activate });
-});
-
describe('generated image result', () => {
- it('shows the filename and image as one card that opens and activates a new app split', () => {
+ it('renders the SFS URL directly without a document card or filename', () => {
const view = imageTool();
- const card = view.getByRole('button', {
- name: 'Open frog.png in a new split',
- });
- expect(card.getAttribute('type')).toBe('button');
- expect(card.textContent).toBe('frog.png');
- fireEvent.click(card);
- expect(splits.insertSplit).toHaveBeenCalledExactlyOnceWith({
- type: 'image',
- id: 'image-id',
- });
- expect(splits.activate).toHaveBeenCalledOnce();
- expect(splits.replaceOrInsertSplit).not.toHaveBeenCalled();
expect(
- view.getByRole('img', { name: 'frog.png' }).getAttribute('src')
- ).toBe(preview.url);
- expect(view.getByText(result.note)).toBeTruthy();
- expect(view.queryByText('Generate image')).toBeNull();
+ view.getByRole('img', { name: 'Generated image' }).getAttribute('src')
+ ).toBe(result.url);
+ expect(view.queryByRole('button')).toBeNull();
expect(view.queryByRole('link')).toBeNull();
- });
-
- it('keeps the file card while the upload is pending without reading query data', () => {
- preview.isSuccess = false;
- const view = imageTool();
- expect(view.getByText('Preparing preview')).toBeTruthy();
- expect(view.getByRole('button')).toBeTruthy();
- expect(preview.dataReads).toBe(0);
- });
-
- it('keeps the file card when the preview query fails', () => {
- preview.isSuccess = false;
- preview.isError = true;
- const view = imageTool();
- expect(view.getByText('Preview unavailable')).toBeTruthy();
- expect(view.getByRole('button')).toBeTruthy();
- expect(preview.dataReads).toBe(0);
+ expect(view.queryByText(result.note)).toBeNull();
+ expect(view.container.textContent).toBe('');
});
it('replaces a failed image load with an inline status', () => {
@@ -134,12 +58,11 @@ describe('generated image result', () => {
fireEvent.error(view.getByRole('img'));
expect(view.getByText('Preview unavailable')).toBeTruthy();
expect(view.queryByRole('img')).toBeNull();
- expect(view.getByRole('button')).toBeTruthy();
+ expect(view.queryByRole('button')).toBeNull();
});
- it('shows the requested filename while generation is pending', () => {
+ it('shows a status while generation is pending', () => {
const view = imageTool(false);
- expect(view.getByText('frog')).toBeTruthy();
expect(view.getByText('Generating image')).toBeTruthy();
expect(view.queryByRole('button')).toBeNull();
});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/GenerateImage.tsx b/apps/web/src/lib/core/component/AI/component/tool/GenerateImage.tsx
index 6419dd0911..d8dfb0c31b 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/GenerateImage.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/GenerateImage.tsx
@@ -1,11 +1,28 @@
-import {
- ImageDocumentCard,
- ImageDocumentCardHeader,
- ImageDocumentPreviewStatus,
-} from '@core/component/ImageDocumentCard';
-import { Show } from 'solid-js';
+import LoadingSpinner from '@phosphor/spinner.svg';
+import { createSignal, Show } from 'solid-js';
import { createToolRenderer, useToolError } from './ToolRenderer';
+function GeneratedImage(props: { url: string }) {
+ const [failedUrl, setFailedUrl] = createSignal<string>();
+ return (
+ <Show
+ when={failedUrl() !== props.url}
+ fallback={
+ <div role="status" class="text-sm text-ink-muted">
+ Preview unavailable
+ </div>
+ }
+ >
+ <img
+ src={props.url}
+ alt="Generated image"
+ class="my-2 block h-auto max-h-96 w-auto max-w-full rounded-xl"
+ onError={() => setFailedUrl(props.url)}
+ />
+ </Show>
+ );
+}
+
export const generateImageHandler = createToolRenderer({
name: 'GenerateImage',
render: (ctx) => {
@@ -14,38 +31,18 @@ export const generateImageHandler = createToolRenderer({
<Show
when={ctx.response?.data}
fallback={
- <div class="w-full max-w-md overflow-hidden rounded-xl border border-edge-muted">
- <ImageDocumentCardHeader
- fileName={ctx.tool.data.fileName ?? 'Generated image'}
- />
- <Show
- when={!error()}
- fallback={
- <div class="px-3 py-4 text-sm text-ink-muted">
- Image generation failed
- </div>
- }
- >
- <ImageDocumentPreviewStatus label="Generating image" />
+ <div
+ class="flex items-center gap-2 py-4 text-sm text-ink-muted"
+ role="status"
+ >
+ <Show when={!error()} fallback="Image generation failed">
+ <LoadingSpinner class="size-4 animate-spin" />
+ <span>Generating image</span>
</Show>
</div>
}
>
- {(result) => (
- <div class="my-2 max-w-md space-y-2">
- <ImageDocumentCard
- documentId={result().documentId}
- fileName={result().fileName}
- />
- <Show when={result().note}>
- {(note) => (
- <div class="whitespace-pre-wrap text-sm text-ink-muted">
- {note()}
- </div>
- )}
- </Show>
- </div>
- )}
+ {(result) => <GeneratedImage url={result().url} />}
</Show>
);
},
diff --git a/apps/web/src/lib/core/component/AI/component/tool/LegacyGeneratedImage.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/LegacyGeneratedImage.test.tsx
new file mode 100644
index 0000000000..8fcf7b5ed0
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/LegacyGeneratedImage.test.tsx
@@ -0,0 +1,77 @@
+import { cleanup, render } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { LegacyGeneratedImage } from './LegacyGeneratedImage';
+
+vi.mock('@core/component/ImageDocumentCard', () => ({
+ ImageDocumentCard: (props: { documentId: string; fileName: string }) => (
+ <div data-testid="document-image" data-document-id={props.documentId}>
+ {props.fileName}
+ </div>
+ ),
+}));
+
+afterEach(cleanup);
+
+const historicalResult = {
+ documentId: 'old-image-id',
+ fileName: 'lighthouse.png',
+ mimeType: 'image/png',
+ sizeBytes: 100,
+ note: 'A calm scene.',
+};
+
+describe('historical generated images', () => {
+ it('renders the saved document and note without mounting the new result renderer', () => {
+ const fallback = vi.fn(() => <div>Current renderer</div>);
+ const view = render(() => (
+ <LegacyGeneratedImage name="GenerateImage" response={historicalResult}>
+ {fallback()}
+ </LegacyGeneratedImage>
+ ));
+ expect(view.getByTestId('document-image').dataset.documentId).toBe(
+ 'old-image-id'
+ );
+ expect(view.getByText('lighthouse.png')).toBeTruthy();
+ expect(view.getByText('A calm scene.')).toBeTruthy();
+ expect(fallback).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [
+ 'GenerateImage',
+ {
+ staticFileId: 'new-image-id',
+ url: 'https://static.example/file/new-image-id',
+ },
+ ],
+ ['GenerateImage', undefined],
+ ['GenerateImage', { documentId: 'id' }],
+ ['GenerateImage', { documentId: '', fileName: 'invalid' }],
+ ['CreateDocument', historicalResult],
+ ])(
+ 'leaves %s responses that are not historical images to the current renderer',
+ (name, response) => {
+ const view = render(() => (
+ <LegacyGeneratedImage name={name} response={response}>
+ <div>Current renderer</div>
+ </LegacyGeneratedImage>
+ ));
+ expect(view.getByText('Current renderer')).toBeTruthy();
+ expect(view.queryByTestId('document-image')).toBeNull();
+ }
+ );
+
+ it('recognizes a historical result when it arrives after the call', () => {
+ const [response, setResponse] = createSignal<unknown>();
+ const view = render(() => (
+ <LegacyGeneratedImage name="GenerateImage" response={response()}>
+ <div>Current renderer</div>
+ </LegacyGeneratedImage>
+ ));
+ expect(view.getByText('Current renderer')).toBeTruthy();
+ setResponse(historicalResult);
+ expect(view.getByTestId('document-image')).toBeTruthy();
+ expect(view.queryByText('Current renderer')).toBeNull();
+ });
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/LegacyGeneratedImage.tsx b/apps/web/src/lib/core/component/AI/component/tool/LegacyGeneratedImage.tsx
new file mode 100644
index 0000000000..5053bf4135
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/LegacyGeneratedImage.tsx
@@ -0,0 +1,34 @@
+import { ImageDocumentCard } from '@core/component/ImageDocumentCard';
+import { createMemo, type JSX, Show } from 'solid-js';
+import { parseLegacyGeneratedImage } from './legacy-generated-image';
+
+/** Persisted results from before GenerateImage switched to static file service. */
+export function LegacyGeneratedImage(props: {
+ name: string;
+ response: unknown;
+ children: JSX.Element;
+}) {
+ const image = createMemo(() =>
+ parseLegacyGeneratedImage(props.name, props.response)
+ );
+
+ return (
+ <Show when={image()} fallback={props.children}>
+ {(result) => (
+ <div class="my-2 max-w-md space-y-2">
+ <ImageDocumentCard
+ documentId={result().documentId}
+ fileName={result().fileName}
+ />
+ <Show when={result().note}>
+ {(note) => (
+ <div class="whitespace-pre-wrap text-sm text-ink-muted">
+ {note()}
+ </div>
+ )}
+ </Show>
+ </div>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index 31de997917..bad43b45d7 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -52,6 +52,7 @@ import {
listImportEntitiesHandler,
} from './ImportTools';
import { initiativeToolHandlers } from './Initiatives';
+import { LegacyGeneratedImage } from './LegacyGeneratedImage';
import { listEntitiesHandler } from './ListEntities';
import { listInboxesHandler } from './ListInboxes';
import { listLabelsHandler } from './ListLabels';
@@ -294,19 +295,26 @@ export function RenderTool(props: ToolProps) {
});
return (
- <ToolErrorContext.Provider
- value={() => (props.isComplete && !response() ? 'failed' : undefined)}
+ <LegacyGeneratedImage
+ name={props.name}
+ response={
+ props.response?.name === props.name ? props.response.json : undefined
+ }
>
- <Dynamic
- component={handler.render}
- {...context}
- response={response()}
- renderContext={{
- isStreaming: props.renderContext.renderContext.isStreaming,
- grouped: props.renderContext.renderContext.grouped,
- }}
- />
- </ToolErrorContext.Provider>
+ <ToolErrorContext.Provider
+ value={() => (props.isComplete && !response() ? 'failed' : undefined)}
+ >
+ <Dynamic
+ component={handler.render}
+ {...context}
+ response={response()}
+ renderContext={{
+ isStreaming: props.renderContext.renderContext.isStreaming,
+ grouped: props.renderContext.renderContext.grouped,
+ }}
+ />
+ </ToolErrorContext.Provider>
+ </LegacyGeneratedImage>
);
}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/legacy-generated-image.ts b/apps/web/src/lib/core/component/AI/component/tool/legacy-generated-image.ts
new file mode 100644
index 0000000000..3b6b84b500
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/legacy-generated-image.ts
@@ -0,0 +1,14 @@
+import { z } from 'zod/v3';
+
+const legacyImageResponse = z.object({
+ documentId: z.string().min(1),
+ fileName: z.string().min(1),
+ note: z.string().nullish(),
+});
+
+/** Validate historical image results before selecting their document renderer. */
+export function parseLegacyGeneratedImage(name: string, response: unknown) {
+ if (name !== 'GenerateImage') return;
+ const parsed = legacyImageResponse.safeParse(response);
+ return parsed.success ? parsed.data : undefined;
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index f5451c87d2..9658e32c23 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -2725,14 +2725,12 @@ export const EditTagResponse = z.object({
export const GenerateImage = z.object({
prompt: z.string(),
- fileName: z.union([z.string(), z.null()]).optional(),
aspectRatio: z
.union([
z.enum(['square', 'landscape', 'portrait', 'widescreen', 'tall']),
z.null(),
])
.optional(),
- projectId: z.union([z.string().uuid(), z.null()]).optional(),
referenceImages: z
.union([
z
@@ -2770,8 +2768,8 @@ export const GenerateImage = z.object({
});
export const GenerateImageResponse = z.object({
- documentId: z.string(),
- fileName: z.string(),
+ staticFileId: z.string(),
+ url: z.string(),
mimeType: z.string(),
sizeBytes: z.number().int().gte(0),
note: z.union([z.string(), z.null()]).optional(),
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index c8d40f4a89..088bb01af8 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -3665,27 +3665,19 @@ export interface EditTagResponse {
summary: string;
}
/**
- * Generate or edit an image with Google's Nano Banana image model and save the result as a new image document in Macro. Use for pictures, illustrations, diagram concepts, logo ideas, mockups, or edits based on reference photos. When the user supplies photos or asks to modify an existing image, pass them in referenceImages; describing a photo in the prompt alone does not send it to the image model. Describe the subject, style, composition, lighting, and any text to render; only the prompt is required. Refer to reference images by their order (image 1, image 2, image 3) when explaining how to use them. Returns the new document ID to cite inline. Generation takes several seconds.
+ * Generate or edit an image with Google's Nano Banana image model and save the result in static file service. Use for pictures, illustrations, diagram concepts, logo ideas, mockups, or edits based on reference photos. When the user supplies photos or asks to modify an existing image, pass them in referenceImages; describing a photo in the prompt alone does not send it to the image model. Describe the subject, style, composition, lighting, and any text to render; only the prompt is required. Refer to reference images by their order (image 1, image 2, image 3) when explaining how to use them. Returns the static file ID and image URL. The tool displays the image inline in chat. In channel messages without tool cards, embed the returned URL as a Markdown image. Do not cite it as a document. Generation takes several seconds.
*/
export interface GenerateImage {
/**
* Detailed description of the image to generate: subject, style (photo, illustration, flat vector...), composition, colours, mood, and any text that must appear.
*/
prompt: string;
- /**
- * Optional short descriptive name for the saved image, for example `sunset-lighthouse`. The file extension is added from the generated format. No directory path. Omit to name the image after the prompt.
- */
- fileName?: string | null;
/**
* Shape of the image. Omit for the model default (square). `widescreen` (16:9) suits banners and slides, `tall` (9:16) suits phone screens and stories.
*/
aspectRatio?: AspectRatio | null;
/**
- * Optional destination project (folder) ID. Requires edit access. Omit to save to the user's top-level files.
- */
- projectId?: string | null;
- /**
- * Up to three reference photos, in the order used by the prompt. Use type document with a Macro image document ID, or type staticFile with the UUID from /file/<id> in an uploaded attachment's source URL. Use the actual IDs supplied in the conversation or by tools; do not invent IDs. Omit for text-only generation.
+ * Up to three reference photos, in the order used by the prompt. Use type document with a Macro image document ID, or type staticFile with the UUID from /file/<id> in an uploaded attachment's source URL or the staticFileId of a previous generation. Use the actual IDs supplied in the conversation or by tools; do not invent IDs. Omit for text-only generation.
*
* @maxItems 3
*/
@@ -3701,13 +3693,13 @@ export interface GenerateImage {
*/
export interface GenerateImageResponse {
/**
- * ID of the new image document.
+ * ID of the static file, reusable in referenceImages.
*/
- documentId: string;
+ staticFileId: string;
/**
- * Saved filename, including its extension.
+ * Permanent URL of the generated image.
*/
- fileName: string;
+ url: string;
/**
* IANA media type of the image, e.g. `image/png`.
*/
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index 196b02b6b1..1ecfabd9bd 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -95,6 +95,7 @@ sqs_client = { path = "../sqs_client", default-features = false, features = ["em
teams = { path = "../teams", default-features = false, features = ["ai_tools", "outbound"] }
sqlx.workspace = true
strum.workspace = true
+static_file_service_client = { path = "../static_file_service_client" }
sync_service_client = { path = "../sync_service_client" }
system_properties = { path = "../system_properties" }
thiserror.workspace = true
diff --git a/crates/ai_tools/src/tool_context/images.rs b/crates/ai_tools/src/tool_context/images.rs
index 2142e0c21a..a37ffe9c62 100644
--- a/crates/ai_tools/src/tool_context/images.rs
+++ b/crates/ai_tools/src/tool_context/images.rs
@@ -1,4 +1,4 @@
-//! Composition of image generation with document uploads and reference-image reads.
+//! Composition of image generation with static file uploads and reference-image reads.
use super::{ToolDocumentService, ToolDocumentToolContext, ToolEntityAccessService};
use std::sync::Arc;
@@ -7,6 +7,11 @@ macro_env_var::env_var! {
pub struct StaticStorageBucket;
}
+macro_env_var::env_var! {
+ /// Internal service authentication for static file uploads.
+ struct InternalApiKey;
+}
+
/// Reference photos resolved by their owning domains.
pub type ToolImageReferenceReader =
image_generation::outbound::references::AttachmentImageReferenceReader<
@@ -19,22 +24,17 @@ pub type ToolImageReferenceReader =
>,
>;
-/// Image generation service composed with the document upload capability.
+/// Image generation service composed with the static file upload capability.
pub type ToolImageGenerationService = image_generation::domain::service::ImageGenerationServiceImpl<
- image_generation::outbound::documents::DocumentsImageStore<
- documents::inbound::toolset::DefaultDocumentToolCreator<ToolDocumentService>,
- >,
+ image_generation::outbound::static_files::StaticFileImageStore,
ToolImageReferenceReader,
>;
/// Image-generation context shared by all AI hosts.
pub type ToolImageGenerationToolContext =
- image_generation::inbound::toolset::ImageGenerationToolContext<
- ToolImageGenerationService,
- ToolEntityAccessService,
- >;
+ image_generation::inbound::toolset::ImageGenerationToolContext<ToolImageGenerationService>;
-/// Compose image generation with an already-wired document upload service.
+/// Compose static file uploads and document reference reads for image generation.
pub fn build_image_generation_tool_context(
documents: &ToolDocumentToolContext,
generator: Arc<dyn image_generation::domain::ports::ImageGenerator>,
@@ -50,13 +50,18 @@ pub fn build_image_generation_tool_context(
} else {
macro_service_urls::StaticFileServiceUrl::new()?.to_string()
};
- Ok(build_with_cdn(documents, generator, cdn_base))
+ let storage = static_file_service_client::StaticFileServiceClient::new(
+ InternalApiKey::new()?.to_string(),
+ macro_service_urls::StaticFileServiceUrl::new()?.to_string(),
+ );
+ Ok(build_with_cdn(documents, generator, cdn_base, storage))
}
fn build_with_cdn(
documents: &ToolDocumentToolContext,
generator: Arc<dyn image_generation::domain::ports::ImageGenerator>,
cdn_base: String,
+ storage: static_file_service_client::StaticFileServiceClient,
) -> ToolImageGenerationToolContext {
let references = image_generation::outbound::references::AttachmentImageReferenceReader::new(
documents::inbound::attachment::DocumentAttachmentService::new(
@@ -71,12 +76,9 @@ fn build_with_cdn(
image_generation::inbound::toolset::ImageGenerationToolContext::new(
image_generation::domain::service::ImageGenerationServiceImpl::new(
generator,
- image_generation::outbound::documents::DocumentsImageStore::new(
- documents.creator.clone(),
- ),
+ image_generation::outbound::static_files::StaticFileImageStore::new(storage),
)
.with_reference_reader(references),
- documents.entity_access_service.clone(),
documents.actor,
)
}
@@ -90,5 +92,9 @@ pub fn build_image_generation_tool_context_test(
documents,
Arc::new(image_generation::domain::ports::UnconfiguredImageGenerator),
"https://static.example.test".to_string(),
+ static_file_service_client::StaticFileServiceClient::new(
+ "test-key".to_string(),
+ "https://static.example.test".to_string(),
+ ),
)
}
diff --git a/crates/image_generation/Cargo.toml b/crates/image_generation/Cargo.toml
index 5bba06f950..b5a8d5c747 100644
--- a/crates/image_generation/Cargo.toml
+++ b/crates/image_generation/Cargo.toml
@@ -11,8 +11,6 @@ async-trait.workspace = true
attachment = { path = "../attachment" }
base64.workspace = true
bot_id = { path = "../bot_id" }
-documents = { path = "../documents", default-features = false, features = ["document_create"] }
-entity_access = { path = "../entity_access" }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
model_owner = { path = "../model_owner" }
@@ -22,13 +20,13 @@ rootcause.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
+static_file_service_client = { path = "../static_file_service_client" }
thiserror.workspace = true
tracing.workspace = true
uuid.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
-models_permissions = { path = "../models_permissions" }
macro_user_id = { path = "../macro_user_id" }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
wiremock.workspace = true
diff --git a/crates/image_generation/README.md b/crates/image_generation/README.md
index 38ea312669..fca74a92e6 100644
--- a/crates/image_generation/README.md
+++ b/crates/image_generation/README.md
@@ -1,24 +1,22 @@
# Image generation
`image_generation_toolset()` exposes `GenerateImage` to the shared AI toolset.
-The tool mints an edit receipt for an optional destination project and invokes
-`ImageGenerationService` with the requesting user and delegated bot identity.
+The tool invokes `ImageGenerationService` with the requesting user and delegated
+bot identity.
The domain service validates the prompt, resolves up to three ordered reference
images through `ImageReferenceReader`, asks `ImageGenerator` for image bytes,
-chooses the filename, and saves through `ImageDocumentStore`. Gemini implements
-the provider port and receives references as inline image bytes.
-`DocumentsImageStore` implements the save port by calling the `documents`
-domain's `DocumentUploadService` inbound port.
+and saves through `ImageStore`. Gemini implements the provider port and receives
+references as inline image bytes. `StaticFileImageStore` uploads through the
+existing static file service client and returns the static file ID and permanent
+URL only after the byte upload succeeds. The tool creates no DSS document and
+accepts no filename or destination project.
`AttachmentImageReferenceReader` uses the document and static-file domains'
existing inbound `AttachmentService` implementations. Document references require
view access for the acting user. Static-file IDs retain their existing bearer
capability semantics and resolve only through configured storage; arbitrary URLs
-are not accepted. Cross-domain adapters depend only on inbound ports.
+are not accepted. Generated static file IDs can be reused for subsequent edits.
-Document creation, destination authorization, filename and size validation,
-byte uploads, and failure cleanup remain in the existing document upload
-lifecycle. The storage adapter uses no document repositories or outbound
-adapters. Hosts compose the provider, reference reader, and storage services in
-`ai_tools`.
+Hosts compose the provider, reference reader, and storage client in `ai_tools`.
+The frontend renders the returned SFS image directly.
diff --git a/crates/image_generation/src/domain/models.rs b/crates/image_generation/src/domain/models.rs
index f2174b40d3..3b916d2e05 100644
--- a/crates/image_generation/src/domain/models.rs
+++ b/crates/image_generation/src/domain/models.rs
@@ -1,6 +1,5 @@
//! Image requests, generated bytes, and provider errors.
-use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt};
use model::document::FileType;
/// The shape of image the model is asked for, as the model vocabulary calls
@@ -139,30 +138,21 @@ pub const MAX_REFERENCE_IMAGES: usize = 3;
/// Total encoded image bytes before Base64 expansion, below the provider's 20 MB request limit.
pub const MAX_REFERENCE_BYTES: usize = 12 * 1024 * 1024;
-/// An image to generate and store as a document.
+/// An image to generate and store as a static file.
pub struct NewGeneratedImage {
/// Natural-language description of the image.
pub prompt: String,
/// Requested shape; the provider default when `None`.
pub aspect_ratio: Option<ImageAspectRatio>,
- /// Document name; the extension is added from the generated format. A
- /// name that already carries an image extension keeps it. `None` names
- /// the document after the opening words of the prompt.
- pub file_name: Option<String>,
- /// Edit capability for the destination project, minted for the creating
- /// principal; absent for top-level files.
- pub project: Option<EntityAccessReceipt<EditAccessLevel>>,
/// Reference images, resolved under the creating principal before generation.
pub reference_images: Vec<ImageReference>,
}
-/// A generated image stored as a document.
+/// A generated image stored in static file service.
#[derive(Debug)]
-pub struct GeneratedImageDocument {
- /// The created document.
- pub document_id: uuid::Uuid,
- /// Final filename, including its extension.
- pub file_name: String,
+pub struct StoredGeneratedImage {
+ /// The stored static file.
+ pub static_file: StoredImage,
/// IANA media type of the stored bytes.
pub mime_type: String,
/// Number of stored bytes.
@@ -171,7 +161,7 @@ pub struct GeneratedImageDocument {
pub note: Option<String>,
}
-/// Why a generated image document was not created.
+/// Why a generated image was not created.
#[derive(Debug, thiserror::Error)]
pub enum GenerateImageError {
/// The prompt is invalid.
@@ -185,35 +175,30 @@ pub enum GenerateImageError {
Generation(#[from] ImageGenerationError),
/// The image was generated but not stored.
#[error(transparent)]
- Document(#[from] SaveImageError),
+ Storage(#[from] SaveImageError),
}
-/// Generated bytes and metadata to persist as a Macro document.
-pub struct NewImageDocument {
- /// Filename including the image extension.
- pub file_name: String,
+/// Generated bytes and media type to persist in static file service.
+pub struct NewStaticImage {
/// Encoded image bytes.
pub bytes: Vec<u8>,
- /// Verified edit capability for the destination project.
- pub project: Option<EntityAccessReceipt<EditAccessLevel>>,
+ /// IANA media type of the encoded bytes.
+ pub mime_type: String,
+}
+
+/// A successfully uploaded static image.
+#[derive(Debug)]
+pub struct StoredImage {
+ /// Static file ID, reusable as a reference image.
+ pub id: uuid::Uuid,
+ /// Permanent URL of the uploaded image.
+ pub url: String,
}
-/// Failure returned by the document-saving capability.
+/// Failure returned by the image-saving capability.
#[derive(Debug, thiserror::Error)]
pub enum SaveImageError {
- /// Invalid filename or file bytes.
- #[error("{0}")]
- BadRequest(String),
- /// The document name exceeds its allowed length.
- #[error("fileName is too long (maximum {max} characters)")]
- NameTooLong {
- /// Maximum permitted name length.
- max: usize,
- },
- /// The supplied destination capability does not authorize this principal.
- #[error("unauthorized destination project")]
- Unauthorized,
- /// Document persistence failed.
+ /// Static file persistence failed.
#[error("could not save the generated image: {0}")]
Internal(rootcause::Report),
}
diff --git a/crates/image_generation/src/domain/ports.rs b/crates/image_generation/src/domain/ports.rs
index fb0cceb628..f291f80467 100644
--- a/crates/image_generation/src/domain/ports.rs
+++ b/crates/image_generation/src/domain/ports.rs
@@ -1,12 +1,11 @@
//! Inbound image-generation service and outbound provider/storage capabilities.
use super::models::{
- GenerateImageError, GeneratedImage, GeneratedImageDocument, ImageGenerationError,
- ImageGenerationRequest, ImageReference, NewGeneratedImage, NewImageDocument, ReadImageError,
- ReferenceImage, SaveImageError,
+ GenerateImageError, GeneratedImage, ImageGenerationError, ImageGenerationRequest,
+ ImageReference, NewGeneratedImage, NewStaticImage, ReadImageError, ReferenceImage,
+ SaveImageError, StoredGeneratedImage, StoredImage,
};
use model_owner::CreationPrincipal;
use std::future::Future;
-use uuid::Uuid;
/// Renders an image from a text prompt and optional reference photos.
#[async_trait::async_trait]
@@ -57,22 +56,21 @@ impl ImageReferenceReader for UnconfiguredImageReferenceReader {
}
}
-/// Saves generated image bytes through the owning document domain.
-pub trait ImageDocumentStore: Send + Sync {
- /// Store a document using the caller's identity and verified destination.
+/// Saves generated image bytes to static file service.
+pub trait ImageStore: Send + Sync {
+ /// Upload image bytes and return their permanent location.
fn save_image(
&self,
- principal: &CreationPrincipal,
- image: NewImageDocument,
- ) -> impl Future<Output = Result<Uuid, SaveImageError>> + Send;
+ image: NewStaticImage,
+ ) -> impl Future<Output = Result<StoredImage, SaveImageError>> + Send;
}
-/// Inbound port for generating an image and saving it as a Macro document.
+/// Inbound port for generating an image and saving it as a static file.
pub trait ImageGenerationService: Send + Sync {
/// Generate and persist an image for the creating principal.
fn create_generated_image(
&self,
principal: &CreationPrincipal,
image: NewGeneratedImage,
- ) -> impl Future<Output = Result<GeneratedImageDocument, GenerateImageError>> + Send;
+ ) -> impl Future<Output = Result<StoredGeneratedImage, GenerateImageError>> + Send;
}
diff --git a/crates/image_generation/src/domain/service.rs b/crates/image_generation/src/domain/service.rs
index 22550f2f43..f027e1c775 100644
--- a/crates/image_generation/src/domain/service.rs
+++ b/crates/image_generation/src/domain/service.rs
@@ -1,21 +1,20 @@
-//! Prompt validation, naming, and generation-to-document orchestration.
+//! Prompt validation and generation-to-static-file orchestration.
use super::models::{
- GenerateImageError, GeneratedImageDocument, ImageGenerationError, ImageGenerationRequest,
- MAX_PROMPT_BYTES, MAX_REFERENCE_BYTES, MAX_REFERENCE_IMAGES, NewGeneratedImage,
- NewImageDocument,
+ GenerateImageError, ImageGenerationError, ImageGenerationRequest, MAX_PROMPT_BYTES,
+ MAX_REFERENCE_BYTES, MAX_REFERENCE_IMAGES, NewGeneratedImage, NewStaticImage,
+ StoredGeneratedImage,
};
use super::ports::{
- ImageDocumentStore, ImageGenerationService, ImageGenerator, ImageReferenceReader,
+ ImageGenerationService, ImageGenerator, ImageReferenceReader, ImageStore,
UnconfiguredImageReferenceReader,
};
-use model::document::{FileType, FileTypeExt};
use model_owner::CreationPrincipal;
use std::sync::Arc;
#[cfg(test)]
mod test;
-/// Image generation use case composed from a model provider and document store.
+/// Image generation use case composed from a model provider and static file store.
pub struct ImageGenerationServiceImpl<Store, References = UnconfiguredImageReferenceReader> {
generator: Arc<dyn ImageGenerator>,
store: Store,
@@ -23,7 +22,7 @@ pub struct ImageGenerationServiceImpl<Store, References = UnconfiguredImageRefer
}
impl<Store> ImageGenerationServiceImpl<Store> {
- /// Compose the provider and document-saving capability.
+ /// Compose the provider and image-saving capability.
pub fn new(generator: Arc<dyn ImageGenerator>, store: Store) -> Self {
Self {
generator,
@@ -44,21 +43,19 @@ impl<Store, References> ImageGenerationServiceImpl<Store, References> {
}
}
-impl<Store: ImageDocumentStore, References: ImageReferenceReader> ImageGenerationService
+impl<Store: ImageStore, References: ImageReferenceReader> ImageGenerationService
for ImageGenerationServiceImpl<Store, References>
{
- /// Generate an image and store it through the document-saving port.
+ /// Generate an image and store it through the image-saving port.
#[tracing::instrument(skip_all, err)]
async fn create_generated_image(
&self,
principal: &CreationPrincipal,
image: NewGeneratedImage,
- ) -> Result<GeneratedImageDocument, GenerateImageError> {
+ ) -> Result<StoredGeneratedImage, GenerateImageError> {
let NewGeneratedImage {
prompt,
aspect_ratio,
- file_name,
- project,
reference_images,
} = image;
let prompt = prompt.trim();
@@ -77,11 +74,6 @@ impl<Store: ImageDocumentStore, References: ImageReferenceReader> ImageGeneratio
"referenceImages accepts at most {MAX_REFERENCE_IMAGES} images"
)));
}
- let file_name = match file_name.as_deref().map(str::trim) {
- Some(name) if !name.is_empty() => name.to_string(),
- _ => file_name_from_prompt(prompt),
- };
-
let mut references = Vec::with_capacity(reference_images.len());
let mut reference_bytes = 0;
for reference in &reference_images {
@@ -114,66 +106,33 @@ impl<Store: ImageDocumentStore, References: ImageReferenceReader> ImageGeneratio
reference_images: references,
})
.await?;
- let file_type = generated.file_type().ok_or_else(|| {
+ generated.file_type().ok_or_else(|| {
ImageGenerationError::Provider(anyhow::anyhow!(
"provider returned an unsupported image type {}",
generated.mime_type
))
})?;
- let file_name = with_extension(&file_name, file_type);
+ if generated.bytes.is_empty() {
+ return Err(ImageGenerationError::Provider(anyhow::anyhow!(
+ "provider returned an empty image"
+ ))
+ .into());
+ }
let size_bytes = generated.bytes.len();
- let document_id = self
+ let static_file = self
.store
- .save_image(
- principal,
- NewImageDocument {
- file_name: file_name.clone(),
- bytes: generated.bytes,
- project,
- },
- )
+ .save_image(NewStaticImage {
+ mime_type: generated.mime_type.clone(),
+ bytes: generated.bytes,
+ })
.await?;
- Ok(GeneratedImageDocument {
- document_id,
- file_name,
+ Ok(StoredGeneratedImage {
+ static_file,
mime_type: generated.mime_type,
size_bytes,
note: generated.note,
})
}
}
-
-/// Words of `prompt` used as the document name when the caller gave none.
-const FILE_NAME_WORDS: usize = 6;
-
-/// A document name from the opening words of `prompt`: letters, digits, and
-/// plain hyphens only, so the name needs no further filename validation.
-fn file_name_from_prompt(prompt: &str) -> String {
- let name = prompt
- .split(|c: char| !(c.is_alphanumeric() || c == '-'))
- .filter(|word| !word.is_empty())
- .take(FILE_NAME_WORDS)
- .collect::<Vec<_>>()
- .join(" ");
- if name.is_empty() {
- "Generated image".to_string()
- } else {
- name
- }
-}
-
-/// `name` with `file_type`'s extension, unless it already ends in an image
-/// extension the storage pipeline recognises.
-fn with_extension(name: &str, file_type: FileType) -> String {
- let lower = name.to_ascii_lowercase();
- let already_image = FileType::split_suffix_match(&lower)
- .and_then(|(_, extension)| extension.parse::<FileType>().ok())
- .is_some_and(|existing| existing.is_image());
- if already_image {
- name.to_string()
- } else {
- format!("{name}.{}", file_type.as_str())
- }
-}
diff --git a/crates/image_generation/src/domain/service/test.rs b/crates/image_generation/src/domain/service/test.rs
index 433914f01a..2b7f36a648 100644
--- a/crates/image_generation/src/domain/service/test.rs
+++ b/crates/image_generation/src/domain/service/test.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::domain::models::{
GeneratedImage, ImageAspectRatio, ImageReference, ReadImageError, ReferenceImage,
- SaveImageError,
+ SaveImageError, StoredImage,
};
use crate::domain::ports::UnconfiguredImageGenerator;
use macro_user_id::user_id::MacroUserIdStr;
@@ -9,7 +9,7 @@ use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use uuid::Uuid;
-const DOCUMENT_ID: Uuid = Uuid::from_u128(0x123);
+const STATIC_FILE_ID: Uuid = Uuid::from_u128(0x123);
const PNG: &[u8] = b"\x89PNG\r\n\x1a\nfake";
const DOCUMENT_REFERENCE: ImageReference = ImageReference::Document(Uuid::from_u128(0x456));
const STATIC_REFERENCE: ImageReference = ImageReference::StaticFile(Uuid::from_u128(0x789));
@@ -23,21 +23,22 @@ fn principal() -> CreationPrincipal {
#[derive(Default)]
struct RecordingStore {
- saves: Mutex<Vec<(CreationPrincipal, NewImageDocument)>>,
- deny: bool,
+ saves: Mutex<Vec<NewStaticImage>>,
+ fail: bool,
}
-impl ImageDocumentStore for Arc<RecordingStore> {
- async fn save_image(
- &self,
- principal: &CreationPrincipal,
- image: NewImageDocument,
- ) -> Result<Uuid, SaveImageError> {
- if self.deny {
- return Err(SaveImageError::Unauthorized);
+impl ImageStore for Arc<RecordingStore> {
+ async fn save_image(&self, image: NewStaticImage) -> Result<StoredImage, SaveImageError> {
+ if self.fail {
+ return Err(SaveImageError::Internal(rootcause::report!(
+ "upload failed"
+ )));
}
- self.saves.lock().unwrap().push((principal.clone(), image));
- Ok(DOCUMENT_ID)
+ self.saves.lock().unwrap().push(image);
+ Ok(StoredImage {
+ id: STATIC_FILE_ID,
+ url: "https://static.example/file/image".to_string(),
+ })
}
}
@@ -84,30 +85,25 @@ fn png() -> GeneratedImage {
}
}
-fn request(prompt: &str, file_name: &str) -> NewGeneratedImage {
+fn request(prompt: &str) -> NewGeneratedImage {
NewGeneratedImage {
prompt: prompt.to_string(),
aspect_ratio: Some(ImageAspectRatio::Widescreen),
- file_name: Some(file_name.to_string()),
- project: None,
reference_images: Vec::new(),
}
}
#[tokio::test]
-async fn generates_then_saves_with_the_delegated_identity() {
+async fn generates_then_uploads_bytes_and_returns_the_static_file() {
let store = Arc::new(RecordingStore::default());
let generator = Arc::new(FakeGenerator::returning(png()));
let service = ImageGenerationServiceImpl::new(generator.clone(), store.clone());
let created = service
- .create_generated_image(
- &principal(),
- request(" a lighthouse at dusk ", "Lighthouse"),
- )
+ .create_generated_image(&principal(), request(" a lighthouse at dusk "))
.await
.unwrap();
- assert_eq!(created.document_id, DOCUMENT_ID);
- assert_eq!(created.file_name, "Lighthouse.png");
+ assert_eq!(created.static_file.id, STATIC_FILE_ID);
+ assert_eq!(created.static_file.url, "https://static.example/file/image");
assert_eq!(created.mime_type, "image/png");
assert_eq!(created.size_bytes, PNG.len());
assert_eq!(created.note.as_deref(), Some("A calm scene."));
@@ -121,71 +117,8 @@ async fn generates_then_saves_with_the_delegated_identity() {
);
let saves = store.saves.lock().unwrap();
assert_eq!(saves.len(), 1);
- assert_eq!(saves[0].0, principal());
- assert_eq!(saves[0].1.bytes, PNG);
- assert_eq!(saves[0].1.file_name, "Lighthouse.png");
- assert!(saves[0].1.project.is_none());
-}
-
-#[tokio::test]
-async fn keeps_an_existing_image_extension_and_adds_the_generated_one_otherwise() {
- for (file_name, mime_type, expected) in [
- ("hero.png", "image/png", "hero.png"),
- ("hero.PNG", "image/jpeg", "hero.PNG"),
- ("hero", "image/jpeg", "hero.jpg"),
- ("hero", "image/webp", "hero.webp"),
- ("v1.2 draft", "image/png", "v1.2 draft.png"),
- ("notes.md", "image/png", "notes.md.png"),
- ] {
- let generator = Arc::new(FakeGenerator::returning(GeneratedImage {
- mime_type: mime_type.to_string(),
- ..png()
- }));
- let service =
- ImageGenerationServiceImpl::new(generator, Arc::new(RecordingStore::default()));
- let created = service
- .create_generated_image(&principal(), request("prompt", file_name))
- .await
- .unwrap();
- assert_eq!(created.file_name, expected, "{file_name} / {mime_type}");
- }
-}
-
-#[tokio::test]
-async fn names_the_document_after_the_prompt_when_no_name_is_given() {
- for (prompt, file_name, expected) in [
- (
- "A red lighthouse on a rocky shore at dusk, flat vector",
- None,
- "A red lighthouse on a rocky.png",
- ),
- (
- "Draw: \"Q3 revenue\" chart (bar)!",
- Some(" "),
- "Draw Q3 revenue chart bar.png",
- ),
- ("café-style sign", None, "café-style sign.png"),
- ("!!! ???", None, "Generated image.png"),
- ] {
- let service = ImageGenerationServiceImpl::new(
- Arc::new(FakeGenerator::returning(png())),
- Arc::new(RecordingStore::default()),
- );
- let created = service
- .create_generated_image(
- &principal(),
- NewGeneratedImage {
- prompt: prompt.to_string(),
- aspect_ratio: None,
- file_name: file_name.map(str::to_string),
- project: None,
- reference_images: Vec::new(),
- },
- )
- .await
- .unwrap();
- assert_eq!(created.file_name, expected, "{prompt:?}");
- }
+ assert_eq!(saves[0].bytes, PNG);
+ assert_eq!(saves[0].mime_type, "image/png");
}
#[tokio::test]
@@ -193,10 +126,7 @@ async fn rejects_bad_input_before_calling_the_provider() {
let generator = Arc::new(FakeGenerator::returning(png()));
let store = Arc::new(RecordingStore::default());
let service = ImageGenerationServiceImpl::new(generator.clone(), store.clone());
- for image in [
- request(" ", "name"),
- request(&"p".repeat(MAX_PROMPT_BYTES + 1), "name"),
- ] {
+ for image in [request(" "), request(&"p".repeat(MAX_PROMPT_BYTES + 1))] {
assert!(matches!(
service.create_generated_image(&principal(), image).await,
Err(GenerateImageError::BadRequest(_))
@@ -207,58 +137,66 @@ async fn rejects_bad_input_before_calling_the_provider() {
}
#[tokio::test]
-async fn provider_failures_create_no_document() {
+async fn provider_failures_upload_no_image() {
let store = Arc::new(RecordingStore::default());
let service = ImageGenerationServiceImpl::new(
Arc::new(FakeGenerator::refusing("blocked by safety filters")),
store.clone(),
);
assert!(
- matches!(service.create_generated_image(&principal(), request("prompt", "name")).await,
+ matches!(service.create_generated_image(&principal(), request("prompt")).await,
Err(GenerateImageError::Generation(ImageGenerationError::Refused(ref reason))) if reason == "blocked by safety filters")
);
let service =
ImageGenerationServiceImpl::new(Arc::new(UnconfiguredImageGenerator), store.clone());
assert!(matches!(
service
- .create_generated_image(&principal(), request("prompt", "name"))
+ .create_generated_image(&principal(), request("prompt"))
.await,
Err(GenerateImageError::Generation(
ImageGenerationError::Unavailable
))
));
- let service = ImageGenerationServiceImpl::new(
- Arc::new(FakeGenerator::returning(GeneratedImage {
+ for image in [
+ GeneratedImage {
mime_type: "application/pdf".to_string(),
..png()
- })),
- store.clone(),
- );
- assert!(matches!(
- service
- .create_generated_image(&principal(), request("prompt", "name"))
- .await,
- Err(GenerateImageError::Generation(
- ImageGenerationError::Provider(_)
- ))
- ));
+ },
+ GeneratedImage {
+ bytes: Vec::new(),
+ ..png()
+ },
+ ] {
+ let service = ImageGenerationServiceImpl::new(
+ Arc::new(FakeGenerator::returning(image)),
+ store.clone(),
+ );
+ assert!(matches!(
+ service
+ .create_generated_image(&principal(), request("prompt"))
+ .await,
+ Err(GenerateImageError::Generation(
+ ImageGenerationError::Provider(_)
+ ))
+ ));
+ }
assert!(store.saves.lock().unwrap().is_empty());
}
#[tokio::test]
-async fn propagates_document_authorization_failures() {
+async fn propagates_static_file_upload_failures() {
let service = ImageGenerationServiceImpl::new(
Arc::new(FakeGenerator::returning(png())),
Arc::new(RecordingStore {
- deny: true,
+ fail: true,
..Default::default()
}),
);
assert!(matches!(
service
- .create_generated_image(&principal(), request("prompt", "name"))
+ .create_generated_image(&principal(), request("prompt"))
.await,
- Err(GenerateImageError::Document(SaveImageError::Unauthorized))
+ Err(GenerateImageError::Storage(SaveImageError::Internal(_)))
));
}
@@ -314,7 +252,7 @@ async fn resolves_references_in_order_under_the_creating_principal_before_genera
let store = Arc::new(RecordingStore::default());
let service = ImageGenerationServiceImpl::new(generator.clone(), store.clone())
.with_reference_reader(reader.clone());
- let mut image = request(" edit image 1 using image 2 ", "Edited image");
+ let mut image = request(" edit image 1 using image 2 ");
image.reference_images = vec![DOCUMENT_REFERENCE, STATIC_REFERENCE];
let created = service
@@ -322,7 +260,7 @@ async fn resolves_references_in_order_under_the_creating_principal_before_genera
.await
.unwrap();
- assert_eq!(created.document_id, DOCUMENT_ID);
+ assert_eq!(created.static_file.id, STATIC_FILE_ID);
assert_eq!(
*reader.calls.lock().unwrap(),
[
@@ -340,9 +278,8 @@ async fn resolves_references_in_order_under_the_creating_principal_before_genera
);
let saves = store.saves.lock().unwrap();
assert_eq!(saves.len(), 1);
- assert_eq!(saves[0].0, principal());
- assert_eq!(saves[0].1.bytes, PNG);
- assert_eq!(saves[0].1.file_name, "Edited image.png");
+ assert_eq!(saves[0].bytes, PNG);
+ assert_eq!(saves[0].mime_type, "image/png");
}
#[tokio::test]
@@ -352,7 +289,7 @@ async fn excessive_reference_count_is_rejected_before_any_read_or_generation() {
let store = Arc::new(RecordingStore::default());
let service = ImageGenerationServiceImpl::new(generator.clone(), store.clone())
.with_reference_reader(reader.clone());
- let mut image = request("edit these images", "Edited");
+ let mut image = request("edit these images");
image.reference_images = vec![DOCUMENT_REFERENCE; MAX_REFERENCE_IMAGES + 1];
assert!(matches!(
@@ -381,7 +318,7 @@ async fn failed_reference_reads_never_generate_from_a_partial_set() {
let store = Arc::new(RecordingStore::default());
let service = ImageGenerationServiceImpl::new(generator.clone(), store.clone())
.with_reference_reader(reader.clone());
- let mut image = request("combine all three images", "Combined");
+ let mut image = request("combine all three images");
image.reference_images = vec![DOCUMENT_REFERENCE, STATIC_REFERENCE, DOCUMENT_REFERENCE];
assert!(matches!(
@@ -416,7 +353,7 @@ async fn invalid_reference_content_is_rejected_before_generation_or_storage() {
let store = Arc::new(RecordingStore::default());
let service = ImageGenerationServiceImpl::new(generator.clone(), store.clone())
.with_reference_reader(reader.clone());
- let mut image = request("edit these images", "Edited");
+ let mut image = request("edit these images");
image.reference_images = vec![DOCUMENT_REFERENCE; image_count];
assert!(matches!(
@@ -443,7 +380,7 @@ async fn accepts_three_supported_images_at_the_total_byte_limit() {
let store = Arc::new(RecordingStore::default());
let service = ImageGenerationServiceImpl::new(generator.clone(), store.clone())
.with_reference_reader(reader);
- let mut image = request("combine all three images", "Combined");
+ let mut image = request("combine all three images");
image.reference_images = vec![DOCUMENT_REFERENCE, STATIC_REFERENCE, DOCUMENT_REFERENCE];
service
@@ -470,7 +407,7 @@ async fn missing_reference_reader_does_not_silently_fall_back_to_text_only() {
let generator = Arc::new(FakeGenerator::returning(png()));
let store = Arc::new(RecordingStore::default());
let service = ImageGenerationServiceImpl::new(generator.clone(), store.clone());
- let mut image = request("edit this photo", "Edited");
+ let mut image = request("edit this photo");
image.reference_images = vec![DOCUMENT_REFERENCE];
assert!(matches!(
diff --git a/crates/image_generation/src/inbound/toolset.rs b/crates/image_generation/src/inbound/toolset.rs
index 5fa5233a8b..04e0cf7397 100644
--- a/crates/image_generation/src/inbound/toolset.rs
+++ b/crates/image_generation/src/inbound/toolset.rs
@@ -4,36 +4,31 @@ mod generate_image;
use crate::domain::ports::ImageGenerationService;
use ai_toolset::AsyncToolCollection;
use bot_id::BotId;
-use entity_access::domain::ports::EntityAccessService;
use generate_image::GenerateImage;
use std::sync::Arc;
/// Services and delegated bot identity used by the image-generation tool.
-pub struct ImageGenerationToolContext<Svc, Access> {
+pub struct ImageGenerationToolContext<Svc> {
/// Image-generation use case.
pub service: Arc<Svc>,
- /// Inbound access service for minting destination capabilities.
- pub entity_access_service: Arc<Access>,
/// Bot creating images on behalf of the requesting user.
pub actor: BotId,
}
-impl<Svc, Access> Clone for ImageGenerationToolContext<Svc, Access> {
+impl<Svc> Clone for ImageGenerationToolContext<Svc> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
- entity_access_service: self.entity_access_service.clone(),
actor: self.actor,
}
}
}
-impl<Svc, Access> ImageGenerationToolContext<Svc, Access> {
- /// Compose the use case, access boundary, and delegated bot identity.
- pub fn new(service: Svc, entity_access_service: Arc<Access>, actor: BotId) -> Self {
+impl<Svc> ImageGenerationToolContext<Svc> {
+ /// Compose the use case and delegated bot identity.
+ pub fn new(service: Svc, actor: BotId) -> Self {
Self {
service: Arc::new(service),
- entity_access_service,
actor,
}
}
@@ -46,9 +41,7 @@ impl<Svc, Access> ImageGenerationToolContext<Svc, Access> {
}
/// Image-generation tools shared by chat, agent, and MCP hosts.
-pub fn image_generation_toolset<
- Svc: ImageGenerationService + 'static,
- Access: EntityAccessService,
->() -> AsyncToolCollection<ImageGenerationToolContext<Svc, Access>> {
- AsyncToolCollection::new().add_tool::<GenerateImage, ImageGenerationToolContext<Svc, Access>>()
+pub fn image_generation_toolset<Svc: ImageGenerationService + 'static>()
+-> AsyncToolCollection<ImageGenerationToolContext<Svc>> {
+ AsyncToolCollection::new().add_tool::<GenerateImage, ImageGenerationToolContext<Svc>>()
}
diff --git a/crates/image_generation/src/inbound/toolset/generate_image.rs b/crates/image_generation/src/inbound/toolset/generate_image.rs
index fbe8680e8d..aeec6135ea 100644
--- a/crates/image_generation/src/inbound/toolset/generate_image.rs
+++ b/crates/image_generation/src/inbound/toolset/generate_image.rs
@@ -1,15 +1,11 @@
//! GenerateImage renders a prompt with the configured image model and stores
-//! the result as an image document.
+//! the result in static file service.
use ai_toolset::{
AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
ToolResult,
};
use async_trait::async_trait;
-use entity_access::domain::{
- models::{BotAccessScope, EditAccessLevel, EntityType},
- ports::EntityAccessService,
-};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -17,7 +13,7 @@ use super::ImageGenerationToolContext;
use crate::domain::{
models::{
GenerateImageError, ImageAspectRatio, ImageGenerationError, ImageReference,
- NewGeneratedImage, ReadImageError, SaveImageError,
+ NewGeneratedImage, ReadImageError,
},
ports::ImageGenerationService,
};
@@ -55,12 +51,12 @@ impl From<AspectRatio> for ImageAspectRatio {
#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase")]
enum ImageReferenceInput {
- /// An image document the user can view, including a previously generated image.
+ /// An image document the user can view.
Document {
/// The Macro document ID.
id: uuid::Uuid,
},
- /// A photo uploaded with the conversation's attachment control.
+ /// An uploaded photo or a previously generated static image.
StaticFile {
/// Uploaded file ID from the /file/<id> segment of its attachment URL.
id: uuid::Uuid,
@@ -80,32 +76,22 @@ impl From<ImageReferenceInput> for ImageReference {
#[serde(rename_all = "camelCase")]
#[schemars(
title = "GenerateImage",
- description = "Generate or edit an image with Google's Nano Banana image model and save the result as a new image document in Macro. Use for pictures, illustrations, diagram concepts, logo ideas, mockups, or edits based on reference photos. When the user supplies photos or asks to modify an existing image, pass them in referenceImages; describing a photo in the prompt alone does not send it to the image model. Describe the subject, style, composition, lighting, and any text to render; only the prompt is required. Refer to reference images by their order (image 1, image 2, image 3) when explaining how to use them. Returns the new document ID to cite inline. Generation takes several seconds."
+ description = "Generate or edit an image with Google's Nano Banana image model and save the result in static file service. Use for pictures, illustrations, diagram concepts, logo ideas, mockups, or edits based on reference photos. When the user supplies photos or asks to modify an existing image, pass them in referenceImages; describing a photo in the prompt alone does not send it to the image model. Describe the subject, style, composition, lighting, and any text to render; only the prompt is required. Refer to reference images by their order (image 1, image 2, image 3) when explaining how to use them. Returns the static file ID and image URL. The tool displays the image inline in chat. In channel messages without tool cards, embed the returned URL as a Markdown image. Do not cite it as a document. Generation takes several seconds."
)]
-/// Generate an image and save it as a Macro document.
+/// Generate an image and save it as a static file.
pub struct GenerateImage {
#[schemars(
description = "Detailed description of the image to generate: subject, style (photo, illustration, flat vector...), composition, colours, mood, and any text that must appear."
)]
prompt: String,
#[serde(default)]
- #[schemars(
- description = "Optional short descriptive name for the saved image, for example `sunset-lighthouse`. The file extension is added from the generated format. No directory path. Omit to name the image after the prompt."
- )]
- file_name: Option<String>,
- #[serde(default)]
#[schemars(
description = "Shape of the image. Omit for the model default (square). `widescreen` (16:9) suits banners and slides, `tall` (9:16) suits phone screens and stories."
)]
aspect_ratio: Option<AspectRatio>,
#[serde(default)]
#[schemars(
- description = "Optional destination project (folder) ID. Requires edit access. Omit to save to the user's top-level files."
- )]
- project_id: Option<uuid::Uuid>,
- #[serde(default)]
- #[schemars(
- description = "Up to three reference photos, in the order used by the prompt. Use type document with a Macro image document ID, or type staticFile with the UUID from /file/<id> in an uploaded attachment's source URL. Use the actual IDs supplied in the conversation or by tools; do not invent IDs. Omit for text-only generation.",
+ description = "Up to three reference photos, in the order used by the prompt. Use type document with a Macro image document ID, or type staticFile with the UUID from /file/<id> in an uploaded attachment's source URL or the staticFileId of a previous generation. Use the actual IDs supplied in the conversation or by tools; do not invent IDs. Omit for text-only generation.",
length(max = 3)
)]
reference_images: Option<Vec<ImageReferenceInput>>,
@@ -115,10 +101,10 @@ pub struct GenerateImage {
#[derive(Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct GenerateImageResponse {
- /// ID of the new image document.
- pub document_id: String,
- /// Saved filename, including its extension.
- pub file_name: String,
+ /// ID of the static file, reusable in referenceImages.
+ pub static_file_id: String,
+ /// Permanent URL of the generated image.
+ pub url: String,
/// IANA media type of the image, e.g. `image/png`.
pub mime_type: String,
/// Size of the image in bytes.
@@ -149,14 +135,7 @@ fn generate_error(error: GenerateImageError) -> ToolCallError {
GenerateImageError::Generation(ImageGenerationError::Provider(_)) => {
"the image model request failed; try again shortly".to_string()
}
- GenerateImageError::Document(SaveImageError::BadRequest(message)) => message.clone(),
- GenerateImageError::Document(SaveImageError::NameTooLong { max }) => {
- format!("fileName is too long (maximum {max} characters)")
- }
- GenerateImageError::Document(SaveImageError::Unauthorized) => {
- "you need edit access to the destination project".to_string()
- }
- GenerateImageError::Document(_) => {
+ GenerateImageError::Storage(_) => {
"the image was generated but could not be saved to Macro".to_string()
}
};
@@ -167,38 +146,17 @@ fn generate_error(error: GenerateImageError) -> ToolCallError {
}
#[async_trait]
-impl<Svc, ESvc> AsyncTool<ImageGenerationToolContext<Svc, ESvc>> for GenerateImage
+impl<Svc> AsyncTool<ImageGenerationToolContext<Svc>> for GenerateImage
where
Svc: ImageGenerationService + 'static,
- ESvc: EntityAccessService,
{
type Output = GenerateImageResponse;
async fn call(
&self,
- service_context: ServiceContext<ImageGenerationToolContext<Svc, ESvc>>,
+ service_context: ServiceContext<ImageGenerationToolContext<Svc>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
- let project = match self.project_id {
- Some(project_id) => Some(
- service_context
- .entity_access_service
- .generate_bot_entity_access_receipt::<EditAccessLevel>(
- service_context.actor,
- BotAccessScope::user(request_context.user_id.clone()),
- &project_id.to_string(),
- EntityType::Project,
- )
- .await
- .map_err(|error| ToolCallError {
- description:
- "you need edit access to the destination project, or it does not exist"
- .to_string(),
- internal_error: error.into(),
- })?,
- ),
- None => None,
- };
let created = service_context
.service
.create_generated_image(
@@ -209,8 +167,6 @@ where
NewGeneratedImage {
prompt: self.prompt.clone(),
aspect_ratio: self.aspect_ratio.map(Into::into),
- file_name: self.file_name.clone(),
- project,
reference_images: self
.reference_images
.iter()
@@ -224,8 +180,8 @@ where
.map_err(generate_error)?;
Ok(GenerateImageResponse {
- document_id: created.document_id.to_string(),
- file_name: created.file_name,
+ static_file_id: created.static_file.id.to_string(),
+ url: created.static_file.url,
mime_type: created.mime_type,
size_bytes: created.size_bytes,
note: created.note,
diff --git a/crates/image_generation/src/inbound/toolset/generate_image/test.rs b/crates/image_generation/src/inbound/toolset/generate_image/test.rs
index 8809cc88f1..a74e1ad58d 100644
--- a/crates/image_generation/src/inbound/toolset/generate_image/test.rs
+++ b/crates/image_generation/src/inbound/toolset/generate_image/test.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::domain::models::SaveImageError;
use ai_toolset::schema::generate_validated_input_schema;
#[test]
@@ -9,16 +10,13 @@ fn schema_is_valid_and_optional_fields_default() {
"prompt": "a lighthouse at dusk"
}))
.unwrap();
- assert!(tool.file_name.is_none());
assert!(tool.aspect_ratio.is_none());
- assert!(tool.project_id.is_none());
assert!(tool.reference_images.is_none());
let tool: GenerateImage = serde_json::from_value(serde_json::json!({
- "prompt": "a lighthouse at dusk", "fileName": "lighthouse", "aspectRatio": "widescreen"
+ "prompt": "a lighthouse at dusk", "aspectRatio": "widescreen"
}))
.unwrap();
- assert_eq!(tool.file_name.as_deref(), Some("lighthouse"));
assert_eq!(
tool.aspect_ratio.map(ImageAspectRatio::from),
Some(ImageAspectRatio::Widescreen)
@@ -124,10 +122,6 @@ fn errors_describe_what_the_agent_can_do_about_them() {
)),
"prompt must not be empty"
);
- assert_eq!(
- description(SaveImageError::Unauthorized.into()),
- "you need edit access to the destination project"
- );
assert_eq!(
description(SaveImageError::Internal(rootcause::report!("save failed")).into()),
"the image was generated but could not be saved to Macro"
@@ -149,8 +143,8 @@ fn errors_describe_what_the_agent_can_do_about_them() {
#[test]
fn response_omits_an_absent_note() {
let json = serde_json::to_value(GenerateImageResponse {
- document_id: "doc".to_string(),
- file_name: "lighthouse.png".to_string(),
+ static_file_id: "file".to_string(),
+ url: "https://static.example/file/image".to_string(),
mime_type: "image/png".to_string(),
size_bytes: 3,
note: None,
@@ -159,8 +153,8 @@ fn response_omits_an_absent_note() {
assert_eq!(
json,
serde_json::json!({
- "documentId": "doc",
- "fileName": "lighthouse.png",
+ "staticFileId": "file",
+ "url": "https://static.example/file/image",
"mimeType": "image/png",
"sizeBytes": 3
})
diff --git a/crates/image_generation/src/lib.rs b/crates/image_generation/src/lib.rs
index ead4f4ae9d..897797fb41 100644
--- a/crates/image_generation/src/lib.rs
+++ b/crates/image_generation/src/lib.rs
@@ -1,4 +1,4 @@
-//! Image generation and storage as Macro documents, exposed through an AI toolset.
+//! Image generation and storage as static files, exposed through an AI toolset.
#![deny(missing_docs)]
pub mod domain;
diff --git a/crates/image_generation/src/outbound.rs b/crates/image_generation/src/outbound.rs
index 53d4512a64..dbb3fe6884 100644
--- a/crates/image_generation/src/outbound.rs
+++ b/crates/image_generation/src/outbound.rs
@@ -1,4 +1,4 @@
-//! Provider and document storage adapters.
-pub mod documents;
+//! Provider and static file storage adapters.
pub mod gemini;
pub mod references;
+pub mod static_files;
diff --git a/crates/image_generation/src/outbound/documents.rs b/crates/image_generation/src/outbound/documents.rs
deleted file mode 100644
index 5267eba549..0000000000
--- a/crates/image_generation/src/outbound/documents.rs
+++ /dev/null
@@ -1,56 +0,0 @@
-//! Saves images through the documents domain's inbound upload port.
-use crate::domain::{
- models::{NewImageDocument, SaveImageError},
- ports::ImageDocumentStore,
-};
-use documents::domain::{
- create::upload::NewFileUpload, models::DocumentError, ports::create::DocumentUploadService,
-};
-use model_owner::CreationPrincipal;
-use uuid::Uuid;
-
-/// Adapter to the existing document upload lifecycle.
-pub struct DocumentsImageStore<Svc> {
- service: Svc,
-}
-
-impl<Svc> DocumentsImageStore<Svc> {
- /// Use an already-composed document upload service.
- pub fn new(service: Svc) -> Self {
- Self { service }
- }
-}
-
-impl<Svc: DocumentUploadService> ImageDocumentStore for DocumentsImageStore<Svc> {
- #[tracing::instrument(skip_all, err)]
- async fn save_image(
- &self,
- principal: &CreationPrincipal,
- image: NewImageDocument,
- ) -> Result<Uuid, SaveImageError> {
- let created = self
- .service
- .upload_file(
- principal,
- NewFileUpload {
- file_name: image.file_name,
- bytes: image.bytes,
- project: image.project,
- },
- )
- .await
- .map_err(|error| match error {
- DocumentError::BadRequest(message) => SaveImageError::BadRequest(message),
- DocumentError::NameTooLong { max } => SaveImageError::NameTooLong { max },
- DocumentError::Unauthorized => SaveImageError::Unauthorized,
- error => SaveImageError::Internal(rootcause::report!(error).into()),
- })?;
- created
- .document_id()
- .parse::<Uuid>()
- .map_err(|error| SaveImageError::Internal(rootcause::report!(error).into()))
- }
-}
-
-#[cfg(test)]
-mod test;
diff --git a/crates/image_generation/src/outbound/documents/test.rs b/crates/image_generation/src/outbound/documents/test.rs
deleted file mode 100644
index 5b4a8768af..0000000000
--- a/crates/image_generation/src/outbound/documents/test.rs
+++ /dev/null
@@ -1,186 +0,0 @@
-use super::*;
-use documents::domain::{
- content::DocumentContent,
- create::DocumentCreator,
- models::{CreateTaskRequest, NewDocument},
- ports::create::{DocumentBytesUpload, DocumentBytesUploadPort, DocumentCreationService},
- response::{CreateDocumentResponseData, DocumentResponse, DocumentResponseMetadataWithContent},
-};
-use macro_user_id::user_id::MacroUserIdStr;
-use model::document::{FileType, response::DocumentResponseMetadata};
-use std::sync::{Arc, Mutex};
-const DOCUMENT_ID: &str = "00000000-0000-0000-0000-000000000123";
-const PNG: &[u8] = b"\x89PNG\r\n\x1a\nfake";
-
-fn principal() -> CreationPrincipal {
- CreationPrincipal::BotForUser {
- bot: bot_id::MACRO_AI_BOT_ID,
- user: MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),
- }
-}
-#[derive(Default)]
-struct RecordingService {
- creates: Mutex<Vec<NewDocument>>,
-}
-
-impl DocumentCreationService for RecordingService {
- async fn create_document(
- &self,
- principal: &CreationPrincipal,
- document: NewDocument,
- _job_id: Option<String>,
- ) -> Result<CreateDocumentResponseData, DocumentError> {
- let file_type = document.file_type.map(|kind| kind.to_string());
- let document_name = document.document_name.clone();
- self.creates.lock().unwrap().push(document);
- Ok(CreateDocumentResponseData {
- document_response: DocumentResponse {
- document_metadata: DocumentResponseMetadataWithContent::new(
- DocumentResponseMetadata {
- document_id: DOCUMENT_ID.to_string(),
- document_version_id: 1,
- owner: principal.owner(),
- document_name,
- file_type: file_type.clone(),
- sha: None,
- branched_from_id: None,
- branched_from_version_id: None,
- document_family_id: None,
- document_bom: None,
- modification_data: None,
- created_at: None,
- updated_at: None,
- sub_type: None,
- },
- DocumentContent::pending(),
- ),
- presigned_url: Some("https://storage.example/upload".to_string()),
- },
- content_type: "image/png".to_string(),
- file_type,
- })
- }
-
- async fn handle_task_properties(
- &self,
- _: &CreationPrincipal,
- _: &str,
- _: &CreateTaskRequest,
- ) -> Result<(), DocumentError> {
- panic!("generated images are not tasks")
- }
-
- async fn mark_document_uploaded(&self, _: &str) -> Result<(), DocumentError> {
- panic!("the storage event pipeline finalizes uploads")
- }
-
- async fn set_document_content(&self, _: &str, _: DocumentContent) -> Result<(), DocumentError> {
- panic!("the storage event pipeline finalizes uploads")
- }
-
- async fn cleanup_created_document(&self, _: &str) {}
-}
-
-#[derive(Clone, Default)]
-struct RecordingUploader {
- uploads: Arc<Mutex<Vec<DocumentBytesUpload>>>,
-}
-
-impl DocumentBytesUploadPort for RecordingUploader {
- async fn upload_document_bytes(
- &self,
- upload: DocumentBytesUpload,
- ) -> Result<(), DocumentError> {
- self.uploads.lock().unwrap().push(upload);
- Ok(())
- }
-}
-
-#[tokio::test]
-async fn saves_through_the_existing_document_upload_lifecycle() {
- let service = Arc::new(RecordingService::default());
- let uploader = RecordingUploader::default();
- let store = DocumentsImageStore::new(DocumentCreator::new(
- service.clone(),
- (),
- uploader.clone(),
- (),
- ));
- let id = store
- .save_image(
- &principal(),
- NewImageDocument {
- file_name: "Lighthouse.png".to_string(),
- bytes: PNG.to_vec(),
- project: None,
- },
- )
- .await
- .unwrap();
- assert_eq!(id.to_string(), DOCUMENT_ID);
- let creates = service.creates.lock().unwrap();
- assert_eq!(creates.len(), 1);
- assert_eq!(creates[0].document_name, "Lighthouse");
- assert_eq!(creates[0].file_type, Some(FileType::Png));
- let uploads = uploader.uploads.lock().unwrap();
- assert_eq!(uploads.len(), 1);
- assert_eq!(uploads[0].bytes, PNG);
- assert_eq!(uploads[0].content_type, "image/png");
-}
-
-#[tokio::test]
-async fn preserves_destination_capabilities_and_document_authorization() {
- use entity_access::domain::models::{
- BotReceiptScope, EditAccessLevel, Entity, EntityAccessReceipt, EntityPermission, EntityType,
- };
- use models_permissions::share_permission::access_level::AccessLevel;
-
- let project_id = Uuid::from_u128(0x456);
- for (user, entity_type, allowed) in [
- ("macro|[email protected]", EntityType::Project, true),
- ("macro|[email protected]", EntityType::Project, false),
- ("macro|[email protected]", EntityType::Document, false),
- ] {
- let receipt = EntityAccessReceipt::<EditAccessLevel>::try_new_bot(
- bot_id::MACRO_AI_BOT_ID.into(),
- BotReceiptScope::User {
- acting_user: MacroUserIdStr::try_from(user.to_string()).unwrap(),
- },
- Entity {
- entity_id: project_id.to_string(),
- entity_type,
- },
- EntityPermission::AccessLevel {
- access_level: AccessLevel::Edit,
- },
- )
- .unwrap();
- let service = Arc::new(RecordingService::default());
- let uploader = RecordingUploader::default();
- let store = DocumentsImageStore::new(DocumentCreator::new(
- service.clone(),
- (),
- uploader.clone(),
- (),
- ));
- let result = store
- .save_image(
- &principal(),
- NewImageDocument {
- file_name: "Lighthouse.png".to_string(),
- bytes: PNG.to_vec(),
- project: Some(receipt),
- },
- )
- .await;
- let creates = service.creates.lock().unwrap();
- if allowed {
- assert_eq!(result.unwrap().to_string(), DOCUMENT_ID);
- assert_eq!(creates[0].project_id, Some(project_id));
- } else {
- assert!(matches!(result, Err(SaveImageError::Unauthorized)));
- assert!(creates.is_empty());
- assert!(uploader.uploads.lock().unwrap().is_empty());
- }
- }
-}
diff --git a/crates/image_generation/src/outbound/static_files.rs b/crates/image_generation/src/outbound/static_files.rs
new file mode 100644
index 0000000000..98e340909f
--- /dev/null
+++ b/crates/image_generation/src/outbound/static_files.rs
@@ -0,0 +1,39 @@
+//! Saves generated images through the static file service client.
+use crate::domain::{
+ models::{NewStaticImage, SaveImageError, StoredImage},
+ ports::ImageStore,
+};
+use static_file_service_client::StaticFileServiceClient;
+
+/// Adapter to the static file upload lifecycle.
+pub struct StaticFileImageStore {
+ client: StaticFileServiceClient,
+}
+
+impl StaticFileImageStore {
+ /// Use an already-configured static file service client.
+ pub fn new(client: StaticFileServiceClient) -> Self {
+ Self { client }
+ }
+}
+
+impl ImageStore for StaticFileImageStore {
+ #[tracing::instrument(skip_all, err)]
+ async fn save_image(&self, image: NewStaticImage) -> Result<StoredImage, SaveImageError> {
+ let stored = self
+ .client
+ .put_named_bytes("generated-image", image.bytes.into(), &image.mime_type)
+ .await
+ .map_err(|error| SaveImageError::Internal(rootcause::report!(error).into()))?;
+ Ok(StoredImage {
+ id: stored
+ .id
+ .parse::<uuid::Uuid>()
+ .map_err(|error| SaveImageError::Internal(rootcause::report!(error).into()))?,
+ url: stored.file_location,
+ })
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/image_generation/src/outbound/static_files/test.rs b/crates/image_generation/src/outbound/static_files/test.rs
new file mode 100644
index 0000000000..bb90b39a67
--- /dev/null
+++ b/crates/image_generation/src/outbound/static_files/test.rs
@@ -0,0 +1,88 @@
+use super::*;
+use wiremock::{
+ Mock, MockServer, ResponseTemplate,
+ matchers::{body_bytes, body_json, header, method, path},
+};
+
+const PNG: &[u8] = b"\x89PNG\r\n\x1a\nfake";
+const FILE_ID: &str = "00000000-0000-0000-0000-000000000123";
+
+fn image() -> NewStaticImage {
+ NewStaticImage {
+ bytes: PNG.to_vec(),
+ mime_type: "image/png".to_string(),
+ }
+}
+
+fn store(server: &MockServer) -> StaticFileImageStore {
+ StaticFileImageStore::new(StaticFileServiceClient::new(
+ "test-key".to_string(),
+ server.uri(),
+ ))
+}
+
+async fn reserve(server: &MockServer) {
+ Mock::given(method("PUT"))
+ .and(path("/internal/file"))
+ .and(header("x-internal-auth-key", "test-key"))
+ .and(body_json(serde_json::json!({
+ "file_name": "generated-image",
+ "content_type": "image/png",
+ "extension_data": null
+ })))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "id": FILE_ID,
+ "file_location": format!("{}/file/{FILE_ID}", server.uri()),
+ "upload_url": format!("{}/upload", server.uri())
+ })))
+ .expect(1)
+ .mount(server)
+ .await;
+}
+
+#[tokio::test]
+async fn uploads_image_bytes_before_returning_the_permanent_location() {
+ let server = MockServer::start().await;
+ reserve(&server).await;
+ Mock::given(method("PUT"))
+ .and(path("/upload"))
+ .and(header("content-type", "image/png"))
+ .and(body_bytes(PNG))
+ .respond_with(ResponseTemplate::new(200))
+ .expect(1)
+ .mount(&server)
+ .await;
+
+ let stored = store(&server).save_image(image()).await.unwrap();
+ assert_eq!(stored.id.to_string(), FILE_ID);
+ assert_eq!(stored.url, format!("{}/file/{FILE_ID}", server.uri()));
+}
+
+#[tokio::test]
+async fn failed_upload_does_not_return_a_successful_image() {
+ let server = MockServer::start().await;
+ reserve(&server).await;
+ Mock::given(method("PUT"))
+ .and(path("/upload"))
+ .respond_with(ResponseTemplate::new(500))
+ .expect(1)
+ .mount(&server)
+ .await;
+ assert!(matches!(
+ store(&server).save_image(image()).await,
+ Err(SaveImageError::Internal(_))
+ ));
+}
+
+#[tokio::test]
+async fn failed_reservation_does_not_upload() {
+ let server = MockServer::start().await;
+ Mock::given(method("PUT"))
+ .and(path("/internal/file"))
+ .respond_with(ResponseTemplate::new(503))
+ .expect(1)
+ .mount(&server)
+ .await;
+ assert!(store(&server).save_image(image()).await.is_err());
+ assert_eq!(server.received_requests().await.unwrap().len(), 1);
+}
diff --git a/crates/prompt/src/tool_usage.rs b/crates/prompt/src/tool_usage.rs
index 30a8145763..7daeec6aab 100644
--- a/crates/prompt/src/tool_usage.rs
+++ b/crates/prompt/src/tool_usage.rs
@@ -32,7 +32,7 @@ when the user explicitely asks you to _execute_ code.
(which creates a file for the code execution environment) for the `CreateDocument` tool which creates a document in the
users workspace. If the user asks you to create a document, write a code file, or create any file you should use the `CreateDocument` tool.
-- To make a picture (illustration, photo-style image, logo concept, mockup, diagram concept), use `GenerateImage`. It renders the prompt with an image model and saves the result as an image document; cite the returned document with a mention tag using `blockName` `image` so the picture itself shows inline in chat and channel messages. `CreateDocument` cannot produce image bytes.
+- To make a picture (illustration, photo-style image, logo concept, mockup, diagram concept), use `GenerateImage`. It renders the prompt with an image model and saves the result to static file service. The tool renders the image inline in chat. In channel messages or other surfaces without tool cards, embed the returned URL as a Markdown image. Never cite the result as a document. Use the returned staticFileId for subsequent edits. `CreateDocument` cannot produce image bytes.
- `CreateDocument` content (for Markdown documents) is rendered with the same Markdown parser as your chat responses, channel messages, and email bodies, and citation syntax (`[[uuid]]`, `[[md;...]]`) works identically inside created documents. For linking to other Macro items from within that content, see the "Linking Macro items inside document content" rules. Non-Markdown documents (PDF, CSV, images, etc.) take raw content instead — no Markdown syntax or mention tags.
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 9ac289ec48..f7412b85e3 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -36,11 +36,10 @@ permission failures should display a failed tool call without a successful resul
## Generating images with AI
`GenerateImage` takes a text prompt, renders it with Google's Nano Banana image
-model, and saves the result as an image document. Optional arguments: a short file
-name (otherwise the opening words of the prompt name the document), an aspect ratio
-(`square`, `landscape`, `portrait`, `widescreen`, `tall`), and a project ID (edit
-access required). The file extension comes from the generated format, so
-`fileName: "lighthouse"` yields `lighthouse.png`.
+model, and saves the result to static file service. An optional aspect ratio
+(`square`, `landscape`, `portrait`, `widescreen`, `tall`) controls its shape.
+The response includes `staticFileId` and the permanent image `url`; it does not
+create a document or take a filename or destination project.
For edits or variations, attach photos with the existing paperclip or use Macro
image documents the user can view. Pass up to three references in `referenceImages`,
@@ -48,18 +47,17 @@ for example `[{"type":"staticFile","id":"<UUID>"},{"type":"document","id":"<UUID
For an uploaded photo, use the UUID from `/file/<id>` in its attachment URL;
for a document, use its document ID. Describe the edit in `prompt`, referring to
image 1, image 2, and image 3 in array order. A description alone does not send
-the photo to the image model. The result is saved as a new document.
-
-The result appears as a standalone image card outside grouped tool calls. A
-rounded header shows the filename above the image preview; clicking the card
-opens the image document in a new app split. The card fits the image's scaled
-width without side padding, preserves its aspect ratio, and truncates long
-filenames in the header. The preview loads once the upload
-is ready, with a placeholder while it is being prepared. Any commentary the
-model added appears below the image.
-In a channel thread, where the bot's reply is plain message text with a
-mention chip rather than a tool card, the same image card renders beneath the
-message for every image document the reply mentions (see channels.md).
+the photo to the image model. For a previous generation, use its `staticFileId`
+with type `staticFile`. Each result is saved as a new static file.
+
+The result appears directly as an image outside grouped tool calls, loaded from
+its SFS URL without a filename header or document navigation. It preserves its
+aspect ratio and fits the available width. A status appears while generation is
+pending; a failed image load shows “Preview unavailable”. The tool already renders
+the result in chat, so the assistant should not add a document mention or duplicate
+image there. In channel messages, embed the returned URL as a Markdown image.
+Earlier generations saved as DSS documents still render their original document
+card when viewing historical conversations.
Refused prompts, provider failures, and hosts without a Google Generative AI key
display a failed tool call; the error tells the agent whether to rephrase, retry,
or stop.
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 4ddac63642..9b18c5d711 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -266,10 +266,13 @@ bottom of the area carries the other decisions, refusal first: `Dismiss · Open
for a tool draft, `Decline · Submit · Open in session` (or `Open` for a URL) for a question.
Only the session's owner can act; other viewers see the question read-only and the header
names who is being waited on. Once answered, the area shows the agent's passage again.
+Images made with `GenerateImage` are saved to static file service. The bot embeds
+the returned URL as a Markdown image in its channel reply; generated images have
+no document mention or filename card.
Agent replies may contain mention chips (`<m-document-mention>`) that render like any
-other channel mention. A mention of an image document (PNG, JPG, GIF, SVG, WebP —
-including a picture the bot made with `GenerateImage`) also unfurls beneath the
-message text as an image card: a header with the filename above the picture,
+other channel mention. A mention of an image document (PNG, JPG, GIF, SVG, WebP)
+also unfurls beneath the message text as an image card: a header with the filename
+above the picture,
inside the message's `[data-message-mentioned-images]` element. The chip stays;
clicking the card opens the image document in a split. The same image mentioned
twice unfurls once, mentions of other document types, channels, and chats never