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: safer optimistic task creation (backend-first) (#5717)

Wolf Mermelsteinbc874007318d
diff --git a/apps/web/src/features/block-email/util/decodeBase64.ts b/apps/web/src/features/block-email/util/decodeBase64.ts
index 0f8fee863f..c2b9d51d8d 100644
--- a/apps/web/src/features/block-email/util/decodeBase64.ts
+++ b/apps/web/src/features/block-email/util/decodeBase64.ts
@@ -1,16 +1,8 @@
-function normalizeBase64String(input: string): string {
- const replaced = input.replace(/-/g, '+').replace(/_/g, '/');
- const padding = (4 - (replaced.length % 4)) % 4;
- return replaced + '='.repeat(padding);
-}
+import { decodeBase64Bytes } from '@core/util/base64';
export function decodeBase64Utf8(input: string): string {
try {
- const normalized = normalizeBase64String(input);
- const binary = atob(normalized);
- const bytes = new Uint8Array(binary.length);
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
- return new TextDecoder('utf-8').decode(bytes);
+ return new TextDecoder('utf-8').decode(decodeBase64Bytes(input));
} catch {
return input;
}
diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsx
index 3dd38545a5..1db1f9c674 100644
--- a/apps/web/src/features/block-md/component/ComposeTask.tsx
+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx
@@ -27,7 +27,6 @@ import { useUserId } from '@core/context/user';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { buildSimpleEntityUrl } from '@core/util/url';
import { mergeRegister } from '@lexical/utils';
-import { markdownToLoroSnapshot } from '@macro-inc/lexical-core/markdown-loro-snapshot';
import ArrowSquareOutIcon from '@phosphor/arrow-square-out.svg';
import ArrowsOutIcon from '@phosphor/arrows-out.svg';
import PaperclipIcon from '@phosphor/paperclip.svg';
@@ -559,7 +558,7 @@ export function ComposeTask(props: ComposeTaskProps) {
);
props.onCreateStart?.({ title: taskTitle, content: taskContent });
- const documentId = await createTaskWithProperties(
+ const createdTask = await createTaskWithProperties(
taskTitle,
taskContent,
properties,
@@ -569,7 +568,7 @@ export function ComposeTask(props: ComposeTaskProps) {
setIsCreating(false);
- if (!documentId) {
+ if (!createdTask) {
props.onCreateFailure?.();
// Restore the draft and re-open so the user can retry
saveTaskComposerDraft(draftSnapshot);
@@ -577,11 +576,11 @@ export function ComposeTask(props: ComposeTaskProps) {
return;
}
- const optimisticSnapshot = await markdownToLoroSnapshot(taskContent);
+ const { documentId, initialSnapshot } = createdTask;
if (props.onSuccess) {
props.onSuccess({ documentId, title: taskTitle, content: taskContent });
} else {
- showTaskCreatedToast(documentId, optimisticSnapshot);
+ showTaskCreatedToast(documentId, initialSnapshot);
}
props.onCreateTask?.(taskTitle, taskContent);
return;
@@ -590,7 +589,7 @@ export function ComposeTask(props: ComposeTaskProps) {
resetTitleAndBody();
setIsCreating(false);
- const documentId = await createTaskWithProperties(
+ const createdTask = await createTaskWithProperties(
taskTitle,
taskContent,
properties,
@@ -598,17 +597,17 @@ export function ComposeTask(props: ComposeTaskProps) {
(params) => upsertToHistoryMutation.mutate(params)
);
- if (!documentId) {
+ if (!createdTask) {
return;
}
// Success: clear draft and notify
clearTaskComposerDraft();
- const optimisticSnapshot = await markdownToLoroSnapshot(taskContent);
+ const { documentId, initialSnapshot } = createdTask;
if (props.onSuccess) {
props.onSuccess({ documentId, title: taskTitle, content: taskContent });
} else {
- showTaskCreatedToast(documentId, optimisticSnapshot);
+ showTaskCreatedToast(documentId, initialSnapshot);
}
props.onCreateTask?.(taskTitle, taskContent);
};
@@ -638,7 +637,7 @@ export function ComposeTask(props: ComposeTaskProps) {
{ referredFrom: 'launcher', preferNewSplit: true }
);
- const documentId = await createTaskWithProperties(
+ const createdTask = await createTaskWithProperties(
taskTitle,
taskContent,
properties,
@@ -648,16 +647,19 @@ export function ComposeTask(props: ComposeTaskProps) {
setIsCreating(false);
- if (!documentId) {
+ if (!createdTask) {
split?.goBack();
saveTaskComposerDraft(draftSnapshot);
popoverSplit({ type: 'component', id: 'task-compose' });
return;
}
- const optimisticSnapshot = await markdownToLoroSnapshot(taskContent);
- const snapshotParams = optimisticSnapshot
- ? { params: { optimisticSnapshot }, preserveParams: true as const }
+ const { documentId, initialSnapshot } = createdTask;
+ const snapshotParams = initialSnapshot
+ ? {
+ params: { optimisticSnapshot: initialSnapshot },
+ preserveParams: true as const,
+ }
: {};
if (split) {
diff --git a/apps/web/src/features/block-md/util/taskComposerProperties.ts b/apps/web/src/features/block-md/util/taskComposerProperties.ts
index c92088dc05..b41796a85a 100644
--- a/apps/web/src/features/block-md/util/taskComposerProperties.ts
+++ b/apps/web/src/features/block-md/util/taskComposerProperties.ts
@@ -1,5 +1,5 @@
import { toast } from '@core/component/Toast/Toast';
-import { createTask } from '@core/util/create';
+import { createTaskWithInitialSnapshot } from '@core/util/create';
import { filterMap } from '@core/util/list';
import {
propertyApiValuesToNormalized,
@@ -80,27 +80,27 @@ export async function createTaskWithProperties(
return [{ propertyId: id, value: apiValue }];
});
- const documentId = await createTask({
+ const createdTask = await createTaskWithInitialSnapshot({
title: taskTitle,
content: taskContent,
propertyValues: propertyValues.length > 0 ? propertyValues : undefined,
});
- if (!documentId) {
+ if (!createdTask) {
toast.failure('Failed to create Task');
return null;
}
// refetchSoupEntity is already called inside createTask — just upsert to history
- refetchSoupEntity(documentId, 'document');
+ refetchSoupEntity(createdTask.documentId, 'document');
// Upsert the new task to history
upsertToHistory({
- itemId: documentId,
+ itemId: createdTask.documentId,
itemType: 'document',
});
- return documentId;
+ return createdTask;
}
/**
diff --git a/apps/web/src/features/channel/Input/TaskComposer.tsx b/apps/web/src/features/channel/Input/TaskComposer.tsx
index 75ebd88ef3..b087f0a941 100644
--- a/apps/web/src/features/channel/Input/TaskComposer.tsx
+++ b/apps/web/src/features/channel/Input/TaskComposer.tsx
@@ -185,7 +185,7 @@ export function TaskComposer(props: {
const taskProperties = structuredClone(
Object.entries(unwrap(propertyValues))
);
- const documentId = await createTaskWithProperties(
+ const createdTask = await createTaskWithProperties(
taskTitle,
taskContent,
taskProperties,
@@ -195,9 +195,13 @@ export function TaskComposer(props: {
setIsCreating(false);
// createTaskWithProperties surfaces its own failure toast; keep the
// draft so the user can retry.
- if (!documentId) return;
+ if (!createdTask) return;
resetComposer();
- props.onSend({ documentId, title: taskTitle, content: taskContent });
+ props.onSend({
+ documentId: createdTask.documentId,
+ title: taskTitle,
+ content: taskContent,
+ });
};
const [attachHotkeys, composerHotkeyScope] = useHotkeyDOMScope(
diff --git a/apps/web/src/lib/core/util/base64.test.ts b/apps/web/src/lib/core/util/base64.test.ts
new file mode 100644
index 0000000000..a08af3ec8a
--- /dev/null
+++ b/apps/web/src/lib/core/util/base64.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+import { decodeBase64Bytes } from './base64';
+
+describe('decodeBase64Bytes', () => {
+ it('decodes standard base64', () => {
+ expect(decodeBase64Bytes('AAEC/w==')).toEqual(
+ new Uint8Array([0, 1, 2, 255])
+ );
+ });
+
+ it('decodes unpadded URL-safe base64', () => {
+ expect(decodeBase64Bytes('-_8')).toEqual(new Uint8Array([251, 255]));
+ });
+});
diff --git a/apps/web/src/lib/core/util/base64.ts b/apps/web/src/lib/core/util/base64.ts
new file mode 100644
index 0000000000..836ad9f333
--- /dev/null
+++ b/apps/web/src/lib/core/util/base64.ts
@@ -0,0 +1,7 @@
+/** Decode standard or URL-safe base64 into bytes. */
+export function decodeBase64Bytes(input: string): Uint8Array {
+ const replaced = input.replace(/-/g, '+').replace(/_/g, '/');
+ const padding = (4 - (replaced.length % 4)) % 4;
+ const binary = atob(replaced + '='.repeat(padding));
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
+}
diff --git a/apps/web/src/lib/core/util/create.ts b/apps/web/src/lib/core/util/create.ts
index 280060dd4c..f8dd292b7f 100644
--- a/apps/web/src/lib/core/util/create.ts
+++ b/apps/web/src/lib/core/util/create.ts
@@ -17,6 +17,7 @@ import type { PropertyInput } from '@service-storage/generated/schemas/propertyI
import { uploadToPresignedUrl } from '@service-storage/util/uploadToPresignedUrl';
import { err, ok } from 'neverthrow';
+import { decodeBase64Bytes } from './base64';
import { isPaymentError } from './handlePaymentError';
import { contentHash } from './hash';
import {
@@ -93,6 +94,29 @@ type CreateTaskArgs = {
export async function createTask(
args?: CreateTaskArgs
): Promise<string | undefined> {
+ return (await createTaskResponse(args))?.documentId;
+}
+
+/**
+ * Creates a task and returns the canonical snapshot used to initialize it.
+ */
+export async function createTaskWithInitialSnapshot(args?: CreateTaskArgs) {
+ const createdTask = await createTaskResponse(args);
+ if (!createdTask) return;
+
+ let initialSnapshot: Uint8Array | undefined;
+ if (typeof createdTask.initialSnapshot === 'string') {
+ try {
+ initialSnapshot = decodeBase64Bytes(createdTask.initialSnapshot);
+ } catch (error) {
+ console.error('Failed to decode initial task snapshot', error);
+ }
+ }
+
+ return { documentId: createdTask.documentId, initialSnapshot };
+}
+
+async function createTaskResponse(args?: CreateTaskArgs) {
// Ensure status is always set, defaulting to NOT_STARTED
const existingPropertyValues = args?.propertyValues ?? [];
const hasStatus = existingPropertyValues.some(
@@ -123,7 +147,7 @@ export async function createTask(
if (result.isErr()) return;
- const { documentId, documentMetadata, token } = result.value;
+ const { documentId, documentMetadata, token, initialSnapshot } = result.value;
seedDocumentLoadBundle(documentId, {
documentMetadata,
@@ -159,7 +183,7 @@ export async function createTask(
),
});
- return documentId;
+ return { documentId, initialSnapshot };
}
type CreateSnippetArgs = {
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createTaskHandler200.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createTaskHandler200.ts
index 5492d6a2b1..1536125b34 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createTaskHandler200.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createTaskHandler200.ts
@@ -17,6 +17,8 @@ export type CreateTaskHandler200 = {
documentId: string;
/** Metadata for the created document */
documentMetadata: DocumentResponseMetadata;
+ /** Base64-encoded canonical Loro snapshot used to initialize the task. */
+ initialSnapshot: string;
/** The team this task number is scoped to. */
teamId?: CreateTaskHandler200TeamId;
/** The task number assigned within the team. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createTaskResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createTaskResponse.ts
index e7b11fec15..249b312517 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createTaskResponse.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createTaskResponse.ts
@@ -17,6 +17,8 @@ export interface CreateTaskResponse {
documentId: string;
/** Metadata for the created document */
documentMetadata: DocumentResponseMetadata;
+ /** Base64-encoded canonical Loro snapshot used to initialize the task. */
+ initialSnapshot: string;
/** The team this task number is scoped to. */
teamId?: CreateTaskResponseTeamId;
/** The task number assigned within the team. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 605a21778c..6784d426b7 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -4913,6 +4913,11 @@ export const createTaskHandlerResponse = zod
.nullish()
.describe('The time the document instance \/ document BOM was updated'),
}),
+ initialSnapshot: zod
+ .string()
+ .describe(
+ 'Base64-encoded canonical Loro snapshot used to initialize the task.'
+ ),
teamId: zod
.uuid()
.nullish()
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index f521f8691e..8021b2e5cd 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -5671,7 +5671,12 @@
"schema": {
"type": "object",
"description": "Response for creating a task.",
- "required": ["documentId", "documentMetadata", "token"],
+ "required": [
+ "documentId",
+ "documentMetadata",
+ "token",
+ "initialSnapshot"
+ ],
"properties": {
"documentId": {
"type": "string",
@@ -5681,6 +5686,10 @@
"$ref": "#/components/schemas/DocumentResponseMetadata",
"description": "Metadata for the created document"
},
+ "initialSnapshot": {
+ "type": "string",
+ "description": "Base64-encoded canonical Loro snapshot used to initialize the task."
+ },
"teamId": {
"type": ["string", "null"],
"format": "uuid",
@@ -15254,7 +15263,12 @@
"CreateTaskResponse": {
"type": "object",
"description": "Response for creating a task.",
- "required": ["documentId", "documentMetadata", "token"],
+ "required": [
+ "documentId",
+ "documentMetadata",
+ "token",
+ "initialSnapshot"
+ ],
"properties": {
"documentId": {
"type": "string",
@@ -15264,6 +15278,10 @@
"$ref": "#/components/schemas/DocumentResponseMetadata",
"description": "Metadata for the created document"
},
+ "initialSnapshot": {
+ "type": "string",
+ "description": "Base64-encoded canonical Loro snapshot used to initialize the task."
+ },
"teamId": {
"type": ["string", "null"],
"format": "uuid",
diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.toml
index 200a8f30c5..5a8c9d2c9c 100644
--- a/crates/documents/Cargo.toml
+++ b/crates/documents/Cargo.toml
@@ -33,6 +33,7 @@ attachment = [
axum = [
"dep:axum",
"dep:axum-extra",
+ "dep:base64",
"dep:jsonwebtoken",
"dep:lexical_client",
"dep:macro_authorization",
diff --git a/crates/documents/src/bin/backfill_markdown_content_location.rs b/crates/documents/src/bin/backfill_markdown_content_location.rs
index 527efc453e..7207e119a7 100644
--- a/crates/documents/src/bin/backfill_markdown_content_location.rs
+++ b/crates/documents/src/bin/backfill_markdown_content_location.rs
@@ -225,7 +225,7 @@ impl MarkdownInitializationPort for OptionalMarkdownInitializer {
&self,
document_id: &str,
markdown: &str,
- ) -> Result<(), DocumentError> {
+ ) -> Result<Vec<u8>, DocumentError> {
match self {
Self::Disabled => Err(DocumentError::Internal(anyhow::anyhow!(
"markdown initializer disabled"
diff --git a/crates/documents/src/domain/create/mod.rs b/crates/documents/src/domain/create/mod.rs
index fc8c627de0..aff8a5effc 100644
--- a/crates/documents/src/domain/create/mod.rs
+++ b/crates/documents/src/domain/create/mod.rs
@@ -413,11 +413,22 @@ impl NewTextFileDocument {
#[derive(Debug)]
pub struct CreatedDocument {
response: CreateDocumentResponseData,
+ initial_snapshot: Option<Vec<u8>>,
}
impl CreatedDocument {
fn new(response: CreateDocumentResponseData) -> Self {
- Self { response }
+ Self {
+ response,
+ initial_snapshot: None,
+ }
+ }
+
+ fn new_markdown(response: CreateDocumentResponseData, initial_snapshot: Vec<u8>) -> Self {
+ Self {
+ response,
+ initial_snapshot: Some(initial_snapshot),
+ }
}
/// The created document id.
@@ -435,6 +446,11 @@ impl CreatedDocument {
&self.response
}
+ /// Get the canonical snapshot used to initialize a markdown document.
+ pub fn initial_snapshot(&self) -> Option<&[u8]> {
+ self.initial_snapshot.as_deref()
+ }
+
/// Consume into the raw create response.
pub fn into_response(self) -> CreateDocumentResponseData {
self.response
@@ -583,7 +599,8 @@ where
.await?;
}
- self.markdown_initializer
+ let initial_snapshot = self
+ .markdown_initializer
.initialize_existing_markdown(&document_id, &markdown)
.await?;
@@ -594,19 +611,22 @@ where
)
.await?;
- Ok(())
+ Ok(initial_snapshot)
}
.await;
- if let Err(error) = finalize_result {
- self.cleanup_created_document(&document_id).await;
- return Err(error);
- }
+ let initial_snapshot = match finalize_result {
+ Ok(initial_snapshot) => initial_snapshot,
+ Err(error) => {
+ self.cleanup_created_document(&document_id).await;
+ return Err(error);
+ }
+ };
response.document_response.document_metadata.content =
DocumentContent::ready(DocumentContentLocation::SyncService);
- Ok(CreatedDocument::new(response))
+ Ok(CreatedDocument::new_markdown(response, initial_snapshot))
}
/// Create a text file and upload it to document storage.
diff --git a/crates/documents/src/domain/markdown_backfill.rs b/crates/documents/src/domain/markdown_backfill.rs
index f6cfa040a7..1abb06e549 100644
--- a/crates/documents/src/domain/markdown_backfill.rs
+++ b/crates/documents/src/domain/markdown_backfill.rs
@@ -340,7 +340,7 @@ where
.initialize_existing_markdown(&candidate.id, &markdown)
.await
{
- Ok(()) => CandidateResult::Initialized,
+ Ok(_) => CandidateResult::Initialized,
Err(error) if sync_snapshot_already_exists(&error) => CandidateResult::Initialized,
Err(error) => CandidateResult::InitializeError {
error: error.to_string(),
diff --git a/crates/documents/src/domain/models.rs b/crates/documents/src/domain/models.rs
index df5ae3e918..55b68d80f0 100644
--- a/crates/documents/src/domain/models.rs
+++ b/crates/documents/src/domain/models.rs
@@ -477,6 +477,8 @@ pub struct CreateTaskResponse {
pub document_metadata: DocumentResponseMetadata,
/// A pre-generated permission token that you can use for SS
pub token: String,
+ /// Base64-encoded canonical Loro snapshot used to initialize the task.
+ pub initial_snapshot: String,
/// The team this task number is scoped to.
#[serde(skip_serializing_if = "Option::is_none")]
pub team_id: Option<uuid::Uuid>,
diff --git a/crates/documents/src/domain/ports/markdown.rs b/crates/documents/src/domain/ports/markdown.rs
index bbbf722f61..1f5da33e80 100644
--- a/crates/documents/src/domain/ports/markdown.rs
+++ b/crates/documents/src/domain/ports/markdown.rs
@@ -6,12 +6,12 @@ use crate::domain::models::DocumentError;
/// Initializes markdown document content in the collaborative editor backend.
pub trait MarkdownInitializationPort: Send + Sync {
- /// Initialize an already-created markdown document from markdown text.
+ /// Initialize an already-created markdown document and return the canonical snapshot.
fn initialize_existing_markdown(
&self,
document_id: &str,
markdown: &str,
- ) -> impl Future<Output = Result<(), DocumentError>> + Send;
+ ) -> impl Future<Output = Result<Vec<u8>, DocumentError>> + Send;
}
/// Utilities from the lexical service
diff --git a/crates/documents/src/domain/upload_finalize.rs b/crates/documents/src/domain/upload_finalize.rs
index 8ff79ca1b1..acef966af3 100644
--- a/crates/documents/src/domain/upload_finalize.rs
+++ b/crates/documents/src/domain/upload_finalize.rs
@@ -198,7 +198,7 @@ where
.initialize_existing_markdown(&document_context.document_id, markdown)
.await
{
- Ok(()) => {}
+ Ok(_) => {}
Err(error) if sync_snapshot_already_exists(&error) => {}
Err(error) => return Err(error),
}
diff --git a/crates/documents/src/inbound/axum_router/create_task.rs b/crates/documents/src/inbound/axum_router/create_task.rs
index debe73c0f2..dfb1374a1d 100644
--- a/crates/documents/src/inbound/axum_router/create_task.rs
+++ b/crates/documents/src/inbound/axum_router/create_task.rs
@@ -1,6 +1,7 @@
//! Handler for `POST /documents/create_task`.
use axum::{Json, extract::State};
+use base64::Engine;
use entity_access::domain::models::MemberTeamRole;
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::{
@@ -80,6 +81,12 @@ pub async fn create_task_handler<
let task_metadata = &created.response().document_response.document_metadata;
let document_id = created.document_id().to_string();
+ let initial_snapshot = created.initial_snapshot().ok_or_else(|| {
+ DocumentError::Internal(anyhow::anyhow!(
+ "markdown creation did not return its initial snapshot"
+ ))
+ })?;
+ let initial_snapshot = base64::engine::general_purpose::STANDARD.encode(initial_snapshot);
spawn_task_duplicate_detection(
state.task_dedup_service.clone(),
state.lexical_client.clone(),
@@ -110,6 +117,7 @@ pub async fn create_task_handler<
document_id,
document_metadata: task_metadata.metadata.clone(),
token,
+ initial_snapshot,
team_id: task_metadata.team_id,
team_task_id: task_metadata.team_task_id,
}))
diff --git a/crates/documents/src/outbound/markdown_init.rs b/crates/documents/src/outbound/markdown_init.rs
index de61de2d57..1f05c5f1a4 100644
--- a/crates/documents/src/outbound/markdown_init.rs
+++ b/crates/documents/src/outbound/markdown_init.rs
@@ -66,7 +66,7 @@ where
&self,
document_id: &str,
markdown: &str,
- ) -> Result<(), DocumentError> {
+ ) -> Result<Vec<u8>, DocumentError> {
let loro_snapshot = if markdown.is_empty() {
MARKDOWN_GOLDEN_SNAPSHOT.into()
} else {
@@ -78,6 +78,7 @@ where
let sync_service_client = self.sync_service_client.clone();
let document_id = document_id.to_owned();
+ let initial_snapshot = loro_snapshot.clone();
tokio::spawn(async move {
const MAX_ATTEMPTS: usize = 3;
const RETRY_DELAY: Duration = Duration::from_secs(1);
@@ -111,7 +112,7 @@ where
}
});
- Ok(())
+ Ok(initial_snapshot)
}
}
@@ -132,10 +133,11 @@ mod tests {
.returning(|_, _| Box::pin(async { Ok(()) }));
let initializer = LexicalSyncMarkdownInitializer::new(lexical, sync);
- initializer
+ let snapshot = initializer
.initialize_existing_markdown("doc1", "")
.await
.unwrap();
+ assert_eq!(snapshot, MARKDOWN_GOLDEN_SNAPSHOT);
}
#[tokio::test]
@@ -154,9 +156,10 @@ mod tests {
.returning(|_, _| Box::pin(async { Ok(()) }));
let initializer = LexicalSyncMarkdownInitializer::new(lexical, sync);
- initializer
+ let snapshot = initializer
.initialize_existing_markdown("doc2", "# hi")
.await
.unwrap();
+ assert_eq!(snapshot, [1, 2, 3]);
}
}
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index dc371d35ee..6cb3e7ab69 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -2979,6 +2979,10 @@ export type CreateTaskResponse = {
* Metadata for the created document
*/
documentMetadata: DocumentResponseMetadata;
+ /**
+ * Base64-encoded canonical Loro snapshot used to initialize the task.
+ */
+ initialSnapshot: string;
/**
* The team this task number is scoped to.
*/
@@ -10468,6 +10472,10 @@ export type CreateTaskHandlerResponses = {
* Metadata for the created document
*/
documentMetadata: DocumentResponseMetadata;
+ /**
+ * Base64-encoded canonical Loro snapshot used to initialize the task.
+ */
+ initialSnapshot: string;
/**
* The team this task number is scoped to.
*/
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index f521f8691e..8021b2e5cd 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -5671,7 +5671,12 @@
"schema": {
"type": "object",
"description": "Response for creating a task.",
- "required": ["documentId", "documentMetadata", "token"],
+ "required": [
+ "documentId",
+ "documentMetadata",
+ "token",
+ "initialSnapshot"
+ ],
"properties": {
"documentId": {
"type": "string",
@@ -5681,6 +5686,10 @@
"$ref": "#/components/schemas/DocumentResponseMetadata",
"description": "Metadata for the created document"
},
+ "initialSnapshot": {
+ "type": "string",
+ "description": "Base64-encoded canonical Loro snapshot used to initialize the task."
+ },
"teamId": {
"type": ["string", "null"],
"format": "uuid",
@@ -15254,7 +15263,12 @@
"CreateTaskResponse": {
"type": "object",
"description": "Response for creating a task.",
- "required": ["documentId", "documentMetadata", "token"],
+ "required": [
+ "documentId",
+ "documentMetadata",
+ "token",
+ "initialSnapshot"
+ ],
"properties": {
"documentId": {
"type": "string",
@@ -15264,6 +15278,10 @@
"$ref": "#/components/schemas/DocumentResponseMetadata",
"description": "Metadata for the created document"
},
+ "initialSnapshot": {
+ "type": "string",
+ "description": "Base64-encoded canonical Loro snapshot used to initialize the task."
+ },
"teamId": {
"type": ["string", "null"],
"format": "uuid",