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(dcs): fix non-sync-service `md` attachments (#926)

Eric Hayesea066f6a296b
diff --git a/js/lexical-service/bun.lock b/js/lexical-service/bun.lock
index 6c7ed619d5..ee3b12f50a 100644
--- a/js/lexical-service/bun.lock
+++ b/js/lexical-service/bun.lock
@@ -1,5 +1,6 @@
{
"lockfileVersion": 1,
+ "configVersion": 0,
"workspaces": {
"": {
"name": "cloudflare-workers-openapi",
diff --git a/js/lexical-service/src/endpoints/cognition-presigned.ts b/js/lexical-service/src/endpoints/cognition-presigned.ts
new file mode 100644
index 0000000000..cbf2eb2508
--- /dev/null
+++ b/js/lexical-service/src/endpoints/cognition-presigned.ts
@@ -0,0 +1,78 @@
+import { OpenAPIRoute } from 'chanfana';
+import type { Context } from 'hono';
+import type { SerializedEditorState } from 'lexical';
+import { z } from 'zod';
+import { toCognitionText } from '../lib/convsersions';
+import { ConversionError, handleEndpointError } from '../lib/error-handler';
+import { cognitionNodeSchema, standardErrorResponses } from '../lib/schemas';
+import type { CognitionNode } from '../types';
+
+export class CognitionPresignedEndpoint extends OpenAPIRoute {
+ schema = {
+ summary: 'Convert content from presigned URL to cognition text',
+ description:
+ 'Downloads content from a presigned URL and converts it to cognition text. Attempts to parse as Lexical JSON, falls back to plain markdown.',
+ request: {
+ query: z.object({
+ url: z.string().url('A valid presigned URL is required'),
+ }),
+ },
+ responses: {
+ 200: {
+ description: 'Successfully converted content to cognition text',
+ content: {
+ 'application/json': {
+ schema: z.object({
+ data: z.array(cognitionNodeSchema),
+ }),
+ },
+ },
+ },
+ ...standardErrorResponses,
+ },
+ };
+
+ async handle(c: Context) {
+ let presignedUrl = 'unknown';
+ try {
+ const { query } = await this.getValidatedData<typeof this.schema>();
+ presignedUrl = query.url;
+
+ const response = await fetch(presignedUrl, {
+ signal: AbortSignal.timeout(5000),
+ });
+
+ if (!response.ok) {
+ throw new ConversionError(
+ `Failed to download content: ${response.status} ${response.statusText}`
+ );
+ }
+
+ const contentText = await response.text();
+
+ // Try to parse as Lexical JSON first
+ try {
+ const lexicalData = JSON.parse(contentText) as SerializedEditorState;
+ // Validate it looks like Lexical editor state
+ if (lexicalData.root && lexicalData.root.children) {
+ const cognitionNodes = toCognitionText(lexicalData);
+ return c.json({ data: cognitionNodes });
+ }
+ } catch {
+ // Not valid Lexical JSON, fall through to plain markdown handling
+ }
+
+ // Treat as plain markdown - return as single node
+ const plainMarkdownNode: CognitionNode = {
+ nodeId: 'plain-text',
+ content: contentText,
+ rawContent: contentText,
+ type: 'markdown',
+ };
+
+ return c.json({ data: [plainMarkdownNode] });
+ } catch (error) {
+ return handleEndpointError(error, c, `presigned:${presignedUrl}`);
+ }
+ }
+}
diff --git a/js/lexical-service/src/index.ts b/js/lexical-service/src/index.ts
index fe7f9be2c7..84f6657345 100644
--- a/js/lexical-service/src/index.ts
+++ b/js/lexical-service/src/index.ts
@@ -5,6 +5,7 @@ import { fromHono } from 'chanfana';
import { Hono } from 'hono';
import { PlaintextEndpoint } from './endpoints/plaintext';
import { CognitionTextEndpoint } from './endpoints/cognition-text';
+import { CognitionPresignedEndpoint } from './endpoints/cognition-presigned';
import { SearchTextEndpoint } from './endpoints/search-text';
import { MarkdownEndpoint } from './endpoints/markdown';
@@ -27,9 +28,9 @@ app.use('/plaintext/*', async (c, next) => {
});
app.use('/cognition/*', async (c, next) => {
- const authKey = c.req.header('x-internal-auth-key');
+ const authKey = c.req.header("x-internal-auth-key");
if (!authKey || authKey !== c.env.INTERNAL_AUTH_KEY) {
- return c.json({ error: 'Unauthorized' }, 401);
+ return c.json({ error: "Unauthorized" }, 401);
}
await next();
});
@@ -71,6 +72,7 @@ const openapi = fromHono(app, {
openapi.get('/health', (c) => c.json({ message: 'Healthy' }));
openapi.get('/plaintext/:docId', PlaintextEndpoint);
+openapi.get('/cognition/presigned', CognitionPresignedEndpoint);
openapi.get('/cognition/:docId', CognitionTextEndpoint);
openapi.get('/search/:docId', SearchTextEndpoint);
openapi.get('/markdown/:docId', MarkdownEndpoint);
diff --git a/rust/cloud-storage/lexical_client/src/parse_markdown.rs b/rust/cloud-storage/lexical_client/src/parse_markdown.rs
index 8982951897..94d1a33cfd 100644
--- a/rust/cloud-storage/lexical_client/src/parse_markdown.rs
+++ b/rust/cloud-storage/lexical_client/src/parse_markdown.rs
@@ -70,6 +70,34 @@ impl LexicalClient {
response.json().await.context("unexpected response")
}
+
+ /// Parse markdown content from a presigned URL (for documents not in sync-service)
+ #[tracing::instrument(skip(self), err)]
+ pub async fn parse_markdown_for_ai_from_url(
+ &self,
+ presigned_url: &str,
+ ) -> Result<CognitionResponseData> {
+ let full_url = format!("{}/cognition/presigned", self.url);
+ let response = self
+ .client
+ .get(&full_url)
+ .query(&[("url", presigned_url)])
+ .send()
+ .await?;
+
+ let status_code = response.status();
+ if status_code != reqwest::StatusCode::OK {
+ let body: String = response.text().await?;
+ tracing::error!(
+ body=%body,
+ status=%status_code,
+ "unexpected response from lexical service while parsing presigned URL content"
+ );
+ anyhow::bail!(body);
+ }
+
+ response.json().await.context("unexpected response")
+ }
}
#[cfg(test)]
diff --git a/rust/cloud-storage/scribe/src/document/fetcher.rs b/rust/cloud-storage/scribe/src/document/fetcher.rs
index 04aa94e830..0e89fe4b48 100644
--- a/rust/cloud-storage/scribe/src/document/fetcher.rs
+++ b/rust/cloud-storage/scribe/src/document/fetcher.rs
@@ -244,18 +244,37 @@ impl<L: Debug, D: Debug> DocumentFetcher<L, D> {
&self.document_id,
models_properties::EntityType::Task,
)
- .await?;
+ .await;
+ if let Err(e) = &properties {
+ tracing::warn!(error=?e, location=?location, "no properties found for md");
+ }
- self.inner_lexical
- .parse_markdown_for_ai(&self.document_id)
- .await
- .map(|content| DocumentContent {
- properties: Some(properties),
- data: Data::Markdown(content),
- document_id: self.document_id.clone(),
- location: location.clone(),
- file_type: FileType::Md,
- })
+ // Choose endpoint based on document location
+ let content = match location {
+ LocationResponseV3::PresignedUrl { presigned_url, .. } => {
+ // Document is in S3, use presigned URL endpoint
+ self.inner_lexical
+ .parse_markdown_for_ai_from_url(presigned_url)
+ .await?
+ }
+ LocationResponseV3::SyncServiceContent { .. } => {
+ // Document is in sync-service, use standard endpoint
+ self.inner_lexical
+ .parse_markdown_for_ai(&self.document_id)
+ .await?
+ }
+ LocationResponseV3::PresignedUrls { .. } => {
+ anyhow::bail!("Multi-part presigned URLs not supported for markdown documents")
+ }
+ };
+
+ Ok(DocumentContent {
+ properties: properties.ok(),
+ data: Data::Markdown(content),
+ document_id: self.document_id.clone(),
+ location: location.clone(),
+ file_type: FileType::Md,
+ })
}
}