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.

feat(ai): persist code execution file creation with mention pill (#1137)

Eric Hayesfee87ba1a972
diff --git a/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx b/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx
index 9a67b9cf84..67e8e7477d 100644
--- a/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx
+++ b/js/app/packages/core/component/AI/component/tool/TextEditorCodeExecution.tsx
@@ -1,10 +1,24 @@
+import type { CodeFileExtension } from '@block-code/util/languageSupport';
+import { asFileType } from '@core/component/AI/util/attachment';
+import { EntityIcon } from '@core/component/EntityIcon';
+import { TruncatedText } from '@core/component/FileList/TruncatedText';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import { createCodeFileFromText } from '@core/util/create';
+import {
+ allSupportedExtensionSet,
+ isCodeEditorExtensionSupported,
+} from '@core/util/languageQuery';
+import { isOk } from '@core/util/maybeResult';
import CaretDown from '@phosphor-icons/core/regular/caret-down.svg';
import CaretRight from '@phosphor-icons/core/regular/caret-right.svg';
import File from '@phosphor-icons/core/regular/file.svg';
+import { cognitionApiServiceClient } from '@service-cognition/client';
import type {
TextEditorCodeExecutionContent,
TextEditorCodeExecutionResult,
} from '@service-cognition/generated/tools/types';
+import { useSplitLayout } from 'app/component/split-layout/layout';
+import { createSignal, Match, onMount, Show, Switch } from 'solid-js';
// Type aliases for backwards compatibility with discriminated union variants
type TextEditorCodeExecutionViewResult = TextEditorCodeExecutionResult & {
@@ -16,10 +30,35 @@ type TextEditorCodeExecutionCreateResult = TextEditorCodeExecutionResult & {
type TextEditorCodeExecutionStrReplaceResult = TextEditorCodeExecutionResult & {
type: 'text_editor_code_execution_str_replace_result';
};
-import { createSignal, Match, Show, Switch } from 'solid-js';
import { BaseTool } from './BaseTool';
import { createToolRenderer } from './ToolRenderer';
+// Store file creation data from tool calls to use when handling responses
+type FileCreationData = {
+ path: string;
+ fileText: string;
+};
+
+type CreatedFileInfo = {
+ documentId: string;
+ fileName: string;
+ extension: string;
+};
+
+const toolFileDataMap: Record<string, FileCreationData> = {};
+const createdFilesMap: Record<string, CreatedFileInfo> = {};
+
+function getExtensionFromPath(path: string): string | null {
+ const fileName = path.split('/').pop() ?? '';
+ const parts = fileName.split('.');
+ if (parts.length < 2) return null;
+ return parts.pop()?.toLowerCase() ?? null;
+}
+
+function getFileNameFromPath(path: string): string {
+ return path.split('/').pop() ?? 'file';
+}
+
const MAX_OUTPUT_LINES = 5;
function getCommandLabel(command: string): string {
@@ -88,11 +127,64 @@ function ViewResult(props: { result: TextEditorCodeExecutionViewResult }) {
);
}
-function CreateResult(props: { result: TextEditorCodeExecutionCreateResult }) {
+function CreateResult(props: {
+ result: TextEditorCodeExecutionCreateResult;
+ toolId: string;
+}) {
+ const { replaceOrInsertSplit } = useSplitLayout();
+ const [createdFile, setCreatedFile] = createSignal<CreatedFileInfo | null>(
+ createdFilesMap[props.toolId] ?? null
+ );
+
+ // Fetch the mapping from backend if not in memory (e.g., after page refresh)
+ onMount(async () => {
+ if (createdFile()) return;
+
+ const result = await cognitionApiServiceClient.getIdMapping({
+ source_id: props.toolId,
+ });
+
+ if (isOk(result) && result[1]) {
+ try {
+ const fileInfo = JSON.parse(result[1]) as CreatedFileInfo;
+ createdFilesMap[props.toolId] = fileInfo;
+ setCreatedFile(fileInfo);
+ } catch {
+ // Invalid JSON, ignore
+ }
+ }
+ });
+
+ const handleClick = () => {
+ const file = createdFile();
+ if (file) {
+ const blockName = fileTypeToBlockName(file.extension);
+ replaceOrInsertSplit({ type: blockName, id: file.documentId });
+ }
+ };
+
return (
- <span class="text-ink-muted">
- {props.result.is_file_update ? 'File updated' : 'File created'}
- </span>
+ <div class="flex items-center gap-2">
+ <span class="text-ink-muted">
+ {props.result.is_file_update ? 'File updated' : 'File created'}
+ </span>
+ <Show when={createdFile()}>
+ {(file) => (
+ <button
+ type="button"
+ class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-hover transition-colors cursor-pointer"
+ onClick={handleClick}
+ >
+ <EntityIcon size="xs" targetType={asFileType(file().extension)} />
+ <TruncatedText size="sm">
+ <span class="underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">
+ {file().fileName}
+ </span>
+ </TruncatedText>
+ </button>
+ )}
+ </Show>
+ </div>
);
}
@@ -112,7 +204,10 @@ function StrReplaceResult(props: {
);
}
-function TextEditorResult(props: { content: TextEditorCodeExecutionContent }) {
+function TextEditorResult(props: {
+ content: TextEditorCodeExecutionContent;
+ toolId: string;
+}) {
return (
<Switch>
<Match
@@ -134,6 +229,7 @@ function TextEditorResult(props: { content: TextEditorCodeExecutionContent }) {
{(result) => (
<CreateResult
result={result() as TextEditorCodeExecutionCreateResult}
+ toolId={props.toolId}
/>
)}
</Match>
@@ -162,6 +258,64 @@ function TextEditorResult(props: { content: TextEditorCodeExecutionContent }) {
const handler = createToolRenderer({
name: 'text_editor_code_execution',
+ handleCall: async (ctx) => {
+ // Store file creation data for use in handleResponse
+ if (ctx.tool.data.command === 'create' && ctx.tool.data.file_text) {
+ toolFileDataMap[ctx.tool.id] = {
+ path: ctx.tool.data.path,
+ fileText: ctx.tool.data.file_text,
+ };
+ }
+ },
+ handleResponse: async (ctx) => {
+ const { content } = ctx.tool.data;
+
+ // Only create macro files for successful file creations
+ if (content.type !== 'text_editor_code_execution_create_result') {
+ return;
+ }
+
+ const fileData = toolFileDataMap[ctx.tool.id];
+ if (!fileData) {
+ return;
+ }
+
+ // Clean up stored data
+ delete toolFileDataMap[ctx.tool.id];
+
+ const extension = getExtensionFromPath(fileData.path);
+ if (!extension || !allSupportedExtensionSet.has(extension)) {
+ return;
+ }
+
+ // Only create macro files for supported code file extensions
+ if (!isCodeEditorExtensionSupported(extension)) {
+ return;
+ }
+
+ const fileName = getFileNameFromPath(fileData.path);
+
+ const result = await createCodeFileFromText({
+ code: fileData.fileText,
+ extension: extension as CodeFileExtension,
+ title: fileName,
+ });
+
+ if (isOk(result)) {
+ const documentId = result[1].documentId;
+ createdFilesMap[ctx.tool.id] = {
+ documentId,
+ fileName,
+ extension,
+ };
+
+ // Persist the mapping to the backend for retrieval on chat refresh
+ await cognitionApiServiceClient.createIdMapping({
+ source_id: ctx.tool.id,
+ target_id: JSON.stringify({ documentId, fileName, extension }),
+ });
+ }
+ },
renderCall: (ctx) => (
<BaseTool
icon={File}
@@ -180,7 +334,10 @@ const handler = createToolRenderer({
renderContext={ctx.renderContext}
type="response"
>
- <TextEditorResult content={ctx.tool.data.content} />
+ <TextEditorResult
+ content={ctx.tool.data.content}
+ toolId={ctx.tool.id}
+ />
</BaseTool>
);
},
diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.ts
index 4639fc46a1..413235367d 100644
--- a/js/app/packages/service-clients/service-cognition/client.ts
+++ b/js/app/packages/service-clients/service-cognition/client.ts
@@ -77,7 +77,32 @@ export function dcsFetch<T extends ObjectLike = never>(
}
export type Success = { success: boolean };
+type IdMappingResponse = { target_id: string | null };
+
export const cognitionApiServiceClient = {
+ /** Creates a mapping from source_id to target_id */
+ async createIdMapping(args: { source_id: string; target_id: string }) {
+ const { source_id, target_id } = args;
+ return mapOk(
+ await dcsFetch<{ success: boolean }>(`/id_mapping/${source_id}`, {
+ method: 'POST',
+ body: JSON.stringify({ target_id }),
+ }),
+ (result) => result
+ );
+ },
+
+ /** Gets the target_id for a given source_id */
+ async getIdMapping(args: { source_id: string }) {
+ const { source_id } = args;
+ return mapOk(
+ await dcsFetch<IdMappingResponse>(`/id_mapping/${source_id}`, {
+ method: 'GET',
+ }),
+ (result) => result.target_id
+ );
+ },
+
getChat: cache(
async function getChat(args: WithChatId) {
const { chat_id } = args;
diff --git a/rust/cloud-storage/document_cognition_service/.sqlx/query-bbeef57c72ec7a197daf71146f0a5c409a5a54b41a9dd9e3db2267c9ee17d9fd.json b/rust/cloud-storage/document_cognition_service/.sqlx/query-bbeef57c72ec7a197daf71146f0a5c409a5a54b41a9dd9e3db2267c9ee17d9fd.json
new file mode 100644
index 0000000000..653140af10
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/.sqlx/query-bbeef57c72ec7a197daf71146f0a5c409a5a54b41a9dd9e3db2267c9ee17d9fd.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT target_id\n FROM id_mapping\n WHERE source_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "target_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "bbeef57c72ec7a197daf71146f0a5c409a5a54b41a9dd9e3db2267c9ee17d9fd"
+}
diff --git a/rust/cloud-storage/document_cognition_service/.sqlx/query-ce97d5a94360438e17479379fcab57a8d30a1d2a7c03150526322a2aa8175c71.json b/rust/cloud-storage/document_cognition_service/.sqlx/query-ce97d5a94360438e17479379fcab57a8d30a1d2a7c03150526322a2aa8175c71.json
new file mode 100644
index 0000000000..30efbd4948
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/.sqlx/query-ce97d5a94360438e17479379fcab57a8d30a1d2a7c03150526322a2aa8175c71.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO id_mapping (source_id, target_id)\n VALUES ($1, $2)\n ON CONFLICT (source_id)\n DO UPDATE SET target_id = EXCLUDED.target_id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ce97d5a94360438e17479379fcab57a8d30a1d2a7c03150526322a2aa8175c71"
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/id_mapping/create.rs b/rust/cloud-storage/document_cognition_service/src/api/id_mapping/create.rs
new file mode 100644
index 0000000000..58e74019c2
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/src/api/id_mapping/create.rs
@@ -0,0 +1,67 @@
+//! Handler for creating ID mappings.
+
+use crate::service::id_mapping::create_id_mapping;
+use axum::{
+ Json,
+ extract::{Path, State},
+ http::StatusCode,
+};
+use serde::{Deserialize, Serialize};
+use sqlx::PgPool;
+
+/// Path parameters for the create endpoint.
+#[derive(Deserialize)]
+pub struct Params {
+ /// The source ID to create a mapping for.
+ pub source_id: String,
+}
+
+/// Request body for creating an ID mapping.
+#[derive(Debug, Deserialize, Serialize, utoipa::ToSchema)]
+pub struct CreateIdMappingRequest {
+ /// The target ID to map to.
+ pub target_id: String,
+}
+
+/// Response for successful ID mapping creation.
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct CreateIdMappingResponse {
+ /// Whether the operation was successful.
+ pub success: bool,
+}
+
+/// Creates a mapping from source_id to target_id.
+#[utoipa::path(
+ post,
+ path = "/id_mapping/{source_id}",
+ params(
+ ("source_id" = String, Path, description = "The source ID to create a mapping for")
+ ),
+ request_body = CreateIdMappingRequest,
+ responses(
+ (status = 201, body = CreateIdMappingResponse),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
+#[tracing::instrument(skip(db))]
+pub async fn create_id_mapping_handler(
+ State(db): State<PgPool>,
+ Path(Params { source_id }): Path<Params>,
+ Json(req): Json<CreateIdMappingRequest>,
+) -> Result<(StatusCode, Json<CreateIdMappingResponse>), (StatusCode, String)> {
+ create_id_mapping(&db, &source_id, &req.target_id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error = ?e, source_id, "failed to create id mapping");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "unable to create id mapping".to_string(),
+ )
+ })?;
+
+ Ok((
+ StatusCode::CREATED,
+ Json(CreateIdMappingResponse { success: true }),
+ ))
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/id_mapping/get_mapping.rs b/rust/cloud-storage/document_cognition_service/src/api/id_mapping/get_mapping.rs
new file mode 100644
index 0000000000..1d4459f06a
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/src/api/id_mapping/get_mapping.rs
@@ -0,0 +1,53 @@
+//! Handler for retrieving ID mappings.
+
+use crate::service::id_mapping::get_id_mapping;
+use axum::{
+ Json,
+ extract::{Path, State},
+ http::StatusCode,
+};
+use serde::{Deserialize, Serialize};
+use sqlx::PgPool;
+
+/// Path parameters for the get endpoint.
+#[derive(Deserialize)]
+pub struct Params {
+ /// The source ID to look up.
+ pub source_id: String,
+}
+
+/// Response for getting an ID mapping.
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct GetIdMappingResponse {
+ /// The target ID if found, null otherwise.
+ pub target_id: Option<String>,
+}
+
+/// Gets the target_id for a given source_id.
+#[utoipa::path(
+ get,
+ path = "/id_mapping/{source_id}",
+ params(
+ ("source_id" = String, Path, description = "The source ID to look up")
+ ),
+ responses(
+ (status = 200, body = GetIdMappingResponse),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
+#[tracing::instrument(skip(db))]
+pub async fn get_id_mapping_handler(
+ State(db): State<PgPool>,
+ Path(Params { source_id }): Path<Params>,
+) -> Result<Json<GetIdMappingResponse>, (StatusCode, String)> {
+ let target_id = get_id_mapping(&db, &source_id).await.map_err(|e| {
+ tracing::error!(error = ?e, source_id, "failed to get id mapping");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "unable to get id mapping".to_string(),
+ )
+ })?;
+
+ Ok(Json(GetIdMappingResponse { target_id }))
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/id_mapping/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/id_mapping/mod.rs
new file mode 100644
index 0000000000..ab7b547cb6
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/src/api/id_mapping/mod.rs
@@ -0,0 +1,31 @@
+//! API endpoints for ID mapping operations.
+//!
+//! Provides a simple key-value store for mapping source IDs to target IDs.
+
+use axum::{
+ Router,
+ routing::{get, post},
+};
+use tower::ServiceBuilder;
+
+use crate::api::context::ApiContext;
+
+mod create;
+mod get_mapping;
+
+/// Creates the router for id_mapping endpoints.
+pub fn router() -> Router<ApiContext> {
+ Router::new()
+ .route(
+ "/:source_id",
+ post(create::create_id_mapping_handler).layer(ServiceBuilder::new().layer(
+ axum::middleware::from_fn(macro_middleware::auth::ensure_user_exists::handler),
+ )),
+ )
+ .route(
+ "/:source_id",
+ get(get_mapping::get_id_mapping_handler).layer(ServiceBuilder::new().layer(
+ axum::middleware::from_fn(macro_middleware::auth::ensure_user_exists::handler),
+ )),
+ )
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rs
index 6e7ce6f81a..7f3b42819c 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs
@@ -16,6 +16,7 @@ mod completions;
pub mod context;
mod document_text;
mod health;
+mod id_mapping;
mod internal;
mod models;
mod preview;
@@ -82,6 +83,7 @@ fn api_router(api_context: ApiContext) -> Router {
.nest("/attachments", attachments::router())
.nest("/citations", citations::router())
.nest("/preview", preview::router())
+ .nest("/id_mapping", id_mapping::router())
.with_state(api_context.clone())
.nest("/completions", completions::router())
.nest("/models", models::router())
diff --git a/rust/cloud-storage/document_cognition_service/src/service/id_mapping.rs b/rust/cloud-storage/document_cognition_service/src/service/id_mapping.rs
new file mode 100644
index 0000000000..7936df76ff
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/src/service/id_mapping.rs
@@ -0,0 +1,51 @@
+//! Database operations for the id_mapping table.
+//!
+//! Provides a simple key-value store for mapping source IDs to target IDs.
+//! Used for persisting associations like tool_id -> document_id.
+
+use anyhow::Result;
+use sqlx::{Pool, Postgres};
+
+/// Creates a mapping from source_id to target_id.
+/// If the source_id already exists, updates the target_id.
+#[tracing::instrument(err, skip(db))]
+pub async fn create_id_mapping(
+ db: &Pool<Postgres>,
+ source_id: &str,
+ target_id: &str,
+) -> Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO id_mapping (source_id, target_id)
+ VALUES ($1, $2)
+ ON CONFLICT (source_id)
+ DO UPDATE SET target_id = EXCLUDED.target_id
+ "#,
+ source_id,
+ target_id
+ )
+ .execute(db)
+ .await?;
+ Ok(())
+}
+
+/// Gets the target_id for a given source_id.
+/// Returns None if no mapping exists.
+#[tracing::instrument(err, skip(db))]
+pub async fn get_id_mapping(db: &Pool<Postgres>, source_id: &str) -> Result<Option<String>> {
+ let result = sqlx::query!(
+ r#"
+ SELECT target_id
+ FROM id_mapping
+ WHERE source_id = $1
+ "#,
+ source_id
+ )
+ .fetch_optional(db)
+ .await?;
+
+ Ok(result.map(|r| r.target_id))
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/document_cognition_service/src/service/id_mapping/test.rs b/rust/cloud-storage/document_cognition_service/src/service/id_mapping/test.rs
new file mode 100644
index 0000000000..3767298aa8
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/src/service/id_mapping/test.rs
@@ -0,0 +1,37 @@
+use super::*;
+use sqlx::{Pool, Postgres};
+
+#[sqlx::test]
+async fn test_create_and_get_id_mapping(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ // Create a mapping
+ create_id_mapping(&pool, "source-123", "target-456").await?;
+
+ // Get the mapping
+ let target = get_id_mapping(&pool, "source-123").await?;
+ assert_eq!(target, Some("target-456".to_string()));
+
+ Ok(())
+}
+
+#[sqlx::test]
+async fn test_get_nonexistent_mapping(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let target = get_id_mapping(&pool, "nonexistent").await?;
+ assert_eq!(target, None);
+
+ Ok(())
+}
+
+#[sqlx::test]
+async fn test_upsert_id_mapping(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ // Create initial mapping
+ create_id_mapping(&pool, "source-abc", "target-old").await?;
+
+ // Update the mapping
+ create_id_mapping(&pool, "source-abc", "target-new").await?;
+
+ // Verify it was updated
+ let target = get_id_mapping(&pool, "source-abc").await?;
+ assert_eq!(target, Some("target-new".to_string()));
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/service/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/mod.rs
index beaae02e36..3643711327 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/mod.rs
@@ -1,3 +1,4 @@
pub mod ai;
pub mod attachment;
pub mod get_chat;
+pub mod id_mapping;
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260122144921_create_id_mapping_table.sql b/rust/cloud-storage/macro_db_client/migrations/20260122144921_create_id_mapping_table.sql
new file mode 100644
index 0000000000..b53380e315
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260122144921_create_id_mapping_table.sql
@@ -0,0 +1,14 @@
+-- Create a simple key-value table for storing ID mappings
+-- Used for mapping tool IDs to document IDs (e.g., code execution files)
+
+CREATE TABLE id_mapping
+(
+ source_id TEXT NOT NULL,
+ target_id TEXT NOT NULL,
+ created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT id_mapping_pkey PRIMARY KEY (source_id)
+);
+
+-- Index for looking up by target ID if needed
+CREATE INDEX id_mapping_target_id_idx ON id_mapping (target_id);