Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: collab surface (#5654)
Eric Hayes85db53132ead
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex adebd361e5..bd89dde815 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -1495,6 +1495,87 @@"crates/webhook_signature","crates/workspace-hack"],+ "collab_surface": [+ "crates/activity",+ "crates/agent",+ "crates/agent_fold",+ "crates/agent_runtime_protocol",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment",+ "crates/authentication_service_client",+ "crates/bot_id",+ "crates/bot_token",+ "crates/broadcast",+ "crates/call",+ "crates/channel_sender",+ "crates/channels",+ "crates/collab_surface",+ "crates/connection",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts",+ "crates/cowlike",+ "crates/crm",+ "crates/document_sub_type",+ "crates/email",+ "crates/email_utils",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_access_management",+ "crates/entity_mutation",+ "crates/filter_ast",+ "crates/frecency",+ "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_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/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_notifications",+ "crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_entity_access_management",+ "crates/models_opensearch",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/models_properties",+ "crates/models_search",+ "crates/models_search_cursor",+ "crates/models_soup",+ "crates/non_empty",+ "crates/notification",+ "crates/opensearch_client",+ "crates/opensearch_query_builder",+ "crates/prompt",+ "crates/properties",+ "crates/rate_limit",+ "crates/reminders",+ "crates/remote_env_var",+ "crates/share_permission_db_utils",+ "crates/sqs_worker",+ "crates/sync_service",+ "crates/sync_service_client",+ "crates/system_properties",+ "crates/unfurl",+ "crates/workspace-hack"+ ],"comms_db_client": ["crates/activity","crates/agent",@@ -2241,6 +2322,7 @@"crates/channel_sender","crates/channels","crates/chat",+ "crates/collab_surface","crates/comms_db_client","crates/complete_graph","crates/connection",diff --git a/.sqlx/query-1bd25788e7c41cb8dca1963c6109ced1880bb935721d1413fb1668e4d5930e6f.json b/.sqlx/query-1bd25788e7c41cb8dca1963c6109ced1880bb935721d1413fb1668e4d5930e6f.jsonnew file mode 100644index 0000000000..390098c530--- /dev/null+++ b/.sqlx/query-1bd25788e7c41cb8dca1963c6109ced1880bb935721d1413fb1668e4d5930e6f.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE collab_surfaces\n SET deleted_at = now(), updated_at = now()\n WHERE id = $1 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "1bd25788e7c41cb8dca1963c6109ced1880bb935721d1413fb1668e4d5930e6f"+}diff --git a/.sqlx/query-3333c704ff808a5ea7608b45ee8193347a344b04ea23ab784e9355cbd2b38689.json b/.sqlx/query-3333c704ff808a5ea7608b45ee8193347a344b04ea23ab784e9355cbd2b38689.jsonnew file mode 100644index 0000000000..14673affb3--- /dev/null+++ b/.sqlx/query-3333c704ff808a5ea7608b45ee8193347a344b04ea23ab784e9355cbd2b38689.json@@ -0,0 +1,52 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, parent_entity_type, parent_entity_id, state, created_at, updated_at\n FROM collab_surfaces\n WHERE id = $1 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "parent_entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "parent_entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "3333c704ff808a5ea7608b45ee8193347a344b04ea23ab784e9355cbd2b38689"+}diff --git a/.sqlx/query-37f798658d9f6b76800239ddc98eafd64ce5699e573eed0cbaeeb1c7e3e48f9a.json b/.sqlx/query-37f798658d9f6b76800239ddc98eafd64ce5699e573eed0cbaeeb1c7e3e48f9a.jsonnew file mode 100644index 0000000000..37fb53ff4d--- /dev/null+++ b/.sqlx/query-37f798658d9f6b76800239ddc98eafd64ce5699e573eed0cbaeeb1c7e3e48f9a.json@@ -0,0 +1,53 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, parent_entity_type, parent_entity_id, state, created_at, updated_at\n FROM collab_surfaces\n WHERE parent_entity_type = $1 AND parent_entity_id = $2 AND deleted_at IS NULL\n ORDER BY created_at, id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "parent_entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "parent_entity_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "state",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "37f798658d9f6b76800239ddc98eafd64ce5699e573eed0cbaeeb1c7e3e48f9a"+}diff --git a/.sqlx/query-59b9abcc8ea0cbbc0af9640cf2da9fc9641f75b73d8ce92e36675a5395df5137.json b/.sqlx/query-59b9abcc8ea0cbbc0af9640cf2da9fc9641f75b73d8ce92e36675a5395df5137.jsonnew file mode 100644index 0000000000..23d5e5c696--- /dev/null+++ b/.sqlx/query-59b9abcc8ea0cbbc0af9640cf2da9fc9641f75b73d8ce92e36675a5395df5137.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO collab_surfaces\n (id, parent_entity_type, parent_entity_id, state, created_at, updated_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Text",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "59b9abcc8ea0cbbc0af9640cf2da9fc9641f75b73d8ce92e36675a5395df5137"+}diff --git a/.sqlx/query-baf08af5ac2a601faa3cc32c96de78ddf03aa06abff07bde9b583df951030bf5.json b/.sqlx/query-baf08af5ac2a601faa3cc32c96de78ddf03aa06abff07bde9b583df951030bf5.jsonnew file mode 100644index 0000000000..3d61ff4dba--- /dev/null+++ b/.sqlx/query-baf08af5ac2a601faa3cc32c96de78ddf03aa06abff07bde9b583df951030bf5.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE collab_surfaces\n SET state = 'ready', updated_at = now()\n WHERE id = $1 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "baf08af5ac2a601faa3cc32c96de78ddf03aa06abff07bde9b583df951030bf5"+}diff --git a/Cargo.lock b/Cargo.lockindex 440b291378..e0d7eded65 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3467,6 +3467,38 @@ dependencies = ["workspace-hack",]+[[package]]+name = "collab_surface"+version = "0.1.0"+dependencies = [+ "axum",+ "chrono",+ "entity_access",+ "lexical_client",+ "macro_authorization",+ "macro_db_migrator",+ "macro_sync_service_jwt",+ "macro_user_id",+ "macro_uuid",+ "mockall",+ "model",+ "model-entity",+ "model-error-response",+ "models_permissions",+ "rootcause",+ "serde",+ "serde_json",+ "sqlx",+ "sync_service_client",+ "thiserror 2.0.18",+ "tokio",+ "tokio-retry",+ "tracing",+ "utoipa",+ "uuid",+ "workspace-hack",+]+[[package]]name = "color_quant"version = "1.1.0"@@ -4908,6 +4940,7 @@ dependencies = ["chrono","clap","cloudfront_sign",+ "collab_surface","comms_db_client","complete_graph","connection",diff --git a/Cargo.toml b/Cargo.tomlindex 3c2d35aac1..64fb351212 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -20,6 +20,7 @@ members = ["crates/client/cache-wasm","crates/client/turso-opfs","crates/coding_agent_worker",+ "crates/collab_surface","crates/complete_graph","crates/cowlike","crates/crm",diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex 2ea3e5c2be..5ae966fef2 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -752,6 +752,12 @@ if (DEV_MODE_ENV) {() => import('@core/component/LexicalMarkdown/builder/BuilderTestPage')));+ registerComponent(+ 'collab-surface-demo',+ withAuth(+ lazy(() => import('@core/collab-surface/debug/CollabSurfaceDemoPage'))+ )+ );}// Icon gallerydiff --git a/apps/web/src/features/block-md/component/MarkdownCollabProvider.tsx b/apps/web/src/features/block-md/component/MarkdownCollabProvider.tsxindex 5c7adefea5..405e5531e6 100644--- a/apps/web/src/features/block-md/component/MarkdownCollabProvider.tsx+++ b/apps/web/src/features/block-md/component/MarkdownCollabProvider.tsx@@ -1,77 +1,24 @@import { markdownBlockErrorSignal } from '@block-md/signal/error';-import {- $convertLexicalSelectionToCursors,- $createSelectionFromPeerAwareness,-} from '@core/component/LexicalMarkdown/collaboration/cursor';-import {- type LexicalSelectionAwareness,- lexicalSelectionCodec,-} from '@core/component/LexicalMarkdown/collaboration/LexicalAwareness';-import { $reconcileLexicalState } from '@core/component/LexicalMarkdown/collaboration/reconcile';-import { useRemoteCursors } from '@core/component/LexicalMarkdown/collaboration/remote-cursor';+import { CollabProvider } from '@core/component/LexicalMarkdown/collaboration/CollabProvider';import type { MarkdownEditorErrors } from '@core/component/LexicalMarkdown/constants';import type { PluginManager } from '@core/component/LexicalMarkdown/plugins';-import {- initializeEditorEmpty,- initializeEditorWithVersionedState,- isStateEmpty,- loroSyncState,-} from '@core/component/LexicalMarkdown/utils';-import { useUserId } from '@core/context/user';import { blockSourceSignal, blockSyncSourceSignal } from '@core/signal/load';import { useCanComment, useCanEdit } from '@core/signal/permissions';import { isSourceSyncService } from '@core/util/source';-import {- $isCodeHighlightNode,- $isCodeNode,- CodeHighlightNode,- CodeNode,-} from '@lexical/code';-import { mergeRegister } from '@lexical/utils';-import { createAwareness } from '@macro-inc/collaboration/collab/awareness';-import { createSyncEngine } from '@macro-inc/collaboration/collab/engine';-import { logSyncService } from '@macro-inc/collaboration/collab/logger';import type { LoroManager } from '@macro-inc/collaboration/collab/manager';-import {- IDBSnapshotStore,- LORO_SNAPSHOT_DB_NAME,-} from '@macro-inc/collaboration/collab/snapshot-store';-import { createWALSyncSource } from '@macro-inc/collaboration/collab/wal';-import {- $isCustomCodeNode,- $updateAllNodeIds,- COLLABORATION_TAG,- CustomCodeNode,- LOCAL_STATUS_TAG,- type NodeIdMappings,- SKIP_DOM_SELECTION_TAG,- SKIP_SCROLL_INTO_VIEW_TAG,-} from '@macro-inc/lexical-core';-import type { NodeKey, UpdateListenerPayload } from 'lexical';-import {- $addUpdateTag,- $getNodeByKey,- $getSelection,- $isRangeSelection,- $setSelection,- COMMAND_PRIORITY_NORMAL,- createCommand,- type EditorState,- type LexicalEditor,- type SerializedEditorState,-} from 'lexical';-import {- type Accessor,- createEffect,- createSignal,- on,- onCleanup,- type Setter,-} from 'solid-js';+import type { NodeIdMappings } from '@macro-inc/lexical-core';+import type { LexicalEditor } from 'lexical';+import type { Accessor, Setter } from 'solid-js';import { endDocumentSpan, resumeDocumentSpan } from '../observability';import { CollabStatus } from './CollabStatus';-type MutatedNodes = UpdateListenerPayload['mutatedNodes'];+// The sync tags and force-sync command live with the generic provider now;+// re-exported here so existing md-block imports keep working.+export {+ CODE_HIGHLIGHT_IDS_TAG,+ FORCE_SYNC_COMMAND,+ FROM_LORO_TAG,+} from '@core/component/LexicalMarkdown/collaboration/CollabProvider';export type MarkdownCollabProviderProps = {editor: LexicalEditor;@@ -85,489 +32,42 @@ export type MarkdownCollabProviderProps = {loroManager: LoroManager;};-export const FROM_LORO_TAG = 'from-loro';-export const CODE_HIGHLIGHT_IDS_TAG = 'code-highlight-ids-tag';--export const FORCE_SYNC_COMMAND = createCommand<void>('FORCE_SYNC_COMMAND');-+/**+ * The md block's collaboration wiring: the generic {@link CollabProvider}+ * fed from block-scoped signals (sync source, permissions, error state) and+ * the block's document tracing spans, with the CollabStatus chrome.+ */export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {- const [didFirstSync, setDidFirstSync] = createSignal(false);const docSource = blockSourceSignal.get;- const loroManager = props.loroManager;const syncSource = blockSyncSourceSignal.get;- const userId = useUserId();const canEdit = useCanEdit();const canComment = useCanComment();const [editorError] = markdownBlockErrorSignal;- if (!syncSource()) return null;-- const awareness = createAwareness(- loroManager.peerIdStr,- userId(),- lexicalSelectionCodec,- {- timeout: 5_000,- }- );-- const readOnly = () => !(canEdit() || canComment());-- const walSyncer = createWALSyncSource(syncSource()!);- const syncEngine = createSyncEngine({- loroManager,- awareness,- syncs: { wal: walSyncer, live: syncSource()! },- bindings: {- onRemoteState: (state) =>- syncStateToLexical(state as unknown as SerializedEditorState),- },- readonly: readOnly,- snapshotStore: new IDBSnapshotStore(- LORO_SNAPSHOT_DB_NAME,- syncSource()!.documentId- ),- });-- const { refreshRemoteCursors, RemoteCursorsOverlay } = useRemoteCursors({- loroManager: loroManager,- mapping: props.mappings,- editor: props.editor,- awareness: awareness,- });-- /**- * Responsible for syncing incoming state from the loro manager to the lexical editor- *- * @param state - The state to sync to the lexical editor- */- function syncStateToLexical(state: SerializedEditorState) {- if (!syncEngine.isRunning()) {- console.warn('tried to sync state to lexical, but engine is not running');- return;- }- const hadFocus = props.editorFocus();- let manager = loroManager;- if (!manager) {- console.error(- 'registering sync state to lexical, but no manager -- this should never happen'- );- return;- }-- props.editor.update(- () => {- $addUpdateTag(SKIP_DOM_SELECTION_TAG);- $addUpdateTag(COLLABORATION_TAG);-- let selectionFormat = 0;- const selection = $getSelection();- if ($isRangeSelection(selection)) {- selectionFormat = selection.format;- }-- // Clear the selection first- $setSelection(null);-- // Reconcile the new lexical state with the current one- // This uses the stable nodeIds to determine which nodes have changed- // and need to be updated.- $reconcileLexicalState(- props.editor.getEditorState().toJSON(),- state,- props.mappings,- () => loroManager.peerIdStr- );-- // Queue microtask after this `editor.update` to ensure that all the nodeIds are updated- queueMicrotask(() => {- props.editor.update(() => {- $updateAllNodeIds(props.mappings);- // If we import a remote update, it's possible that the update- // has shifted out own selection / cursor. We need to re-position our local- // cursor based on the new lexical state using the stable LoroCursor.- let localAwareness = awareness.local();- if (localAwareness.selection) {- if (!hadFocus) {- $addUpdateTag(SKIP_DOM_SELECTION_TAG);- }- $addUpdateTag(SKIP_SCROLL_INTO_VIEW_TAG);- $createSelectionFromPeerAwareness(- manager,- props.editor,- localAwareness.selection,- props.mappings,- selectionFormat- );- }- });- });- },- {- discrete: true,- tag: FROM_LORO_TAG,- onUpdate: () => {- refreshRemoteCursors();- },- }- );- }-- /** Convert the current local selection to a loro cursor */- function localCursorUpdate():- | { awareness: LexicalSelectionAwareness; format: number }- | undefined {- if (!loroManager) {- console.error(- 'tried to convert selection to cursor, but no loro manager'- );- return;- }-- props.editor.read(() => {- const selection = $getSelection();-- if (!selection) {- return;- }-- // Convert the current selection to a set of LoroCursors- const cursors = $convertLexicalSelectionToCursors(- loroManager,- props.mappings,- selection- );-- if (!cursors) {- console.warn(- 'MarkdownCollabProvider: Failed to convert selection to cursors'- );- return;- }-- let localSelection: LexicalSelectionAwareness = {- anchor: cursors.anchor,- focus: cursors.focus,- };-- let format = $isRangeSelection(selection) ? selection.format : 0;-- // Update the local awareness with the new cursors- // If a engine is configured, it will sync the local awareness to other peers- awareness.updateLocalAwareness(localSelection);- return {- awareness,- format,- };- });- }-- /** Handle the cursor state after successful sync from Lexical->Loro */- function $afterSyncCursorUpdate(manager: LoroManager) {- // Update the local cursor after the state has been synced- let newLocalSelection = localCursorUpdate();-- if (newLocalSelection) {- $addUpdateTag(SKIP_SCROLL_INTO_VIEW_TAG);- $createSelectionFromPeerAwareness(- manager,- props.editor,- newLocalSelection.awareness,- props.mappings,- newLocalSelection.format- );- }-- // Refresh / re-render the remote cursors- // to put them in the correct positions- refreshRemoteCursors();- }-- /**- * Enforce an extra nodeId pass over the state if the incoming mutations are code syntax highlights. When a- * line of code changes, Lexical:- * 1) Creates or appends to the current text node children of the code node- * 2) Runs the code node line-by-line through PrismJS to get tokens- * 3) Upgrades to code highlight nodes using the new tokens with the skipTransforms flag set to true - so our- * id-assigning node transform does not run on new highlights. This pass enforces ids before making it to Loro.- * @param mutatedNodes- * @returns True if code highlight mutations were found and a node id update was manually triggered.- */- function codeNodeUpdateHandler(mutatedNodes: MutatedNodes): boolean {- if (!mutatedNodes || mutatedNodes.size === 0) {- return false;- }-- const nodeKeysToUpdate = new Set<NodeKey>();- for (const [klass, mutations] of mutatedNodes) {- if (- klass === CodeHighlightNode ||- klass === CodeNode ||- klass === CustomCodeNode- ) {- for (const [nodeKey, mutationType] of mutations) {- if (mutationType !== 'destroyed') {- nodeKeysToUpdate.add(nodeKey);- }- }- }- }-- if (nodeKeysToUpdate.size > 0) {- props.editor.update(- () => {- const parentNodes = new Set<CodeNode | CustomCodeNode>();- for (const key of nodeKeysToUpdate) {- const node = $getNodeByKey(key);- if ($isCodeNode(node) || $isCustomCodeNode(node)) {- parentNodes.add(node);- continue;- }- if ($isCodeHighlightNode(node)) {- const parent = node.getParent();- if ($isCodeNode(parent) || $isCustomCodeNode(parent)) {- parentNodes.add(parent);- }- }- }- for (const node of parentNodes) {- $updateAllNodeIds(props.mappings, node);- }- },- {- discrete: true,- tag: CODE_HIGHLIGHT_IDS_TAG,- onUpdate: async () => {- const stateToSync = loroSyncState(props.editor.getEditorState());- await syncEngine.syncStateToLoro(stateToSync as any);- $afterSyncCursorUpdate(loroManager);- },- }- );- }- return nodeKeysToUpdate.size > 0;- }-- async function syncLexicalToLoro(- state: EditorState,- mutatedNodes: MutatedNodes,- tags: Set<string>- ) {- if (!syncEngine.isRunning()) {- console.warn(- 'tried to sync lexical state to loro, but engine is not running'- );- return;- }- if (!loroManager) {- console.error(- 'registering sync state to lexical, but no manager -- this should never happen'- );- return;- }- // State updates tagged with 'FROM_LORO' are from the syncToLexical function- // and should not be synced to the loroManager. This would cause an infinite loop.- // LOCAL_STATUS_TAG updates carry only per-peer ownership state, which is- // resolved independently on each client — producers of this tag must not- // mutate node content in the same update, or those changes will be dropped here.- if (- tags.has(FROM_LORO_TAG) ||- tags.has(COLLABORATION_TAG) ||- tags.has(LOCAL_STATUS_TAG) ||- tags.has(CODE_HIGHLIGHT_IDS_TAG)- ) {- return false;- }-- if (!didFirstSync()) {- return false;- }-- // Only sync state if there are changes- if (mutatedNodes && mutatedNodes.size > 0) {- // Do not try to send any state to Loro until code highlight ids have resolved.- if (codeNodeUpdateHandler(mutatedNodes)) {- return false;- }-- // Clean the state to remove any state properties that should not be synced- const stateToSync = loroSyncState(state);- await syncEngine.syncStateToLoro(stateToSync as any);- }-- $afterSyncCursorUpdate(loroManager);- }-- function lexicalStateSyncPlugin() {- return mergeRegister(- props.editor.registerUpdateListener(- ({ editorState, tags, mutatedNodes }) => {- syncLexicalToLoro(editorState, mutatedNodes, tags);- return false;- }- ),- props.editor.registerCommand(- FORCE_SYNC_COMMAND,- () => {- const stateToSync = loroSyncState(props.editor.getEditorState());- syncEngine.syncStateToLoro(stateToSync as any);- return true;- },- COMMAND_PRIORITY_NORMAL- )- );- }-- function startSync() {- syncEngine.start();- props.pluginManager.use(lexicalStateSyncPlugin);- }-- const [managerInitialized, setManagerInitialized] = createSignal(- loroManager.initialized- );- onCleanup(loroManager.onInitializedChange(setManagerInitialized));-- /** Initializes the loroManager and starts the sync engine */- createEffect(- on(- () => managerInitialized() ?? false,- (isInitialized) => {- if (!isInitialized) {- logSyncService({- documentId: syncSource()?.documentId ?? 'unknown',- level: 'debug',- context: {},- message: 'MarkdownCollabProvider: manager not yet initialized',- });- return;- }-- const source = docSource();- if (!source) {- logSyncService({- documentId: syncSource()?.documentId ?? 'unknown',- level: 'debug',- context: {},- message: 'editor init: no docSource yet, waiting (skeleton stays)',- });- return;- }- if (isSourceSyncService(source)) {- // Get the current state from the loroManager- // At this point, the loroManager should be initialized and should- // have the initial state from the sync service- const state = loroManager.state;- const empty = state- ? isStateEmpty(state.state as unknown as SerializedEditorState)- : undefined;-- logSyncService({- documentId: syncSource()!.documentId,- level: 'info',- context: { misc: { hasState: !!state, isEmpty: empty } },- message:- 'MarkdownCollabProvider: manager initialized, initializing editor',- });-- //TODO: some more descriptive user facing error should be displayed here- if (!state) {- logSyncService({- documentId: syncSource()!.documentId,- level: 'error',- context: {},- message:- 'editor init: no state from loroManager — editor will NOT become ready (skeleton stays)',- });- endDocumentSpan(syncSource()!.documentId);- return;- }-- // Indicate that we have completed the first sync- setDidFirstSync(true);-- // Initialize the editor with the initial state from the sync service- if (empty) {- logSyncService({- documentId: syncSource()!.documentId,- level: 'debug',- context: {},- message: 'editor init: empty',- });- initializeEditorEmpty(props.editor);- } else {- logSyncService({- documentId: syncSource()!.documentId,- level: 'debug',- context: {},- message: 'editor init: versioned state',- });- const initError = initializeEditorWithVersionedState(- props.editor,- state.state as unknown as SerializedEditorState,- () => loroManager.peerIdStr- );- if (initError !== null) {- logSyncService({- documentId: syncSource()!.documentId,- level: 'error',- context: { misc: { initError } },- message:- 'editor init: initializeEditorWithVersionedState failed',- });- props.setEditorError(initError);- endDocumentSpan(syncSource()!.documentId);- return;- }- }-- // Start the sync engine- startSync();- props.setEditorReady(true);- const documentId = syncSource()!.documentId;- resumeDocumentSpan(documentId)?.event('editor.ready');- endDocumentSpan(documentId);- logSyncService({- documentId: syncSource()!.documentId,- level: 'info',- context: {},- message: 'editor ready (skeleton cleared)',- });- } else {- logSyncService({- documentId: syncSource()?.documentId ?? 'unknown',- level: 'debug',- context: {},- message:- 'editor init: source is not sync-service, skipping editor init (skeleton stays)',- });- }- }- )- );-- createEffect(- on(editorError, () => {- if (editorError() !== null) {- syncEngine.stop();- }- })- );-- onCleanup(() => {- syncEngine.stop();- walSyncer.destroy();- const documentId = syncSource()?.documentId;- if (documentId) endDocumentSpan(documentId);- });-return (- <>- <RemoteCursorsOverlay- anchorElem={props.editorContainerRef}- highlightLayer={props.highlighLayerRef}- />- <CollabStatus />- </>+ <CollabProvider+ editor={props.editor}+ pluginManager={props.pluginManager}+ editorContainerRef={props.editorContainerRef}+ highlightLayerRef={props.highlighLayerRef}+ mappings={props.mappings}+ editorFocus={props.editorFocus}+ setEditorReady={props.setEditorReady}+ setEditorError={props.setEditorError}+ loroManager={props.loroManager}+ syncSource={syncSource}+ sourceReady={() => {+ const source = docSource();+ return !!source && isSourceSyncService(source);+ }}+ canEdit={canEdit}+ canComment={canComment}+ editorError={editorError}+ observability={{+ resumeSpan: resumeDocumentSpan,+ endSpan: endDocumentSpan,+ }}+ statusChrome={<CollabStatus />}+ />);}diff --git a/apps/web/src/lib/core/collab-surface/CollabMdSurface.tsx b/apps/web/src/lib/core/collab-surface/CollabMdSurface.tsxnew file mode 100644index 0000000000..98c13a40b6--- /dev/null+++ b/apps/web/src/lib/core/collab-surface/CollabMdSurface.tsx@@ -0,0 +1,333 @@+import { CollabProvider } from '@core/component/LexicalMarkdown/collaboration/CollabProvider';+import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';+import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';+import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu';+import { SnippetsMenu } from '@core/component/LexicalMarkdown/component/menu/SnippetsMenu';+import {+ getErrorDescription,+ type MarkdownEditorErrors,+} from '@core/component/LexicalMarkdown/constants';+import {+ createLexicalWrapper,+ LexicalWrapperContext,+} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';+import {+ awaitPlugin,+ DefaultShortcuts,+ documentMetadataPlugin,+ keyboardShortcutsPlugin,+ markdownPastePlugin,+ mentionsPlugin,+ textPastePlugin,+} from '@core/component/LexicalMarkdown/plugins';+import { emojisPlugin } from '@core/component/LexicalMarkdown/plugins/emojis/emojisPlugin';+import { snippetsPlugin } from '@core/component/LexicalMarkdown/plugins/snippets';+import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';+import {+ editorFocusSignal,+ editorIsEmpty,+ initializeEditorEmpty,+} from '@core/component/LexicalMarkdown/utils';+import {+ AwaitNode,+ CommentNode,+ createPeerIdValidator,+ InlineSearchNode,+ peerIdPlugin,+} from '@macro-inc/lexical-core';+import { onElementConnect } from '@solid-primitives/lifecycle';+import type { LexicalEditor } from 'lexical';+import {+ type Accessor,+ createEffect,+ createSignal,+ type JSX,+ onCleanup,+ Show,+} from 'solid-js';+import { useBlockCollabParent } from './blockParent';+import {+ type CollabSurfaceSessionOptions,+ createCollabSurfaceSession,+} from './createCollabSurface';++/** Imperative handle for embedding surfaces in composer-style UIs. */+export type CollabMdSurfaceControls = {+ /** The current content, serialized to markdown. */+ getMarkdown: () => string;+ /**+ * Clear the surface for everyone. This is a normal collaborative edit: it+ * syncs through Loro, so every connected peer's surface empties.+ */+ clear: () => void;+ /** Focus the editor. */+ focus: () => void;+ /** The underlying Lexical editor, for registering commands (e.g. submit-on-enter). */+ getLexical: () => LexicalEditor;+ /**+ * Whether an inline menu (mentions, emoji, snippets) is open. Submit-on-enter+ * handlers must not fire while one is — Enter belongs to the menu.+ */+ isInlineMenuOpen: () => boolean;+};++export type CollabMdSurfaceProps = {+ /**+ * The stable, caller-supplied surface id (a uuid). The component+ * load-or-creates: the first mount anywhere ensures the surface exists,+ * every later mount joins the same session.+ */+ surfaceId: string;+ /** Markdown seed used only if this mount creates the surface. */+ initialMarkdown?: string;+ /**+ * Whether the caller may edit. UI-only: the server enforces the real+ * permission via the connection token's access level, so a lying caller+ * merely gets its updates rejected. Defaults to editable.+ */+ canEdit?: Accessor<boolean>;+ /** Whether the caller may comment. Defaults to false. */+ canComment?: Accessor<boolean>;+ /** See {@link CollabSurfaceSessionOptions.optimisticSnapshot}. */+ optimisticSnapshot?: Uint8Array;+ /** Lexical namespace, for devtools disambiguation. */+ namespace?: string;+ /** Class applied to the outer container. */+ class?: string;+ /** Placeholder shown while the surface is empty. */+ placeholder?: string;+ /** Called once the editor is live (initial state applied, engine running). */+ onReady?: () => void;+ /** Receives the imperative controls once, at mount. */+ onControls?: (controls: CollabMdSurfaceControls) => void;+ /** Called when the editor enters an error state. */+ onError?: (error: MarkdownEditorErrors) => void;+ /** Optional status UI rendered by the collab provider. */+ statusChrome?: JSX.Element;+};++/**+ * A self-contained collaborative markdown surface: give it a `surfaceId` and+ * it renders a live multi-user Lexical editor synced through sync-service —+ * remote edits merge in real time, cursors render for other peers, offline+ * edits buffer in the WAL, and state persists in the surface's Loro session.+ *+ * The primitive intentionally excludes block chrome: no comments margin, no+ * history UI, no presence header (pass `statusChrome` for that).+ */+export function CollabMdSurface(props: CollabMdSurfaceProps) {+ const canEdit = props.canEdit ?? (() => true);+ const canComment = props.canComment ?? (() => false);++ // The parent entity is always the enclosing block's entity (a channel+ // block ⇒ that channel, an md/task block ⇒ that document); throws when+ // mounted outside a block or in a block with no entity mapping.+ const parent = useBlockCollabParent();++ const session = createCollabSurfaceSession(props.surfaceId, {+ parent,+ initialMarkdown: props.initialMarkdown,+ optimisticSnapshot: props.optimisticSnapshot,+ });+ onCleanup(session.dispose);++ const [editorReady, setEditorReady] = createSignal(false);+ const [editorError, setEditorError] =+ createSignal<MarkdownEditorErrors | null>(null);+ const [editorHasNoContent, setEditorHasNoContent] = createSignal(false);++ const isContentEditable = () => canEdit() && !editorError();++ const lexicalWrapper = createLexicalWrapper({+ type: 'markdown-sync',+ namespace: props.namespace ?? 'collab-surface',+ isInteractable: isContentEditable,+ withIds: true,+ });+ const { editor, plugins, cleanup: cleanupPlugins } = lexicalWrapper;+ onCleanup(cleanupPlugins);++ const [editorFocus, setEditorFocus] = createSignal(false);+ editorFocusSignal(editor, setEditorFocus);++ // Markdown-serialized view of the editor state, for `controls.getMarkdown`.+ const [markdownState, setMarkdownState] = createSignal('');++ const mentionsMenuOperations = createMenuOperations();+ const emojiMenuOperations = createMenuOperations();+ const snippetsMenuOperations = createMenuOperations();++ // Collab is the point of this component, so the validator is always live:+ // it keeps this peer from committing another peer's in-flight inline nodes+ // (mentions, emoji searches, snippets).+ const peerId = () => session.loroManager.peerIdStr;+ const peerIdValidator = createPeerIdValidator(peerId, true);++ plugins+ .richText()+ .list()+ .markdownShortcuts()+ .delete()+ .state<string>(setMarkdownState, 'markdown')+ .history(400, session.loroManager)+ .use(+ emojisPlugin({+ menu: emojiMenuOperations,+ peerIdValidator,+ })+ )+ .use(+ mentionsPlugin({+ menu: mentionsMenuOperations,+ peerIdValidator,+ sourceDocumentId: props.surfaceId,+ disableMentionTracking: true,+ })+ )+ .use(+ snippetsPlugin({+ menu: snippetsMenuOperations,+ peerIdValidator,+ sourceDocumentId: props.surfaceId,+ })+ )+ .use(textPastePlugin())+ .use(markdownPastePlugin())+ .use(awaitPlugin())+ .use(+ keyboardShortcutsPlugin({+ shortcuts: DefaultShortcuts,+ })+ )+ .use(+ documentMetadataPlugin({+ onVersionError: (error) => setEditorError(error),+ })+ )+ .use(+ peerIdPlugin({+ peerId,+ nodes: [InlineSearchNode, CommentNode, AwaitNode],+ })+ );++ createEffect(() => {+ editor.setEditable(canEdit());+ });++ props.onControls?.({+ getMarkdown: () => markdownState(),+ clear: () => initializeEditorEmpty(editor, peerId),+ focus: () => editor.focus(),+ getLexical: () => editor,+ isInlineMenuOpen: () =>+ mentionsMenuOperations.isOpen() ||+ emojiMenuOperations.isOpen() ||+ snippetsMenuOperations.isOpen(),+ });++ createEffect(() => {+ if (editorReady()) props.onReady?.();+ });+ createEffect(() => {+ const error = editorError();+ if (error !== null) props.onError?.(error);+ });++ onCleanup(+ editor.registerUpdateListener(({ editorState }) => {+ setEditorHasNoContent(editorIsEmpty(editorState));+ })+ );++ let editorContainerRef!: HTMLDivElement;++ return (+ <LexicalWrapperContext.Provider value={lexicalWrapper}>+ <div class={props.class ?? ''}>+ <Show when={editorError()}>+ {(error) => (+ <div class="pointer-events-none text-alert-ink p-2 bg-alert-bg w-full border-alert/30 border mb-2">+ {getErrorDescription(error())}+ </div>+ )}+ </Show>+ <Show when={session.connectionError()}>+ <div class="text-alert-ink p-2 bg-alert-bg w-full border-alert/30 border mb-2">+ Failed to connect to this surface.+ </div>+ </Show>+ <div class="relative" ref={editorContainerRef}>+ <div+ ref={(el) => {+ onElementConnect(el, () => {+ editor.setRootElement(el);+ });+ }}+ contentEditable={isContentEditable()}+ class="w-full max-w-full outline-none"+ classList={{+ 'select-auto': !canEdit(),+ 'md-no-comments': true,+ }}+ />++ <Show when={!editorReady()}>+ <div class="absolute inset-0 flex flex-col gap-2 pointer-events-none">+ <div class="h-4 w-2/3 animate-pulse rounded bg-ink/10" />+ <div class="h-4 w-1/2 animate-pulse rounded bg-ink/10" />+ </div>+ </Show>++ <Show when={editorReady() && editorHasNoContent()}>+ <div class="pointer-events-none text-ink-placeholder absolute top-0">+ {props.placeholder ?? 'Start typing…'}+ </div>+ </Show>++ {/* The provider's syncSource check is non-reactive, so mount it only+ once the session's socket exists. */}+ <Show when={session.syncSource()}>+ <CollabProvider+ editor={editor}+ pluginManager={plugins}+ editorContainerRef={editorContainerRef}+ highlightLayerRef={editorContainerRef}+ mappings={lexicalWrapper.mapping!}+ editorFocus={editorFocus}+ setEditorReady={setEditorReady}+ setEditorError={setEditorError}+ loroManager={session.loroManager}+ syncSource={session.syncSource}+ sourceReady={() => true}+ canEdit={canEdit}+ canComment={canComment}+ editorError={editorError}+ statusChrome={props.statusChrome}+ />+ </Show>++ <DecoratorRenderer editor={editor} />++ <EmojiMenu+ editor={editor}+ menu={emojiMenuOperations}+ useBlockBoundary={false}+ />+ <MentionsMenu+ editor={editor}+ menu={mentionsMenuOperations}+ useBlockBoundary={false}+ disableMentionTracking={true}+ />+ <SnippetsMenu+ editor={editor}+ menu={snippetsMenuOperations}+ useBlockBoundary={false}+ sourceDocumentId={props.surfaceId}+ />+ </div>+ </div>+ </LexicalWrapperContext.Provider>+ );+}diff --git a/apps/web/src/lib/core/collab-surface/blockParent.ts b/apps/web/src/lib/core/collab-surface/blockParent.tsnew file mode 100644index 0000000000..b036827dcb--- /dev/null+++ b/apps/web/src/lib/core/collab-surface/blockParent.ts@@ -0,0 +1,56 @@+import {+ type BlockName,+ useMaybeBlockId,+ useMaybeBlockName,+} from '@core/block';+import type { CollabSurfaceParent } from './createCollabSurface';++/**+ * The parent entity type implied by hosting a surface inside a block of the+ * given name. A block's id is the entity id: document-backed blocks (md and+ * friends, incl. task/snippet/skill aliases) are `Document` rows; the rest map+ * to their own entity type.+ *+ * Absent entries (contact, company, automation, pr, unknown) have no+ * backend-supported parent type — a collab surface cannot be hosted in them.+ */+const BLOCK_PARENT_TYPE: Partial<+ Record<BlockName, CollabSurfaceParent['entityType']>+> = {+ md: 'document',+ write: 'document',+ pdf: 'document',+ code: 'document',+ image: 'document',+ canvas: 'document',+ video: 'document',+ channel: 'channel',+ project: 'project',+ chat: 'chat',+ email: 'email_thread',+ call: 'call',+};++/**+ * The collab-surface parent derived from the nearest enclosing block.+ *+ * @throws when used outside a Block component, or inside a block whose type+ * has no parent-entity mapping — a collab surface is always scoped to its+ * hosting block's entity, so both are programming errors.+ */+export function useBlockCollabParent(): CollabSurfaceParent {+ const id = useMaybeBlockId();+ const name = useMaybeBlockName();+ if (!id || !name) {+ throw new Error(+ 'CollabMdSurface must be mounted inside a Block component — its parent entity is derived from the enclosing block'+ );+ }+ const entityType = BLOCK_PARENT_TYPE[name];+ if (!entityType) {+ throw new Error(+ `CollabMdSurface cannot be hosted in a '${name}' block: no parent-entity mapping`+ );+ }+ return { entityType, entityId: id };+}diff --git a/apps/web/src/lib/core/collab-surface/createCollabSurface.ts b/apps/web/src/lib/core/collab-surface/createCollabSurface.tsnew file mode 100644index 0000000000..1c1f88d67b--- /dev/null+++ b/apps/web/src/lib/core/collab-surface/createCollabSurface.ts@@ -0,0 +1,193 @@+import type { LoroManager } from '@macro-inc/collaboration/collab/manager';+import { createLoroManager } from '@macro-inc/collaboration/collab/manager';+import type { RawUpdate } from '@macro-inc/collaboration/collab/shared';+import {+ IDBSnapshotStore,+ LORO_SNAPSHOT_DB_NAME,+} from '@macro-inc/collaboration/collab/snapshot-store';+import type { LiveSyncSource } from '@macro-inc/collaboration/collab/source';+import {+ BrowserWALStore,+ LORO_WAL_DB_NAME,+} from '@macro-inc/collaboration/collab/wal';+import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-schema';+import { storageServiceClient } from '@service-storage/client';+import type { CollabSurfaceResponse } from '@service-storage/service';+import { createCollabSurfaceSource } from '@service-sync/source';+import { type Accessor, createSignal } from 'solid-js';+import { getCollabSurfaceToken } from './token';++export type CollabSurfaceLoroManager = LoroManager<typeof MARKDOWN_LORO_SCHEMA>;++/** The parent entity a surface hangs off; all access derives from it. */+export type CollabSurfaceParent = {+ entityType: CollabSurfaceResponse['parentEntityType'];+ entityId: string;+};++export type CollabSurfaceSessionOptions = {+ /**+ * The surface's parent entity. The session idempotently ensures the surface+ * exists (load-or-create) before connecting, so a caller only needs a+ * stable id and the parent — no separate creation step.+ */+ parent: CollabSurfaceParent;+ /**+ * Markdown to seed the surface with if this ensure creates it. Ignored when+ * the surface already exists.+ */+ initialMarkdown?: string;+ /**+ * Snapshot to seed the editor with while waiting for local/remote state.+ * Loses the seed race gracefully if local or remote state lands first.+ */+ optimisticSnapshot?: Uint8Array;+};++export type CollabSurfaceSession = {+ surfaceId: string;+ loroManager: CollabSurfaceLoroManager;+ /**+ * The live sync source. Undefined until the initial connection token is+ * minted and the socket created — gate the collab provider on it.+ */+ syncSource: Accessor<LiveSyncSource | undefined>;+ /** Set when the session could not connect (e.g. token minting failed). */+ connectionError: Accessor<string | undefined>;+ /** Close the websocket. Call from `onCleanup`. */+ dispose: () => void;+};++/**+ * Ingest the local IDB snapshot plus any buffered WAL edits. Mirrors the md+ * block's local ingest (`Block.tsx`), including folding replayed WAL entries+ * into a fresh snapshot so a reload during recovery doesn't show stale state.+ */+async function ingestLocalSnapshot(+ loroManager: CollabSurfaceLoroManager,+ snapshotStore: IDBSnapshotStore<RawUpdate>,+ walStore: BrowserWALStore<RawUpdate>+): Promise<void> {+ const localSnapshot = await snapshotStore.load();+ if (!localSnapshot) return;+ const walEntries = await walStore.getAll();+ await loroManager.ingest({+ kind: 'local',+ snapshot: localSnapshot,+ walUpdates: walEntries.map((entry) => entry.update),+ });++ if (walEntries.length >= 1) {+ const doc = loroManager.doc;+ const snapshot = doc.export({+ mode: 'shallow-snapshot',+ frontiers: doc.oplogFrontiers(),+ });+ await snapshotStore.save(snapshot);+ }+}++/**+ * A live collaboration session for an arbitrary markdown surface,+ * load-or-create: give it a stable surface id plus its parent entity, and it+ * idempotently ensures the surface exists before connecting.+ *+ * Creates the Loro manager and local stores synchronously (so cached state can+ * seed the editor before the network round-trips), then ensures the surface,+ * mints a connection token, and opens the sync-service websocket. Three+ * snapshot sources race to seed the manager — optimistic (if provided), local+ * IDB+WAL, and the remote initial sync — and the manager ignores all but the+ * first.+ *+ * No S3 cached-snapshot ingest: `fetchCachedSnapshot` is a documents-only+ * route today. Add a fourth race entry here if surfaces grow a backend+ * snapshot cache.+ */+export function createCollabSurfaceSession(+ surfaceId: string,+ opts: CollabSurfaceSessionOptions+): CollabSurfaceSession {+ const loroManager = createLoroManager(MARKDOWN_LORO_SCHEMA, {+ documentId: surfaceId,+ });+ const snapshotStore = new IDBSnapshotStore<RawUpdate>(+ LORO_SNAPSHOT_DB_NAME,+ surfaceId+ );+ const walStore = new BrowserWALStore<RawUpdate>(LORO_WAL_DB_NAME, surfaceId);++ const [syncSource, setSyncSource] = createSignal<LiveSyncSource>();+ const [connectionError, setConnectionError] = createSignal<string>();+ let disposed = false;++ const optimisticSnapshot = opts.optimisticSnapshot;+ if (optimisticSnapshot) {+ void loroManager+ .ingest({ kind: 'optimistic', snapshot: optimisticSnapshot })+ .catch((error) => {+ console.error('collab surface: optimistic ingest failed', error);+ });+ }++ void ingestLocalSnapshot(loroManager, snapshotStore, walStore).catch(+ (error) => {+ console.error('collab surface: local snapshot ingest failed', error);+ }+ );++ void (async () => {+ // Load-or-create. Idempotent on the backend, so mounting the same+ // surface in several places (or racing another client) is fine.+ const ensured = await storageServiceClient.collabSurfaces.ensure({+ id: surfaceId,+ parentEntityType: opts.parent.entityType,+ parentEntityId: opts.parent.entityId,+ initialMarkdown: opts.initialMarkdown,+ });+ if (disposed) return;+ if (ensured.isErr()) {+ console.error('collab surface: ensure failed', ensured.error);+ setConnectionError('failed to load or create the surface');+ return;+ }++ const token = await getCollabSurfaceToken(surfaceId);+ if (disposed) return;+ if (!token) {+ setConnectionError('failed to mint a sync connection token');+ return;+ }++ const { source, doInitialSync } = createCollabSurfaceSource(+ surfaceId,+ token,+ () => getCollabSurfaceToken(surfaceId)+ );+ if (disposed) {+ source.cleanup();+ return;+ }+ setSyncSource(source);++ const sync = await doInitialSync();+ if (sync.isErr()) {+ console.error(+ 'collab surface: failed to receive initial sync',+ sync.error+ );+ return;+ }+ await loroManager.ingest({ kind: 'dss', snapshot: sync.value.snapshot });+ })();++ return {+ surfaceId,+ loroManager,+ syncSource,+ connectionError,+ dispose: () => {+ disposed = true;+ syncSource()?.cleanup();+ },+ };+}diff --git a/apps/web/src/lib/core/collab-surface/debug/CollabSurfaceDemoPage.tsx b/apps/web/src/lib/core/collab-surface/debug/CollabSurfaceDemoPage.tsxnew file mode 100644index 0000000000..9a25c21cc5--- /dev/null+++ b/apps/web/src/lib/core/collab-surface/debug/CollabSurfaceDemoPage.tsx@@ -0,0 +1,149 @@+import { Block, type BlockName } from '@core/block';+import { createSignal, Show } from 'solid-js';+import { CollabMdSurface } from '../CollabMdSurface';+import type { CollabSurfaceParent } from '../createCollabSurface';++/** The block type that hosts each parent entity type, for the demo's+ * stand-in Block wrapper (in the app the hosting block already exists). */+const BLOCK_FOR_PARENT: Partial<+ Record<CollabSurfaceParent['entityType'], BlockName>+> = {+ document: 'md',+ channel: 'channel',+ project: 'project',+ chat: 'chat',+ email_thread: 'email',+ call: 'call',+};++type Mounted = {+ surfaceId: string;+ parent: CollabSurfaceParent;+ initialMarkdown: string;+};++/**+ * Dev-only playground for the collab-surface primitive+ * (`collab-surface-demo` in the split-component registry).+ *+ * The component derives its parent from the enclosing block, so this page+ * wraps it in a stand-in `<Block>` for the entity you name (a document you+ * own, a channel you're in). Enter a stable surface id — generate a fresh+ * one, or paste one from another window to join its session. Open the same+ * id in two windows and type in both.+ */+export default function CollabSurfaceDemoPage() {+ const [parentType, setParentType] =+ createSignal<CollabSurfaceParent['entityType']>('document');+ const [parentId, setParentId] = createSignal('');+ const [surfaceId, setSurfaceId] = createSignal<string>(crypto.randomUUID());+ const [seedMarkdown, setSeedMarkdown] = createSignal('# Hello surface');+ const [mounted, setMounted] = createSignal<Mounted>();++ const open = () => {+ setMounted(undefined);+ // Re-mount on next tick so opening the same id twice re-creates the session.+ queueMicrotask(() =>+ setMounted({+ surfaceId: surfaceId().trim(),+ parent: { entityType: parentType(), entityId: parentId().trim() },+ initialMarkdown: seedMarkdown(),+ })+ );+ };++ return (+ <div class="flex flex-col gap-4 p-6 max-w-2xl mx-auto overflow-y-auto">+ <h1 class="text-lg font-semibold">Collab surface demo</h1>++ <div class="flex flex-col gap-2 border border-ink/10 rounded p-4">+ <label class="flex items-center gap-2 text-sm">+ Parent type+ <select+ class="border border-ink/20 rounded px-2 py-1 bg-transparent"+ value={parentType()}+ onChange={(e) =>+ setParentType(+ e.currentTarget.value as CollabSurfaceParent['entityType']+ )+ }+ >+ <option value="document">document</option>+ <option value="channel">channel</option>+ <option value="project">project</option>+ <option value="chat">chat</option>+ <option value="email_thread">email_thread</option>+ <option value="call">call</option>+ </select>+ </label>+ <label class="flex items-center gap-2 text-sm">+ Parent id+ <input+ class="border border-ink/20 rounded px-2 py-1 grow bg-transparent font-mono"+ placeholder="uuid of an entity you can access"+ value={parentId()}+ onInput={(e) => setParentId(e.currentTarget.value)}+ />+ </label>+ <label class="flex items-center gap-2 text-sm">+ Surface id+ <input+ class="border border-ink/20 rounded px-2 py-1 grow bg-transparent font-mono"+ value={surfaceId()}+ onInput={(e) => setSurfaceId(e.currentTarget.value)}+ />+ <button+ type="button"+ class="border border-ink/20 rounded px-3 py-1 text-sm hover:bg-ink/5"+ onClick={() => setSurfaceId(crypto.randomUUID())}+ >+ Generate+ </button>+ <button+ type="button"+ class="border border-ink/20 rounded px-3 py-1 text-sm hover:bg-ink/5"+ onClick={() => navigator.clipboard.writeText(surfaceId())}+ >+ Copy+ </button>+ </label>+ <label class="flex items-center gap-2 text-sm">+ Seed markdown+ <input+ class="border border-ink/20 rounded px-2 py-1 grow bg-transparent font-mono"+ value={seedMarkdown()}+ onInput={(e) => setSeedMarkdown(e.currentTarget.value)}+ />+ </label>+ <button+ type="button"+ class="self-start border border-ink/20 rounded px-3 py-1 text-sm hover:bg-ink/5 disabled:opacity-50"+ disabled={!parentId().trim() || !surfaceId().trim()}+ onClick={open}+ >+ Open (load or create)+ </button>+ </div>++ <Show when={mounted()} keyed>+ {(m) => (+ <div class="border border-ink/10 rounded p-4 min-h-64">+ <div class="text-xs text-ink-placeholder font-mono mb-2">+ {m.surfaceId}+ </div>+ <Block+ id={m.parent.entityId}+ name={BLOCK_FOR_PARENT[m.parent.entityType] ?? 'md'}+ >+ <CollabMdSurface+ surfaceId={m.surfaceId}+ initialMarkdown={m.initialMarkdown}+ placeholder="Type here…"+ />+ </Block>+ </div>+ )}+ </Show>+ </div>+ );+}diff --git a/apps/web/src/lib/core/collab-surface/token.ts b/apps/web/src/lib/core/collab-surface/token.tsnew file mode 100644index 0000000000..3f593e0bcf--- /dev/null+++ b/apps/web/src/lib/core/collab-surface/token.ts@@ -0,0 +1,36 @@+import { isTokenExpired } from '@core/signal/token';+import { storageServiceClient } from '@service-storage/client';++type Token = string;++/**+ * Cache of sync-service connection tokens per surface id. Mirrors the block+ * permission-token store (`@core/signal/token`): tokens are reused until 60s+ * before expiry, then re-minted.+ */+const surfaceTokenCache = new Map<string, Token>();++/**+ * A valid sync-service connection token for the surface, from cache or freshly+ * minted via `POST /collab_surfaces/{id}/token`. Undefined when minting fails+ * (no access, deleted surface, network error).+ */+export async function getCollabSurfaceToken(+ surfaceId: string+): Promise<string | undefined> {+ const cached = surfaceTokenCache.get(surfaceId);+ if (cached && !isTokenExpired(cached)) {+ return cached;+ }++ const response = await storageServiceClient.collabSurfaces.createToken({+ id: surfaceId,+ });+ if (response.isErr()) {+ console.error('failed to mint collab surface token', response.error);+ return undefined;+ }++ surfaceTokenCache.set(surfaceId, response.value.token);+ return response.value.token;+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/CollabProvider.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/CollabProvider.tsxnew file mode 100644index 0000000000..cafd47ff3f--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/collaboration/CollabProvider.tsx@@ -0,0 +1,594 @@+import {+ $convertLexicalSelectionToCursors,+ $createSelectionFromPeerAwareness,+} from '@core/component/LexicalMarkdown/collaboration/cursor';+import {+ type LexicalSelectionAwareness,+ lexicalSelectionCodec,+} from '@core/component/LexicalMarkdown/collaboration/LexicalAwareness';+import { $reconcileLexicalState } from '@core/component/LexicalMarkdown/collaboration/reconcile';+import { useRemoteCursors } from '@core/component/LexicalMarkdown/collaboration/remote-cursor';+import type { MarkdownEditorErrors } from '@core/component/LexicalMarkdown/constants';+import type { PluginManager } from '@core/component/LexicalMarkdown/plugins';+import {+ initializeEditorEmpty,+ initializeEditorWithVersionedState,+ isStateEmpty,+ loroSyncState,+} from '@core/component/LexicalMarkdown/utils';+import { useUserId } from '@core/context/user';+import {+ $isCodeHighlightNode,+ $isCodeNode,+ CodeHighlightNode,+ CodeNode,+} from '@lexical/code';+import { mergeRegister } from '@lexical/utils';+import { createAwareness } from '@macro-inc/collaboration/collab/awareness';+import { createSyncEngine } from '@macro-inc/collaboration/collab/engine';+import { logSyncService } from '@macro-inc/collaboration/collab/logger';+import type { LoroManager } from '@macro-inc/collaboration/collab/manager';+import {+ IDBSnapshotStore,+ LORO_SNAPSHOT_DB_NAME,+} from '@macro-inc/collaboration/collab/snapshot-store';+import type { LiveSyncSource } from '@macro-inc/collaboration/collab/source';+import { createWALSyncSource } from '@macro-inc/collaboration/collab/wal';+import {+ $isCustomCodeNode,+ $updateAllNodeIds,+ COLLABORATION_TAG,+ CustomCodeNode,+ LOCAL_STATUS_TAG,+ type NodeIdMappings,+ SKIP_DOM_SELECTION_TAG,+ SKIP_SCROLL_INTO_VIEW_TAG,+} from '@macro-inc/lexical-core';+import type { Span } from '@macro-inc/observability';+import type { NodeKey, UpdateListenerPayload } from 'lexical';+import {+ $addUpdateTag,+ $getNodeByKey,+ $getSelection,+ $isRangeSelection,+ $setSelection,+ COMMAND_PRIORITY_NORMAL,+ createCommand,+ type EditorState,+ type LexicalEditor,+ type SerializedEditorState,+} from 'lexical';+import {+ type Accessor,+ createEffect,+ createSignal,+ type JSX,+ on,+ onCleanup,+ type Setter,+} from 'solid-js';++type MutatedNodes = UpdateListenerPayload['mutatedNodes'];++/** Hooks into the caller's tracing, all optional. */+export type CollabObservability = {+ /** Resume the caller's open span for this session id, if any. */+ resumeSpan?: (id: string) => Span | undefined;+ /** End the caller's span for this session id. */+ endSpan?: (id: string) => void;+};++export type CollabProviderProps = {+ editor: LexicalEditor;+ pluginManager: PluginManager;+ editorContainerRef: HTMLDivElement;+ highlightLayerRef: HTMLDivElement;+ mappings: NodeIdMappings;+ editorFocus: Accessor<boolean>;+ setEditorReady: Setter<boolean>;+ setEditorError: Setter<MarkdownEditorErrors | null>;+ loroManager: LoroManager;+ /**+ * The live sync source for this session. Must be non-undefined by the time+ * the provider mounts — the check below is NOT reactive, so gate mounting+ * with `<Show when={syncSource()}>` (or equivalent) in the caller.+ */+ syncSource: Accessor<LiveSyncSource | undefined>;+ /**+ * Whether the content source has resolved to a live sync-service session.+ * The md block passes `isSourceSyncService(blockSource)`; standalone collab+ * surfaces are always live and pass `() => true`.+ */+ sourceReady: Accessor<boolean>;+ canEdit: Accessor<boolean | undefined>;+ canComment: Accessor<boolean | undefined>;+ /** External error state; the engine stops when it becomes non-null. */+ editorError: Accessor<MarkdownEditorErrors | null>;+ observability?: CollabObservability;+ /** Optional status UI (e.g. the md block's CollabStatus chrome). */+ statusChrome?: JSX.Element;+};++export const FROM_LORO_TAG = 'from-loro';+export const CODE_HIGHLIGHT_IDS_TAG = 'code-highlight-ids-tag';++export const FORCE_SYNC_COMMAND = createCommand<void>('FORCE_SYNC_COMMAND');++/**+ * Wires a Lexical editor to a Loro sync session, in both directions:+ * remote state is reconciled onto the live Lexical tree by stable node id,+ * and local updates are diffed into Loro via the sync engine (with WAL+ * buffering for offline edits). Also renders remote peer cursors.+ *+ * Generic over where the session came from — an md-block document or a+ * standalone collab surface — via `syncSource`/`sourceReady`/`canEdit`+ * accessors instead of block-scoped signals.+ */+export function CollabProvider(props: CollabProviderProps) {+ const [didFirstSync, setDidFirstSync] = createSignal(false);+ const loroManager = props.loroManager;+ const syncSource = props.syncSource;+ const userId = useUserId();++ if (!syncSource()) return null;++ const resumeSpan = (id: string): Span | undefined =>+ props.observability?.resumeSpan?.(id);+ const endSpan = (id: string): void => props.observability?.endSpan?.(id);++ const awareness = createAwareness(+ loroManager.peerIdStr,+ userId(),+ lexicalSelectionCodec,+ {+ timeout: 5_000,+ }+ );++ const readOnly = () => !(props.canEdit() || props.canComment());++ const walSyncer = createWALSyncSource(syncSource()!);+ const syncEngine = createSyncEngine({+ loroManager,+ awareness,+ syncs: { wal: walSyncer, live: syncSource()! },+ bindings: {+ onRemoteState: (state) =>+ syncStateToLexical(state as unknown as SerializedEditorState),+ },+ readonly: readOnly,+ snapshotStore: new IDBSnapshotStore(+ LORO_SNAPSHOT_DB_NAME,+ syncSource()!.documentId+ ),+ });++ const { refreshRemoteCursors, RemoteCursorsOverlay } = useRemoteCursors({+ loroManager: loroManager,+ mapping: props.mappings,+ editor: props.editor,+ awareness: awareness,+ });++ /**+ * Responsible for syncing incoming state from the loro manager to the lexical editor+ *+ * @param state - The state to sync to the lexical editor+ */+ function syncStateToLexical(state: SerializedEditorState) {+ if (!syncEngine.isRunning()) {+ console.warn('tried to sync state to lexical, but engine is not running');+ return;+ }+ const hadFocus = props.editorFocus();+ let manager = loroManager;+ if (!manager) {+ console.error(+ 'registering sync state to lexical, but no manager -- this should never happen'+ );+ return;+ }++ props.editor.update(+ () => {+ $addUpdateTag(SKIP_DOM_SELECTION_TAG);+ $addUpdateTag(COLLABORATION_TAG);++ let selectionFormat = 0;+ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ selectionFormat = selection.format;+ }++ // Clear the selection first+ $setSelection(null);++ // Reconcile the new lexical state with the current one+ // This uses the stable nodeIds to determine which nodes have changed+ // and need to be updated.+ $reconcileLexicalState(+ props.editor.getEditorState().toJSON(),+ state,+ props.mappings,+ () => loroManager.peerIdStr+ );++ // Queue microtask after this `editor.update` to ensure that all the nodeIds are updated+ queueMicrotask(() => {+ props.editor.update(() => {+ $updateAllNodeIds(props.mappings);+ // If we import a remote update, it's possible that the update+ // has shifted out own selection / cursor. We need to re-position our local+ // cursor based on the new lexical state using the stable LoroCursor.+ let localAwareness = awareness.local();+ if (localAwareness.selection) {+ if (!hadFocus) {+ $addUpdateTag(SKIP_DOM_SELECTION_TAG);+ }+ $addUpdateTag(SKIP_SCROLL_INTO_VIEW_TAG);+ $createSelectionFromPeerAwareness(+ manager,+ props.editor,+ localAwareness.selection,+ props.mappings,+ selectionFormat+ );+ }+ });+ });+ },+ {+ discrete: true,+ tag: FROM_LORO_TAG,+ onUpdate: () => {+ refreshRemoteCursors();+ },+ }+ );+ }++ /** Convert the current local selection to a loro cursor */+ function localCursorUpdate():+ | { awareness: LexicalSelectionAwareness; format: number }+ | undefined {+ if (!loroManager) {+ console.error(+ 'tried to convert selection to cursor, but no loro manager'+ );+ return;+ }++ props.editor.read(() => {+ const selection = $getSelection();++ if (!selection) {+ return;+ }++ // Convert the current selection to a set of LoroCursors+ const cursors = $convertLexicalSelectionToCursors(+ loroManager,+ props.mappings,+ selection+ );++ if (!cursors) {+ console.warn('CollabProvider: Failed to convert selection to cursors');+ return;+ }++ let localSelection: LexicalSelectionAwareness = {+ anchor: cursors.anchor,+ focus: cursors.focus,+ };++ let format = $isRangeSelection(selection) ? selection.format : 0;++ // Update the local awareness with the new cursors+ // If a engine is configured, it will sync the local awareness to other peers+ awareness.updateLocalAwareness(localSelection);+ return {+ awareness,+ format,+ };+ });+ }++ /** Handle the cursor state after successful sync from Lexical->Loro */+ function $afterSyncCursorUpdate(manager: LoroManager) {+ // Update the local cursor after the state has been synced+ let newLocalSelection = localCursorUpdate();++ if (newLocalSelection) {+ $addUpdateTag(SKIP_SCROLL_INTO_VIEW_TAG);+ $createSelectionFromPeerAwareness(+ manager,+ props.editor,+ newLocalSelection.awareness,+ props.mappings,+ newLocalSelection.format+ );+ }++ // Refresh / re-render the remote cursors+ // to put them in the correct positions+ refreshRemoteCursors();+ }++ /**+ * Enforce an extra nodeId pass over the state if the incoming mutations are code syntax highlights. When a+ * line of code changes, Lexical:+ * 1) Creates or appends to the current text node children of the code node+ * 2) Runs the code node line-by-line through PrismJS to get tokens+ * 3) Upgrades to code highlight nodes using the new tokens with the skipTransforms flag set to true - so our+ * id-assigning node transform does not run on new highlights. This pass enforces ids before making it to Loro.+ * @param mutatedNodes+ * @returns True if code highlight mutations were found and a node id update was manually triggered.+ */+ function codeNodeUpdateHandler(mutatedNodes: MutatedNodes): boolean {+ if (!mutatedNodes || mutatedNodes.size === 0) {+ return false;+ }++ const nodeKeysToUpdate = new Set<NodeKey>();+ for (const [klass, mutations] of mutatedNodes) {+ if (+ klass === CodeHighlightNode ||+ klass === CodeNode ||+ klass === CustomCodeNode+ ) {+ for (const [nodeKey, mutationType] of mutations) {+ if (mutationType !== 'destroyed') {+ nodeKeysToUpdate.add(nodeKey);+ }+ }+ }+ }++ if (nodeKeysToUpdate.size > 0) {+ props.editor.update(+ () => {+ const parentNodes = new Set<CodeNode | CustomCodeNode>();+ for (const key of nodeKeysToUpdate) {+ const node = $getNodeByKey(key);+ if ($isCodeNode(node) || $isCustomCodeNode(node)) {+ parentNodes.add(node);+ continue;+ }+ if ($isCodeHighlightNode(node)) {+ const parent = node.getParent();+ if ($isCodeNode(parent) || $isCustomCodeNode(parent)) {+ parentNodes.add(parent);+ }+ }+ }+ for (const node of parentNodes) {+ $updateAllNodeIds(props.mappings, node);+ }+ },+ {+ discrete: true,+ tag: CODE_HIGHLIGHT_IDS_TAG,+ onUpdate: async () => {+ const stateToSync = loroSyncState(props.editor.getEditorState());+ await syncEngine.syncStateToLoro(stateToSync as any);+ $afterSyncCursorUpdate(loroManager);+ },+ }+ );+ }+ return nodeKeysToUpdate.size > 0;+ }++ async function syncLexicalToLoro(+ state: EditorState,+ mutatedNodes: MutatedNodes,+ tags: Set<string>+ ) {+ if (!syncEngine.isRunning()) {+ console.warn(+ 'tried to sync lexical state to loro, but engine is not running'+ );+ return;+ }+ if (!loroManager) {+ console.error(+ 'registering sync state to lexical, but no manager -- this should never happen'+ );+ return;+ }+ // State updates tagged with 'FROM_LORO' are from the syncToLexical function+ // and should not be synced to the loroManager. This would cause an infinite loop.+ // LOCAL_STATUS_TAG updates carry only per-peer ownership state, which is+ // resolved independently on each client — producers of this tag must not+ // mutate node content in the same update, or those changes will be dropped here.+ if (+ tags.has(FROM_LORO_TAG) ||+ tags.has(COLLABORATION_TAG) ||+ tags.has(LOCAL_STATUS_TAG) ||+ tags.has(CODE_HIGHLIGHT_IDS_TAG)+ ) {+ return false;+ }++ if (!didFirstSync()) {+ return false;+ }++ // Only sync state if there are changes+ if (mutatedNodes && mutatedNodes.size > 0) {+ // Do not try to send any state to Loro until code highlight ids have resolved.+ if (codeNodeUpdateHandler(mutatedNodes)) {+ return false;+ }++ // Clean the state to remove any state properties that should not be synced+ const stateToSync = loroSyncState(state);+ await syncEngine.syncStateToLoro(stateToSync as any);+ }++ $afterSyncCursorUpdate(loroManager);+ }++ function lexicalStateSyncPlugin() {+ return mergeRegister(+ props.editor.registerUpdateListener(+ ({ editorState, tags, mutatedNodes }) => {+ syncLexicalToLoro(editorState, mutatedNodes, tags);+ return false;+ }+ ),+ props.editor.registerCommand(+ FORCE_SYNC_COMMAND,+ () => {+ const stateToSync = loroSyncState(props.editor.getEditorState());+ syncEngine.syncStateToLoro(stateToSync as any);+ return true;+ },+ COMMAND_PRIORITY_NORMAL+ )+ );+ }++ function startSync() {+ syncEngine.start();+ props.pluginManager.use(lexicalStateSyncPlugin);+ }++ const [managerInitialized, setManagerInitialized] = createSignal(+ loroManager.initialized+ );+ onCleanup(loroManager.onInitializedChange(setManagerInitialized));++ /** Initializes the loroManager and starts the sync engine */+ createEffect(+ on(+ () => managerInitialized() ?? false,+ (isInitialized) => {+ if (!isInitialized) {+ logSyncService({+ documentId: syncSource()?.documentId ?? 'unknown',+ level: 'debug',+ context: {},+ message: 'CollabProvider: manager not yet initialized',+ });+ return;+ }++ if (props.sourceReady()) {+ // Get the current state from the loroManager+ // At this point, the loroManager should be initialized and should+ // have the initial state from the sync service+ const state = loroManager.state;+ const empty = state+ ? isStateEmpty(state.state as unknown as SerializedEditorState)+ : undefined;++ logSyncService({+ documentId: syncSource()!.documentId,+ level: 'info',+ context: { misc: { hasState: !!state, isEmpty: empty } },+ message: 'CollabProvider: manager initialized, initializing editor',+ });++ //TODO: some more descriptive user facing error should be displayed here+ if (!state) {+ logSyncService({+ documentId: syncSource()!.documentId,+ level: 'error',+ context: {},+ message:+ 'editor init: no state from loroManager — editor will NOT become ready (skeleton stays)',+ });+ endSpan(syncSource()!.documentId);+ return;+ }++ // Indicate that we have completed the first sync+ setDidFirstSync(true);++ // Initialize the editor with the initial state from the sync service+ if (empty) {+ logSyncService({+ documentId: syncSource()!.documentId,+ level: 'debug',+ context: {},+ message: 'editor init: empty',+ });+ initializeEditorEmpty(props.editor, () => loroManager.peerIdStr);+ } else {+ logSyncService({+ documentId: syncSource()!.documentId,+ level: 'debug',+ context: {},+ message: 'editor init: versioned state',+ });+ const initError = initializeEditorWithVersionedState(+ props.editor,+ state.state as unknown as SerializedEditorState,+ () => loroManager.peerIdStr+ );+ if (initError !== null) {+ logSyncService({+ documentId: syncSource()!.documentId,+ level: 'error',+ context: { misc: { initError } },+ message:+ 'editor init: initializeEditorWithVersionedState failed',+ });+ props.setEditorError(initError);+ endSpan(syncSource()!.documentId);+ return;+ }+ }++ // Start the sync engine+ startSync();+ props.setEditorReady(true);+ const documentId = syncSource()!.documentId;+ resumeSpan(documentId)?.event('editor.ready');+ endSpan(documentId);+ logSyncService({+ documentId: syncSource()!.documentId,+ level: 'info',+ context: {},+ message: 'editor ready (skeleton cleared)',+ });+ } else {+ logSyncService({+ documentId: syncSource()?.documentId ?? 'unknown',+ level: 'debug',+ context: {},+ message:+ 'editor init: source is not sync-service, skipping editor init (skeleton stays)',+ });+ }+ }+ )+ );++ createEffect(+ on(props.editorError, () => {+ if (props.editorError() !== null) {+ syncEngine.stop();+ }+ })+ );++ onCleanup(() => {+ syncEngine.stop();+ walSyncer.destroy();+ const documentId = syncSource()?.documentId;+ if (documentId) endSpan(documentId);+ });++ return (+ <>+ <RemoteCursorsOverlay+ anchorElem={props.editorContainerRef}+ highlightLayer={props.highlightLayerRef}+ />+ {props.statusChrome}+ </>+ );+}diff --git a/apps/web/src/lib/core/signal/token.ts b/apps/web/src/lib/core/signal/token.tsindex 2e04ced7d4..35df6679af 100644--- a/apps/web/src/lib/core/signal/token.ts+++ b/apps/web/src/lib/core/signal/token.ts@@ -28,7 +28,11 @@ async function fetchNewToken(blockId: string) {return token.value.token;}-function isTokenExpired(token: string) {+/**+ * Whether a JWT expires within {@link EXPIRATION_THRESHOLD_SECONDS}. Treats an+ * unparseable token as expired.+ */+export function isTokenExpired(token: string) {try {const payload = JSON.parse(atob(token.split('.')[1]));const currentTime = Math.floor(Date.now() / 1000);diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex f4e319473c..38ea903276 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -167,6 +167,8 @@ import type { ItemType } from './itemType';export type { ItemType } from './itemType';import type {+ CollabSurfaceResponse,+ CollabSurfaceTokenResponse,GetDocumentPermissionsTokenResponse,ProcessingResultType,StorageServiceClient,@@ -1084,6 +1086,43 @@ export const storageServiceClient = {);},},++ collabSurfaces: {+ async ensure(args) {+ return await dssFetch<CollabSurfaceResponse>(+ `/collab_surfaces/${args.id}`,+ {+ method: 'PUT',+ body: JSON.stringify({+ parentEntityType: args.parentEntityType,+ parentEntityId: args.parentEntityId,+ initialMarkdown: args.initialMarkdown ?? '',+ }),+ }+ );+ },+ async get(args) {+ return await dssFetch<CollabSurfaceResponse>(+ `/collab_surfaces/${args.id}`+ );+ },+ // Uses SYNC_PERMISSION_TOKEN_DSS_HOST (like createPermissionToken) so the+ // token is always signed by the DSS whose JWT secret matches the sync+ // service's secret.+ async createToken(args) {+ return await fetchWithToken<CollabSurfaceTokenResponse>(+ `${SYNC_PERMISSION_TOKEN_DSS_HOST}/collab_surfaces/${args.id}/token`,+ {+ method: 'POST',+ }+ );+ },+ async delete(args) {+ return await dssFetch(`/collab_surfaces/${args.id}`, {+ method: 'DELETE',+ });+ },+ },async getUsersHistory() {return (await dssFetch<{ data: Item[] }>(`/history`)).map((result) => ({data: result.data,diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponse.tsnew file mode 100644index 0000000000..be08c5f3e2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponse.ts@@ -0,0 +1,22 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CollabSurfaceResponseParentEntityType } from './collabSurfaceResponseParentEntityType';+import type { SurfaceState } from './surfaceState';++/**+ * A collab surface, as returned by the API.+ */+export interface CollabSurfaceResponse {+ /** The surface id — also the sync-service session key. */+ id: string;+ /** Id of the parent entity. */+ parentEntityId: string;+ /** Type of the parent entity. */+ parentEntityType: CollabSurfaceResponseParentEntityType;+ /** Lifecycle state (`ready` for every surface visible via the API). */+ state: SurfaceState;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponseParentEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponseParentEntityType.tsnew file mode 100644index 0000000000..8d2bf3c135--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponseParentEntityType.ts@@ -0,0 +1,28 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Type of the parent entity.+ */+export type CollabSurfaceResponseParentEntityType =+ | 'user'+ | 'chat'+ | 'channel'+ | 'channel_message'+ | 'document'+ | 'project'+ | 'email_thread'+ | 'calendar_event'+ | 'team'+ | 'call'+ | 'foreign_entity'+ | 'static_file'+ | 'crm_company'+ | 'crm_contact'+ | 'reminder'+ | 'skill'+ | 'agent_session';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceTokenResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceTokenResponse.tsnew file mode 100644index 0000000000..871f51a36c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceTokenResponse.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Response carrying a freshly minted sync-service connection token.+ */+export interface CollabSurfaceTokenResponse {+ /** The signed JWT to pass to the sync-service websocket connect. */+ token: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequest.tsnew file mode 100644index 0000000000..3624acce48--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequest.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { EnsureCollabSurfaceRequestParentEntityType } from './ensureCollabSurfaceRequestParentEntityType';++/**+ * Request body for ensuring a collab surface.+ */+export interface EnsureCollabSurfaceRequest {+ /** Markdown to seed the surface with when this ensure creates it. Empty+(or omitted) seeds the canonical blank document. Ignored when the+surface already exists and is ready. */+ initialMarkdown?: string;+ /** Id of the parent entity (a uuid). */+ parentEntityId: string;+ /** Type of the parent entity access derives from. */+ parentEntityType: EnsureCollabSurfaceRequestParentEntityType;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequestParentEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequestParentEntityType.tsnew file mode 100644index 0000000000..316facbb86--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequestParentEntityType.ts@@ -0,0 +1,28 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Type of the parent entity access derives from.+ */+export type EnsureCollabSurfaceRequestParentEntityType =+ | 'user'+ | 'chat'+ | 'channel'+ | 'channel_message'+ | 'document'+ | 'project'+ | 'email_thread'+ | 'calendar_event'+ | 'team'+ | 'call'+ | 'foreign_entity'+ | 'static_file'+ | 'crm_company'+ | 'crm_contact'+ | 'reminder'+ | 'skill'+ | 'agent_session';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 7a0a76f5fe..b11d65782e 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -278,6 +278,9 @@ export * from './chatTokenCount';export * from './chatType';export * from './chatUpdatedAt';export * from './cloudStorageItemType';+export * from './collabSurfaceResponse';+export * from './collabSurfaceResponseParentEntityType';+export * from './collabSurfaceTokenResponse';export * from './comment';export * from './commentCreatedAt';export * from './commentDeletedAt';@@ -568,6 +571,8 @@ export * from './emailFilters';export * from './emailFiltersCalendarOnly';export * from './emailFiltersImportance';export * from './emptyResponse';+export * from './ensureCollabSurfaceRequest';+export * from './ensureCollabSurfaceRequestParentEntityType';export * from './entityFilters';export * from './entityPermission';export * from './entityPermissionOneOf';@@ -1142,6 +1147,7 @@ export * from './soupThreadReplyEditedAt';export * from './starterDocumentsResponse';export * from './string';export * from './successResponse';+export * from './surfaceState';export * from './syncServiceVersionID';export * from './systemSkillSummary';export * from './tagFilterMode';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/surfaceState.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/surfaceState.tsnew file mode 100644index 0000000000..fa3e180e9f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/surfaceState.ts@@ -0,0 +1,24 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Lifecycle state of a collab surface.++`Pending` means the row exists but the sync-service session may not: the+row is inserted before the durable object is initialized and flipped to+`Ready` once the initial snapshot is stored. A persisted `Pending` row is+an ensure that died or failed mid-init; the next ensure for the same id+retries initialization (the initializer tolerates an already-initialized+session), so `Pending` is self-healing rather than terminal.+ */+export type SurfaceState = (typeof SurfaceState)[keyof typeof SurfaceState];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const SurfaceState = {+ pending: 'pending',+ ready: 'ready',+} as const;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.tsindex 4440d94f72..c2e36ce600 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@@ -3257,6 +3257,156 @@ export const postChannelBotWebhookResponse = zod}).describe('Response returned after posting a channel webhook message.');+/**+ * @summary Fetch a collab surface.+ */+export const getCollabSurfaceParams = zod.object({+ id: zod.uuid().describe('The surface id.'),+});++export const getCollabSurfaceResponse = zod+ .object({+ id: zod+ .uuid()+ .describe('The surface id — also the sync-service session key.'),+ parentEntityId: zod.string().describe('Id of the parent entity.'),+ parentEntityType: zod+ .enum([+ 'user',+ 'chat',+ 'channel',+ 'channel_message',+ 'document',+ 'project',+ 'email_thread',+ 'calendar_event',+ 'team',+ 'call',+ 'foreign_entity',+ 'static_file',+ 'crm_company',+ 'crm_contact',+ 'reminder',+ 'skill',+ 'agent_session',+ ])+ .describe('The type of an entity in Macro')+ .describe('Type of the parent entity.'),+ state: zod+ .enum(['pending', 'ready'])+ .describe(+ 'Lifecycle state of a collab surface.\n\n`Pending` means the row exists but the sync-service session may not: the\nrow is inserted before the durable object is initialized and flipped to\n`Ready` once the initial snapshot is stored. A persisted `Pending` row is\nan ensure that died or failed mid-init; the next ensure for the same id\nretries initialization (the initializer tolerates an already-initialized\nsession), so `Pending` is self-healing rather than terminal.'+ ),+ })+ .describe('A collab surface, as returned by the API.');++/**+ * The id is caller-supplied, so an embedding surface can hold a stable id+and blindly ensure it on mount: the first ensure creates and initializes+the session, every later one (including concurrent ones) returns the same+surface. A soft-deleted id is `410 Gone` and never comes back.+ * @summary Idempotently ensure a collab surface exists (load-or-create).+ */+export const ensureCollabSurfaceParams = zod.object({+ id: zod.uuid().describe('The surface id.'),+});++export const ensureCollabSurfaceBody = zod+ .object({+ initialMarkdown: zod+ .string()+ .optional()+ .describe(+ 'Markdown to seed the surface with when this ensure creates it. Empty\n(or omitted) seeds the canonical blank document. Ignored when the\nsurface already exists and is ready.'+ ),+ parentEntityId: zod.string().describe('Id of the parent entity (a uuid).'),+ parentEntityType: zod+ .enum([+ 'user',+ 'chat',+ 'channel',+ 'channel_message',+ 'document',+ 'project',+ 'email_thread',+ 'calendar_event',+ 'team',+ 'call',+ 'foreign_entity',+ 'static_file',+ 'crm_company',+ 'crm_contact',+ 'reminder',+ 'skill',+ 'agent_session',+ ])+ .describe('The type of an entity in Macro')+ .describe('Type of the parent entity access derives from.'),+ })+ .describe('Request body for ensuring a collab surface.');++export const ensureCollabSurfaceResponse = zod+ .object({+ id: zod+ .uuid()+ .describe('The surface id — also the sync-service session key.'),+ parentEntityId: zod.string().describe('Id of the parent entity.'),+ parentEntityType: zod+ .enum([+ 'user',+ 'chat',+ 'channel',+ 'channel_message',+ 'document',+ 'project',+ 'email_thread',+ 'calendar_event',+ 'team',+ 'call',+ 'foreign_entity',+ 'static_file',+ 'crm_company',+ 'crm_contact',+ 'reminder',+ 'skill',+ 'agent_session',+ ])+ .describe('The type of an entity in Macro')+ .describe('Type of the parent entity.'),+ state: zod+ .enum(['pending', 'ready'])+ .describe(+ 'Lifecycle state of a collab surface.\n\n`Pending` means the row exists but the sync-service session may not: the\nrow is inserted before the durable object is initialized and flipped to\n`Ready` once the initial snapshot is stored. A persisted `Pending` row is\nan ensure that died or failed mid-init; the next ensure for the same id\nretries initialization (the initializer tolerates an already-initialized\nsession), so `Pending` is self-healing rather than terminal.'+ ),+ })+ .describe('A collab surface, as returned by the API.');++/**+ * @summary Soft-delete a collab surface.+ */+export const deleteCollabSurfaceParams = zod.object({+ id: zod.uuid().describe('The surface id.'),+});++/**+ * @summary Mint a sync-service connection token for a surface.+ */+export const createCollabSurfaceTokenParams = zod.object({+ id: zod.uuid().describe('The surface id.'),+});++export const createCollabSurfaceTokenResponse = zod+ .object({+ token: zod+ .string()+ .describe(+ 'The signed JWT to pass to the sync-service websocket connect.'+ ),+ })+ .describe(+ 'Response carrying a freshly minted sync-service connection token.'+ );+/*** @summary Handle channel list requests for `GET /comms/channels`.*/diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 68cebb21ad..7caac442b7 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -4132,6 +4132,313 @@}}},+ "/collab_surfaces/{id}": {+ "get": {+ "tags": ["collab_surfaces"],+ "summary": "Fetch a collab surface.",+ "operationId": "get_collab_surface",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The surface id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CollabSurfaceResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "put": {+ "tags": ["collab_surfaces"],+ "summary": "Idempotently ensure a collab surface exists (load-or-create).",+ "description": "The id is caller-supplied, so an embedding surface can hold a stable id\nand blindly ensure it on mount: the first ensure creates and initializes\nthe session, every later one (including concurrent ones) returns the same\nsurface. A soft-deleted id is `410 Gone` and never comes back.",+ "operationId": "ensure_collab_surface",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The surface id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EnsureCollabSurfaceRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CollabSurfaceResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "No access to the parent entity",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "The parent entity does not exist",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "410": {+ "description": "The surface id was deleted and cannot be reused",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "422": {+ "description": "Malformed request body (plain text)"+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["collab_surfaces"],+ "summary": "Soft-delete a collab surface.",+ "operationId": "delete_collab_surface",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The surface id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "Deleted"+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/collab_surfaces/{id}/token": {+ "post": {+ "tags": ["collab_surfaces"],+ "summary": "Mint a sync-service connection token for a surface.",+ "operationId": "create_collab_surface_token",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The surface id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CollabSurfaceTokenResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/comms/channels": {"get": {"tags": ["channels"],@@ -14827,6 +15134,65 @@"type": "string","enum": ["document", "chat", "project"]},+ "CollabSurfaceResponse": {+ "type": "object",+ "description": "A collab surface, as returned by the API.",+ "required": ["id", "parentEntityType", "parentEntityId", "state"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "The surface id — also the sync-service session key."+ },+ "parentEntityId": {+ "type": "string",+ "description": "Id of the parent entity."+ },+ "parentEntityType": {+ "oneOf": [+ {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder",+ "skill",+ "agent_session"+ ]+ }+ ],+ "description": "Type of the parent entity."+ },+ "state": {+ "$ref": "#/components/schemas/SurfaceState",+ "description": "Lifecycle state (`ready` for every surface visible via the API)."+ }+ }+ },+ "CollabSurfaceTokenResponse": {+ "type": "object",+ "description": "Response carrying a freshly minted sync-service connection token.",+ "required": ["token"],+ "properties": {+ "token": {+ "type": "string",+ "description": "The signed JWT to pass to the sync-service websocket connect."+ }+ }+ },"Comment": {"type": "object","required": ["commentId", "threadId", "owner", "text"],@@ -17766,6 +18132,49 @@"type": "object","description": "Empty response is required due to custom fetch forcing `response.json()`"},+ "EnsureCollabSurfaceRequest": {+ "type": "object",+ "description": "Request body for ensuring a collab surface.",+ "required": ["parentEntityType", "parentEntityId"],+ "properties": {+ "initialMarkdown": {+ "type": "string",+ "description": "Markdown to seed the surface with when this ensure creates it. Empty\n(or omitted) seeds the canonical blank document. Ignored when the\nsurface already exists and is ready."+ },+ "parentEntityId": {+ "type": "string",+ "description": "Id of the parent entity (a uuid)."+ },+ "parentEntityType": {+ "oneOf": [+ {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder",+ "skill",+ "agent_session"+ ]+ }+ ],+ "description": "Type of the parent entity access derives from."+ }+ }+ },"EntityFilters": {"type": "object","description": "a bundle of all of the filters for each entity type",@@ -23833,6 +24242,11 @@}}},+ "SurfaceState": {+ "type": "string",+ "description": "Lifecycle state of a collab surface.\n\n`Pending` means the row exists but the sync-service session may not: the\nrow is inserted before the durable object is initialized and flipped to\n`Ready` once the initial snapshot is stored. A persisted `Pending` row is\nan ensure that died or failed mid-init; the next ensure for the same id\nretries initialization (the initializer tolerates an already-initialized\nsession), so `Pending` is self-healing rather than terminal.",+ "enum": ["pending", "ready"]+ },"SyncServiceVersionID": {"type": "object","required": ["peer", "counter"],diff --git a/apps/web/src/lib/service-clients/service-storage/service.ts b/apps/web/src/lib/service-clients/service-storage/service.tsindex 7273403d1f..bd05e4745c 100644--- a/apps/web/src/lib/service-clients/service-storage/service.ts+++ b/apps/web/src/lib/service-clients/service-storage/service.ts@@ -290,6 +290,37 @@ const PermissionsTokensSvc = new Svc('Permissions Tokens Service')throws: withFetchErrors(),});+const CollabSurfacesSvc = new Svc('Collab Surfaces Service')+ .use('fetchErrors', fetchErrorsSvc)+ .fn('ensure', {+ description:+ 'idempotently ensures a collab surface exists (load-or-create) attached to a parent entity, with its sync-service session initialized',+ args: schemas.ensureCollabSurfaceBody.extend(+ schemas.ensureCollabSurfaceParams.shape+ ).shape,+ result: schemas.ensureCollabSurfaceResponse.shape,+ modifies: true,+ throws: withFetchErrors(),+ })+ .fn('get', {+ description: 'fetches a collab surface',+ args: schemas.getCollabSurfaceParams.shape,+ result: schemas.getCollabSurfaceResponse.shape,+ throws: withFetchErrors(),+ })+ .fn('createToken', {+ description: 'mints a sync-service connection token for a collab surface',+ args: schemas.createCollabSurfaceTokenParams.shape,+ result: schemas.createCollabSurfaceTokenResponse.shape,+ throws: withFetchErrors(),+ })+ .fn('delete', {+ description: 'soft-deletes a collab surface',+ args: schemas.deleteCollabSurfaceParams.shape,+ modifies: true,+ throws: withFetchErrors(),+ });+const InstructionsSvc = new Svc('Instructions Service').use('fetchErrors', fetchErrorsSvc).fn('create', {@@ -312,6 +343,12 @@ export type GetDocumentPermissionsTokenResponse = z.infer<export type ValidateDocumentPermissionsTokenResponse = z.infer<typeof schemas.validateDocumentPermissionsTokenResponse>;+export type CollabSurfaceResponse = z.infer<+ typeof schemas.getCollabSurfaceResponse+>;+export type CollabSurfaceTokenResponse = z.infer<+ typeof schemas.createCollabSurfaceTokenResponse+>;export const StorageService = new Svc('Document++ Storage Service API').err('INVALID_RESPONSE', { description: 'Invalid response from server' })@@ -725,6 +762,7 @@ export const StorageService = new Svc('Document++ Storage Service API').use('annotations', AnnotationsSvc).use('projects', ProjectsSvc).use('permissionsTokens', PermissionsTokensSvc)+ .use('collabSurfaces', CollabSurfacesSvc).use('instructions', InstructionsSvc).use('views', ViewsSvc).use('favorites', FavoritesSvc);diff --git a/apps/web/src/lib/service-clients/service-sync/source/helpers.ts b/apps/web/src/lib/service-clients/service-sync/source/helpers.tsindex 3be192f2d4..fb03b14042 100644--- a/apps/web/src/lib/service-clients/service-sync/source/helpers.ts+++ b/apps/web/src/lib/service-clients/service-sync/source/helpers.ts@@ -20,23 +20,29 @@ import type { ResultAsync } from 'neverthrow';const SYNC_SERVICE_WS_URL = `${SYNC_SERVICE_HOSTS['ws']}/document`;+/** Fetches a fresh sync-service connection token, or undefined on failure. */+type GetToken = () => Promise<string | undefined>;+/**- * Browser sync websocket: uses the already-fetched token for the initial- * connect, then refetches a fresh permission token on every reconnect.+ * Sync websocket over any token source: uses the already-fetched token for the+ * initial connect, then calls `getToken` for a fresh token on every reconnect.+ *+ * `documentId` is the sync-service session key — a document id or a collab+ * surface id; the transport is identical.*/-export function createSyncServiceSocket(+export function createTokenRefreshingSocket(documentId: string,- initialToken: string+ initialToken: string,+ getToken: GetToken,+ traceparent?: () => string | undefined): SyncWebsocket {const connectUrl = (token: string) => {const url = `${SYNC_SERVICE_WS_URL}/${documentId}/connect?token=${token}`;// Browsers can't set websocket headers, so the trace context rides a// query param; the sync service joins its spans to the active// transaction's trace.- const traceparent = resumeDocumentSpan(documentId)?.traceparent();- return traceparent- ? `${url}&traceparent=${encodeURIComponent(traceparent)}`- : url;+ const trace = traceparent?.();+ return trace ? `${url}&traceparent=${encodeURIComponent(trace)}` : url;};let initialUrl: string | undefined = connectUrl(initialToken);let fallbackUrl = initialUrl;@@ -48,17 +54,13 @@ export function createSyncServiceSocket(return url;}- const response =- await storageServiceClient.permissionsTokens.createPermissionToken({- document_id: documentId,- });-- if (response.isErr()) {- console.error('failed to fetch permission token', response);+ const token = await getToken();+ if (!token) {+ console.error('failed to fetch sync connection token');return fallbackUrl;}- const refreshedUrl = connectUrl(response.value.token);+ const refreshedUrl = connectUrl(token);fallbackUrl = refreshedUrl;return refreshedUrl;};@@ -66,6 +68,33 @@ export function createSyncServiceSocket(return createSyncSocket(getUrl);}+/**+ * Browser sync websocket for a document: uses the already-fetched token for+ * the initial connect, then refetches a fresh permission token on every+ * reconnect.+ */+export function createSyncServiceSocket(+ documentId: string,+ initialToken: string+): SyncWebsocket {+ return createTokenRefreshingSocket(+ documentId,+ initialToken,+ async () => {+ const response =+ await storageServiceClient.permissionsTokens.createPermissionToken({+ document_id: documentId,+ });+ if (response.isErr()) {+ console.error('failed to fetch permission token', response);+ return undefined;+ }+ return response.value.token;+ },+ () => resumeDocumentSpan(documentId)?.traceparent()+ );+}+export const createSyncServiceSource = (documentId: string,token: string@@ -80,3 +109,23 @@ export const createSyncServiceSource = (});return { source, doInitialSync: source.doInitialSync };};++/**+ * Live sync source for a collab surface. Same transport as documents; only+ * the token endpoint differs (`/collab_surfaces/{id}/token`).+ */+export const createCollabSurfaceSource = (+ surfaceId: string,+ initialToken: string,+ getToken: GetToken+): {+ source: LiveSyncSource;+ doInitialSync: () => ResultAsync<InitialSync, TimeoutError>;+} => {+ const ws = createTokenRefreshingSocket(surfaceId, initialToken, getToken);+ const state = createWebsocketStateSignal(ws);+ const source = new SyncServiceSource(ws, surfaceId, {+ status: () => mapToSyncStatus(state()),+ });+ return { source, doInitialSync: source.doInitialSync };+};diff --git a/crates/collab_surface/Cargo.toml b/crates/collab_surface/Cargo.tomlnew file mode 100644index 0000000000..c27f976c71--- /dev/null+++ b/crates/collab_surface/Cargo.toml@@ -0,0 +1,49 @@+[package]+edition = "2024"+name = "collab_surface"+publish = false+version = "0.1.0"++[features]+default = []+inbound = [+ "dep:axum",+ "dep:macro_authorization",+ "dep:model-error-response",+ "dep:utoipa",+ "entity_access/inbound",+ "ports",+]+outbound = ["dep:lexical_client", "dep:sync_service_client", "ports"]+ports = ["dep:entity_access", "dep:tracing"]+postgres = ["dep:sqlx", "outbound"]++[dependencies]+axum = { workspace = true, optional = true }+chrono = { workspace = true, features = ["serde"] }+entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["ports"] }+lexical_client = { path = "../lexical_client", optional = true }+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum"] }+macro_sync_service_jwt = { path = "../macro_sync_service_jwt" }+macro_user_id = { path = "../macro_user_id" }+macro_uuid = { path = "../macro_uuid" }+model = { path = "../model" }+model-entity = { path = "../model-entity" }+model-error-response = { path = "../model-error-response", optional = true }+models_permissions = { path = "../models_permissions" }+rootcause = { workspace = true }+serde = { workspace = true }+sqlx = { workspace = true, optional = true }+sync_service_client = { path = "../sync_service_client", optional = true }+thiserror = { workspace = true }+tokio-retry = { workspace = true }+tracing = { workspace = true, optional = true }+utoipa = { workspace = true, optional = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+mockall = { workspace = true }+serde_json = { workspace = true }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/crates/collab_surface/src/domain.rs b/crates/collab_surface/src/domain.rsnew file mode 100644index 0000000000..c53683e098--- /dev/null+++ b/crates/collab_surface/src/domain.rs@@ -0,0 +1,9 @@+//! Domain layer: models, ports, and the collab-surface service.++pub mod models;+#[cfg(feature = "ports")]+pub mod ports;+#[cfg(feature = "ports")]+pub mod service;+#[cfg(feature = "ports")]+pub mod token;diff --git a/crates/collab_surface/src/domain/models.rs b/crates/collab_surface/src/domain/models.rsnew file mode 100644index 0000000000..bb472bf87a--- /dev/null+++ b/crates/collab_surface/src/domain/models.rs@@ -0,0 +1,92 @@+//! Domain models for collab surfaces.++use chrono::{DateTime, Utc};+use model_entity::Entity;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++/// Lifecycle state of a collab surface.+///+/// `Pending` means the row exists but the sync-service session may not: the+/// row is inserted before the durable object is initialized and flipped to+/// `Ready` once the initial snapshot is stored. A persisted `Pending` row is+/// an ensure that died or failed mid-init; the next ensure for the same id+/// retries initialization (the initializer tolerates an already-initialized+/// session), so `Pending` is self-healing rather than terminal.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum SurfaceState {+ /// Row inserted, sync-service session not yet initialized.+ Pending,+ /// Sync-service session initialized; the surface is connectable.+ Ready,+}++impl SurfaceState {+ /// The value stored in the `state` column.+ pub fn db_value(&self) -> &'static str {+ match self {+ SurfaceState::Pending => "pending",+ SurfaceState::Ready => "ready",+ }+ }++ /// Parse a `state` column value.+ pub fn from_db_value(value: &str) -> Option<Self> {+ match value {+ "pending" => Some(SurfaceState::Pending),+ "ready" => Some(SurfaceState::Ready),+ _ => None,+ }+ }+}++/// A collab surface: a stable id bound to a parent entity, backed by a Loro+/// session in sync-service. Content lives in the CRDT, not here.+#[derive(Debug, Clone)]+pub struct CollabSurface {+ /// The surface id — also the sync-service session (durable object) key.+ pub id: Uuid,+ /// The parent entity access derives from.+ pub parent: Entity<'static>,+ /// Lifecycle state.+ pub state: SurfaceState,+ /// When the row was created.+ pub created_at: DateTime<Utc>,+ /// When the row was last updated.+ pub updated_at: DateTime<Utc>,+}++/// Errors returned by the collab-surface service.+#[derive(Debug, thiserror::Error)]+pub enum CollabSurfaceError {+ /// No such surface (or it has been deleted).+ #[error("collab surface not found")]+ NotFound,+ /// The parent entity named at creation does not exist.+ #[error("parent entity not found")]+ ParentNotFound,+ /// The surface id was soft-deleted. Distinct from+ /// [`CollabSurfaceError::NotFound`] so an ensure with a recycled id fails+ /// loudly instead of looking like a race to retry.+ #[error("this surface id was deleted and cannot be reused")]+ Gone,+ /// The request was invalid.+ #[error("{0}")]+ BadRequest(String),+ /// The caller may not act on this surface's parent entity. Maps to `403`;+ /// authentication failures (`401`) are produced by the authorization+ /// extractor before a handler runs.+ #[error("you do not have access to this surface")]+ AccessDenied,+ /// Any other internal error.+ #[error("internal collab surface error: {0:?}")]+ Internal(rootcause::Report),+}++impl From<rootcause::Report> for CollabSurfaceError {+ fn from(report: rootcause::Report) -> Self {+ CollabSurfaceError::Internal(report)+ }+}diff --git a/crates/collab_surface/src/domain/ports.rs b/crates/collab_surface/src/domain/ports.rsnew file mode 100644index 0000000000..6db30bd161--- /dev/null+++ b/crates/collab_surface/src/domain/ports.rs@@ -0,0 +1,118 @@+//! Ports (trait contracts) for the collab-surface domain.++use entity_access::domain::models::{AnyEntityPermission, EntityAccessReceipt};+use macro_sync_service_jwt::DocumentPermissionToken;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::Entity;+use uuid::Uuid;++use crate::domain::models::{CollabSurface, CollabSurfaceError};++/// Outbound persistence port for collab surfaces.+pub trait CollabSurfaceRepo: Send + Sync + 'static {+ /// The error type returned by repository operations.+ type Err: std::error::Error + Send + Sync + 'static;++ /// Insert a surface in `pending` state. Returns `false` (without error)+ /// when a row with this id already exists — live or soft-deleted — so+ /// concurrent ensures race safely.+ fn insert(+ &self,+ surface: &CollabSurface,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Fetch a surface by id. Soft-deleted surfaces read as absent.+ fn get(+ &self,+ id: Uuid,+ ) -> impl Future<Output = Result<Option<CollabSurface>, Self::Err>> + Send;++ /// All live surfaces attached to a parent entity.+ fn list_by_parent(+ &self,+ parent: &Entity<'_>,+ ) -> impl Future<Output = Result<Vec<CollabSurface>, Self::Err>> + Send;++ /// Flip a surface to `ready` after its sync-service session initialized.+ fn mark_ready(&self, id: Uuid) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Soft-delete a surface. Idempotent.+ fn soft_delete(&self, id: Uuid) -> impl Future<Output = Result<(), Self::Err>> + Send;+}++/// Outbound port that boots a surface's sync-service session from markdown.+///+/// Implementations convert the markdown to a Loro snapshot (an empty string+/// maps to the canonical blank-document snapshot) and store it as the+/// session's initial state. Initialization is one-shot per id on the+/// sync-service side.+#[cfg_attr(test, mockall::automock)]+pub trait SurfaceInitializer: Send + Sync + 'static {+ /// Initialize the sync-service session for `surface_id` with `markdown`.+ fn initialize(+ &self,+ surface_id: &str,+ markdown: &str,+ ) -> impl Future<Output = Result<(), CollabSurfaceError>> + Send;+}++/// The collab-surface use-cases, generic over the outbound ports.+pub trait CollabSurfaceService: Send + Sync + 'static {+ /// Idempotently ensure surface `id` exists, attached to the parent entity+ /// the receipt proves access to, with its sync-service session+ /// initialized. Returns only once the surface is `ready`:+ ///+ /// - missing → created with the caller-supplied id, initialized, `ready`.+ /// - exists (live) → parent must match the receipt's entity; a `pending`+ /// row (an earlier ensure died or failed mid-init) has its+ /// initialization retried.+ /// - soft-deleted → [`CollabSurfaceError::Gone`]; ids are never reused.+ ///+ /// Concurrent ensures for the same id converge: the insert is+ /// conflict-tolerant and the initializer treats an already-initialized+ /// session as success.+ fn ensure_surface(+ &self,+ user_id: &MacroUserIdStr<'_>,+ parent_receipt: EntityAccessReceipt<AnyEntityPermission>,+ id: Uuid,+ initial_markdown: String,+ ) -> impl Future<Output = Result<CollabSurface, CollabSurfaceError>> + Send;++ /// Fetch a surface. The caller must already hold a receipt for the+ /// surface's parent (resolved by the inbound layer via+ /// [`CollabSurfaceService::get_parent`]).+ fn get_surface(+ &self,+ user_id: &MacroUserIdStr<'_>,+ parent_receipt: EntityAccessReceipt<AnyEntityPermission>,+ id: Uuid,+ ) -> impl Future<Output = Result<CollabSurface, CollabSurfaceError>> + Send;++ /// The parent entity of a surface, for the inbound layer to mint a receipt+ /// against before any surface operation. `NotFound` for missing/deleted.+ fn get_parent(+ &self,+ id: Uuid,+ ) -> impl Future<Output = Result<Entity<'static>, CollabSurfaceError>> + Send;++ /// Mint a sync-service connection token for the surface, at the access+ /// level implied by the caller's permission on the parent entity.+ fn mint_token(+ &self,+ user_id: &MacroUserIdStr<'_>,+ parent_receipt: EntityAccessReceipt<AnyEntityPermission>,+ id: Uuid,+ ) -> impl Future<Output = Result<DocumentPermissionToken, CollabSurfaceError>> + Send;++ /// Soft-delete a surface. Requires an edit-capable permission on the+ /// parent. The sync-service session is not reclaimed (documented gap+ /// shared with documents); deletion makes the surface unmintable, which+ /// cuts off all access.+ fn delete_surface(+ &self,+ user_id: &MacroUserIdStr<'_>,+ parent_receipt: EntityAccessReceipt<AnyEntityPermission>,+ id: Uuid,+ ) -> impl Future<Output = Result<(), CollabSurfaceError>> + Send;+}diff --git a/crates/collab_surface/src/domain/service.rs b/crates/collab_surface/src/domain/service.rsnew file mode 100644index 0000000000..6c22d3f81c--- /dev/null+++ b/crates/collab_surface/src/domain/service.rs@@ -0,0 +1,249 @@+//! The collab-surface service implementation.++#[cfg(test)]+mod test;++use std::sync::Arc;++use entity_access::domain::models::{AnyEntityPermission, EntityAccessReceipt};+use macro_sync_service_jwt::DocumentPermissionToken;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::Entity;+use uuid::Uuid;++use crate::domain::models::{CollabSurface, CollabSurfaceError, SurfaceState};+use crate::domain::ports::{CollabSurfaceRepo, CollabSurfaceService, SurfaceInitializer};+use crate::domain::token::{access_level_for, encode_surface_token};++/// Upper bound on initial markdown, mirroring the lexical-service request cap.+const MAX_INITIAL_MARKDOWN_LEN: usize = 1_000_000;++/// Production implementation of [`CollabSurfaceService`].+pub struct CollabSurfaceServiceImpl<R, I> {+ repo: Arc<R>,+ initializer: Arc<I>,+ jwt_secret: String,+}++impl<R, I> CollabSurfaceServiceImpl<R, I> {+ /// Build the service from its ports and the sync-service JWT secret.+ pub fn new(repo: Arc<R>, initializer: Arc<I>, jwt_secret: String) -> Self {+ Self {+ repo,+ initializer,+ jwt_secret,+ }+ }+}++/// The parent entity and caller identity a receipt proves.+///+/// The receipt is the only source of the parent — a caller cannot name an+/// entity it has not proven access to, because there is nowhere else to put+/// the id. The receipt must also have been minted for this caller, or one+/// user could act using another's receipt.+fn resolve_parent(+ user_id: &MacroUserIdStr<'_>,+ receipt: &EntityAccessReceipt<AnyEntityPermission>,+) -> Result<Entity<'static>, CollabSurfaceError> {+ let receipt_user = receipt+ .get_authenticated_user()+ .map_err(|_| CollabSurfaceError::AccessDenied)?;+ if receipt_user.as_ref() != user_id.as_ref() {+ return Err(CollabSurfaceError::AccessDenied);+ }+ let entity = receipt.entity();+ Ok(entity+ .entity_type+ .with_entity_string(entity.entity_id.to_string()))+}++/// Verify a receipt (already minted against the surface's parent by the+/// inbound layer) actually names that parent. Defense in depth: the inbound+/// layer resolves the parent via [`CollabSurfaceService::get_parent`], so a+/// mismatch means a coding error, not a malicious caller — but the check makes+/// the invariant unskippable.+fn verify_receipt_matches_parent(+ surface: &CollabSurface,+ parent: &Entity<'static>,+) -> Result<(), CollabSurfaceError> {+ if surface.parent.entity_type != parent.entity_type+ || surface.parent.entity_id != parent.entity_id+ {+ return Err(CollabSurfaceError::AccessDenied);+ }+ Ok(())+}++impl<R, I> CollabSurfaceService for CollabSurfaceServiceImpl<R, I>+where+ R: CollabSurfaceRepo,+ I: SurfaceInitializer,+{+ #[tracing::instrument(err, skip(self, user_id, parent_receipt, initial_markdown))]+ async fn ensure_surface(+ &self,+ user_id: &MacroUserIdStr<'_>,+ parent_receipt: EntityAccessReceipt<AnyEntityPermission>,+ id: Uuid,+ initial_markdown: String,+ ) -> Result<CollabSurface, CollabSurfaceError> {+ if initial_markdown.len() > MAX_INITIAL_MARKDOWN_LEN {+ return Err(CollabSurfaceError::BadRequest(format!(+ "initial markdown exceeds {MAX_INITIAL_MARKDOWN_LEN} bytes"+ )));+ }+ let parent = resolve_parent(user_id, &parent_receipt)?;++ // Fast path: the surface already exists. A `pending` row still gets+ // its initialization retried in `finish_init`.+ if let Some(existing) = self.get_optional(id).await? {+ verify_receipt_matches_parent(&existing, &parent)?;+ return self.finish_init(existing, &initial_markdown).await;+ }++ let now = chrono::Utc::now();+ let surface = CollabSurface {+ id,+ parent,+ state: SurfaceState::Pending,+ created_at: now,+ updated_at: now,+ };++ let inserted = self+ .repo+ .insert(&surface)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;++ if !inserted {+ // Lost a race with a concurrent ensure, or the id belongs to a+ // soft-deleted surface (which never comes back).+ let Some(existing) = self.get_optional(id).await? else {+ return Err(CollabSurfaceError::Gone);+ };+ verify_receipt_matches_parent(&existing, &surface.parent)?;+ return self.finish_init(existing, &initial_markdown).await;+ }++ self.finish_init(surface, &initial_markdown).await+ }++ #[tracing::instrument(err, skip(self, user_id, parent_receipt))]+ async fn get_surface(+ &self,+ user_id: &MacroUserIdStr<'_>,+ parent_receipt: EntityAccessReceipt<AnyEntityPermission>,+ id: Uuid,+ ) -> Result<CollabSurface, CollabSurfaceError> {+ let parent = resolve_parent(user_id, &parent_receipt)?;+ let surface = self.get_live(id).await?;+ verify_receipt_matches_parent(&surface, &parent)?;+ Ok(surface)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_parent(&self, id: Uuid) -> Result<Entity<'static>, CollabSurfaceError> {+ Ok(self.get_live(id).await?.parent)+ }++ #[tracing::instrument(err, skip(self, user_id, parent_receipt))]+ async fn mint_token(+ &self,+ user_id: &MacroUserIdStr<'_>,+ parent_receipt: EntityAccessReceipt<AnyEntityPermission>,+ id: Uuid,+ ) -> Result<DocumentPermissionToken, CollabSurfaceError> {+ let parent = resolve_parent(user_id, &parent_receipt)?;+ let surface = self.get_live(id).await?;+ verify_receipt_matches_parent(&surface, &parent)?;++ let access_level = access_level_for(parent_receipt.entity_permission())?;+ encode_surface_token(+ parent_receipt+ .get_authenticated_user()+ .map_err(|_| CollabSurfaceError::AccessDenied)?+ .clone(),+ surface.id.to_string(),+ access_level,+ &self.jwt_secret,+ )+ }++ #[tracing::instrument(err, skip(self, user_id, parent_receipt))]+ async fn delete_surface(+ &self,+ user_id: &MacroUserIdStr<'_>,+ parent_receipt: EntityAccessReceipt<AnyEntityPermission>,+ id: Uuid,+ ) -> Result<(), CollabSurfaceError> {+ let parent = resolve_parent(user_id, &parent_receipt)?;+ let surface = self.get_live(id).await?;+ verify_receipt_matches_parent(&surface, &parent)?;++ // Deletion requires an edit-capable permission on the parent; there is+ // no per-surface owner. `access_level_for` already maps channel+ // membership to Edit and view-only presences to View.+ let level = access_level_for(parent_receipt.entity_permission())?;+ if level < models_permissions::share_permission::access_level::AccessLevel::Edit {+ return Err(CollabSurfaceError::AccessDenied);+ }++ self.repo+ .soft_delete(id)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;+ Ok(())+ }+}++impl<R, I> CollabSurfaceServiceImpl<R, I>+where+ R: CollabSurfaceRepo,+ I: SurfaceInitializer,+{+ /// Fetch a live (non-deleted) surface or `NotFound`.+ async fn get_live(&self, id: Uuid) -> Result<CollabSurface, CollabSurfaceError> {+ self.get_optional(id)+ .await?+ .ok_or(CollabSurfaceError::NotFound)+ }++ /// Fetch a live (non-deleted) surface, absent as `None`.+ async fn get_optional(&self, id: Uuid) -> Result<Option<CollabSurface>, CollabSurfaceError> {+ Ok(self+ .repo+ .get(id)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?)+ }++ /// Take a surface the caller may act on to `Ready`, (re)initializing its+ /// sync-service session when it is still `Pending`. The initializer treats+ /// an already-initialized session as success, so this is safe to run+ /// concurrently and after partial failures.+ async fn finish_init(+ &self,+ surface: CollabSurface,+ initial_markdown: &str,+ ) -> Result<CollabSurface, CollabSurfaceError> {+ if surface.state == SurfaceState::Ready {+ return Ok(surface);+ }++ self.initializer+ .initialize(&surface.id.to_string(), initial_markdown)+ .await?;++ self.repo+ .mark_ready(surface.id)+ .await+ .map_err(|e| rootcause::Report::new(e).into_dynamic())?;++ Ok(CollabSurface {+ state: SurfaceState::Ready,+ ..surface+ })+ }+}diff --git a/crates/collab_surface/src/domain/service/test.rs b/crates/collab_surface/src/domain/service/test.rsnew file mode 100644index 0000000000..bbfe1cea0a--- /dev/null+++ b/crates/collab_surface/src/domain/service/test.rs@@ -0,0 +1,435 @@+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};++use entity_access::domain::models::{+ AnyEntityPermission, EntityAccessReceipt, EntityPermission, ParticipantRole,+};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use models_permissions::share_permission::access_level::AccessLevel;++use super::*;+use crate::domain::ports::MockSurfaceInitializer;++const SECRET: &str = "test-secret";++fn user(id: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(id.to_string()).unwrap()+}++fn surface_id() -> Uuid {+ macro_uuid::generate_uuid_v7()+}++fn receipt_for(+ user_id: &str,+ entity_type: EntityType,+ entity_id: &str,+ permission: EntityPermission,+) -> EntityAccessReceipt<AnyEntityPermission> {+ EntityAccessReceipt::try_new_authenticated_user(+ user(user_id),+ entity_access::domain::models::Entity {+ entity_id: entity_id.to_string(),+ entity_type,+ },+ permission,+ )+ .unwrap()+}++fn edit_permission() -> EntityPermission {+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Edit,+ }+}++/// In-memory repo: one optional surface plus operation flags.+#[derive(Default)]+struct MemRepo {+ surface: std::sync::Mutex<Option<CollabSurface>>,+ soft_deleted: AtomicBool,+}++#[derive(Debug, thiserror::Error)]+#[error("mem repo error")]+struct MemErr;++impl CollabSurfaceRepo for Arc<MemRepo> {+ type Err = MemErr;++ async fn insert(&self, surface: &CollabSurface) -> Result<bool, MemErr> {+ let mut slot = self.surface.lock().unwrap();+ // A row exists (live or soft-deleted) -> conflict, no insert.+ if slot.is_some() {+ return Ok(false);+ }+ *slot = Some(surface.clone());+ Ok(true)+ }++ async fn get(&self, id: Uuid) -> Result<Option<CollabSurface>, MemErr> {+ Ok(self+ .surface+ .lock()+ .unwrap()+ .clone()+ .filter(|s| s.id == id && !self.soft_deleted.load(Ordering::SeqCst)))+ }++ async fn list_by_parent(&self, _parent: &Entity<'_>) -> Result<Vec<CollabSurface>, MemErr> {+ Ok(self.surface.lock().unwrap().clone().into_iter().collect())+ }++ async fn mark_ready(&self, _id: Uuid) -> Result<(), MemErr> {+ if let Some(s) = self.surface.lock().unwrap().as_mut() {+ s.state = SurfaceState::Ready;+ }+ Ok(())+ }++ async fn soft_delete(&self, _id: Uuid) -> Result<(), MemErr> {+ self.soft_deleted.store(true, Ordering::SeqCst);+ Ok(())+ }+}++fn service_with(+ repo: Arc<MemRepo>,+ initializer: MockSurfaceInitializer,+) -> CollabSurfaceServiceImpl<Arc<MemRepo>, MockSurfaceInitializer> {+ CollabSurfaceServiceImpl::new(Arc::new(repo), Arc::new(initializer), SECRET.to_string())+}++#[tokio::test]+async fn ensure_creates_initializes_then_marks_ready() {+ let repo = Arc::new(MemRepo::default());+ let mut init = MockSurfaceInitializer::new();+ init.expect_initialize()+ .times(1)+ .returning(|_, _| Box::pin(async { Ok(()) }));++ let svc = service_with(repo.clone(), init);+ let receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ edit_permission(),+ );+ let id = surface_id();+ let surface = svc+ .ensure_surface(&user("macro|[email protected]"), receipt, id, "# hi".to_string())+ .await+ .unwrap();++ assert_eq!(surface.id, id);+ assert_eq!(surface.state, SurfaceState::Ready);+ assert_eq!(+ repo.surface.lock().unwrap().as_ref().unwrap().state,+ SurfaceState::Ready+ );+}++#[tokio::test]+async fn ensure_is_idempotent_for_a_ready_surface() {+ let repo = Arc::new(MemRepo::default());+ let mut init = MockSurfaceInitializer::new();+ // Exactly one initialization across both ensures: the second sees a+ // ready surface and does not touch the initializer.+ init.expect_initialize()+ .times(1)+ .returning(|_, _| Box::pin(async { Ok(()) }));++ let svc = service_with(repo.clone(), init);+ let id = surface_id();+ let make_receipt = || {+ receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ edit_permission(),+ )+ };++ let first = svc+ .ensure_surface(&user("macro|[email protected]"), make_receipt(), id, "# hi".to_string())+ .await+ .unwrap();+ let second = svc+ .ensure_surface(+ &user("macro|[email protected]"),+ make_receipt(),+ id,+ "# different seed, ignored".to_string(),+ )+ .await+ .unwrap();++ assert_eq!(first.id, second.id);+ assert_eq!(second.state, SurfaceState::Ready);+}++#[tokio::test]+async fn ensure_retries_init_for_a_pending_surface() {+ let repo = Arc::new(MemRepo::default());+ let mut init = MockSurfaceInitializer::new();+ // First ensure: init fails, row stays pending. Second ensure: init+ // succeeds and the surface becomes ready.+ let calls = Arc::new(AtomicUsize::new(0));+ let calls_in_mock = calls.clone();+ init.expect_initialize().times(2).returning(move |_, _| {+ let call = calls_in_mock.fetch_add(1, Ordering::SeqCst);+ Box::pin(async move {+ if call == 0 {+ Err(CollabSurfaceError::Internal(+ rootcause::Report::new(MemErr).into_dynamic(),+ ))+ } else {+ Ok(())+ }+ })+ });++ let svc = service_with(repo.clone(), init);+ let id = surface_id();+ let make_receipt = || {+ receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ edit_permission(),+ )+ };++ let err = svc+ .ensure_surface(&user("macro|[email protected]"), make_receipt(), id, String::new())+ .await+ .unwrap_err();+ assert!(matches!(err, CollabSurfaceError::Internal(_)));+ // The row survives as pending — no unwind.+ assert_eq!(+ repo.surface.lock().unwrap().as_ref().unwrap().state,+ SurfaceState::Pending+ );++ let surface = svc+ .ensure_surface(&user("macro|[email protected]"), make_receipt(), id, String::new())+ .await+ .unwrap();+ assert_eq!(surface.state, SurfaceState::Ready);+}++#[tokio::test]+async fn ensure_maps_insert_conflict_on_deleted_id_to_gone() {+ let repo = Arc::new(MemRepo::default());+ let mut init = MockSurfaceInitializer::new();+ init.expect_initialize()+ .returning(|_, _| Box::pin(async { Ok(()) }));++ let svc = service_with(repo.clone(), init);+ let id = surface_id();+ let make_receipt = || {+ receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ edit_permission(),+ )+ };++ svc.ensure_surface(&user("macro|[email protected]"), make_receipt(), id, String::new())+ .await+ .unwrap();+ svc.delete_surface(&user("macro|[email protected]"), make_receipt(), id)+ .await+ .unwrap();++ let err = svc+ .ensure_surface(&user("macro|[email protected]"), make_receipt(), id, String::new())+ .await+ .unwrap_err();+ assert!(matches!(err, CollabSurfaceError::Gone));+}++#[tokio::test]+async fn ensure_rejects_mismatched_parent() {+ let repo = Arc::new(MemRepo::default());+ let mut init = MockSurfaceInitializer::new();+ init.expect_initialize()+ .returning(|_, _| Box::pin(async { Ok(()) }));+ let svc = service_with(repo, init);+ let id = surface_id();++ let chan1_receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ edit_permission(),+ );+ svc.ensure_surface(&user("macro|[email protected]"), chan1_receipt, id, String::new())+ .await+ .unwrap();++ // Ensuring the same id against a different parent must fail: the id is+ // bound to chan-1, and a receipt for chan-2 proves nothing about it.+ let chan2_receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-2",+ edit_permission(),+ );+ let err = svc+ .ensure_surface(&user("macro|[email protected]"), chan2_receipt, id, String::new())+ .await+ .unwrap_err();+ assert!(matches!(err, CollabSurfaceError::AccessDenied));+}++#[tokio::test]+async fn ensure_rejects_receipt_for_other_user() {+ let repo = Arc::new(MemRepo::default());+ let svc = service_with(repo, MockSurfaceInitializer::new());+ let receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ edit_permission(),+ );+ let err = svc+ .ensure_surface(&user("macro|[email protected]"), receipt, surface_id(), String::new())+ .await+ .unwrap_err();+ assert!(matches!(err, CollabSurfaceError::AccessDenied));+}++#[tokio::test]+async fn mint_token_maps_channel_role_to_edit() {+ let repo = Arc::new(MemRepo::default());+ let mut init = MockSurfaceInitializer::new();+ init.expect_initialize()+ .returning(|_, _| Box::pin(async { Ok(()) }));+ let svc = service_with(repo, init);++ let channel_role = EntityPermission::ChannelRole {+ role: ParticipantRole::Member,+ };+ let create_receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ channel_role.clone(),+ );+ let surface = svc+ .ensure_surface(+ &user("macro|[email protected]"),+ create_receipt,+ surface_id(),+ String::new(),+ )+ .await+ .unwrap();++ let mint_receipt = receipt_for("macro|[email protected]", EntityType::Channel, "chan-1", channel_role);+ let token = svc+ .mint_token(&user("macro|[email protected]"), mint_receipt, surface.id)+ .await+ .unwrap();++ let claims: model::document::DocumentPermissionsToken =+ macro_sync_service_jwt::decode(token.as_str(), SECRET).unwrap();+ assert_eq!(claims.document_id, surface.id.to_string());+ assert_eq!(claims.access_level, AccessLevel::Edit);+}++#[tokio::test]+async fn mint_token_rejects_receipt_for_wrong_parent() {+ let repo = Arc::new(MemRepo::default());+ let mut init = MockSurfaceInitializer::new();+ init.expect_initialize()+ .returning(|_, _| Box::pin(async { Ok(()) }));+ let svc = service_with(repo, init);++ let create_receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ edit_permission(),+ );+ let surface = svc+ .ensure_surface(+ &user("macro|[email protected]"),+ create_receipt,+ surface_id(),+ String::new(),+ )+ .await+ .unwrap();++ // Receipt proves access to a different channel than the surface's parent.+ let wrong_receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-2",+ edit_permission(),+ );+ let err = svc+ .mint_token(&user("macro|[email protected]"), wrong_receipt, surface.id)+ .await+ .unwrap_err();+ assert!(matches!(err, CollabSurfaceError::AccessDenied));+}++#[tokio::test]+async fn delete_requires_edit_capable_permission() {+ let repo = Arc::new(MemRepo::default());+ let mut init = MockSurfaceInitializer::new();+ init.expect_initialize()+ .returning(|_, _| Box::pin(async { Ok(()) }));+ let svc = service_with(repo.clone(), init);++ let create_receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ edit_permission(),+ );+ let surface = svc+ .ensure_surface(+ &user("macro|[email protected]"),+ create_receipt,+ surface_id(),+ String::new(),+ )+ .await+ .unwrap();++ // View-only presence cannot delete.+ let view_receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ EntityPermission::ChannelViewOnly,+ );+ let err = svc+ .delete_surface(&user("macro|[email protected]"), view_receipt, surface.id)+ .await+ .unwrap_err();+ assert!(matches!(err, CollabSurfaceError::AccessDenied));++ // Member can.+ let member_receipt = receipt_for(+ "macro|[email protected]",+ EntityType::Channel,+ "chan-1",+ EntityPermission::ChannelRole {+ role: ParticipantRole::Member,+ },+ );+ svc.delete_surface(&user("macro|[email protected]"), member_receipt, surface.id)+ .await+ .unwrap();++ // Deleted surfaces read as absent.+ let gone = svc.get_parent(surface.id).await.unwrap_err();+ assert!(matches!(gone, CollabSurfaceError::NotFound));+}diff --git a/crates/collab_surface/src/domain/token.rs b/crates/collab_surface/src/domain/token.rsnew file mode 100644index 0000000000..89de698ea3--- /dev/null+++ b/crates/collab_surface/src/domain/token.rs@@ -0,0 +1,58 @@+//! Minting sync-service connection tokens for collab surfaces.+//!+//! A surface token is the same JWT shape the sync service already validates+//! for documents ([`model::document::DocumentPermissionsToken`], signed with+//! the shared `document_permission_jwt` secret): the worker string-compares+//! the `document_id` claim against its session key, so a surface id flows+//! through the existing claim unchanged. Deliberately not lifted into+//! `macro_sync_service_jwt` — that crate stays dependency-minimal because it+//! also compiles to wasm for the sync-service worker.++use std::time::{SystemTime, UNIX_EPOCH};++use entity_access::domain::models::EntityPermission;+use macro_sync_service_jwt::{DocumentPermissionToken, ISSUER, TOKEN_TTL_SECS};+use macro_user_id::user_id::MacroUserIdStr;+use model::document::DocumentPermissionsToken;+use models_permissions::share_permission::access_level::AccessLevel;++use crate::domain::models::CollabSurfaceError;++/// The sync-service access level implied by a parent-entity permission.+///+/// Channel members collaborate as editors; a view-only channel presence gets a+/// read-only session. Team roles have no surface semantics yet and fail+/// closed.+pub fn access_level_for(permission: &EntityPermission) -> Result<AccessLevel, CollabSurfaceError> {+ match permission {+ EntityPermission::AccessLevel { access_level } => Ok(*access_level),+ EntityPermission::ChannelRole { .. } => Ok(AccessLevel::Edit),+ EntityPermission::ChannelViewOnly => Ok(AccessLevel::View),+ EntityPermission::TeamRole { .. } => Err(CollabSurfaceError::AccessDenied),+ }+}++/// Sign a sync-service connection token for `surface_id`.+pub fn encode_surface_token(+ user_id: MacroUserIdStr<'static>,+ surface_id: String,+ access_level: AccessLevel,+ jwt_secret: &str,+) -> Result<DocumentPermissionToken, CollabSurfaceError> {+ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .expect("system clock before unix epoch")+ .as_secs() as usize;++ macro_sync_service_jwt::encode(+ &DocumentPermissionsToken {+ user_id: Some(user_id),+ document_id: surface_id,+ access_level,+ exp: now + TOKEN_TTL_SECS,+ iss: ISSUER.to_string(),+ },+ jwt_secret,+ )+ .map_err(|e| CollabSurfaceError::Internal(rootcause::Report::new(e).into_dynamic()))+}diff --git a/crates/collab_surface/src/inbound.rs b/crates/collab_surface/src/inbound.rsnew file mode 100644index 0000000000..42245c69c0--- /dev/null+++ b/crates/collab_surface/src/inbound.rs@@ -0,0 +1,3 @@+//! Inbound (driving) adapters for collab surfaces.++pub mod axum_router;diff --git a/crates/collab_surface/src/inbound/axum_router.rs b/crates/collab_surface/src/inbound/axum_router.rsnew file mode 100644index 0000000000..a38fdc8bd6--- /dev/null+++ b/crates/collab_surface/src/inbound/axum_router.rs@@ -0,0 +1,455 @@+//! Axum router for collab-surface endpoints.++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, Path, State},+ http::StatusCode,+ response::IntoResponse,+ routing::{delete, get, post, put},+};+use entity_access::domain::{+ models::{AccessError, AnyEntityPermission, EntityAccessReceipt},+ ports::EntityAccessService,+};+use macro_authorization::{+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,+};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};+use model_error_response::ErrorResponse;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::domain::models::{CollabSurface, CollabSurfaceError, SurfaceState};+use crate::domain::ports::CollabSurfaceService;++/// Router state for collab-surface endpoints.+pub struct CollabSurfaceRouterState<S, Eas, Auth> {+ service: Arc<S>,+ entity_access_service: Arc<Eas>,+ authorization_state: MacroAuthorizationState<Auth>,+}++impl<S, Eas, Auth> Clone for CollabSurfaceRouterState<S, Eas, Auth> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ entity_access_service: self.entity_access_service.clone(),+ authorization_state: self.authorization_state.clone(),+ }+ }+}++impl<S, Eas, Auth> CollabSurfaceRouterState<S, Eas, Auth>+where+ S: CollabSurfaceService,+ Eas: EntityAccessService,+{+ /// Create router state from shared service references and authorization state.+ pub fn new(+ service: Arc<S>,+ entity_access_service: Arc<Eas>,+ authorization_state: MacroAuthorizationState<Auth>,+ ) -> Self {+ Self {+ service,+ entity_access_service,+ authorization_state,+ }+ }+}++impl<S, Eas, Auth> FromRef<CollabSurfaceRouterState<S, Eas, Auth>> for Arc<Eas> {+ fn from_ref(state: &CollabSurfaceRouterState<S, Eas, Auth>) -> Self {+ state.entity_access_service.clone()+ }+}++impl<S, Eas, Auth> FromRef<CollabSurfaceRouterState<S, Eas, Auth>>+ for MacroAuthorizationState<Auth>+{+ fn from_ref(state: &CollabSurfaceRouterState<S, Eas, Auth>) -> Self {+ state.authorization_state.clone()+ }+}++/// Build the collab-surfaces router.+///+/// Routes:+/// - `PUT /{id}` — idempotently ensure a surface exists (load-or-create).+/// - `GET /{id}` — fetch a surface.+/// - `POST /{id}/token` — mint a sync-service connection token.+/// - `DELETE /{id}` — soft-delete a surface.+pub fn collab_surface_router<S, Eas, Auth, T>(+ state: CollabSurfaceRouterState<S, Eas, Auth>,+) -> Router<T>+where+ S: CollabSurfaceService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+ T: Send + Sync + 'static,+{+ Router::new()+ .route("/{id}", put(ensure_surface_handler::<S, Eas, Auth>))+ .route("/{id}", get(get_surface_handler::<S, Eas, Auth>))+ .route("/{id}/token", post(mint_token_handler::<S, Eas, Auth>))+ .route("/{id}", delete(delete_surface_handler::<S, Eas, Auth>))+ .with_state(state)+}++/// Parent entity types a surface may attach to in v1.+///+/// `ChannelMessage` is deliberately absent: it has no access resolution in+/// `entity_access` — a message-scoped surface attaches to its channel instead+/// (the `Call → Channel` precedent). The rest are excluded until they have a+/// surface story.+const SUPPORTED_PARENT_TYPES: &[EntityType] = &[+ EntityType::Document,+ EntityType::Channel,+ EntityType::Project,+ EntityType::Chat,+ EntityType::EmailThread,+ EntityType::Call,+];++/// Request body for ensuring a collab surface.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct EnsureCollabSurfaceRequest {+ /// Type of the parent entity access derives from.+ #[schema(inline)]+ pub parent_entity_type: EntityType,+ /// Id of the parent entity (a uuid).+ pub parent_entity_id: String,+ /// Markdown to seed the surface with when this ensure creates it. Empty+ /// (or omitted) seeds the canonical blank document. Ignored when the+ /// surface already exists and is ready.+ #[serde(default)]+ pub initial_markdown: String,+}++/// A collab surface, as returned by the API.+#[derive(Debug, Serialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CollabSurfaceResponse {+ /// The surface id — also the sync-service session key.+ pub id: Uuid,+ /// Type of the parent entity.+ #[schema(inline)]+ pub parent_entity_type: EntityType,+ /// Id of the parent entity.+ pub parent_entity_id: String,+ /// Lifecycle state (`ready` for every surface visible via the API).+ pub state: SurfaceState,+}++impl From<CollabSurface> for CollabSurfaceResponse {+ fn from(surface: CollabSurface) -> Self {+ Self {+ id: surface.id,+ parent_entity_type: surface.parent.entity_type,+ parent_entity_id: surface.parent.entity_id.to_string(),+ state: surface.state,+ }+ }+}++/// Response carrying a freshly minted sync-service connection token.+#[derive(Debug, Serialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CollabSurfaceTokenResponse {+ /// The signed JWT to pass to the sync-service websocket connect.+ pub token: String,+}++/// Path params for the single-surface routes.+#[derive(Debug, Deserialize, utoipa::IntoParams)]+#[into_params(parameter_in = Path)]+pub struct SurfaceIdParams {+ /// The surface id.+ pub id: Uuid,+}++/// Validate a parent entity pair syntactically before touching access control.+fn build_parent(+ entity_type: EntityType,+ entity_id: &str,+) -> Result<Entity<'static>, CollabSurfaceError> {+ if !SUPPORTED_PARENT_TYPES.contains(&entity_type) {+ return Err(CollabSurfaceError::BadRequest(format!(+ "unsupported parent entity type: {entity_type}"+ )));+ }+ let entity_id = entity_id.trim();+ // Stored as uuid, so reject a malformed id here rather than let it surface+ // as an opaque repository error.+ Uuid::parse_str(entity_id)+ .map_err(|_| CollabSurfaceError::BadRequest("parentEntityId must be a uuid".to_string()))?;+ Ok(entity_type.with_entity_string(entity_id.to_string()))+}++/// Mint the receipt that proves the caller may act on `parent`.+///+/// The requirement is [`AnyEntityPermission`], not a leveled one: a channel+/// resolves to `ChannelRole`/`ChannelViewOnly`, which a leveled receipt never+/// matches. The domain service decides what each permission may do.+async fn mint_parent_receipt<Eas: EntityAccessService>(+ entity_access_service: &Eas,+ user_id: &MacroUserIdStr<'_>,+ user_org_id: Option<i64>,+ parent: &Entity<'_>,+) -> Result<EntityAccessReceipt<AnyEntityPermission>, CollabSurfaceError> {+ entity_access_service+ .generate_entity_access_receipt::<AnyEntityPermission>(+ user_id,+ user_org_id,+ parent.entity_id.as_ref(),+ parent.entity_type,+ )+ .await+ .map_err(|e| match e {+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {+ CollabSurfaceError::AccessDenied+ }+ AccessError::NotFound(_) => CollabSurfaceError::ParentNotFound,+ AccessError::BadRequest(msg) => CollabSurfaceError::BadRequest(msg.to_string()),+ other => CollabSurfaceError::Internal(rootcause::Report::new(other).into_dynamic()),+ })+}++/// The caller's identity and org, as the receipt-minting path needs them.+fn caller_identity<Auth: MacroAuthorizationService>(+ user: &MacroAuthorizationExtractor<Auth, UserOrInternal>,+) -> (&MacroUserIdStr<'static>, Option<i64>) {+ (+ &user.authorization.user.macro_user_id,+ // Organization channels grant access by matching org, so the org must+ // be carried through or a member of one reads as a non-participant.+ user.authorization+ .user+ .user_context+ .organization_id+ .map(i64::from),+ )+}++/// Resolve the surface's parent and mint a receipt for it — the shared prelude+/// of every single-surface route.+async fn receipt_for_surface<S, Eas>(+ service: &S,+ entity_access_service: &Eas,+ user_id: &MacroUserIdStr<'_>,+ user_org_id: Option<i64>,+ id: Uuid,+) -> Result<EntityAccessReceipt<AnyEntityPermission>, CollabSurfaceError>+where+ S: CollabSurfaceService,+ Eas: EntityAccessService,+{+ let parent = service.get_parent(id).await?;+ mint_parent_receipt(entity_access_service, user_id, user_org_id, &parent).await+}++/// Idempotently ensure a collab surface exists (load-or-create).+///+/// The id is caller-supplied, so an embedding surface can hold a stable id+/// and blindly ensure it on mount: the first ensure creates and initializes+/// the session, every later one (including concurrent ones) returns the same+/// surface. A soft-deleted id is `410 Gone` and never comes back.+#[utoipa::path(+ put,+ tag = "collab_surfaces",+ operation_id = "ensure_collab_surface",+ path = "/collab_surfaces/{id}",+ params(SurfaceIdParams),+ request_body = EnsureCollabSurfaceRequest,+ responses(+ (status = 200, body = CollabSurfaceResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, description = "Missing or invalid credentials", body = ErrorResponse),+ (status = 403, description = "No access to the parent entity", body = ErrorResponse),+ (status = 404, description = "The parent entity does not exist", body = ErrorResponse),+ (status = 410, description = "The surface id was deleted and cannot be reused", body = ErrorResponse),+ (status = 422, description = "Malformed request body (plain text)"),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn ensure_surface_handler<S, Eas, Auth>(+ State(state): State<CollabSurfaceRouterState<S, Eas, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(SurfaceIdParams { id }): Path<SurfaceIdParams>,+ Json(req): Json<EnsureCollabSurfaceRequest>,+) -> Result<Json<CollabSurfaceResponse>, CollabSurfaceError>+where+ S: CollabSurfaceService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let (user_id, user_org_id) = caller_identity(&user);+ let parent = build_parent(req.parent_entity_type, &req.parent_entity_id)?;+ let receipt = mint_parent_receipt(+ state.entity_access_service.as_ref(),+ user_id,+ user_org_id,+ &parent,+ )+ .await?;++ let surface = state+ .service+ .ensure_surface(user_id, receipt, id, req.initial_markdown)+ .await?;+ Ok(Json(surface.into()))+}++/// Fetch a collab surface.+#[utoipa::path(+ get,+ tag = "collab_surfaces",+ operation_id = "get_collab_surface",+ path = "/collab_surfaces/{id}",+ params(SurfaceIdParams),+ responses(+ (status = 200, body = CollabSurfaceResponse),+ (status = 401, description = "Missing or invalid credentials", body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn get_surface_handler<S, Eas, Auth>(+ State(state): State<CollabSurfaceRouterState<S, Eas, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(SurfaceIdParams { id }): Path<SurfaceIdParams>,+) -> Result<Json<CollabSurfaceResponse>, CollabSurfaceError>+where+ S: CollabSurfaceService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let (user_id, user_org_id) = caller_identity(&user);+ let receipt = receipt_for_surface(+ state.service.as_ref(),+ state.entity_access_service.as_ref(),+ user_id,+ user_org_id,+ id,+ )+ .await?;+ let surface = state.service.get_surface(user_id, receipt, id).await?;+ Ok(Json(surface.into()))+}++/// Mint a sync-service connection token for a surface.+#[utoipa::path(+ post,+ tag = "collab_surfaces",+ operation_id = "create_collab_surface_token",+ path = "/collab_surfaces/{id}/token",+ params(SurfaceIdParams),+ responses(+ (status = 200, body = CollabSurfaceTokenResponse),+ (status = 401, description = "Missing or invalid credentials", body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn mint_token_handler<S, Eas, Auth>(+ State(state): State<CollabSurfaceRouterState<S, Eas, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(SurfaceIdParams { id }): Path<SurfaceIdParams>,+) -> Result<Json<CollabSurfaceTokenResponse>, CollabSurfaceError>+where+ S: CollabSurfaceService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let (user_id, user_org_id) = caller_identity(&user);+ let receipt = receipt_for_surface(+ state.service.as_ref(),+ state.entity_access_service.as_ref(),+ user_id,+ user_org_id,+ id,+ )+ .await?;+ let token = state.service.mint_token(user_id, receipt, id).await?;+ Ok(Json(CollabSurfaceTokenResponse {+ token: token.into_inner(),+ }))+}++/// Soft-delete a collab surface.+#[utoipa::path(+ delete,+ tag = "collab_surfaces",+ operation_id = "delete_collab_surface",+ path = "/collab_surfaces/{id}",+ params(SurfaceIdParams),+ responses(+ (status = 204, description = "Deleted"),+ (status = 401, description = "Missing or invalid credentials", body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn delete_surface_handler<S, Eas, Auth>(+ State(state): State<CollabSurfaceRouterState<S, Eas, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(SurfaceIdParams { id }): Path<SurfaceIdParams>,+) -> Result<StatusCode, CollabSurfaceError>+where+ S: CollabSurfaceService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let (user_id, user_org_id) = caller_identity(&user);+ let receipt = receipt_for_surface(+ state.service.as_ref(),+ state.entity_access_service.as_ref(),+ user_id,+ user_org_id,+ id,+ )+ .await?;+ state.service.delete_surface(user_id, receipt, id).await?;+ Ok(StatusCode::NO_CONTENT)+}++impl IntoResponse for CollabSurfaceError {+ fn into_response(self) -> axum::response::Response {+ let status_code = match &self {+ CollabSurfaceError::NotFound | CollabSurfaceError::ParentNotFound => {+ StatusCode::NOT_FOUND+ }+ CollabSurfaceError::Gone => StatusCode::GONE,+ CollabSurfaceError::BadRequest(_) => StatusCode::BAD_REQUEST,+ CollabSurfaceError::AccessDenied => StatusCode::FORBIDDEN,+ CollabSurfaceError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ let message = match &self {+ CollabSurfaceError::Internal(_) => {+ tracing::error!(error=?self, "collab surface internal server error");+ "internal server error".to_string()+ }+ error => error.to_string(),+ };++ (+ status_code,+ Json(ErrorResponse {+ message: message.into(),+ }),+ )+ .into_response()+ }+}diff --git a/crates/collab_surface/src/lib.rs b/crates/collab_surface/src/lib.rsnew file mode 100644index 0000000000..bee616b3aa--- /dev/null+++ b/crates/collab_surface/src/lib.rs@@ -0,0 +1,29 @@+#![deny(missing_docs)]+//! Collab surfaces: stable ids for arbitrary collaborative markdown surfaces,+//! following the hexagonal architecture pattern.+//!+//! A collab surface gives any markdown UI (an input box, a message editor, a+//! task field) its own Loro CRDT session in sync-service, independent of the+//! `Document` table. The CRDT is the durable source of truth for content; the+//! `collab_surfaces` table records only existence, the parent entity, and+//! lifecycle state.+//!+//! A surface has no owner: it is a shared fixture of its parent entity (e.g. a+//! channel's shared input box). All authorization — creating a surface,+//! minting a sync-service connection token, deleting — derives from the+//! caller's access to the parent entity.+//!+//! # Architecture+//!+//! - **domain**: domain models, ports, and the service implementation.+//! - **inbound**: driving adapters (Axum HTTP router).+//! - **outbound**: driven adapters (Postgres repository, lexical/sync-service+//! initializer).++pub mod domain;++#[cfg(feature = "inbound")]+pub mod inbound;++#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/crates/collab_surface/src/outbound.rs b/crates/collab_surface/src/outbound.rsnew file mode 100644index 0000000000..1a2255b52b--- /dev/null+++ b/crates/collab_surface/src/outbound.rs@@ -0,0 +1,5 @@+//! Outbound (driven) adapters for collab surfaces.++#[cfg(feature = "postgres")]+pub mod pg_collab_surface_repo;+pub mod surface_init;diff --git a/crates/collab_surface/src/outbound/pg_collab_surface_repo.rs b/crates/collab_surface/src/outbound/pg_collab_surface_repo.rsnew file mode 100644index 0000000000..01678d1ae4--- /dev/null+++ b/crates/collab_surface/src/outbound/pg_collab_surface_repo.rs@@ -0,0 +1,187 @@+//! PostgreSQL implementation of the [`CollabSurfaceRepo`] port.++#[cfg(test)]+mod test;++use model_entity::{Entity, EntityType};+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::models::{CollabSurface, SurfaceState};+use crate::domain::ports::CollabSurfaceRepo;++/// Postgres-backed collab-surface repository.+#[derive(Debug, Clone)]+pub struct PgCollabSurfaceRepo {+ pool: PgPool,+}++impl PgCollabSurfaceRepo {+ /// Create a repository backed by the provided pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++/// Errors produced by the Postgres collab-surface repository.+#[derive(Debug, thiserror::Error)]+pub enum CollabSurfaceRepoErr {+ /// Underlying database error.+ #[error(transparent)]+ Db(#[from] sqlx::Error),+ /// A stored parent entity type could not be parsed into [`EntityType`].+ #[error("invalid parent entity type {value:?} stored for surface {surface_id}")]+ InvalidParentType {+ /// The surface carrying the bad value.+ surface_id: Uuid,+ /// The value that could not be parsed.+ value: String,+ },+ /// A stored state is not a known [`SurfaceState`].+ #[error("invalid state {value:?} stored for surface {surface_id}")]+ InvalidState {+ /// The surface carrying the bad value.+ surface_id: Uuid,+ /// The value that could not be parsed.+ value: String,+ },+}++/// A `collab_surfaces` row before parsing the enum-ish columns.+struct SurfaceRow {+ id: Uuid,+ parent_entity_type: String,+ parent_entity_id: Uuid,+ state: String,+ created_at: chrono::DateTime<chrono::Utc>,+ updated_at: chrono::DateTime<chrono::Utc>,+}++impl TryFrom<SurfaceRow> for CollabSurface {+ type Error = CollabSurfaceRepoErr;++ fn try_from(row: SurfaceRow) -> Result<Self, Self::Error> {+ let parent_type: EntityType = row.parent_entity_type.parse().map_err(|_| {+ CollabSurfaceRepoErr::InvalidParentType {+ surface_id: row.id,+ value: row.parent_entity_type.clone(),+ }+ })?;+ let state = SurfaceState::from_db_value(&row.state).ok_or_else(|| {+ CollabSurfaceRepoErr::InvalidState {+ surface_id: row.id,+ value: row.state.clone(),+ }+ })?;+ Ok(CollabSurface {+ id: row.id,+ parent: parent_type.with_entity_string(row.parent_entity_id.to_string()),+ state,+ created_at: row.created_at,+ updated_at: row.updated_at,+ })+ }+}++impl CollabSurfaceRepo for PgCollabSurfaceRepo {+ type Err = CollabSurfaceRepoErr;++ async fn insert(&self, surface: &CollabSurface) -> Result<bool, CollabSurfaceRepoErr> {+ // The parent id was validated as a uuid by the inbound layer; a+ // non-uuid here is a programming error surfaced as a Db error by the+ // failed parse below.+ let parent_id = surface+ .parent+ .entity_id+ .parse::<Uuid>()+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?;+ // Conflict-tolerant so concurrent ensures for the same id race safely:+ // exactly one caller inserts (true); the rest observe the existing row+ // (false) — including a soft-deleted one, which the service maps to+ // `Gone`.+ let result = sqlx::query!(+ r#"+ INSERT INTO collab_surfaces+ (id, parent_entity_type, parent_entity_id, state, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6)+ ON CONFLICT (id) DO NOTHING+ "#,+ surface.id,+ surface.parent.entity_type.to_string(),+ parent_id,+ surface.state.db_value(),+ surface.created_at,+ surface.updated_at,+ )+ .execute(&self.pool)+ .await?;+ Ok(result.rows_affected() > 0)+ }++ async fn get(&self, id: Uuid) -> Result<Option<CollabSurface>, CollabSurfaceRepoErr> {+ let row = sqlx::query_as!(+ SurfaceRow,+ r#"+ SELECT id, parent_entity_type, parent_entity_id, state, created_at, updated_at+ FROM collab_surfaces+ WHERE id = $1 AND deleted_at IS NULL+ "#,+ id,+ )+ .fetch_optional(&self.pool)+ .await?;+ row.map(CollabSurface::try_from).transpose()+ }++ async fn list_by_parent(+ &self,+ parent: &Entity<'_>,+ ) -> Result<Vec<CollabSurface>, CollabSurfaceRepoErr> {+ let Ok(parent_id) = parent.entity_id.parse::<Uuid>() else {+ // A non-uuid parent can never have rows; read as empty.+ return Ok(Vec::new());+ };+ let rows = sqlx::query_as!(+ SurfaceRow,+ r#"+ SELECT id, parent_entity_type, parent_entity_id, state, created_at, updated_at+ FROM collab_surfaces+ WHERE parent_entity_type = $1 AND parent_entity_id = $2 AND deleted_at IS NULL+ ORDER BY created_at, id+ "#,+ parent.entity_type.to_string(),+ parent_id,+ )+ .fetch_all(&self.pool)+ .await?;+ rows.into_iter().map(CollabSurface::try_from).collect()+ }++ async fn mark_ready(&self, id: Uuid) -> Result<(), CollabSurfaceRepoErr> {+ sqlx::query!(+ r#"+ UPDATE collab_surfaces+ SET state = 'ready', updated_at = now()+ WHERE id = $1 AND deleted_at IS NULL+ "#,+ id,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ async fn soft_delete(&self, id: Uuid) -> Result<(), CollabSurfaceRepoErr> {+ sqlx::query!(+ r#"+ UPDATE collab_surfaces+ SET deleted_at = now(), updated_at = now()+ WHERE id = $1 AND deleted_at IS NULL+ "#,+ id,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }+}diff --git a/crates/collab_surface/src/outbound/pg_collab_surface_repo/test.rs b/crates/collab_surface/src/outbound/pg_collab_surface_repo/test.rsnew file mode 100644index 0000000000..0e01d62cbf--- /dev/null+++ b/crates/collab_surface/src/outbound/pg_collab_surface_repo/test.rs@@ -0,0 +1,107 @@+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use model_entity::EntityType;+use sqlx::PgPool;++use super::*;++const CHANNEL_1: &str = "11111111-1111-4111-8111-111111111111";+const CHANNEL_2: &str = "22222222-2222-4222-8222-222222222222";++fn new_surface(parent_type: EntityType, parent_id: &str) -> CollabSurface {+ let now = chrono::Utc::now();+ CollabSurface {+ id: macro_uuid::generate_uuid_v7(),+ parent: parent_type.with_entity_string(parent_id.to_string()),+ state: SurfaceState::Pending,+ created_at: now,+ updated_at: now,+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn surface_round_trips(pool: PgPool) {+ let repo = PgCollabSurfaceRepo::new(pool);+ let surface = new_surface(EntityType::Channel, CHANNEL_1);+ assert!(repo.insert(&surface).await.unwrap());++ let read = repo.get(surface.id).await.unwrap().unwrap();+ assert_eq!(read.id, surface.id);+ assert_eq!(read.parent.entity_type, EntityType::Channel);+ assert_eq!(read.parent.entity_id.as_ref(), CHANNEL_1);+ assert_eq!(read.state, SurfaceState::Pending);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn mark_ready_flips_state(pool: PgPool) {+ let repo = PgCollabSurfaceRepo::new(pool);+ let surface = new_surface(EntityType::Document, CHANNEL_1);+ repo.insert(&surface).await.unwrap();+ repo.mark_ready(surface.id).await.unwrap();++ let read = repo.get(surface.id).await.unwrap().unwrap();+ assert_eq!(read.state, SurfaceState::Ready);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn soft_deleted_surfaces_read_as_absent(pool: PgPool) {+ let repo = PgCollabSurfaceRepo::new(pool);+ let surface = new_surface(EntityType::Channel, CHANNEL_1);+ repo.insert(&surface).await.unwrap();+ repo.soft_delete(surface.id).await.unwrap();++ assert!(repo.get(surface.id).await.unwrap().is_none());+ // Idempotent: deleting again is a no-op, not an error.+ repo.soft_delete(surface.id).await.unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn insert_conflicts_read_as_not_inserted(pool: PgPool) {+ let repo = PgCollabSurfaceRepo::new(pool);+ let surface = new_surface(EntityType::Channel, CHANNEL_1);+ assert!(repo.insert(&surface).await.unwrap());++ // Same id again (a racing ensure): no error, no insert, row unchanged.+ let racer = CollabSurface {+ parent: EntityType::Channel.with_entity_string(CHANNEL_2.to_string()),+ ..surface.clone()+ };+ assert!(!repo.insert(&racer).await.unwrap());+ let read = repo.get(surface.id).await.unwrap().unwrap();+ assert_eq!(read.parent.entity_id.as_ref(), CHANNEL_1);++ // A soft-deleted id also conflicts (and stays invisible to `get`),+ // which is what makes deleted ids unreusable.+ repo.soft_delete(surface.id).await.unwrap();+ assert!(!repo.insert(&surface).await.unwrap());+ assert!(repo.get(surface.id).await.unwrap().is_none());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_by_parent_scopes_to_the_parent_and_skips_deleted(pool: PgPool) {+ let repo = PgCollabSurfaceRepo::new(pool);+ let a = new_surface(EntityType::Channel, CHANNEL_1);+ let b = new_surface(EntityType::Channel, CHANNEL_1);+ let other = new_surface(EntityType::Channel, CHANNEL_2);+ let deleted = new_surface(EntityType::Channel, CHANNEL_1);+ for s in [&a, &b, &other, &deleted] {+ repo.insert(s).await.unwrap();+ }+ repo.soft_delete(deleted.id).await.unwrap();++ let listed = repo+ .list_by_parent(&EntityType::Channel.with_entity_string(CHANNEL_1.to_string()))+ .await+ .unwrap();+ let ids: Vec<Uuid> = listed.iter().map(|s| s.id).collect();+ assert_eq!(ids, vec![a.id, b.id]);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_by_parent_with_non_uuid_parent_reads_empty(pool: PgPool) {+ let repo = PgCollabSurfaceRepo::new(pool);+ let listed = repo+ .list_by_parent(&EntityType::Channel.with_entity_string("not-a-uuid".to_string()))+ .await+ .unwrap();+ assert!(listed.is_empty());+}diff --git a/crates/collab_surface/src/outbound/surface_init.rs b/crates/collab_surface/src/outbound/surface_init.rsnew file mode 100644index 0000000000..63552a8b21--- /dev/null+++ b/crates/collab_surface/src/outbound/surface_init.rs@@ -0,0 +1,88 @@+//! Sync-service session initializer backed by lexical-service and+//! sync-service HTTP clients.+//!+//! Mirrors `crates/documents/src/outbound/markdown_init.rs`, with one+//! deliberate difference: initialization here is awaited by the caller (with+//! the same bounded retry) instead of being spawned fire-and-forget, so+//! surface creation can report `ready` truthfully.++use std::time::Duration;++use lexical_client::LexicalClient;+use sync_service_client::SyncServiceClient;+use tokio_retry::{Retry, strategy::FixedInterval};++use crate::domain::models::CollabSurfaceError;+use crate::domain::ports::SurfaceInitializer;++/// Canonical blank-markdown Loro "golden" snapshot — the same bytes the+/// documents crate seeds empty markdown documents with.+const MARKDOWN_GOLDEN_SNAPSHOT: &[u8] =+ include_bytes!("../../../../static_assets/markdown-golden.1.bin");++const MAX_ATTEMPTS: usize = 3;+const RETRY_DELAY: Duration = Duration::from_secs(1);++/// [`SurfaceInitializer`] over the real lexical-service and sync-service+/// clients.+pub struct LexicalSyncSurfaceInitializer {+ lexical_client: LexicalClient,+ sync_service_client: SyncServiceClient,+}++impl LexicalSyncSurfaceInitializer {+ /// Build the initializer from the shared HTTP clients.+ pub fn new(lexical_client: LexicalClient, sync_service_client: SyncServiceClient) -> Self {+ Self {+ lexical_client,+ sync_service_client,+ }+ }+}++impl SurfaceInitializer for LexicalSyncSurfaceInitializer {+ #[tracing::instrument(err, skip(self, markdown))]+ async fn initialize(&self, surface_id: &str, markdown: &str) -> Result<(), CollabSurfaceError> {+ let snapshot: Vec<u8> = if markdown.is_empty() {+ MARKDOWN_GOLDEN_SNAPSHOT.to_vec()+ } else {+ self.lexical_client+ .markdown_to_loro_snapshot(markdown)+ .await+ .map_err(|e| {+ CollabSurfaceError::Internal(+ rootcause::report!("failed to convert markdown to loro snapshot: {e:?}")+ .into_dynamic(),+ )+ })?+ };++ let result = Retry::start(+ FixedInterval::new(RETRY_DELAY).take(MAX_ATTEMPTS - 1),+ || {+ self.sync_service_client+ .initialize_from_snapshot(surface_id, &snapshot)+ },+ )+ .await;++ match result {+ Ok(()) => Ok(()),+ // Initialization is one-shot on the sync-service side, so "snapshot+ // already exists" means an earlier or concurrent ensure won the+ // init — success for our purposes. This is what makes `ensure`+ // idempotent across retries and races.+ Err(e) if e.to_string().contains("snapshot already exists") => {+ tracing::debug!(+ surface_id = surface_id,+ "sync-service session already initialized; treating as success"+ );+ Ok(())+ }+ Err(e) => Err(CollabSurfaceError::Internal(+ rootcause::report!("failed to initialize sync-service session: {e:?}")+ .into_dynamic(),+ )),+ }+ }+}diff --git a/crates/macro_db_client/migrations/20260814140856_create_collab_surfaces.sql b/crates/macro_db_client/migrations/20260814140856_create_collab_surfaces.sqlnew file mode 100644index 0000000000..b6e1c7c8c3--- /dev/null+++ b/crates/macro_db_client/migrations/20260814140856_create_collab_surfaces.sql@@ -0,0 +1,43 @@+-- Collab surfaces: a stable id for an arbitrary collaborative markdown+-- surface (an input box, a message editor, a task field), backed by its own+-- Loro CRDT session in sync-service. The CRDT is the durable source of truth+-- for content; this table only records the surface's existence, its parent,+-- and its lifecycle state.+--+-- Ids are generated by the application as uuid v7 (macro_uuid), not by the+-- database. Surface ids are write-once by construction: sync-service+-- `initialize` is one-shot and the durable object has no delete route, so an+-- id is never recycled.+CREATE TABLE IF NOT EXISTS collab_surfaces+(+ id UUID PRIMARY KEY NOT NULL,+ -- Required, polymorphic parent entity. All authorization derives from the+ -- caller's access to the parent (channel membership, document access,+ -- ...); a surface has no owner of its own because it is a shared fixture+ -- of the parent (e.g. a channel's shared input box). Every supported+ -- parent is keyed by a uuid (see the reminder table's entity_id note);+ -- polymorphism still rules out an FK, so deletion of the parent leaves+ -- dangling rows that readers must treat as inaccessible.+ parent_entity_type TEXT NOT NULL,+ parent_entity_id UUID NOT NULL,+ -- pending → ready once the sync-service durable object has been+ -- initialized with the surface's first snapshot. Rows stuck in `pending`+ -- are failed creations (the service hard-deletes on init failure, so a+ -- surviving pending row means the service died mid-create).+ state TEXT NOT NULL DEFAULT 'pending'+ CHECK (state IN ('pending', 'ready')),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- Soft delete. The sync-service durable object is NOT reclaimed (same+ -- pre-existing gap as documents); a deleted row simply makes the surface+ -- unmintable, which cuts off all access.+ deleted_at TIMESTAMPTZ,+ CONSTRAINT collab_surfaces_parent_type_non_empty+ CHECK (length(btrim(parent_entity_type)) > 0)+);++-- All live surfaces attached to a given parent entity (e.g. "the channel's+-- surfaces" at channel load).+CREATE INDEX IF NOT EXISTS collab_surfaces_parent_idx+ ON collab_surfaces (parent_entity_type, parent_entity_id)+ WHERE deleted_at IS NULL;diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex 40d10761ca..1dceb4eb5a 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 77919f5c4a..942e4628ea 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -702,6 +702,46 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Soft-delete a collab surface.+ */+ public deleteCollabSurface<ThrowOnError extends boolean = false>(options: Options<DeleteCollabSurfaceData, ThrowOnError>): RequestResult<DeleteCollabSurfaceResponses, DeleteCollabSurfaceErrors, ThrowOnError> {+ return (options.client ?? this.client).delete<DeleteCollabSurfaceResponses, DeleteCollabSurfaceErrors, ThrowOnError>({ url: '/collab_surfaces/{id}', ...options });+ }++ /**+ * Fetch a collab surface.+ */+ public getCollabSurface<ThrowOnError extends boolean = false>(options: Options<GetCollabSurfaceData, ThrowOnError>): RequestResult<GetCollabSurfaceResponses, GetCollabSurfaceErrors, ThrowOnError> {+ return (options.client ?? this.client).get<GetCollabSurfaceResponses, GetCollabSurfaceErrors, ThrowOnError>({ url: '/collab_surfaces/{id}', ...options });+ }++ /**+ * Idempotently ensure a collab surface exists (load-or-create).+ *+ * The id is caller-supplied, so an embedding surface can hold a stable id+ * and blindly ensure it on mount: the first ensure creates and initializes+ * the session, every later one (including concurrent ones) returns the same+ * surface. A soft-deleted id is `410 Gone` and never comes back.+ */+ public ensureCollabSurface<ThrowOnError extends boolean = false>(options: Options<EnsureCollabSurfaceData, ThrowOnError>): RequestResult<EnsureCollabSurfaceResponses, EnsureCollabSurfaceErrors, ThrowOnError> {+ return (options.client ?? this.client).put<EnsureCollabSurfaceResponses, EnsureCollabSurfaceErrors, ThrowOnError>({+ url: '/collab_surfaces/{id}',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Mint a sync-service connection token for a surface.+ */+ public createCollabSurfaceToken<ThrowOnError extends boolean = false>(options: Options<CreateCollabSurfaceTokenData, ThrowOnError>): RequestResult<CreateCollabSurfaceTokenResponses, CreateCollabSurfaceTokenErrors, ThrowOnError> {+ return (options.client ?? this.client).post<CreateCollabSurfaceTokenResponses, CreateCollabSurfaceTokenErrors, ThrowOnError>({ url: '/collab_surfaces/{id}/token', ...options });+ }+/*** Handle channel list requests for `GET /comms/channels`.*/diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 47c5aff7b8..9bb7724110 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -2553,6 +2553,38 @@ export type ChatFilters = {export type CloudStorageItemType = 'document' | 'chat' | 'project';+/**+ * A collab surface, as returned by the API.+ */+export type CollabSurfaceResponse = {+ /**+ * The surface id — also the sync-service session key.+ */+ id: string;+ /**+ * Id of the parent entity.+ */+ parentEntityId: string;+ /**+ * Type of the parent entity.+ */+ parentEntityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session';+ /**+ * Lifecycle state (`ready` for every surface visible via the API).+ */+ state: SurfaceState;+};++/**+ * Response carrying a freshly minted sync-service connection token.+ */+export type CollabSurfaceTokenResponse = {+ /**+ * The signed JWT to pass to the sync-service websocket connect.+ */+ token: string;+};+export type Comment = {commentId: number;createdAt?: string | null;@@ -4498,6 +4530,26 @@ export type EmptyResponse = {[key: string]: unknown;};+/**+ * Request body for ensuring a collab surface.+ */+export type EnsureCollabSurfaceRequest = {+ /**+ * Markdown to seed the surface with when this ensure creates it. Empty+ * (or omitted) seeds the canonical blank document. Ignored when the+ * surface already exists and is ready.+ */+ initialMarkdown?: string;+ /**+ * Id of the parent entity (a uuid).+ */+ parentEntityId: string;+ /**+ * Type of the parent entity access derives from.+ */+ parentEntityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session';+};+/*** a bundle of all of the filters for each entity type*/@@ -7944,6 +7996,18 @@ export type SuccessResponse = {error: boolean;};+/**+ * Lifecycle state of a collab surface.+ *+ * `Pending` means the row exists but the sync-service session may not: the+ * row is inserted before the durable object is initialized and flipped to+ * `Ready` once the initial snapshot is stored. A persisted `Pending` row is+ * an ensure that died or failed mid-init; the next ensure for the same id+ * retries initialization (the initializer tolerates an already-initialized+ * session), so `Pending` is self-healing rather than terminal.+ */+export type SurfaceState = 'pending' | 'ready';+export type SyncServiceVersionId = {counter: number;peer: string;@@ -10104,6 +10168,144 @@ export type PostChannelBotWebhookResponses = {export type PostChannelBotWebhookResponse = PostChannelBotWebhookResponses[keyof PostChannelBotWebhookResponses];+export type DeleteCollabSurfaceData = {+ body?: never;+ path: {+ /**+ * The surface id.+ */+ id: string;+ };+ query?: never;+ url: '/collab_surfaces/{id}';+};++export type DeleteCollabSurfaceErrors = {+ /**+ * Missing or invalid credentials+ */+ 401: ErrorResponse;+ 403: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type DeleteCollabSurfaceError = DeleteCollabSurfaceErrors[keyof DeleteCollabSurfaceErrors];++export type DeleteCollabSurfaceResponses = {+ /**+ * Deleted+ */+ 204: void;+};++export type DeleteCollabSurfaceResponse = DeleteCollabSurfaceResponses[keyof DeleteCollabSurfaceResponses];++export type GetCollabSurfaceData = {+ body?: never;+ path: {+ /**+ * The surface id.+ */+ id: string;+ };+ query?: never;+ url: '/collab_surfaces/{id}';+};++export type GetCollabSurfaceErrors = {+ /**+ * Missing or invalid credentials+ */+ 401: ErrorResponse;+ 403: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type GetCollabSurfaceError = GetCollabSurfaceErrors[keyof GetCollabSurfaceErrors];++export type GetCollabSurfaceResponses = {+ 200: CollabSurfaceResponse;+};++export type GetCollabSurfaceResponse = GetCollabSurfaceResponses[keyof GetCollabSurfaceResponses];++export type EnsureCollabSurfaceData = {+ body: EnsureCollabSurfaceRequest;+ path: {+ /**+ * The surface id.+ */+ id: string;+ };+ query?: never;+ url: '/collab_surfaces/{id}';+};++export type EnsureCollabSurfaceErrors = {+ 400: ErrorResponse;+ /**+ * Missing or invalid credentials+ */+ 401: ErrorResponse;+ /**+ * No access to the parent entity+ */+ 403: ErrorResponse;+ /**+ * The parent entity does not exist+ */+ 404: ErrorResponse;+ /**+ * The surface id was deleted and cannot be reused+ */+ 410: ErrorResponse;+ /**+ * Malformed request body (plain text)+ */+ 422: unknown;+ 500: ErrorResponse;+};++export type EnsureCollabSurfaceError = EnsureCollabSurfaceErrors[keyof EnsureCollabSurfaceErrors];++export type EnsureCollabSurfaceResponses = {+ 200: CollabSurfaceResponse;+};++export type EnsureCollabSurfaceResponse = EnsureCollabSurfaceResponses[keyof EnsureCollabSurfaceResponses];++export type CreateCollabSurfaceTokenData = {+ body?: never;+ path: {+ /**+ * The surface id.+ */+ id: string;+ };+ query?: never;+ url: '/collab_surfaces/{id}/token';+};++export type CreateCollabSurfaceTokenErrors = {+ /**+ * Missing or invalid credentials+ */+ 401: ErrorResponse;+ 403: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type CreateCollabSurfaceTokenError = CreateCollabSurfaceTokenErrors[keyof CreateCollabSurfaceTokenErrors];++export type CreateCollabSurfaceTokenResponses = {+ 200: CollabSurfaceTokenResponse;+};++export type CreateCollabSurfaceTokenResponse = CreateCollabSurfaceTokenResponses[keyof CreateCollabSurfaceTokenResponses];+export type GetChannelsData = {body?: never;path?: never;diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 68cebb21ad..7caac442b7 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -4132,6 +4132,313 @@}}},+ "/collab_surfaces/{id}": {+ "get": {+ "tags": ["collab_surfaces"],+ "summary": "Fetch a collab surface.",+ "operationId": "get_collab_surface",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The surface id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CollabSurfaceResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "put": {+ "tags": ["collab_surfaces"],+ "summary": "Idempotently ensure a collab surface exists (load-or-create).",+ "description": "The id is caller-supplied, so an embedding surface can hold a stable id\nand blindly ensure it on mount: the first ensure creates and initializes\nthe session, every later one (including concurrent ones) returns the same\nsurface. A soft-deleted id is `410 Gone` and never comes back.",+ "operationId": "ensure_collab_surface",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The surface id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EnsureCollabSurfaceRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CollabSurfaceResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "No access to the parent entity",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "The parent entity does not exist",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "410": {+ "description": "The surface id was deleted and cannot be reused",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "422": {+ "description": "Malformed request body (plain text)"+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["collab_surfaces"],+ "summary": "Soft-delete a collab surface.",+ "operationId": "delete_collab_surface",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The surface id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "Deleted"+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/collab_surfaces/{id}/token": {+ "post": {+ "tags": ["collab_surfaces"],+ "summary": "Mint a sync-service connection token for a surface.",+ "operationId": "create_collab_surface_token",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The surface id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CollabSurfaceTokenResponse"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/comms/channels": {"get": {"tags": ["channels"],@@ -14827,6 +15134,65 @@"type": "string","enum": ["document", "chat", "project"]},+ "CollabSurfaceResponse": {+ "type": "object",+ "description": "A collab surface, as returned by the API.",+ "required": ["id", "parentEntityType", "parentEntityId", "state"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "The surface id — also the sync-service session key."+ },+ "parentEntityId": {+ "type": "string",+ "description": "Id of the parent entity."+ },+ "parentEntityType": {+ "oneOf": [+ {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder",+ "skill",+ "agent_session"+ ]+ }+ ],+ "description": "Type of the parent entity."+ },+ "state": {+ "$ref": "#/components/schemas/SurfaceState",+ "description": "Lifecycle state (`ready` for every surface visible via the API)."+ }+ }+ },+ "CollabSurfaceTokenResponse": {+ "type": "object",+ "description": "Response carrying a freshly minted sync-service connection token.",+ "required": ["token"],+ "properties": {+ "token": {+ "type": "string",+ "description": "The signed JWT to pass to the sync-service websocket connect."+ }+ }+ },"Comment": {"type": "object","required": ["commentId", "threadId", "owner", "text"],@@ -17766,6 +18132,49 @@"type": "object","description": "Empty response is required due to custom fetch forcing `response.json()`"},+ "EnsureCollabSurfaceRequest": {+ "type": "object",+ "description": "Request body for ensuring a collab surface.",+ "required": ["parentEntityType", "parentEntityId"],+ "properties": {+ "initialMarkdown": {+ "type": "string",+ "description": "Markdown to seed the surface with when this ensure creates it. Empty\n(or omitted) seeds the canonical blank document. Ignored when the\nsurface already exists and is ready."+ },+ "parentEntityId": {+ "type": "string",+ "description": "Id of the parent entity (a uuid)."+ },+ "parentEntityType": {+ "oneOf": [+ {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder",+ "skill",+ "agent_session"+ ]+ }+ ],+ "description": "Type of the parent entity access derives from."+ }+ }+ },"EntityFilters": {"type": "object","description": "a bundle of all of the filters for each entity type",@@ -23833,6 +24242,11 @@}}},+ "SurfaceState": {+ "type": "string",+ "description": "Lifecycle state of a collab surface.\n\n`Pending` means the row exists but the sync-service session may not: the\nrow is inserted before the durable object is initialized and flipped to\n`Ready` once the initial snapshot is stored. A persisted `Pending` row is\nan ensure that died or failed mid-init; the next ensure for the same id\nretries initialization (the initializer tolerates an already-initialized\nsession), so `Pending` is self-healing rather than terminal.",+ "enum": ["pending", "ready"]+ },"SyncServiceVersionID": {"type": "object","required": ["peer", "counter"],diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 2be0152dd9..ce2f9c8a29 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -251,8 +251,11 @@ export const storageExcluded = ['callWebhook','checkActiveCall','createChannelScopedBot',+ 'createCollabSurfaceToken','createInstructionsHandler','createViewHandler',+ 'deleteCollabSurface',+ 'ensureCollabSurface','deleteHistoryHandler','deleteUserDocumentViewLocation','deleteViewHandler',@@ -263,6 +266,7 @@ export const storageExcluded = ['getBatchPreviewHandler','getActiveCalls','getBatchProjectPreview',+ 'getCollabSurface','getDocumentListHandler','getDocumentLocationV3','getDocumentProcessingResult',@@ -282,8 +286,8 @@ export const storageExcluded = ['ingestTranscript','initializeUserDocuments','installSync',- 'joinChannelByCode','jobProcessingResultHandler',+ 'joinChannelByCode','leaveOrEndCall','mentionPreviews','patchViewHandler',diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex 4ef3ac5b9e..b839cb5ea9 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -69,6 +69,10 @@ chat = { path = "../../crates/chat", default-features = false, features = [] }chrono = { workspace = true }clap = { workspace = true }+collab_surface = { path = "../../crates/collab_surface", features = [+ "inbound",+ "postgres",+] }cloudfront_sign = { workspace = true }comms_db_client = { path = "../../crates/comms_db_client" }complete_graph = { path = "../../crates/complete_graph" }diff --git a/services/document_storage_service/src/api.rs b/services/document_storage_service/src/api.rsindex d940221306..7ad9f0d63f 100644--- a/services/document_storage_service/src/api.rs+++ b/services/document_storage_service/src/api.rs@@ -229,6 +229,12 @@ fn api_router(state: ApiContext) -> Router {"/reminders",reminders::inbound::axum_router::reminders_router(state.reminders_state.clone()),)+ .nest(+ "/collab_surfaces",+ collab_surface::inbound::axum_router::collab_surface_router(+ state.collab_surface_state.clone(),+ ),+ ).nest("/foreign_entity",foreign_entity::inbound::axum_router::foreign_entity_router(diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex dc55030ada..4ed3129a42 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -63,6 +63,11 @@ use favorites::{};use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};+use collab_surface::{+ domain::service::CollabSurfaceServiceImpl, inbound::axum_router::CollabSurfaceRouterState,+ outbound::pg_collab_surface_repo::PgCollabSurfaceRepo,+ outbound::surface_init::LexicalSyncSurfaceInitializer,+};use foreign_entity::{domain::service::ForeignEntityServiceImpl, inbound::axum_router::ForeignEntityRouterState,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,@@ -439,6 +444,14 @@ pub(crate) type RemindersServiceType = RemindersServiceImpl<PgRemindersRepo>;pub(crate) type DssRemindersState =RemindersRouterState<RemindersServiceType, EntityAccessService, AuthorizationService>;+/// Type alias for the collab-surface service.+pub(crate) type CollabSurfaceServiceType =+ CollabSurfaceServiceImpl<PgCollabSurfaceRepo, LexicalSyncSurfaceInitializer>;++/// Type alias for the collab-surface router state.+pub(crate) type DssCollabSurfaceState =+ CollabSurfaceRouterState<CollabSurfaceServiceType, EntityAccessService, AuthorizationService>;+/// Type alias for the foreign entity service.pub(crate) type ForeignEntityServiceType = ForeignEntityServiceImpl<PgForeignEntityRepo>;@@ -490,6 +503,7 @@ pub(crate) struct ApiContext {pub favorites_state: DssFavoritesState,pub favorites_service: Arc<FavoritesServiceType>,pub reminders_state: DssRemindersState,+ pub collab_surface_state: DssCollabSurfaceState,pub foreign_entity_state: DssForeignEntityState,pub macro_event_broker: DssEventBroker,pub sqs_client: Arc<sqs_client::SQS>,diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex da36526704..d94dc18659 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -67,6 +67,10 @@ use channels::inbound::axum_router::{DeleteEntityMentionResponse, GetAttachmentReferencesResponse, GetMessageWithContextResponse,PostActivityRequest,};+use collab_surface::domain::models::SurfaceState;+use collab_surface::inbound::axum_router::{+ CollabSurfaceResponse, CollabSurfaceTokenResponse, EnsureCollabSurfaceRequest,+};use document_sub_type::DocumentSubType;use documents_hex::inbound::axum_router::{edit_document::EditDocumentResponse, get_branch_name::BranchNameResponse,@@ -312,6 +316,11 @@ use utoipa::OpenApi;reminders::inbound::axum_router::get_reminder_handler,reminders::inbound::axum_router::update_reminder_handler,reminders::inbound::axum_router::delete_reminder_handler,+ // collab surfaces+ collab_surface::inbound::axum_router::ensure_surface_handler,+ collab_surface::inbound::axum_router::get_surface_handler,+ collab_surface::inbound::axum_router::mint_token_handler,+ collab_surface::inbound::axum_router::delete_surface_handler,// foreign_entityforeign_entity::inbound::axum_router::get_foreign_entity_handler,@@ -455,6 +464,10 @@ use utoipa::OpenApi;ReminderSchedule,CreateReminderRequest,UpdateReminderRequest,+ CollabSurfaceResponse,+ CollabSurfaceTokenResponse,+ EnsureCollabSurfaceRequest,+ SurfaceState,SoupApiSort,SoupPage,SoupEnrichedEmailThreadPreview<SoupPropertiesField>,diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 3422c41102..3047729f08 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -51,6 +51,11 @@ use channels::{pg_channels_repo::PgChannelsRepo, pg_side_effect_context::PgChannelSideEffectContext,},};+use collab_surface::{+ domain::service::CollabSurfaceServiceImpl, inbound::axum_router::CollabSurfaceRouterState,+ outbound::pg_collab_surface_repo::PgCollabSurfaceRepo,+ outbound::surface_init::LexicalSyncSurfaceInitializer,+};use config::{Config, Environment};use connection::{domain::service::ConnectionServiceImpl,@@ -997,6 +1002,15 @@ async fn run() -> anyhow::Result<()> {// pool handle, so cloning is cheap and `SoupImpl` needs an owned service.let reminders_service = RemindersServiceImpl::new(PgRemindersRepo::new(db.clone()));+ let collab_surface_service = CollabSurfaceServiceImpl::new(+ Arc::new(PgCollabSurfaceRepo::new(db.clone())),+ Arc::new(LexicalSyncSurfaceInitializer::new(+ lexical_client.as_ref().clone(),+ sync_service_client.as_ref().clone(),+ )),+ config.document_permission_jwt.as_ref().to_string(),+ );+let soup_service = Arc::new(SoupImpl::new(PgSoupRepo::new(readonly_pool::ReadOnlyPool(readonly_db.clone())),frecency_service,@@ -1256,6 +1270,11 @@ async fn run() -> anyhow::Result<()> {entity_access_service.clone(),authorization_state.clone(),),+ collab_surface_state: CollabSurfaceRouterState::new(+ Arc::new(collab_surface_service),+ entity_access_service.clone(),+ authorization_state.clone(),+ ),graphql_soup_schema: complete_graph::build_schema_from_arcs(soup_service,soup_realtime_service,diff --git a/tooling/xtask/crates/xtask_nextest_filter/src/main.rs b/tooling/xtask/crates/xtask_nextest_filter/src/main.rsindex 62b9884e94..3e9d0ce59f 100644--- a/tooling/xtask/crates/xtask_nextest_filter/src/main.rs+++ b/tooling/xtask/crates/xtask_nextest_filter/src/main.rs@@ -31,6 +31,7 @@ const EMBEDDED_ASSET_PACKAGES: &[(&str, &[&str])] = &[("static_assets",&["cache-core",+ "collab_surface","complete_graph","documents","seed_cli",diff --git a/tooling/xtask/crates/xtask_nextest_filter/src/test.rs b/tooling/xtask/crates/xtask_nextest_filter/src/test.rsindex b59cdfe545..c79e4b6f31 100644--- a/tooling/xtask/crates/xtask_nextest_filter/src/test.rs+++ b/tooling/xtask/crates/xtask_nextest_filter/src/test.rs@@ -28,7 +28,7 @@ fn embedded_assets_select_their_consumers() {let filter = compute_filter(&graph, "static_assets/schema.graphql\n").unwrap();assert_eq!(filter,- "rdeps(=cache-core)|rdeps(=complete_graph)|rdeps(=documents)|rdeps(=seed_cli)|rdeps(=xtask_workflows)"+ "rdeps(=cache-core)|rdeps(=collab_surface)|rdeps(=complete_graph)|rdeps(=documents)|rdeps(=seed_cli)|rdeps(=xtask_workflows)");let mixed = compute_filter(@@ -38,7 +38,7 @@ fn embedded_assets_select_their_consumers() {.unwrap();assert_eq!(mixed,- "rdeps(=cache-core)|rdeps(=complete_graph)|rdeps(=documents)|rdeps(=email_validator)|rdeps(=seed_cli)|rdeps(=xtask_workflows)"+ "rdeps(=cache-core)|rdeps(=collab_surface)|rdeps(=complete_graph)|rdeps(=documents)|rdeps(=email_validator)|rdeps(=seed_cli)|rdeps(=xtask_workflows)");}