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
Add snippet document type with typeahead menu and team sharing (#3947)
Jacob Beckermandfc575c6e488
diff --git a/js/app/packages/app/component/Launcher.tsx b/js/app/packages/app/component/Launcher.tsxindex 79dbacfc20..33f223ae56 100644--- a/js/app/packages/app/component/Launcher.tsx+++ b/js/app/packages/app/component/Launcher.tsx@@ -1,8 +1,13 @@import { analytics } from '@app/lib/analytics';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { setAutomationComposerOpen } from '@block-automation/component';import type { BlockAlias, BlockName } from '@core/block';import { getIconConfig } from '@core/component/EntityIcon';-import { ENABLE_ANIMATED_ICONS } from '@core/constant/featureFlags';+import {+ ENABLE_ANIMATED_ICONS,+ ENABLE_SNIPPETS_FLAG,+ ENABLE_SNIPPETS_OVERRIDE,+} from '@core/constant/featureFlags';import {createHotkeyGroup,registerHotkey,@@ -20,6 +25,7 @@ import {createChat,createCodeFileFromText,createMarkdownFile,+ createSnippet,} from '@core/util/create';import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';import { AnimatedChatIcon } from '@icon/wide-chat';@@ -34,6 +40,8 @@ import { AnimatedFileCodeIcon } from '@icon/wide-fileCode';import { AnimatedFileMdIcon } from '@icon/wide-fileMd';import { AnimatedFolderIcon } from '@icon/wide-folder';import WideFolder from '@icon/wide-folder.svg';+import { AnimatedSnippetIcon } from '@icon/wide-snippet';+import WideSnippet from '@icon/wide-snippet.svg';import { AnimatedStarIcon } from '@icon/wide-star';import WideStar from '@icon/wide-star.svg';import { AnimatedTaskIcon } from '@icon/wide-task';@@ -98,7 +106,7 @@ const createBlock = async (spec: {// If we are creating a new markdown document "from scratch" then we can let// them instantly start editingconst createMdParams =- blockName === 'md'+ blockName === 'md' || blockName === 'snippet'? { optimisticSnapshot: await getMarkdownGoldenBytes() }: undefined;@@ -186,6 +194,18 @@ export function runCreateAction(asPopover: true,});return;+ case 'snippet':+ createBlock({+ blockName: 'snippet',+ loading: true,+ createFn: () =>+ createSnippet({+ title: '',+ content: '',+ }),+ shouldInsert,+ });+ return;case 'email':createComponent({componentId: 'email-compose',@@ -277,6 +297,20 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [return true;},},+ {+ label: 'Snippet',+ icon: WideSnippet,+ animatedIcon: AnimatedSnippetIcon,+ description: 'Create snippet',+ blockName: 'snippet',+ hotkeyToken: TOKENS.create.snippet,+ altHotkeyToken: TOKENS.create.snippetNewSplit,+ hotkey: 's' as const,+ keyDownHandler: () => {+ runCreateAction('snippet', { shouldInsert: pressedKeys().has('shift') });+ return true;+ },+ },{label: 'Email',icon: WideEmail,@@ -469,7 +503,13 @@ type LauncherInnerProps = {export const LauncherInner = (props: LauncherInnerProps) => {const hkGroup = createHotkeyGroup();- const blocks = () => props.blocks ?? CREATABLE_BLOCKS;+ const snippetsFlag = useFeatureFlag(ENABLE_SNIPPETS_FLAG, {+ enabledOverride: ENABLE_SNIPPETS_OVERRIDE,+ });+ const blocks = () =>+ (props.blocks ?? CREATABLE_BLOCKS).filter(+ (block) => block.blockName !== 'snippet' || snippetsFlag().enabled+ );const [attachHotkeys, launcherScope] = useHotkeyDOMScope('create-menu', true);let ref!: HTMLDivElement;diff --git a/js/app/packages/app/component/PreviewPanel.tsx b/js/app/packages/app/component/PreviewPanel.tsxindex eef76f657a..1b48479f1f 100644--- a/js/app/packages/app/component/PreviewPanel.tsx+++ b/js/app/packages/app/component/PreviewPanel.tsx@@ -4,7 +4,12 @@ import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';import type { BlockOrchestrator } from '@core/orchestrator';import { throttledDependent } from '@core/util/debounce';import type { NonNullableFields } from '@core/util/withRequired';-import { type EntityData, isChannelMessageEntity, isTaskEntity } from '@entity';+import {+ type EntityData,+ isChannelMessageEntity,+ isSnippetEntity,+ isTaskEntity,+} from '@entity';import { createContextProvider } from '@solid-primitives/context';import {type Component,@@ -68,7 +73,12 @@ const PreviewPanelContent: Component<NonNullableFields<PreviewPanel>> = (alias: 'task',baseType: 'md',} as BlockAliasContext)- : undefined;+ : isSnippetEntity(props.selectedEntity)+ ? ({+ alias: 'snippet',+ baseType: 'md',+ } as BlockAliasContext)+ : undefined;let blockType: BlockName;let blockId: string;diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.tsindex 002af2f39c..5da98a4815 100644--- a/js/app/packages/app/component/next-soup/utils.ts+++ b/js/app/packages/app/component/next-soup/utils.ts@@ -20,8 +20,8 @@ import {type EntityData,getSnippetHit,isGithubPrEntity,+ isHitSnippetEntity,isSearchEntity,- isSnippetEntity,type SearchLocation,toNotificationEntity,type WithSearch,@@ -324,7 +324,7 @@ export const openEntityInSplitFromUnifiedList = async (const { allowDuplicate, openInNewSplit, splitHandle, mergeHistory } = options;let { location } = options;- if (!location && isSnippetEntity(entity)) {+ if (!location && isHitSnippetEntity(entity)) {location = getSnippetHit(entity)?.location;}diff --git a/js/app/packages/app/index.css b/js/app/packages/app/index.cssindex 638602d973..6931a084ea 100644--- a/js/app/packages/app/index.css+++ b/js/app/packages/app/index.css@@ -154,6 +154,7 @@--color-html: oklch(from var(--a0) l c 47deg);--color-note: oklch(from var(--a0) l c 293deg);--color-task: oklch(from var(--a0) l c 150deg);+ --color-snippet: oklch(from var(--a0) l c 330deg);--color-pdf: oklch(from var(--a0) l c 25deg);--color-rss: oklch(from var(--a0) l c 260deg);--color-default: var(--c1);diff --git a/js/app/packages/block-canvas/component/nodes/TextBox.tsx b/js/app/packages/block-canvas/component/nodes/TextBox.tsxindex 4fb523487b..a3e751942c 100644--- a/js/app/packages/block-canvas/component/nodes/TextBox.tsx+++ b/js/app/packages/block-canvas/component/nodes/TextBox.tsx@@ -5,6 +5,7 @@ import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/corimport { NodeAccessoryRenderer } from '@core/component/LexicalMarkdown/component/core/NodeAccessoryRenderer';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 { LexicalWrapperContext } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';import {DefaultShortcuts,@@ -216,6 +217,15 @@ function TextBoxEditor(props: {menu={state.emojisMenuOps!}useBlockBoundary={true}/>+ <Show when={state.snippetsMenuOps}>+ {(menu) => (+ <SnippetsMenu+ editor={editor}+ menu={menu()}+ useBlockBoundary={true}+ />+ )}+ </Show></ScopedPortal><DecoratorRenderer editor={editor} /><NodeAccessoryRenderer editor={editor} store={state.accessoryStore!} />diff --git a/js/app/packages/block-md/component/InstructionsEditor.tsx b/js/app/packages/block-md/component/InstructionsEditor.tsxindex ee927d8254..8a4396becd 100644--- a/js/app/packages/block-md/component/InstructionsEditor.tsx+++ b/js/app/packages/block-md/component/InstructionsEditor.tsx@@ -7,6 +7,7 @@ import { FocusClickTarget } from '@core/component/LexicalMarkdown/component/coreimport { LexicalStateDebugger } from '@core/component/LexicalMarkdown/component/debug/LexicalStateDebugger';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,MarkdownEditorErrors,@@ -25,6 +26,7 @@ import {textPastePlugin,} from '@core/component/LexicalMarkdown/plugins';import { emojisPlugin } from '@core/component/LexicalMarkdown/plugins/emojis/emojisPlugin';+import { snippetsPlugin } from '@core/component/LexicalMarkdown/plugins/snippets';import { useUserPromptPlugin } from '@core/component/LexicalMarkdown/plugins/userPrompt';import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';import {@@ -149,6 +151,7 @@ export function InstructionsEditor(props: {const mentionsMenuOperations = createMenuOperations();const emojiMenuOperations = createMenuOperations();+ const snippetsMenuOperations = createMenuOperations();const peerIdValidator: Accessor<PeerIdValidator> = () => {if (!IS_SYNC()) {@@ -185,6 +188,12 @@ export function InstructionsEditor(props: {disableMentionTracking: true,}))+ .use(+ snippetsPlugin({+ menu: snippetsMenuOperations,+ peerIdValidator: peerIdValidator(),+ })+ ).use(textPastePlugin()).use(markdownPastePlugin()).use(@@ -423,6 +432,12 @@ export function InstructionsEditor(props: {disableMentionTracking={true}/>+ <SnippetsMenu+ editor={editor}+ menu={snippetsMenuOperations}+ useBlockBoundary={true}+ />+<Show when={DEBUG}><Show when={state()}>{(state) => (diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsxindex ed420c8e3c..8c4fd9ec0a 100644--- a/js/app/packages/block-md/component/MarkdownEditor.tsx+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx@@ -25,6 +25,7 @@ import { FloatingEquationMenu } from '@core/component/LexicalMarkdown/component/import { FloatingLinkMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingLinkMenu';import { GenerateMenu } from '@core/component/LexicalMarkdown/component/menu/GenerateMenu';import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu';+import { SnippetsMenu } from '@core/component/LexicalMarkdown/component/menu/SnippetsMenu';import TableActionMenu, {anchorElemRefSignal,menuButtonRefSignal,@@ -96,6 +97,7 @@ import {} from '@core/component/LexicalMarkdown/plugins/media';import { createAccessoryStore } from '@core/component/LexicalMarkdown/plugins/node-accessory';import { restoreFocusPlugin } from '@core/component/LexicalMarkdown/plugins/restore-focus';+import { snippetsPlugin } from '@core/component/LexicalMarkdown/plugins/snippets';import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';import {editorFocusSignal,@@ -293,6 +295,7 @@ export function MarkdownEditor(props: {const mentionsMenuOperations = createMenuOperations();const emojiMenuOperations = createMenuOperations();const actionsMenuOperations = createMenuOperations();+ const snippetsMenuOperations = createMenuOperations();// store for the drag insert pluign.const [dragInsertStore, setDragInsertStore] = createDragInsertStore();@@ -525,6 +528,12 @@ export function MarkdownEditor(props: {sourceDocumentId: blockId,}))+ .use(+ snippetsPlugin({+ menu: snippetsMenuOperations,+ peerIdValidator: peerIdValidator(),+ })+ ).use(actionsPlugin({menu: actionsMenuOperations,@@ -727,6 +736,7 @@ export function MarkdownEditor(props: {mentionsMenuOperations.isOpen() ||emojiMenuOperations.isOpen() ||actionsMenuOperations.isOpen() ||+ snippetsMenuOperations.isOpen() ||titleEditorMenuOpen());});@@ -1018,6 +1028,12 @@ export function MarkdownEditor(props: {showOpenTabs/>+ <SnippetsMenu+ editor={editor}+ menu={snippetsMenuOperations}+ useBlockBoundary={true}+ />+<ActionMenu editor={editor} menu={actionsMenuOperations} /><FloatingMenuGroup>diff --git a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsxindex f7badbcbc4..5ec5ac9629 100644--- a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx+++ b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx@@ -26,6 +26,10 @@ import {} from '@property/constants';import { useDocumentMetadataQuery } from '@queries/storage/document-metadata';import { useDocumentGithubPullRequestsQuery } from '@queries/storage/github-pull-requests';+import {+ useDocumentTeamShareQuery,+ useSetDocumentTeamShareMutation,+} from '@queries/storage/team-share';import type { EntityType as PropertiesEntityType } from '@service-properties/generated/schemas/entityType';import {blockNameToItemType,@@ -33,6 +37,7 @@ import {} from '@service-storage/client';import type { GithubPullRequest } from '@service-storage/generated/schemas';import { createCallback } from '@solid-primitives/rootless';+import { cn, InlineCheckbox } from '@ui';import {createEffect,createMemo,@@ -63,6 +68,7 @@ export function MarkdownSidePanelSections(const rawBlockName = useBlockName();const blockId = useBlockId();const isTask = () => blockName === 'task';+ const isSnippet = () => blockName === 'snippet';const itemType = blockNameToItemType(rawBlockName);const entity = (): Entity => ({ id: blockId, type: itemType as EntityType });@@ -72,6 +78,9 @@ export function MarkdownSidePanelSections(<SidePanel.Section id="details" title="Details" defaultOpen order={10}><DetailsSectionContent /></SidePanel.Section>+ <Show when={isSnippet()}>+ <SnippetSharingSectionConditional documentId={blockId} />+ </Show><SidePanel.Sectionid="properties"title="Properties"@@ -98,6 +107,69 @@ export function MarkdownSidePanelSections();}+// ─────────────────────────────────────────────────────────────────────────────+// Sharing Section (snippets)+// ─────────────────────────────────────────────────────────────────────────────++/**+ * "Share with team" toggle for snippets — same UI and behavior as the Calls+ * and CRM sharing sections. Only rendered when the snippet owner belongs to a+ * team; sharing grants the team Edit access so the snippet shows up in+ * teammates' `;` menus and they can collaboratively maintain it.+ */+function SnippetSharingSectionConditional(props: { documentId: string }) {+ const teamShareQuery = useDocumentTeamShareQuery(() => props.documentId);++ return (+ <Show when={teamShareQuery.data?.teamId}>+ <SidePanel.Section id="sharing" title="Sharing" defaultOpen order={15}>+ <SnippetSharingSectionContent documentId={props.documentId} />+ </SidePanel.Section>+ </Show>+ );+}++function SnippetSharingSectionContent(props: { documentId: string }) {+ const teamShareQuery = useDocumentTeamShareQuery(() => props.documentId);+ const setTeamShare = useSetDocumentTeamShareMutation();++ const isShared = () => teamShareQuery.data?.sharedWithTeam ?? false;+ const isDisabled = () => setTeamShare.isPending || teamShareQuery.isPending;++ const handleChange = (checked: boolean) => {+ setTeamShare.mutate({+ documentId: props.documentId,+ shareWithTeam: checked,+ });+ };++ return (+ <div class="flex flex-col gap-2 text-xs">+ <button+ type="button"+ role="checkbox"+ aria-checked={isShared()}+ disabled={isDisabled()}+ onClick={() => handleChange(!isShared())}+ class={cn(+ 'inline-flex items-center gap-2 rounded-md h-7 px-2.5 text-xs select-none w-fit',+ 'border border-ink-muted/[0.08] bg-ink-muted/[0.025]',+ 'text-ink-muted/70 hover:text-ink hover:bg-ink-muted/[0.06]',+ isShared() && 'text-ink',+ isDisabled() && 'pointer-events-none opacity-50'+ )}+ >+ <InlineCheckbox checked={isShared()} />+ <span class="whitespace-nowrap">Share with team</span>+ </button>+ <p class="text-ink-muted leading-5">+ Lets everyone on your team insert this snippet from the ; menu and edit+ it.+ </p>+ </div>+ );+}+// ─────────────────────────────────────────────────────────────────────────────// Details Section// ─────────────────────────────────────────────────────────────────────────────diff --git a/js/app/packages/block-md/definition.ts b/js/app/packages/block-md/definition.tsindex 05c3240e5b..5321498413 100644--- a/js/app/packages/block-md/definition.ts+++ b/js/app/packages/block-md/definition.ts@@ -17,7 +17,10 @@ export const definition = defineBlock({name: 'md',description: 'write markdown notes',defaultFilename: 'New Note',- aliases: [{ name: 'task', defaultFileName: 'New Task' }],+ aliases: [+ { name: 'task', defaultFileName: 'New Task' },+ { name: 'snippet', defaultFileName: 'New Snippet' },+ ],component: MarkdownBlock,accepted: {md: 'text/markdown',diff --git a/js/app/packages/core/block.ts b/js/app/packages/core/block.tsindex 777dbb4ad9..1ff8f72cf0 100644--- a/js/app/packages/core/block.ts+++ b/js/app/packages/core/block.ts@@ -77,7 +77,7 @@ export type BlockName = (typeof BlockRegistry)[BlockNameKeys];* List of strongly-typed, valid aliases that can be used as pseudo-differentiated* block types.*/-export const BlockAliasRegistry = ['csv', 'task'] as const;+export const BlockAliasRegistry = ['csv', 'task', 'snippet'] as const;type BlockAliasKeys = keyof typeof BlockAliasRegistry & number;@@ -150,6 +150,7 @@ const _ValidBlockCombinations: BlockCombinationRules = {contact: allBlockNames,company: allBlockNames,task: allBlockNames,+ snippet: allBlockNames,automation: allBlockNames,csv: allBlockNames,} as const;@@ -172,6 +173,7 @@ export const ValidNestingCombinations: BlockCombinationRules = {contact: new Set([]),company: new Set([]),task: new Set([]),+ snippet: new Set([]),automation: new Set([]),csv: new Set([]),};diff --git a/js/app/packages/core/component/EntityIcon.tsx b/js/app/packages/core/component/EntityIcon.tsxindex aee7660460..548bff26ed 100644--- a/js/app/packages/core/component/EntityIcon.tsx+++ b/js/app/packages/core/component/EntityIcon.tsx@@ -30,6 +30,7 @@ import WideFileMd from '@icon/wide-file-md.svg';import WideFiles from '@icon/wide-files.svg';import WideFolder from '@icon/wide-folder.svg';import WideGlobe from '@icon/wide-globe.svg';+import WideSnippet from '@icon/wide-snippet.svg';import WideStar from '@icon/wide-star.svg';import WideTask from '@icon/wide-task.svg';import WideUnknown from '@icon/wide-unknown.svg';@@ -267,6 +268,12 @@ export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {background: 'bg-task/20',prettyName: 'Task',},+ snippet: {+ icon: WideSnippet,+ foreground: 'text-snippet',+ background: 'bg-snippet/20',+ prettyName: 'Snippet',+ },automation: {icon: Robot,foreground: 'text-default',@@ -345,6 +352,7 @@ const WIDE_ICONS: Record<emailInvite: WideCalendar,githubPullRequest: GithubIcon,task: WideTask,+ snippet: WideSnippet,automation: Robot,crm_company: AnimatedCompanyIcon,company: AnimatedCompanyIcon,diff --git a/js/app/packages/core/component/FileList/constants.tsx b/js/app/packages/core/component/FileList/constants.tsxindex e9f32a9180..ad8eeffb2b 100644--- a/js/app/packages/core/component/FileList/constants.tsx+++ b/js/app/packages/core/component/FileList/constants.tsx@@ -75,5 +75,6 @@ const _fileTypeColors: Record<BlockName | BlockAlias | 'default', string> = {project: defaultFileColor,unknown: defaultFileColor,task: defaultFileColor,+ snippet: 'bg-snippet/20 group/item',automation: defaultFileColor,};diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsxindex 0fb47e11ce..049aa06f1b 100644--- a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx@@ -24,6 +24,7 @@ import { ActionMenu } from '../component/menu/ActionsMenu';import { EmojiMenu } from '../component/menu/EmojiMenu';import { FloatingLinkMenu } from '../component/menu/FloatingLinkMenu';import { MentionsMenu } from '../component/menu/MentionsMenu';+import { SnippetsMenu } from '../component/menu/SnippetsMenu';import { DragInsertIndicator } from '../component/misc/DragInsertIndicator';import { FloatingMenuGroup } from '../context/FloatingMenuContext';import { LexicalWrapperContext } from '../context/LexicalWrapperContext';@@ -295,6 +296,18 @@ export const MarkdownShell: Component<)}</Show>+ {/* Snippets Menu */}+ <Show when={state.snippetsMenuOps}>+ {(menu) => (+ <SnippetsMenu+ editor={editor}+ menu={menu()}+ useBlockBoundary={false}+ portalScope={props.portalScope}+ />+ )}+ </Show>+{/* Floating Link Menu */}<Show when={builderConfig.links?.floatingMenu}><FloatingMenuGroup>diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts b/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.tsindex f194a1cd52..60c24f9497 100644--- a/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts+++ b/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts@@ -21,6 +21,7 @@ import {mentionsPlugin,selectionDataPlugin,singleLinePlugin,+ snippetsPlugin,tabIndentationPlugin,textPastePlugin,} from '../plugins';@@ -73,6 +74,14 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {: undefined;const mentionsMenuOps = config.mentions ? createMenuOperations() : undefined;const emojisMenuOps = config.emojis ? createMenuOperations() : undefined;+ // Snippets (`;` menu) follow mentions: any markdown area that can @-mention+ // can also insert snippets, unless explicitly opted out. Editors with a+ // custom mention entity source (sandbox/onboarding) are excluded — the+ // snippets menu reads from quickAccess, which those editors bypass.+ const snippetsMenuOps =+ config.mentions && !config.mentions.entities && config.snippets !== false+ ? createMenuOperations()+ : undefined;const accessoryStoreResult = config.code ? createAccessoryStore() : undefined;const accessoryStore = accessoryStoreResult?.[0];@@ -157,6 +166,10 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {if (emojisMenuOps) {plugins.use(emojisPlugin({ menu: emojisMenuOps }));}++ if (snippetsMenuOps) {+ plugins.use(snippetsPlugin({ menu: snippetsMenuOps }));+ }}// Media (images, videos)@@ -252,7 +265,8 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {ignoreKeys: () =>(actionsMenuOps?.isOpen() ?? false) ||(mentionsMenuOps?.isOpen() ?? false) ||- (emojisMenuOps?.isOpen() ?? false),+ (emojisMenuOps?.isOpen() ?? false) ||+ (snippetsMenuOps?.isOpen() ?? false),}));}@@ -275,7 +289,8 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {const mentions = mentionsMenuOps?.isOpen() ?? false;const emojis = emojisMenuOps?.isOpen() ?? false;const actions = actionsMenuOps?.isOpen() ?? false;- return mentions || emojis || actions;+ const snippets = snippetsMenuOps?.isOpen() ?? false;+ return mentions || emojis || actions || snippets;},};@@ -295,6 +310,7 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {actionsMenuOps,mentionsMenuOps,emojisMenuOps,+ snippetsMenuOps,accessoryStore,dragInsertStore,draggableBlockStore,diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/types.ts b/js/app/packages/core/component/LexicalMarkdown/builder/types.tsindex e775ff6cf0..a75b4abe0a 100644--- a/js/app/packages/core/component/LexicalMarkdown/builder/types.ts+++ b/js/app/packages/core/component/LexicalMarkdown/builder/types.ts@@ -119,6 +119,8 @@ export interface EditorConfig {type: EditorType;namespace: string;mentions?: MentionsOptions;+ /** Snippets (`;` menu) follow mentions by default; pass false to opt out. */+ snippets?: false;emojis?: EmojisOptions;links?: LinksOptions;history?: HistoryOptions;@@ -151,6 +153,7 @@ export interface EditorInternals {actionsMenuOps: ReturnType<typeof createMenuOperations> | undefined;mentionsMenuOps: ReturnType<typeof createMenuOperations> | undefined;emojisMenuOps: ReturnType<typeof createMenuOperations> | undefined;+ snippetsMenuOps: ReturnType<typeof createMenuOperations> | undefined;accessoryStore: ReturnType<typeof createAccessoryStore>[0] | undefined;dragInsertStore: ReturnType<typeof createDragInsertStore>[0] | undefined;draggableBlockStore:diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsxindex b69c291fef..e5c62851e9 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx@@ -42,6 +42,7 @@ import {mentionsPlugin,type SelectionData,selectionDataPlugin,+ snippetsPlugin,tabIndentationPlugin,textPastePlugin,} from '../../plugins';@@ -58,6 +59,7 @@ import type { UserMentionRecord } from '../../utils/mentionsUtils';import { EmojiMenu } from '../menu/EmojiMenu';import { FloatingLinkMenu } from '../menu/FloatingLinkMenu';import { MentionsMenu } from '../menu/MentionsMenu';+import { SnippetsMenu } from '../menu/SnippetsMenu';import { DecoratorRenderer } from './DecoratorRenderer';import { NodeAccessoryRenderer } from './NodeAccessoryRenderer';@@ -179,6 +181,7 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {const mentionsMenuOperations = createMenuOperations();const emojisMenuOperations = createMenuOperations();+ const snippetsMenuOperations = createMenuOperations();plugins.richText()@@ -207,7 +210,8 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {onRemoveMention: props.onRemoveMention,}))- .use(emojisPlugin({ menu: emojisMenuOperations }));+ .use(emojisPlugin({ menu: emojisMenuOperations }))+ .use(snippetsPlugin({ menu: snippetsMenuOperations }));if (props.onPasteFilesAndDirs) {plugins.use(@@ -241,7 +245,9 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {onFocusLeaveStart: props.onFocusLeaveStart,onFocusLeaveEnd: props.onFocusLeaveEnd,ignoreKeys: () =>- mentionsMenuOperations.isOpen() || emojisMenuOperations.isOpen(),+ mentionsMenuOperations.isOpen() ||+ emojisMenuOperations.isOpen() ||+ snippetsMenuOperations.isOpen(),});}}@@ -362,6 +368,12 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {portalScope={props.portalScope}useBlockBoundary={props.useBlockBoundary}/>+ <SnippetsMenu+ editor={editor}+ menu={snippetsMenuOperations}+ portalScope={props.portalScope}+ useBlockBoundary={props.useBlockBoundary}+ /><FloatingMenuGroup><FloatingLinkMenu /></FloatingMenuGroup>diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex e19928c2bd..1939905d32 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -112,7 +112,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {const customDocs = props.entities? useEntityMentionFromList({items: props.entities,- buckets: ['note', 'task', 'document', 'project', 'chat'],+ buckets: ['note', 'task', 'snippet', 'document', 'project', 'chat'],searchTerm,}): undefined;@@ -137,7 +137,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {const { searchedEntities: docs } =customDocs ??useEntityMention({- buckets: ['note', 'task', 'document', 'project', 'chat'],+ buckets: ['note', 'task', 'snippet', 'document', 'project', 'chat'],searchTerm,});diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.tsindex e573e02518..afc1be222f 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts@@ -17,6 +17,7 @@ export function getBlockNameFromEntity(.with('chat', () => 'chat' as const).with('project', () => 'project' as const).with('task', () => 'task' as const)+ .with('snippet', () => 'snippet' as const).with('note', () => 'md' as const).with('crm_company', () => 'company' as const).otherwise(() => {diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsxnew file mode 100644index 0000000000..b80bff140e--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx@@ -0,0 +1,298 @@+import { useAnalytics } from '@app/component/analytics-context';+import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';+import type { EntityItem } from '@core/context/quickAccess';+import clickOutside from '@core/directive/clickOutside';+import { debouncedDependent } from '@core/util/debounce';+import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';+import { syncServiceClient } from '@service-sync/client';+import { Surface } from '@ui';+import {+ $insertNodes,+ $parseSerializedNode,+ createEditor,+ type LexicalEditor,+} from 'lexical';+import {+ createEffect,+ createSignal,+ For,+ onCleanup,+ onMount,+ Show,+ Suspense,+ untrack,+} from 'solid-js';+import { createLexicalWrapper } from '../../../context/LexicalWrapperContext';+import { floatWithSelection } from '../../../directive/floatWithSelection';+import {+ CLOSE_SNIPPET_SEARCH_COMMAND,+ REMOVE_SNIPPET_SEARCH_COMMAND,+} from '../../../plugins/snippets';+import type { MenuOperations } from '../../../shared/inlineMenu';+import {+ editorStateAsMarkdown,+ initializeEditorWithState,+ setEditorStateFromMarkdown,+} from '../../../utils';+import { MentionsMenuItem } from '../MentionsMenu/components/MentionsMenuItem';+import { useEntityMention } from '../MentionsMenu/hooks/useEntityMention';+import { useMenuKeyboardNavigation } from '../useMenuKeyboardNavigation';++false && clickOutside;+false && floatWithSelection;++// Height consumed by Surface's border + vertical padding+const PANEL_DECORATION_HEIGHT = 18;++type SnippetsMenuProps = {+ editor: LexicalEditor;+ menu: MenuOperations;+ /** whether the menu checks against block boundary in floating middleware. uses floating-ui default if false. */+ useBlockBoundary?: boolean;+ portalScope?: PortalScope;+};++/**+ * Fetch a snippet document's content and render it to internal markdown.+ * Content lives in sync-service; a throwaway markdown editor converts the+ * serialized state to a markdown string the target editor can ingest.+ */+async function fetchSnippetMarkdown(documentId: string): Promise<string> {+ const rawState = await syncServiceClient.getRaw({ documentId });++ const { editor, cleanup } = createLexicalWrapper({+ type: 'markdown',+ namespace: 'snippet-markdown-extractor',+ isInteractable: () => false,+ });++ try {+ initializeEditorWithState(editor, rawState);+ return editorStateAsMarkdown(editor, 'internal');+ } finally {+ cleanup();+ }+}++/**+ * Typeahead menu opened by typing `;` in a markdown area. Lists snippet+ * documents the user can access (their own + team-shared); selecting one+ * inserts the snippet's markdown body at the cursor.+ */+export function SnippetsMenu(props: SnippetsMenuProps) {+ return (+ <Suspense>+ <SnippetsMenuInner {...props} />+ </Suspense>+ );+}++function SnippetsMenuInner(props: SnippetsMenuProps) {+ const analytics = useAnalytics();++ const searchTerm = debouncedDependent(props.menu.searchTerm, 60);++ const { searchedEntities: snippets } = useEntityMention({+ buckets: ['snippet'],+ searchTerm,+ });++ const [selectedIndex, setSelectedIndex] = createSignal(0);+ const [mountSelection, setMountSelection] = createSignal<Selection | null>();+ const [escapeSpaceState, setEscapeSpaceState] = createSignal<+ 'start' | 'single' | null+ >('start');++ const { isKeypressActive } = useIsKeyPressActive();+ const setSelectedIndexFromMouse = (index: number) => {+ if (isKeypressActive()) return;+ setSelectedIndex(index);+ };++ const [menuOpen, setMenuOpen] = [props.menu.isOpen, props.menu.setIsOpen];++ createEffect(() => {+ if (menuOpen()) {+ setMountSelection(document.getSelection());+ setSelectedIndex(0);+ setEscapeSpaceState('start');+ } else {+ setMountSelection(null);+ }+ });++ createEffect(() => {+ searchTerm();+ setSelectedIndex(0);+ });++ createEffect(() => {+ const count = snippets().length;+ if (count > 0 && selectedIndex() >= count) {+ setSelectedIndex(count - 1);+ }+ });++ const closeMenu = () => {+ props.editor.dispatchCommand(CLOSE_SNIPPET_SEARCH_COMMAND, undefined);+ setMenuOpen(false);+ };++ const insertSnippet = async (item: EntityItem) => {+ analytics.track('snippets_menu_use', {});+ props.editor.dispatchCommand(REMOVE_SNIPPET_SEARCH_COMMAND, undefined);+ props.menu.setSearchTerm('');+ setMenuOpen(false);++ let markdown: string;+ try {+ markdown = await fetchSnippetMarkdown(item.id);+ } catch (error) {+ console.error('failed to load snippet content', error);+ return;+ }+ if (!markdown.trim()) return;++ // Same technique as the markdown paste plugin: parse the markdown with a+ // throwaway editor restricted to the target editor's nodes, then insert+ // the resulting nodes at the cursor.+ props.editor.update(() => {+ const parseEditor = createEditor({+ namespace: 'snippet-parser',+ editable: false,+ nodes: [+ ...Array.from(props.editor._nodes.values()).map((node) => node.klass),+ ],+ });+ setEditorStateFromMarkdown(parseEditor, markdown, 'both');+ const state = parseEditor.getEditorState().toJSON();+ const nodes = state.root.children.map((node) =>+ $parseSerializedNode(node)+ );+ $insertNodes(nodes);+ });+ };++ const itemAction = (item: EntityItem) => {+ void insertSnippet(item);+ };++ useMenuKeyboardNavigation({+ isActive: menuOpen,+ onUp: () => {+ const items = snippets();+ if (items.length === 0) return;+ setSelectedIndex((selectedIndex() - 1 + items.length) % items.length);+ },+ onDown: () => {+ const items = snippets();+ if (items.length === 0) return;+ setSelectedIndex((selectedIndex() + 1) % items.length);+ },+ onLeft: () => {+ // block horizontal arrows+ },+ onRight: () => {+ // block horizontal arrows+ },+ onSelect: () => {+ const selectedItem = snippets()[selectedIndex()];+ if (selectedItem) {+ itemAction(selectedItem);+ } else {+ closeMenu();+ }+ },+ onClose: closeMenu,+ onSpace: () => {+ switch (escapeSpaceState()) {+ case 'single':+ case 'start':+ closeMenu();+ return true;+ case null:+ setEscapeSpaceState('single');+ return false;+ }+ return false;+ },+ onOtherKey: () => {+ setEscapeSpaceState(null);+ },+ });++ const focusOut = () => {+ closeMenu();+ };+ onMount(() => {+ document.addEventListener('focusout', focusOut);+ onCleanup(() => {+ document.removeEventListener('focusout', focusOut);+ });+ });++ const [menuAvailableHeight, setMenuAvailableHeight] = createSignal<+ number | undefined+ >(undefined);++ const contentMaxHeight = () => {+ const h = menuAvailableHeight();+ if (h === undefined) return 256;+ return Math.min(256, Math.max(0, h - PANEL_DECORATION_HEIGHT));+ };++ return (+ <Show when={menuOpen()}>+ <ScopedPortal scope={props.portalScope}>+ <div+ class="w-96 max-w-[calc(100cqw-1rem-2px)] cursor-default select-none z-modal-content"+ use:floatWithSelection={{+ selection: untrack(mountSelection),+ reactiveOnContainer: props.editor.getRootElement(),+ useBlockBoundary: props.useBlockBoundary,+ onAvailableHeight: setMenuAvailableHeight,+ }}+ use:clickOutside={() => {+ closeMenu();+ }}+ on:touchstart={(e) => e.stopPropagation()}+ >+ <Surface+ depth={2}+ class="pt-2 pb-1.5 shadow-lg shadow-drop-shadow rounded-xl"+ >+ <div class="px-3.5 pb-1 text-xs font-medium text-ink-muted">+ Snippets+ </div>+ <Show+ when={snippets().length > 0}+ fallback={+ <div class="px-3.5 pb-1 text-ink-extra-muted">+ {searchTerm() ? 'No results' : 'No snippets yet'}+ </div>+ }+ >+ <div+ class="overflow-y-auto scrollbar-hidden"+ style={{ 'max-height': `${contentMaxHeight()}px` }}+ >+ <For each={snippets()}>+ {(item, index) => (+ <MentionsMenuItem+ item={item}+ index={index()}+ selected={index() === selectedIndex()}+ itemAction={() => itemAction(item)}+ setIndex={setSelectedIndexFromMouse}+ setOpen={setMenuOpen}+ />+ )}+ </For>+ </div>+ </Show>+ </Surface>+ </div>+ </ScopedPortal>+ </Show>+ );+}diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/index.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/index.tsnew file mode 100644index 0000000000..d937646131--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/index.ts@@ -0,0 +1 @@+export { SnippetsMenu } from './SnippetsMenu';diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/index.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/index.tsindex eb80c50801..fc6010a27d 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/index.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/index.ts@@ -34,6 +34,7 @@ export * from './popup';export * from './selection-data';export * from './shared';export * from './single-line';+export * from './snippets';export * from './tab-indentation';export * from './tables';export * from './text-paste';diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/index.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/index.tsnew file mode 100644index 0000000000..afca96eb0e--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/index.ts@@ -0,0 +1 @@+export * from './snippetsPlugin';diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.tsnew file mode 100644index 0000000000..0aebd6b70f--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts@@ -0,0 +1,142 @@+import { ENABLE_SNIPPETS } from '@core/constant/featureFlags';+import { mergeRegister } from '@lexical/utils';+import type { PeerIdValidator } from '@lexical-core';+import {+ $collapseInlineSearch,+ $createInlineSearchNode,+ $handleInlineSearchNodeMutation,+ $handleInlineSearchNodeTransform,+ $removeInlineSearch,+ InlineSearchNode,+ InlineSearchNodesType,+ validTriggerPosition,+} from '@lexical-core';+import {+ $insertNodes,+ COMMAND_PRIORITY_CRITICAL,+ COMMAND_PRIORITY_HIGH,+ COMMAND_PRIORITY_LOW,+ createCommand,+ KEY_ENTER_COMMAND,+ KEY_ESCAPE_COMMAND,+ type LexicalCommand,+ type LexicalEditor,+} from 'lexical';+import type { MenuOperations } from '../../shared/inlineMenu';++const TYPE_SNIPPET_SYMBOL_COMMAND: LexicalCommand<void> = createCommand(+ 'SNIPPET_SYMBOL_COMMAND'+);++export const CLOSE_SNIPPET_SEARCH_COMMAND: LexicalCommand<void> = createCommand(+ 'CLOSE_SNIPPET_SEARCH_COMMAND'+);++export const REMOVE_SNIPPET_SEARCH_COMMAND: LexicalCommand<void> =+ createCommand('REMOVE_SNIPPET_SEARCH_COMMAND');++type SnippetsPluginProps = {+ menu: MenuOperations;+ peerIdValidator?: PeerIdValidator;+};++/**+ * Registers the `;` trigger for the snippets menu. Typing `;` at a valid+ * trigger position (start of line or after whitespace) opens a typeahead+ * listing snippet documents; selecting one inserts the snippet's markdown+ * body at the cursor (see SnippetsMenu).+ */+function registerSnippetsPlugin(+ editor: LexicalEditor,+ props: SnippetsPluginProps+) {+ function registerSymbolListener() {+ const listener = (e: KeyboardEvent) => {+ if (e.key === ';') {+ editor.dispatchCommand(TYPE_SNIPPET_SYMBOL_COMMAND, undefined);+ }+ };++ return editor.registerRootListener((root, prev) => {+ if (root) {+ root.addEventListener('keydown', listener);+ }+ if (prev) {+ prev.removeEventListener('keydown', listener);+ }+ });+ }++ const { menu } = props;++ function typeSymbolCommand() {+ // Checked per keystroke so the PostHog flag applies without a reload;+ // when disabled the `;` falls through as regular text.+ if (!ENABLE_SNIPPETS()) return false;+ const shouldTrigger = validTriggerPosition(editor);+ if (shouldTrigger) {+ editor.update(() => {+ $insertNodes([$createInlineSearchNode(';')]);+ });+ return true;+ }+ return false;+ }++ return mergeRegister(+ registerSymbolListener(),+ // When you type ;+ editor.registerCommand(+ TYPE_SNIPPET_SYMBOL_COMMAND,+ typeSymbolCommand,+ COMMAND_PRIORITY_LOW+ ),+ editor.registerCommand(+ CLOSE_SNIPPET_SEARCH_COMMAND,+ () => $collapseInlineSearch(props.peerIdValidator),+ COMMAND_PRIORITY_LOW+ ),+ editor.registerCommand(+ KEY_ESCAPE_COMMAND,+ () => $collapseInlineSearch(props.peerIdValidator),+ COMMAND_PRIORITY_HIGH+ ),++ editor.registerCommand(+ REMOVE_SNIPPET_SEARCH_COMMAND,+ () => $removeInlineSearch(props.peerIdValidator),+ COMMAND_PRIORITY_HIGH+ ),+ // Menu ENTERS should not propagate to the editor.+ editor.registerCommand(+ KEY_ENTER_COMMAND,+ () => menu.isOpen(),+ COMMAND_PRIORITY_CRITICAL+ ),+ editor.registerNodeTransform(InlineSearchNode, (node: InlineSearchNode) =>+ $handleInlineSearchNodeTransform(node, InlineSearchNodesType.Snippets)+ ),+ editor.registerMutationListener(+ InlineSearchNode,+ (mutatedNodes, { prevEditorState }) =>+ $handleInlineSearchNodeMutation(+ editor,+ prevEditorState,+ mutatedNodes,+ InlineSearchNodesType.Snippets,+ {+ onDestroy: () => menu.closeMenu(),+ onCreate: () => menu.openMenu(),+ onUpdate: (search) => {+ menu.setSearchTerm(search);+ },+ },+ props.peerIdValidator+ )+ )+ );+}++export function snippetsPlugin(props: SnippetsPluginProps) {+ return (editor: LexicalEditor) => registerSnippetsPlugin(editor, props);+}diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.tsindex 9b916b30c9..6541b2863c 100644--- a/js/app/packages/core/constant/featureFlags.ts+++ b/js/app/packages/core/constant/featureFlags.ts@@ -365,6 +365,22 @@ export const ENABLE_SOUP_GROUP_BY_OVERRIDE = DEV_MODE_ENV ? true : undefined;export const ENABLE_TASK_DUPLICATES_FLAG = 'enable-task-duplicates';export const ENABLE_TASK_DUPLICATES_OVERRIDE = DEV_MODE_ENV ? true : undefined;+// Snippets: reusable markdown documents, the `c` launcher entry, and the `;`+// insert menu. PostHog-gated (currently targeted at the Macro team) with a+// dev-mode default; override with VITE_ENABLE_SNIPPETS.+export const ENABLE_SNIPPETS_FLAG = 'enable-snippets';+export const ENABLE_SNIPPETS_OVERRIDE =+ resolveFeatureFlag('ENABLE_SNIPPETS', DEV_MODE_ENV) || undefined;++/** Non-reactive check for imperative call sites (e.g. editor key handlers). */+export function ENABLE_SNIPPETS(): boolean {+ if (ENABLE_SNIPPETS_OVERRIDE !== undefined) {+ return ENABLE_SNIPPETS_OVERRIDE;+ }++ return analytics.posthog.isFeatureEnabled(ENABLE_SNIPPETS_FLAG) ?? false;+}+export const ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_FLAG ='enable-supported-soup-foreign-entities';export const ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE = DEV_MODE_ENVdiff --git a/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsxindex 37f3aadc13..5be530371f 100644--- a/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx+++ b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx@@ -7,10 +7,11 @@ import {useIsConnectedSecondaryInbox,} from '@core/user';import type { DateValue } from '@core/util/date';-import type { ChannelEntity, CrmCompanyEntity } from '@entity';+import type { ChannelEntity, CrmCompanyEntity, SnippetEntity } from '@entity';import { queryReadyGate } from '@queries/gate';import { type HistoryItem, useHistoryQuery } from '@queries/history/history';import { useQuickAccessCrmCompaniesQuery } from '@queries/soup/quick-access-crm-companies';+import { useQuickAccessSnippetsQuery } from '@queries/soup/quick-access-snippets';import { useRecentlyViewedSoupQuery } from '@queries/soup/recently-viewed';import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';@@ -127,6 +128,7 @@ function getBucketForHistoryItem(item: HistoryItem): EntityBucket {return 'project';case 'document': {if (item.subType?.type === 'task') return 'task';+ if (item.subType?.type === 'snippet') return 'snippet';if (item.fileType === 'md') return 'note';return 'document';}@@ -178,6 +180,10 @@ function getCrmCompanyVersion(return `${company.name}|${domains}|${company.updatedAt}|${viewedAt}`;}+function getSnippetVersion(snippet: SnippetEntity, viewedAt?: string): string {+ return `${snippet.name}|${snippet.updatedAt}|${viewedAt}`;+}+/*** Merge two *already* sorted index arrays into a single sorted array.*/@@ -230,6 +236,8 @@ export const [QuickAccessProvider, useQuickAccess] =const instructionsIdQuery = useInstructionsMdIdQuery();const { query: crmCompaniesQuery, companies: crmCompaniesAccessor } =useQuickAccessCrmCompaniesQuery();+ const { query: snippetsQuery, snippets: snippetsAccessor } =+ useQuickAccessSnippetsQuery();// globally hidden idsconst [hiddenIds, setHiddenIds] = createSignal<Set<string>>(new Set());@@ -505,6 +513,73 @@ export const [QuickAccessProvider, useQuickAccess] =}}+ // Process snippets (live soup list, complements the history feed+ // which only has snippets the user has opened). Widens the pool to+ // team-shared snippets so the `;` menu lists snippets the user has+ // never opened. History-fed entries win for snippets the user has+ // already opened.+ const snippetData = snippetsAccessor();+ for (const snippet of snippetData) {+ if (hidden.has(snippet.id)) continue;+ if (seenIds.has(snippet.id)) continue;+ seenIds.add(snippet.id);++ const viewedAt =+ viewedAtMap.get(snippet.id) ?? snippet.viewedAt ?? undefined;++ const version = getSnippetVersion(+ snippet,+ viewedAt as string | undefined+ );+ const cached = itemCache.get(snippet.id);++ if (!cached || cached.version !== version) {+ const reason = !cached+ ? 'new'+ : `changed (${cached.version} -> ${version})`;+ transformedItems.push({+ id: snippet.id,+ name: snippet.name,+ type: 'snippet',+ reason,+ });+ const entity: SnippetEntity = {+ ...snippet,+ viewedAt: (viewedAt ?? snippet.viewedAt) as DateValue | null,+ };+ const viewedAtMs = toTimestamp(viewedAt);+ const updatedAtMs = toTimestamp(snippet.updatedAt);+ const sortTimestamp = viewedAtMs || updatedAtMs;++ const quickAccessItem: QuickAccessItem = {+ kind: 'entity',+ id: snippet.id,+ bucket: 'snippet',+ searchText: getEntitySearchText(entity),+ sortTimestamp,+ timestamps: {+ viewedAt,+ updatedAt: snippet.updatedAt,+ createdAt: snippet.createdAt,+ },+ data: entity,+ };++ itemCache.set(snippet.id, { item: quickAccessItem, version });+ allEntries.push({+ id: snippet.id,+ bucket: 'snippet',+ sortTimestamp,+ });+ } else {+ allEntries.push({+ id: snippet.id,+ bucket: cached.item.bucket,+ sortTimestamp: cached.item.sortTimestamp,+ });+ }+ }+// Clean up stale cache entries (items that no longer exist)for (const id of itemCache.keys()) {if (!seenIds.has(id)) {@@ -571,6 +646,7 @@ export const [QuickAccessProvider, useQuickAccess] =indices.get('document') ?? [],indices.get('note') ?? [],indices.get('task') ?? [],+ indices.get('snippet') ?? [],indices.get('chat') ?? [],indices.get('project') ?? [],]),@@ -638,6 +714,7 @@ export const [QuickAccessProvider, useQuickAccess] =const refresh = () => {historyQuery.refetch();crmCompaniesQuery.refetch();+ snippetsQuery.refetch();};return {diff --git a/js/app/packages/core/context/quickAccess/types.ts b/js/app/packages/core/context/quickAccess/types.tsindex 6a273d2b28..ca2c5e3fbf 100644--- a/js/app/packages/core/context/quickAccess/types.ts+++ b/js/app/packages/core/context/quickAccess/types.ts@@ -8,6 +8,7 @@ import type {EmailEntity,EntityData,ProjectEntity,+ SnippetEntity,TaskEntity,} from '@entity';import type { Accessor } from 'solid-js';@@ -22,6 +23,7 @@ export type Bucket =| 'person'| 'document'| 'task'+ | 'snippet'| 'note'| 'chat'| 'project'@@ -36,6 +38,7 @@ const ALL_BUCKETS: Bucket[] = ['person','document','task',+ 'snippet','note','chat','project',@@ -48,7 +51,7 @@ export type BucketCombination = 'all' | 'channels' | 'documents';export const BUCKET_COMBINATIONS: Record<BucketCombination, Bucket[]> = {all: ALL_BUCKETS,channels: ['dm', 'channel'],- documents: ['document', 'note', 'task', 'chat', 'project'],+ documents: ['document', 'note', 'task', 'snippet', 'chat', 'project'],};type ItemTimestamps = {@@ -110,6 +113,7 @@ export type BucketItemMap = {dm: EntityItem<ChannelEntity>;document: EntityItem<DocumentEntity>;task: EntityItem<TaskEntity>;+ snippet: EntityItem<SnippetEntity>;note: EntityItem<DocumentEntity>;chat: EntityItem<ChatEntity>;project: EntityItem<ProjectEntity>;diff --git a/js/app/packages/core/hotkey/tokens.ts b/js/app/packages/core/hotkey/tokens.tsindex 33f968b8dd..0ee40dce6c 100644--- a/js/app/packages/core/hotkey/tokens.ts+++ b/js/app/packages/core/hotkey/tokens.ts@@ -244,6 +244,8 @@ export const TOKENS = {codeNewSplit: 'create.codeNewSplit',task: 'create.task',taskNewSplit: 'create.taskNewSplit',+ snippet: 'create.snippet',+ snippetNewSplit: 'create.snippetNewSplit',close_menu: 'create.close_menu',},diff --git a/js/app/packages/core/util/create.ts b/js/app/packages/core/util/create.tsindex bcb9cd431a..d891d62251 100644--- a/js/app/packages/core/util/create.ts+++ b/js/app/packages/core/util/create.ts@@ -119,6 +119,43 @@ export async function createTask(return documentId;}+type CreateSnippetArgs = {+ title?: string;+ content?: string;+ projectId?: string;+};++/**+ * Creates a snippet using the create_snippet endpoint.+ * Content is initialized via sync service. Snippets are created personal;+ * team sharing is toggled from the snippet's side panel.+ */+export async function createSnippet(+ args?: CreateSnippetArgs+): Promise<string | undefined> {+ const result = await storageServiceClient.createSnippet({+ snippetName: args?.title ?? '',+ markdown: args?.content ?? '',+ projectId: args?.projectId,+ });++ invalidateUserQuota();++ if (result.isErr()) return;++ const { documentId } = result.value;++ setPreviewOnCreate({+ itemId: documentId,+ itemType: 'document',+ name: args?.title ?? '',+ fileType: 'md',+ subType: { type: 'snippet' },+ });+ refetchSoupEntity(documentId, 'document');+ return documentId;+}+export async function createCodeFileFromText({code,extension,diff --git a/js/app/packages/entity/src/composed/ListEntity.tsx b/js/app/packages/entity/src/composed/ListEntity.tsxindex 8543132e88..f6c95b0f73 100644--- a/js/app/packages/entity/src/composed/ListEntity.tsx+++ b/js/app/packages/entity/src/composed/ListEntity.tsx@@ -30,7 +30,7 @@ import { Entity } from '../entity';import type { EntityRowConfig } from '../extractors-notification';import {isHitSnippetComplete,- isSnippetEntity,+ isHitSnippetEntity,} from '../extractors-search/snippet-entity';import { isChannelEntity, isEmailEntity } from '../types/entity';import { isWithNotification } from '../types/notification';@@ -115,7 +115,7 @@ export function ListEntity(props: ListEntityProps) {// value when windowSearchMatch trimmed text — otherwise the inline// snippet already shows everything.const isContentHitsRedundant = () => {- if (!isSnippetEntity(props.entity)) return false;+ if (!isHitSnippetEntity(props.entity)) return false;if (!isSearchEntity(props.entity)) return false;const hits = props.entity.search.contentHitData;if (!hits || hits.length !== 1) return false;diff --git a/js/app/packages/entity/src/extractors-search/snippet-entity.ts b/js/app/packages/entity/src/extractors-search/snippet-entity.tsindex 0c21fc1915..be0da823b9 100644--- a/js/app/packages/entity/src/extractors-search/snippet-entity.ts+++ b/js/app/packages/entity/src/extractors-search/snippet-entity.ts@@ -12,21 +12,25 @@ import { type ContentHitData, isSearchEntity } from '../types/search';* Entities whose inline row snippet renders search hit content via* windowSearchMatch + HighlightRender (as opposed to entity-derived previews* such as channel latest messages or task properties).+ *+ * Not to be confused with the Snippet document entity (see types/entity.ts) —+ * "snippet" here refers to the search-hit text rendered in a list row.*/-type SnippetEntity = EmailEntity | CallEntity;+type HitSnippetEntity = EmailEntity | CallEntity;-export const isSnippetEntity = (entity: EntityData): entity is SnippetEntity =>- isEmailEntity(entity) || isCallEntity(entity);+export const isHitSnippetEntity = (+ entity: EntityData+): entity is HitSnippetEntity => isEmailEntity(entity) || isCallEntity(entity);/**- * Hit rendered as the row snippet for a SnippetEntity:+ * Hit rendered as the row snippet for a HitSnippetEntity:* - email: longest hit (best context window around the highlight)* - call: first hit (typically the first transcript match)*/export const getSnippetHit = (entity: EntityData): ContentHitData | undefined => {- if (!isSnippetEntity(entity)) return undefined;+ if (!isHitSnippetEntity(entity)) return undefined;if (!isSearchEntity(entity)) return undefined;const hits = entity.search.contentHitData;if (!hits?.length) return undefined;diff --git a/js/app/packages/entity/src/index.ts b/js/app/packages/entity/src/index.tsindex 0891cd26a3..a1d3464601 100644--- a/js/app/packages/entity/src/index.ts+++ b/js/app/packages/entity/src/index.ts@@ -16,7 +16,7 @@ export { SearchSender } from './extractors-search/search-sender';export { SearchTimestamp } from './extractors-search/search-timestamp';export {getSnippetHit,- isSnippetEntity,+ isHitSnippetEntity,} from './extractors-search/snippet-entity';export * from './types/drag';export * from './types/entity';diff --git a/js/app/packages/entity/src/types/entity.ts b/js/app/packages/entity/src/types/entity.tsindex c185660cde..e7201e5ed7 100644--- a/js/app/packages/entity/src/types/entity.ts+++ b/js/app/packages/entity/src/types/entity.ts@@ -84,10 +84,10 @@ export type ChatEntity = EntityBase & {projectId?: string;};-/** Named sub types - currently only 'task' */-export type NamedSubType = 'task';+/** Named sub types - 'task' and 'snippet' */+export type NamedSubType = 'task' | 'snippet';-/** SubType for documents - currently only tasks */+/** SubType for documents - tasks and snippets */export type SubType = {type: NamedSubType;is_completed?: boolean;@@ -108,6 +108,13 @@ export type TaskEntity = EntityBase & {projectId?: string;};+export type SnippetEntity = EntityBase & {+ type: 'document';+ fileType: 'md';+ subType: { type: 'snippet' };+ projectId?: string;+};+export type MarkdownEntity = EntityBase & {type: 'document';fileType: 'md';@@ -224,6 +231,7 @@ export type EntityData =| ChatEntity| DocumentEntity| TaskEntity+ | SnippetEntity| EmailEntity| ProjectEntity| CallEntity@@ -266,6 +274,16 @@ export const isTaskEntity = (entity: EntityData): entity is TaskEntity => {);};+export const isSnippetEntity = (+ entity: EntityData+): entity is SnippetEntity => {+ return (+ entity.type === 'document' &&+ entity.fileType === 'md' &&+ entity.subType?.type === 'snippet'+ );+};+export const isGithubPrEntity = (entity: EntityData): entity is GithubPullRequestEntity => {diff --git a/js/app/packages/entity/src/utils/buildEntityData.ts b/js/app/packages/entity/src/utils/buildEntityData.tsindex 8dc4f319d3..ff841a5af6 100644--- a/js/app/packages/entity/src/utils/buildEntityData.ts+++ b/js/app/packages/entity/src/utils/buildEntityData.ts@@ -9,6 +9,7 @@ import type {EmailEntity,EntityData,ProjectEntity,+ SnippetEntity,TaskEntity,} from '../types/entity';@@ -66,6 +67,16 @@ export function buildEntityData(projectId: args.projectId,}))+ .with(+ 'snippet',+ (): SnippetEntity => ({+ ...base,+ type: 'document',+ fileType: 'md',+ subType: { type: 'snippet' },+ projectId: args.projectId,+ })+ ).with('md',(): DocumentEntity => ({diff --git a/js/app/packages/icon/wide-snippet.svg b/js/app/packages/icon/wide-snippet.svgnew file mode 100644index 0000000000..5ac7235434--- /dev/null+++ b/js/app/packages/icon/wide-snippet.svg@@ -0,0 +1,6 @@+<svg width="100%" height="100%" viewBox="0 -3 18 18" fill="none" stroke="currentColor" stroke-width="1.125" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">+<path class="brace-left" d="M4.1 0.47 Q2.2 0.47 2.2 2.3 L2.2 3.9 Q2.2 5.53 0.95 5.53 Q2.2 5.53 2.2 7.16 L2.2 8.76 Q2.2 10.59 4.1 10.59"/>+<path class="brace-right" d="M13.9 0.47 Q15.8 0.47 15.8 2.3 L15.8 3.9 Q15.8 5.53 17.05 5.53 Q15.8 5.53 15.8 7.16 L15.8 8.76 Q15.8 10.59 13.9 10.59"/>+<rect class="line-1" x="5.6" y="2.9" width="6.8" height="1.125" rx="0.5625" fill="currentColor" stroke="none"/>+<rect class="line-2" x="5.6" y="7.02" width="4.6" height="1.125" rx="0.5625" fill="currentColor" stroke="none"/>+</svg>diff --git a/js/app/packages/icon/wide-snippet.tsx b/js/app/packages/icon/wide-snippet.tsxnew file mode 100644index 0000000000..fa3d731ff4--- /dev/null+++ b/js/app/packages/icon/wide-snippet.tsx@@ -0,0 +1,73 @@+export const AnimatedSnippetIcon = (props: {+ triggerAnimation?: boolean;+ class?: string;+}) => {+ return (+ <svg+ width="100%"+ height="100%"+ viewBox="0 -3 18 18"+ fill="none"+ stroke="currentColor"+ stroke-width="1.125"+ stroke-linecap="round"+ stroke-linejoin="round"+ xmlns="http://www.w3.org/2000/svg"+ overflow="visible"+ class={`animated-snippet-icon ${props.triggerAnimation ? 'animating' : ''} ${props.class ?? ''}`}+ >+ <style>{`+ .animated-snippet-icon {+ .brace-left, .brace-right {+ transition: transform 0.25s ease;+ }+ .line-2 {+ transform-origin: 0% 50%;+ transform: scaleX(.676);+ transition: transform 0.25s ease-out;+ transform-box: fill-box;+ }+ }+ .animated-snippet-icon.animating {+ .brace-left {+ transform: translateX(-0.75px);+ }+ .brace-right {+ transform: translateX(0.75px);+ }+ .line-2 {+ transform: scaleX(1);+ }+ }+ `}</style>+ {/* Curly braces hug the text; they spread apart as the snippet "expands" */}+ <path+ class="brace-left"+ d="M4.1 0.47 Q2.2 0.47 2.2 2.3 L2.2 3.9 Q2.2 5.53 0.95 5.53 Q2.2 5.53 2.2 7.16 L2.2 8.76 Q2.2 10.59 4.1 10.59"+ />+ <path+ class="brace-right"+ d="M13.9 0.47 Q15.8 0.47 15.8 2.3 L15.8 3.9 Q15.8 5.53 17.05 5.53 Q15.8 5.53 15.8 7.16 L15.8 8.76 Q15.8 10.59 13.9 10.59"+ />+ <rect+ x="5.6"+ y="2.9"+ width="6.8"+ height="1.125"+ rx="0.5625"+ fill="currentColor"+ stroke="none"+ />+ <rect+ class="line-2"+ x="5.6"+ y="7.02"+ width="6.8"+ height="1.125"+ rx="0.5625"+ fill="currentColor"+ stroke="none"+ />+ </svg>+ );+};diff --git a/js/app/packages/queries/preview/fetchers.ts b/js/app/packages/queries/preview/fetchers.tsindex b7b34987d8..cceb44eaae 100644--- a/js/app/packages/queries/preview/fetchers.ts+++ b/js/app/packages/queries/preview/fetchers.ts@@ -105,8 +105,11 @@ async function fetchDocumentPreviews(ids: string[]): Promise<PreviewItem[]> {doc.sub_type === null || doc.sub_type === undefined? undefined: {- type: doc.sub_type.type as 'task',- is_completed: doc.sub_type.is_completed,+ type: doc.sub_type.type,+ is_completed:+ 'is_completed' in doc.sub_type+ ? doc.sub_type.is_completed+ : undefined,},};case 'no_access':diff --git a/js/app/packages/queries/preview/preview.ts b/js/app/packages/queries/preview/preview.tsindex 07fef4e9de..55e2e188fc 100644--- a/js/app/packages/queries/preview/preview.ts+++ b/js/app/packages/queries/preview/preview.ts@@ -218,7 +218,7 @@ export function setPreviewOnCreate({itemType: ItemType;name?: string;fileType?: string;- subType?: { type: 'task'; is_completed?: boolean };+ subType?: { type: 'task' | 'snippet'; is_completed?: boolean };}) {const defaultPreviewItem: AccessiblePreviewItem = {id: itemId,diff --git a/js/app/packages/queries/soup/quick-access-snippets.ts b/js/app/packages/queries/soup/quick-access-snippets.tsnew file mode 100644index 0000000000..8010aa06b7--- /dev/null+++ b/js/app/packages/queries/soup/quick-access-snippets.ts@@ -0,0 +1,57 @@+import { NIL_UUID } from '@app/component/next-soup/filters/filter-store';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import {+ ENABLE_SNIPPETS_FLAG,+ ENABLE_SNIPPETS_OVERRIDE,+} from '@core/constant/featureFlags';+import { isSnippetEntity, type SnippetEntity } from '@entity';+import { useSoupItemsQuery } from '@queries/soup/items';+import { createMemo } from 'solid-js';++const QUICK_ACCESS_SNIPPETS_LIMIT = 500;+const STALE_TIME = 5 * 60 * 1000;++/**+ * Quick Access feed of all snippets the user can access — their own plus+ * team-shared ones.+ *+ * This is the parallel live source feeding the `'snippet'` bucket — the+ * recently-viewed history feed only covers snippets the user has opened,+ * this one widens the pool so the `;` menu lists team snippets the user has+ * never opened.+ *+ * Every other entity type is filtered out via the nil-uuid sentinel pattern+ * (see `quick-access-crm-companies.ts`); documents are narrowed to the+ * snippet sub type.+ */+export function useQuickAccessSnippetsQuery() {+ const snippetsFlag = useFeatureFlag(ENABLE_SNIPPETS_FLAG, {+ enabledOverride: ENABLE_SNIPPETS_OVERRIDE,+ });++ const query = useSoupItemsQuery(+ () => ({+ params: {+ limit: QUICK_ACCESS_SNIPPETS_LIMIT,+ sort_method: 'viewed_updated',+ },+ body: {+ call_filters: { call_ids: [NIL_UUID] },+ channel_filters: { channel_ids: [NIL_UUID] },+ chat_filters: { chat_ids: [NIL_UUID] },+ crm_company_filters: { company_ids: [NIL_UUID] },+ document_filters: { sub_types: ['snippet'] },+ email_filters: { email_thread_ids: [NIL_UUID] },+ foreign_entity_filters: { ids: [NIL_UUID] },+ project_filters: { project_ids: [NIL_UUID] },+ },+ }),+ () => ({ staleTime: STALE_TIME, enabled: snippetsFlag().enabled })+ );++ const snippets = createMemo<SnippetEntity[]>(+ () => query.data?.filter(isSnippetEntity) ?? []+ );++ return { query, snippets };+}diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex 8fa4aafee0..f010e6300f 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -21,6 +21,7 @@ import type {EntityData,ForeignEntity,GithubPullRequestEntity,+ NamedSubType,ProjectEntity,SearchData,WithSearch,@@ -348,7 +349,12 @@ export const useSearchResponseItemMapper = () => {return [{type: 'document',- subType: result.sub_type === 'task' ? { type: 'task' } : null,+ subType:+ result.sub_type === 'task'+ ? { type: 'task' }+ : result.sub_type === 'snippet'+ ? { type: 'snippet' }+ : null,id: result.document_id,name: result.name || blockNameToDefaultFile(result.file_type),ownerId: result.owner_id,@@ -496,7 +502,10 @@ const resolveDocumentEntityName = (? null: {type: entity.subType.type,- is_completed: entity.subType.is_completed,+ is_completed:+ 'is_completed' in entity.subType+ ? entity.subType.is_completed+ : undefined,},});};@@ -688,8 +697,11 @@ export const mapApiSoupItemToEntity = (item: DisplayableSoupItem): SoupEntity =>item.data.subType === null || item.data.subType === undefined? undefined: {- type: item.data.subType.type as 'task',- is_completed: item.data.subType.is_completed,+ type: item.data.subType.type as NamedSubType,+ is_completed:+ 'is_completed' in item.data.subType+ ? item.data.subType.is_completed+ : undefined,},name: resolveDocumentEntityName(item.data),}))diff --git a/js/app/packages/queries/storage/keys.ts b/js/app/packages/queries/storage/keys.tsindex f24a820ba1..10700b67d2 100644--- a/js/app/packages/queries/storage/keys.ts+++ b/js/app/packages/queries/storage/keys.ts@@ -61,6 +61,9 @@ export const entityKeys = createQueryKeys('entity', {taskDuplicates: (documentId: string) => ({queryKey: [documentId, 'duplicates'],}),+ documentTeamShare: (documentId: string) => ({+ queryKey: [documentId, 'teamShare'],+ }),});export const taskSimilaritySearchKeys = createQueryKeys(diff --git a/js/app/packages/queries/storage/team-share.ts b/js/app/packages/queries/storage/team-share.tsnew file mode 100644index 0000000000..9c96909091--- /dev/null+++ b/js/app/packages/queries/storage/team-share.ts@@ -0,0 +1,45 @@+import { throwOnErr } from '@core/util/result';+import { queryClient } from '@queries/client';+import { storageServiceClient } from '@service-storage/client';+import type { DocumentTeamShareResponse } from '@service-storage/generated/schemas/documentTeamShareResponse';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { entityKeys } from './keys';++const STALE_TIME = 60 * 1000;++/**+ * Team-share state of a document, resolved against the owner's team.+ * `teamId` is absent when the owner does not belong to a team — the+ * "Share with team" toggle should be hidden in that case.+ */+export function useDocumentTeamShareQuery(documentId: Accessor<string>) {+ return useQuery(() => ({+ queryKey: entityKeys.documentTeamShare(documentId()).queryKey,+ queryFn: () =>+ throwOnErr(() =>+ storageServiceClient.getDocumentTeamShare({+ documentId: documentId(),+ })+ ),+ staleTime: STALE_TIME,+ enabled: !!documentId(),+ }));+}++/** Share or unshare a document with the owner's team (grants the team Edit). */+export function useSetDocumentTeamShareMutation() {+ return useMutation(() => ({+ mutationFn: (params: { documentId: string; shareWithTeam: boolean }) =>+ throwOnErr(() => storageServiceClient.setDocumentTeamShare(params)),+ onSuccess(data: DocumentTeamShareResponse, { documentId }) {+ queryClient.setQueryData(+ entityKeys.documentTeamShare(documentId).queryKey,+ data+ );+ },+ onError(error: Error) {+ console.error('failed to set document team sharing', error);+ },+ }));+}diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex c7c5224872..99f5bea66f 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -131,7 +131,30 @@ export const SearchToolResponse = z.object({.optional(),name: z.string(),owner_id: z.string(),- sub_type: z.union([z.literal('task'), z.null()]).optional(),+ sub_type: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('task'), z.literal('snippet')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),}),z.object({ type: z.literal('document') })),@@ -1760,7 +1783,29 @@ export const ReadMetadataResponse = z.object({projectId: z.union([z.string(), z.null()]).optional(),projectName: z.union([z.string(), z.null()]).optional(),sha: z.union([z.string(), z.null()]).optional(),- subType: z.union([z.literal('task'), z.null()]).optional(),+ subType: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('task'), z.literal('snippet')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),teamId: z.union([z.string(), z.null()]).optional(),teamTaskId: z.union([z.number().int(), z.null()]).optional(),updatedAt: zdiff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 7f856ee31b..0938ec16ce 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -96,7 +96,7 @@ export type DocumentContentState = 'unknown' | 'pending' | 'ready';* The document sub type enum represents all values of document sub types.* These values should match the `document_sub_type_value` table in macrodb.*/-export type DocumentSubType = 'task';+export type DocumentSubType = 'task' | 'snippet';export type EmailPreset = 'signal';export type EntityItem =| {diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.tsindex c2be2f2162..7cd28c2d5e 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts@@ -114,6 +114,8 @@ export * from './notifEventOneOfTwothreeTag';export * from './notificationBulkRequest';export * from './notificationDocumentSubType';export * from './notificationDocumentSubTypeOneOf';+export * from './notificationDocumentSubTypeOneOfThree';+export * from './notificationDocumentSubTypeOneOfThreeType';export * from './notificationDocumentSubTypeOneOfType';export * from './notificationServiceApiVersion';export * from './notificationTypeName';diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubType.tsindex 07fb3b867d..23388dd27d 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubType.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubType.ts@@ -5,9 +5,12 @@* OpenAPI spec version: 0.1.0*/import type { NotificationDocumentSubTypeOneOf } from './notificationDocumentSubTypeOneOf';+import type { NotificationDocumentSubTypeOneOfThree } from './notificationDocumentSubTypeOneOfThree';/*** The sub type of a document in a notification.Serializes as `{ "type": "task" }` matching the storage service pattern.*/-export type NotificationDocumentSubType = NotificationDocumentSubTypeOneOf;+export type NotificationDocumentSubType =+ | NotificationDocumentSubTypeOneOf+ | NotificationDocumentSubTypeOneOfThree;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubTypeOneOfThree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubTypeOneOfThree.tsnew file mode 100644index 0000000000..c92d3fc744--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubTypeOneOfThree.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotificationDocumentSubTypeOneOfThreeType } from './notificationDocumentSubTypeOneOfThreeType';++export type NotificationDocumentSubTypeOneOfThree = {+ type: NotificationDocumentSubTypeOneOfThreeType;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubTypeOneOfThreeType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubTypeOneOfThreeType.tsnew file mode 100644index 0000000000..b3122aafbb--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notificationDocumentSubTypeOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotificationDocumentSubTypeOneOfThreeType =+ (typeof NotificationDocumentSubTypeOneOfThreeType)[keyof typeof NotificationDocumentSubTypeOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotificationDocumentSubTypeOneOfThreeType = {+ snippet: 'snippet',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/zod.ts b/js/app/packages/service-clients/service-notification/generated/zod.tsindex fce03e6f17..2b2c1c54d4 100644--- a/js/app/packages/service-clients/service-notification/generated/zod.ts+++ b/js/app/packages/service-clients/service-notification/generated/zod.ts@@ -239,9 +239,14 @@ export const listTypedNotificationsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -274,9 +279,14 @@ export const listTypedNotificationsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -313,9 +323,14 @@ export const listTypedNotificationsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -354,9 +369,14 @@ export const listTypedNotificationsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -556,9 +576,14 @@ export const listTypedNotificationsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -892,9 +917,14 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -927,9 +957,14 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -966,9 +1001,14 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -1007,9 +1047,14 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -1209,9 +1254,14 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -1539,9 +1589,14 @@ export const getTypedNotificationsByEventItemIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -1574,9 +1629,14 @@ export const getTypedNotificationsByEventItemIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -1613,9 +1673,14 @@ export const getTypedNotificationsByEventItemIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -1654,9 +1719,14 @@ export const getTypedNotificationsByEventItemIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -1856,9 +1926,14 @@ export const getTypedNotificationsByEventItemIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -2191,9 +2266,14 @@ export const getTypedNotificationByIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -2224,9 +2304,14 @@ export const getTypedNotificationByIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -2259,9 +2344,14 @@ export const getTypedNotificationByIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -2296,9 +2386,14 @@ export const getTypedNotificationByIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),@@ -2484,9 +2579,14 @@ export const getTypedNotificationByIdResponse = zod.union([zod.null(),zod- .object({- type: zod.enum(['task']),- })+ .union([+ zod.object({+ type: zod.enum(['task']),+ }),+ zod.object({+ type: zod.enum(['snippet']),+ }),+ ]).describe('The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern.'),diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex 19e336a25b..edc3baaa6d 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -2015,6 +2015,16 @@"enum": ["task"]}}+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["snippet"]+ }+ }}],"description": "The sub type of a document in a notification.\nSerializes as `{ \"type\": \"task\" }` matching the storage service pattern."diff --git a/js/app/packages/service-clients/service-search/generated/models/documentSubType.ts b/js/app/packages/service-clients/service-search/generated/models/documentSubType.tsindex eedcd6d65d..36c53bdd2a 100644--- a/js/app/packages/service-clients/service-search/generated/models/documentSubType.ts+++ b/js/app/packages/service-clients/service-search/generated/models/documentSubType.ts@@ -15,4 +15,5 @@ export type DocumentSubType =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const DocumentSubType = {task: 'task',+ snippet: 'snippet',} as const;diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex 685aca25a1..422bd8f38d 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -1208,7 +1208,7 @@"DocumentSubType": {"type": "string","description": "The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.",- "enum": ["task"]+ "enum": ["task", "snippet"]},"EmailFilters": {"type": "object",diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex 962697ae0a..a9b028ce59 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -69,6 +69,8 @@ import type { CreateInstructionsDocumentResponse } from './generated/schemas/creimport type { CreateMarkdownDocumentRequest } from './generated/schemas/createMarkdownDocumentRequest';import type { CreateMarkdownHandler200 } from './generated/schemas/createMarkdownHandler200';import type { CreateProjectResponse } from './generated/schemas/createProjectResponse';+import type { CreateSnippetHandler200 } from './generated/schemas/createSnippetHandler200';+import type { CreateSnippetRequest } from './generated/schemas/createSnippetRequest';import type { CreateTaskHandler200 } from './generated/schemas/createTaskHandler200';import type { CreateTaskRequest } from './generated/schemas/createTaskRequest';import type { CreateUnthreadedAnchorResponse } from './generated/schemas/createUnthreadedAnchorResponse';@@ -84,6 +86,7 @@ import type { DeleteUnthreadedAnchorResponse } from './generated/schemas/deleteUimport type { DocumentMetadata } from './generated/schemas/documentMetadata';import type { DocumentPreview } from './generated/schemas/documentPreview';import type { DocumentResponseMetadataWithContent } from './generated/schemas/documentResponseMetadataWithContent';+import type { DocumentTeamShareResponse } from './generated/schemas/documentTeamShareResponse';import type { EditAnchorResponse } from './generated/schemas/editAnchorResponse';import type { EditCommentResponse } from './generated/schemas/editCommentResponse';import type { EditCrmCommentRequest } from './generated/schemas/editCrmCommentRequest';@@ -1034,6 +1037,58 @@ export const storageServiceClient = {return ok(response);},+ /**+ * Creates a snippet and initializes its sync-service content on the backend.+ * Snippets are created personal; team sharing is toggled separately via+ * setDocumentTeamShare.+ */+ async createSnippet(request: CreateSnippetRequest) {+ const result = await dssFetch<CreateSnippetHandler200>(+ `/documents/create_snippet`,+ {+ method: 'POST',+ body: JSON.stringify(request),+ }+ );++ if (!result.isOk()) {+ const errors = result.error;+ if (errors[0].message.includes('403')) {+ showPaywall(PaywallKey.FILE_LIMIT);+ }+ return err(result.error);+ }++ const response = result.value;+ return ok(response);+ },++ /**+ * Gets the team-share state of a document (resolved against the owner's team).+ */+ async getDocumentTeamShare(args: { documentId: string }) {+ return await dssFetch<DocumentTeamShareResponse>(+ `/documents/${args.documentId}/team_share`+ );+ },++ /**+ * Shares or unshares a document with the owner's team. Sharing grants the+ * team Edit access.+ */+ async setDocumentTeamShare(args: {+ documentId: string;+ shareWithTeam: boolean;+ }) {+ return await dssFetch<DocumentTeamShareResponse>(+ `/documents/${args.documentId}/team_share`,+ {+ method: 'PUT',+ body: JSON.stringify({ shareWithTeam: args.shareWithTeam }),+ }+ );+ },+async getTaskDuplicates(params: { documentId: string }) {return (await dssFetch<TaskDuplicatesResponse>(diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubType.tsindex 37e3d056f6..619a0b67ec 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubType.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubType.ts@@ -5,9 +5,12 @@* OpenAPI spec version: 0.1.0*/import type { BasicDocumentSubTypeOneOf } from './basicDocumentSubTypeOneOf';+import type { BasicDocumentSubTypeOneOfThree } from './basicDocumentSubTypeOneOfThree';/*** Sub type of a document with associated properties encoded in each variant.This ensures type-safety: task properties only exist when the document is a task.*/-export type BasicDocumentSubType = BasicDocumentSubTypeOneOf;+export type BasicDocumentSubType =+ | BasicDocumentSubTypeOneOf+ | BasicDocumentSubTypeOneOfThree;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubTypeOneOfThree.ts b/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubTypeOneOfThree.tsnew file mode 100644index 0000000000..5897d2cfe2--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubTypeOneOfThree.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { BasicDocumentSubTypeOneOfThreeType } from './basicDocumentSubTypeOneOfThreeType';++/**+ * A snippet document — reusable markdown+ */+export type BasicDocumentSubTypeOneOfThree = {+ type: BasicDocumentSubTypeOneOfThreeType;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubTypeOneOfThreeType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubTypeOneOfThreeType.tsnew file mode 100644index 0000000000..daa4921b85--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/basicDocumentSubTypeOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type BasicDocumentSubTypeOneOfThreeType =+ (typeof BasicDocumentSubTypeOneOfThreeType)[keyof typeof BasicDocumentSubTypeOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const BasicDocumentSubTypeOneOfThreeType = {+ snippet: 'snippet',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetHandler200.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetHandler200.tsnew file mode 100644index 0000000000..2181da8717--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetHandler200.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 for creating a snippet.+ */+export type CreateSnippetHandler200 = {+ /** The document ID of the created snippet. */+ documentId: string;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetRequest.tsnew file mode 100644index 0000000000..0110c24eef--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetRequest.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 { CreateSnippetRequestMarkdown } from './createSnippetRequestMarkdown';+import type { CreateSnippetRequestProjectId } from './createSnippetRequestProjectId';++/**+ * Request body for creating a snippet — a reusable markdown document that can+be inserted into any markdown area.+ */+export interface CreateSnippetRequest {+ /** Markdown source text. Defaults to an empty snippet document. */+ markdown?: CreateSnippetRequestMarkdown;+ /** Optional project ID to associate the snippet with. */+ projectId?: CreateSnippetRequestProjectId;+ /** The name of the snippet. */+ snippetName: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetRequestMarkdown.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetRequestMarkdown.tsnew file mode 100644index 0000000000..2938192fdf--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetRequestMarkdown.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Markdown source text. Defaults to an empty snippet document.+ */+export type CreateSnippetRequestMarkdown = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetRequestProjectId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetRequestProjectId.tsnew file mode 100644index 0000000000..b4578a32d9--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetRequestProjectId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional project ID to associate the snippet with.+ */+export type CreateSnippetRequestProjectId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetResponse.tsnew file mode 100644index 0000000000..a394e7d8ee--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createSnippetResponse.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 for creating a snippet.+ */+export interface CreateSnippetResponse {+ /** The document ID of the created snippet. */+ documentId: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubType.tsindex 1378541855..6e823b9a41 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubType.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubType.ts@@ -5,9 +5,12 @@* OpenAPI spec version: 0.1.0*/import type { DocumentPreviewDataSubTypeOneOf } from './documentPreviewDataSubTypeOneOf';+import type { DocumentPreviewDataSubTypeOneOfThree } from './documentPreviewDataSubTypeOneOfThree';/*** The sub type of a document preview with associated properties.Task-related properties are encoded within the variant to ensure valid states.*/-export type DocumentPreviewDataSubType = DocumentPreviewDataSubTypeOneOf;+export type DocumentPreviewDataSubType =+ | DocumentPreviewDataSubTypeOneOf+ | DocumentPreviewDataSubTypeOneOfThree;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubTypeOneOfThree.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubTypeOneOfThree.tsnew file mode 100644index 0000000000..5b01159f7a--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubTypeOneOfThree.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { DocumentPreviewDataSubTypeOneOfThreeType } from './documentPreviewDataSubTypeOneOfThreeType';++/**+ * A snippet document — reusable markdown+ */+export type DocumentPreviewDataSubTypeOneOfThree = {+ type: DocumentPreviewDataSubTypeOneOfThreeType;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubTypeOneOfThreeType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubTypeOneOfThreeType.tsnew file mode 100644index 0000000000..229fb329c4--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentPreviewDataSubTypeOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type DocumentPreviewDataSubTypeOneOfThreeType =+ (typeof DocumentPreviewDataSubTypeOneOfThreeType)[keyof typeof DocumentPreviewDataSubTypeOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const DocumentPreviewDataSubTypeOneOfThreeType = {+ snippet: 'snippet',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentSubType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentSubType.tsindex 925d87db71..5493c3fcb1 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/documentSubType.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentSubType.ts@@ -15,4 +15,5 @@ export type DocumentSubType =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const DocumentSubType = {task: 'task',+ snippet: 'snippet',} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentTeamShareResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentTeamShareResponse.tsnew file mode 100644index 0000000000..9be8681f45--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentTeamShareResponse.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { DocumentTeamShareResponseTeamId } from './documentTeamShareResponseTeamId';++/**+ * The team-share state of a document. The team is resolved from the document+owner's team membership.+ */+export interface DocumentTeamShareResponse {+ /** Whether the document is currently shared with the owner's team. */+ sharedWithTeam: boolean;+ /** The owner's team the document is (or would be) shared with. `None` when+the owner does not belong to a team. */+ teamId?: DocumentTeamShareResponseTeamId;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentTeamShareResponseTeamId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentTeamShareResponseTeamId.tsnew file mode 100644index 0000000000..99d7d47e72--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentTeamShareResponseTeamId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The owner's team the document is (or would be) shared with. `None` when+the owner does not belong to a team.+ */+export type DocumentTeamShareResponseTeamId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 195dff343f..ff23d64e13 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -108,6 +108,8 @@ export * from './basicDocumentProjectId';export * from './basicDocumentSha';export * from './basicDocumentSubType';export * from './basicDocumentSubTypeOneOf';+export * from './basicDocumentSubTypeOneOfThree';+export * from './basicDocumentSubTypeOneOfThreeType';export * from './basicDocumentSubTypeOneOfType';export * from './basicDocumentSubTypeProperty';export * from './basicDocumentType';@@ -281,6 +283,11 @@ export * from './createMarkdownHandler200';export * from './createProjectRequest';export * from './createProjectRequestProjectParentId';export * from './createProjectResponse';+export * from './createSnippetHandler200';+export * from './createSnippetRequest';+export * from './createSnippetRequestMarkdown';+export * from './createSnippetRequestProjectId';+export * from './createSnippetResponse';export * from './createTaskHandler200';export * from './createTaskHandler200TeamId';export * from './createTaskHandler200TeamTaskId';@@ -386,6 +393,8 @@ export * from './documentPreviewData';export * from './documentPreviewDataFileType';export * from './documentPreviewDataSubType';export * from './documentPreviewDataSubTypeOneOf';+export * from './documentPreviewDataSubTypeOneOfThree';+export * from './documentPreviewDataSubTypeOneOfThreeType';export * from './documentPreviewDataSubTypeOneOfType';export * from './documentPreviewDataSubTypeProperty';export * from './documentPreviewDataUpdatedAt';@@ -416,6 +425,8 @@ export * from './documentResponseMetadataWithContentAllOfTeamTaskId';export * from './documentResponsePresignedUrl';export * from './documentStorageServiceApiVersion';export * from './documentSubType';+export * from './documentTeamShareResponse';+export * from './documentTeamShareResponseTeamId';export * from './editAnchorRequest';export * from './editAnchorRequestOneOf';export * from './editAnchorRequestOneOfAllOf';@@ -778,6 +789,7 @@ export * from './saveDocumentResponseData';export * from './saveDocumentResponseDataPresignedUrl';export * from './setCompanyHiddenRequest';export * from './setContactHiddenRequest';+export * from './setDocumentTeamShareRequest';export * from './setEmailSyncRequest';export * from './setPropertyValue';export * from './setPropertyValueOneOf';@@ -850,6 +862,8 @@ export * from './soupDocumentProjectId';export * from './soupDocumentSha';export * from './soupDocumentSubType';export * from './soupDocumentSubTypeOneOf';+export * from './soupDocumentSubTypeOneOfThree';+export * from './soupDocumentSubTypeOneOfThreeType';export * from './soupDocumentSubTypeOneOfType';export * from './soupDocumentSubTypeProperty';export * from './soupDocumentViewedAt';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/setDocumentTeamShareRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/setDocumentTeamShareRequest.tsnew file mode 100644index 0000000000..49ccbde271--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/setDocumentTeamShareRequest.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Request body for setting a document's team-share state.+ */+export interface SetDocumentTeamShareRequest {+ /** Whether the document should be shared with the owner's team. */+ shareWithTeam: boolean;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubType.tsindex 132bf635a8..8db581f571 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubType.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubType.ts@@ -5,9 +5,12 @@* OpenAPI spec version: 0.1.0*/import type { SoupDocumentSubTypeOneOf } from './soupDocumentSubTypeOneOf';+import type { SoupDocumentSubTypeOneOfThree } from './soupDocumentSubTypeOneOfThree';/*** Sub type of a document with associated properties encoded in each variant.This ensures type-safety: task properties only exist when the document is a task.*/-export type SoupDocumentSubType = SoupDocumentSubTypeOneOf;+export type SoupDocumentSubType =+ | SoupDocumentSubTypeOneOf+ | SoupDocumentSubTypeOneOfThree;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubTypeOneOfThree.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubTypeOneOfThree.tsnew file mode 100644index 0000000000..d5ab2dc788--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubTypeOneOfThree.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { SoupDocumentSubTypeOneOfThreeType } from './soupDocumentSubTypeOneOfThreeType';++/**+ * A snippet document — reusable markdown+ */+export type SoupDocumentSubTypeOneOfThree = {+ type: SoupDocumentSubTypeOneOfThreeType;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubTypeOneOfThreeType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubTypeOneOfThreeType.tsnew file mode 100644index 0000000000..16a630bbe8--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupDocumentSubTypeOneOfThreeType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type SoupDocumentSubTypeOneOfThreeType =+ (typeof SoupDocumentSubTypeOneOfThreeType)[keyof typeof SoupDocumentSubTypeOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const SoupDocumentSubTypeOneOfThreeType = {+ snippet: 'snippet',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex ac26d3ee1f..2764952c9a 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -85,17 +85,25 @@ export const getRecentActivityHandlerResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe(- 'A task document with its associated properties'- )+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -568,7 +576,7 @@ export const editCommentResponse = zod.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -3387,7 +3395,7 @@ export const getUserDocumentsHandlerResponse = zod.object({.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -3556,7 +3564,7 @@ export const createDocumentResponse = zod.object({.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -3670,6 +3678,35 @@ export const createMarkdownHandlerResponse = zod}).describe('Response for creating a markdown document.');+/**+ * @summary Creates a snippet document with initialized markdown content in one+backend-owned lifecycle. Snippets are created personal; team sharing is+toggled separately via `PUT /documents/{document_id}/team_share`.+ */+export const createSnippetHandlerBody = zod+ .object({+ markdown: zod+ .string()+ .nullish()+ .describe('Markdown source text. Defaults to an empty snippet document.'),+ projectId: zod+ .uuid()+ .nullish()+ .describe('Optional project ID to associate the snippet with.'),+ snippetName: zod.string().describe('The name of the snippet.'),+ })+ .describe(+ 'Request body for creating a snippet — a reusable markdown document that can\nbe inserted into any markdown area.'+ );++export const createSnippetHandlerResponse = zod+ .object({+ documentId: zod+ .string()+ .describe('The document ID of the created snippet.'),+ })+ .describe('Response for creating a snippet.');+/*** @summary Creates a task document with properties and initialized markdown content inone backend-owned lifecycle.@@ -3997,15 +4034,23 @@ export const getBatchPreviewHandlerResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()- .describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'- ),- type: zod.enum(['task']),- })- .describe('A task document with completion status')+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ })+ .describe('A task document with completion status'),+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('The sub type of a document preview with associated properties.\nTask-related properties are encoded within the variant to ensure valid states.'),@@ -4110,15 +4155,25 @@ export const getDocumentResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe('A task document with its associated properties')+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -4293,7 +4348,7 @@ export const saveDocumentHandlerResponse = zod.object({.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -4966,7 +5021,7 @@ export const copyDocumentResponse = zod.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -5349,7 +5404,7 @@ export const getDocumentLocationV3Response = zod.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -5405,7 +5460,7 @@ export const getDocumentLocationV3Response = zod.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -5472,7 +5527,7 @@ export const getDocumentLocationV3Response = zod.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -5641,7 +5696,7 @@ export const simpleSaveResponse = zod.object({.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -5662,6 +5717,68 @@ export const simpleSaveResponse = zod.object({error: zod.boolean().describe('Indicates if an error occurred'),});+/**+ * @summary Gets the team-share state of a document. The team is resolved from the+document owner's team membership; `teamId` is omitted when the owner does+not belong to a team.+ */+export const getDocumentTeamShareParams = zod.object({+ document_id: zod.string().describe('Document ID'),+});++export const getDocumentTeamShareResponse = zod+ .object({+ sharedWithTeam: zod+ .boolean()+ .describe(+ "Whether the document is currently shared with the owner's team."+ ),+ teamId: zod+ .uuid()+ .nullish()+ .describe(+ "The owner's team the document is (or would be) shared with. `None` when\nthe owner does not belong to a team."+ ),+ })+ .describe(+ "The team-share state of a document. The team is resolved from the document\nowner's team membership."+ );++/**+ * @summary Sets the team-share state of a document. Sharing grants the document+owner's team Edit access; unsharing removes the team's access. Requires+Edit access on the document.+ */+export const setDocumentTeamShareParams = zod.object({+ document_id: zod.string().describe('Document ID'),+});++export const setDocumentTeamShareBody = zod+ .object({+ shareWithTeam: zod+ .boolean()+ .describe("Whether the document should be shared with the owner's team."),+ })+ .describe("Request body for setting a document's team-share state.");++export const setDocumentTeamShareResponse = zod+ .object({+ sharedWithTeam: zod+ .boolean()+ .describe(+ "Whether the document is currently shared with the owner's team."+ ),+ teamId: zod+ .uuid()+ .nullish()+ .describe(+ "The owner's team the document is (or would be) shared with. `None` when\nthe owner does not belong to a team."+ ),+ })+ .describe(+ "The team-share state of a document. The team is resolved from the document\nowner's team membership."+ );+/*** @summary Gets the list of users who have viewed a given document*/@@ -5763,7 +5880,7 @@ export const getDocumentVersionResponse = zod.object({.union([zod.null(),zod- .enum(['task'])+ .enum(['task', 'snippet']).describe('The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'),@@ -5938,15 +6055,23 @@ export const getHistoryHandlerResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()- .describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'- ),- type: zod.enum(['task']),- })- .describe('A task document with its associated properties')+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ })+ .describe('A task document with its associated properties'),+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -6362,15 +6487,25 @@ export const getItemsSoupResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe('A task document with its associated properties')+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -8236,15 +8371,25 @@ export const postItemsSoupResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe('A task document with its associated properties')+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -9687,15 +9832,25 @@ export const postItemsSoupAstResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe('A task document with its associated properties')+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -11401,17 +11556,27 @@ export const postItemsSoupAstGroupedResponse = zod.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe(- 'A task document with its associated properties'- )+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe(+ 'A snippet document — reusable markdown'+ ),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -12846,17 +13011,27 @@ export const postItemsSoupAstGroupedResponse = zod.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe(- 'A task document with its associated properties'- )+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe(+ 'A snippet document — reusable markdown'+ ),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -14041,17 +14216,25 @@ export const getPinsHandlerResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe(- 'A task document with its associated properties'- )+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -14171,17 +14354,25 @@ export const getPinsHandlerResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe(- 'A task document with its associated properties'- )+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -15563,15 +15754,25 @@ export const getProjectContentHandlerResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe('A task document with its associated properties')+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),@@ -15768,15 +15969,25 @@ export const recentlyDeletedResponse = zod.object({.union([zod.null(),zod- .object({- is_completed: zod- .boolean()+ .union([+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ }).describe(- 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ 'A task document with its associated properties'),- type: zod.enum(['task']),- })- .describe('A task document with its associated properties')+ zod+ .object({+ type: zod.enum(['snippet']),+ })+ .describe('A snippet document — reusable markdown'),+ ]).describe('Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'),diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 0b46ce6a78..4ba3e208f1 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -4552,6 +4552,73 @@}}},+ "/documents/create_snippet": {+ "post": {+ "tags": ["document"],+ "summary": "Creates a snippet document with initialized markdown content in one\nbackend-owned lifecycle. Snippets are created personal; team sharing is\ntoggled separately via `PUT /documents/{document_id}/team_share`.",+ "operationId": "create_snippet_handler",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateSnippetRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "description": "Response for creating a snippet.",+ "required": ["documentId"],+ "properties": {+ "documentId": {+ "type": "string",+ "description": "The document ID of the created snippet."+ }+ }+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/documents/create_task": {"post": {"tags": ["document"],@@ -6103,6 +6170,144 @@}}},+ "/documents/{document_id}/team_share": {+ "get": {+ "tags": ["document"],+ "summary": "Gets the team-share state of a document. The team is resolved from the\ndocument owner's team membership; `teamId` is omitted when the owner does\nnot belong to a team.",+ "operationId": "get_document_team_share",+ "parameters": [+ {+ "name": "document_id",+ "in": "path",+ "description": "Document ID",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DocumentTeamShareResponse"+ }+ }+ }+ },+ "401": {+ "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": ["document"],+ "summary": "Sets the team-share state of a document. Sharing grants the document\nowner's team Edit access; unsharing removes the team's access. Requires\nEdit access on the document.",+ "operationId": "set_document_team_share",+ "parameters": [+ {+ "name": "document_id",+ "in": "path",+ "description": "Document ID",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetDocumentTeamShareRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DocumentTeamShareResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "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"+ }+ }+ }+ }+ }+ }+ },"/documents/{document_id}/views": {"get": {"tags": ["document"],@@ -9791,6 +9996,17 @@"enum": ["task"]}}+ },+ {+ "type": "object",+ "description": "A snippet document — reusable markdown",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["snippet"]+ }+ }}],"description": "Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task."@@ -11374,6 +11590,37 @@}}},+ "CreateSnippetRequest": {+ "type": "object",+ "description": "Request body for creating a snippet — a reusable markdown document that can\nbe inserted into any markdown area.",+ "required": ["snippetName"],+ "properties": {+ "markdown": {+ "type": ["string", "null"],+ "description": "Markdown source text. Defaults to an empty snippet document."+ },+ "projectId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Optional project ID to associate the snippet with."+ },+ "snippetName": {+ "type": "string",+ "description": "The name of the snippet."+ }+ }+ },+ "CreateSnippetResponse": {+ "type": "object",+ "description": "Response for creating a snippet.",+ "required": ["documentId"],+ "properties": {+ "documentId": {+ "type": "string",+ "description": "The document ID of the created snippet."+ }+ }+ },"CreateTaskRequest": {"type": "object","description": "Request body for creating a task.",@@ -12418,6 +12665,17 @@"enum": ["task"]}}+ },+ {+ "type": "object",+ "description": "A snippet document — reusable markdown",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["snippet"]+ }+ }}],"description": "The sub type of a document preview with associated properties.\nTask-related properties are encoded within the variant to ensure valid states."@@ -12554,7 +12812,23 @@"DocumentSubType": {"type": "string","description": "The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.",- "enum": ["task"]+ "enum": ["task", "snippet"]+ },+ "DocumentTeamShareResponse": {+ "type": "object",+ "description": "The team-share state of a document. The team is resolved from the document\nowner's team membership.",+ "required": ["sharedWithTeam"],+ "properties": {+ "sharedWithTeam": {+ "type": "boolean",+ "description": "Whether the document is currently shared with the owner's team."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "The owner's team the document is (or would be) shared with. `None` when\nthe owner does not belong to a team."+ }+ }},"EditAnchorRequest": {"oneOf": [@@ -16379,6 +16653,17 @@}}},+ "SetDocumentTeamShareRequest": {+ "type": "object",+ "description": "Request body for setting a document's team-share state.",+ "required": ["shareWithTeam"],+ "properties": {+ "shareWithTeam": {+ "type": "boolean",+ "description": "Whether the document should be shared with the owner's team."+ }+ }+ },"SetEmailSyncRequest": {"type": "object","description": "Request body for `PUT /crm/companies/{company_id}/email-sync`.",@@ -17085,6 +17370,17 @@"enum": ["task"]}}+ },+ {+ "type": "object",+ "description": "A snippet document — reusable markdown",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["snippet"]+ }+ }}],"description": "Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task."diff --git a/js/lexical-core/nodes/InlineSearchNode.ts b/js/lexical-core/nodes/InlineSearchNode.tsindex dc90ce0754..34991c3f17 100644--- a/js/lexical-core/nodes/InlineSearchNode.ts+++ b/js/lexical-core/nodes/InlineSearchNode.ts@@ -32,12 +32,14 @@ export enum InlineSearchNodesType {Mentions = '@',Emojis = ':',Actions = '/',+ Snippets = ';',}export const SEARCH_NODE_TYPE_VALUES = {[InlineSearchNodesType.Mentions]: '@@',[InlineSearchNodesType.Emojis]: '::',[InlineSearchNodesType.Actions]: '//',+ [InlineSearchNodesType.Snippets]: ';;',};export function validTriggerPosition(@@ -72,7 +74,7 @@ export function validTriggerPosition(});}-const CLEAN_REGEX = /^[@|:|\/]/g; // Matches @, :, or / to clean the search term.+const CLEAN_REGEX = /^[@:\/;]/g; // Matches @, :, /, or ; to clean the search term.export class InlineSearchNode extends TextNode {static getType() {diff --git a/rust/cloud-storage/.sqlx/query-033759a1748c41359a8cf5204f457eed63182d21b432b58fd25b7524d1dc0092.json b/rust/cloud-storage/.sqlx/query-033759a1748c41359a8cf5204f457eed63182d21b432b58fd25b7524d1dc0092.jsonindex 8e2e7ae90a..a7919cb370 100644--- a/rust/cloud-storage/.sqlx/query-033759a1748c41359a8cf5204f457eed63182d21b432b58fd25b7524d1dc0092.json+++ b/rust/cloud-storage/.sqlx/query-033759a1748c41359a8cf5204f457eed63182d21b432b58fd25b7524d1dc0092.json@@ -51,7 +51,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-056dbddac4957596098ed8444564f7eb4ee08f375c95d9e40bd879d1439a8342.json b/rust/cloud-storage/.sqlx/query-056dbddac4957596098ed8444564f7eb4ee08f375c95d9e40bd879d1439a8342.jsonindex 72038b7a9a..e10b8729ca 100644--- a/rust/cloud-storage/.sqlx/query-056dbddac4957596098ed8444564f7eb4ee08f375c95d9e40bd879d1439a8342.json+++ b/rust/cloud-storage/.sqlx/query-056dbddac4957596098ed8444564f7eb4ee08f375c95d9e40bd879d1439a8342.json@@ -31,7 +31,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-17b1a9529bc693aeb668fd0c432d6b55a4c527fd3105bfa9cf83dbc70516011c.json b/rust/cloud-storage/.sqlx/query-17b1a9529bc693aeb668fd0c432d6b55a4c527fd3105bfa9cf83dbc70516011c.jsonindex e676d23086..6aac09106d 100644--- a/rust/cloud-storage/.sqlx/query-17b1a9529bc693aeb668fd0c432d6b55a4c527fd3105bfa9cf83dbc70516011c.json+++ b/rust/cloud-storage/.sqlx/query-17b1a9529bc693aeb668fd0c432d6b55a4c527fd3105bfa9cf83dbc70516011c.json@@ -46,7 +46,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-1b30e7bb6b67b93826781122a191e243db4c43ec8630b32ea48b1c7e31724264.json b/rust/cloud-storage/.sqlx/query-1b30e7bb6b67b93826781122a191e243db4c43ec8630b32ea48b1c7e31724264.jsonindex cb09769f7a..29a3ad393c 100644--- a/rust/cloud-storage/.sqlx/query-1b30e7bb6b67b93826781122a191e243db4c43ec8630b32ea48b1c7e31724264.json+++ b/rust/cloud-storage/.sqlx/query-1b30e7bb6b67b93826781122a191e243db4c43ec8630b32ea48b1c7e31724264.json@@ -81,7 +81,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-2611958405cf94c91ef85a09da00b0a8701621b42e4c57e74d2da40062d577d4.json b/rust/cloud-storage/.sqlx/query-2611958405cf94c91ef85a09da00b0a8701621b42e4c57e74d2da40062d577d4.jsonindex afc95c996f..06196d06b6 100644--- a/rust/cloud-storage/.sqlx/query-2611958405cf94c91ef85a09da00b0a8701621b42e4c57e74d2da40062d577d4.json+++ b/rust/cloud-storage/.sqlx/query-2611958405cf94c91ef85a09da00b0a8701621b42e4c57e74d2da40062d577d4.json@@ -81,7 +81,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-2930435da61e2e75a6ec3a127f3f1591934bb55a9f2fed8e47dd4406085fa6b2.json b/rust/cloud-storage/.sqlx/query-2930435da61e2e75a6ec3a127f3f1591934bb55a9f2fed8e47dd4406085fa6b2.jsonindex 69a58fd254..1ccf0c370f 100644--- a/rust/cloud-storage/.sqlx/query-2930435da61e2e75a6ec3a127f3f1591934bb55a9f2fed8e47dd4406085fa6b2.json+++ b/rust/cloud-storage/.sqlx/query-2930435da61e2e75a6ec3a127f3f1591934bb55a9f2fed8e47dd4406085fa6b2.json@@ -46,7 +46,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-2b51093ef799db343575cce3aead5f7db7aed774cb8d6fd74645f5e09b2215c6.json b/rust/cloud-storage/.sqlx/query-2b51093ef799db343575cce3aead5f7db7aed774cb8d6fd74645f5e09b2215c6.jsonnew file mode 100644index 0000000000..08b8cc2ff7--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-2b51093ef799db343575cce3aead5f7db7aed774cb8d6fd74645f5e09b2215c6.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = $2\n AND source_type = 'team'\n AND granted_from_project_id IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "2b51093ef799db343575cce3aead5f7db7aed774cb8d6fd74645f5e09b2215c6"+}diff --git a/rust/cloud-storage/.sqlx/query-2d1112d21440f0dfdf8fcbec264389f7abdcc74544558d60d817f56ff0c14524.json b/rust/cloud-storage/.sqlx/query-2d1112d21440f0dfdf8fcbec264389f7abdcc74544558d60d817f56ff0c14524.jsonindex 61b064aaf0..9d5f4be71c 100644--- a/rust/cloud-storage/.sqlx/query-2d1112d21440f0dfdf8fcbec264389f7abdcc74544558d60d817f56ff0c14524.json+++ b/rust/cloud-storage/.sqlx/query-2d1112d21440f0dfdf8fcbec264389f7abdcc74544558d60d817f56ff0c14524.json@@ -31,7 +31,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-2e0d56c9e8fecdbbd5ca1853876f9bf94f8980710a99f36274ab20bd75514a52.json b/rust/cloud-storage/.sqlx/query-2e0d56c9e8fecdbbd5ca1853876f9bf94f8980710a99f36274ab20bd75514a52.jsonnew file mode 100644index 0000000000..e08e9ad42e--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-2e0d56c9e8fecdbbd5ca1853876f9bf94f8980710a99f36274ab20bd75514a52.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, 'document', $2, 'team', $3)\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL\n DO UPDATE SET access_level = EXCLUDED.access_level, updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "2e0d56c9e8fecdbbd5ca1853876f9bf94f8980710a99f36274ab20bd75514a52"+}diff --git a/rust/cloud-storage/.sqlx/query-31dbb9af47386234da706e7c3175a7a2e43c2231040cc399488418eab9f6023a.json b/rust/cloud-storage/.sqlx/query-31dbb9af47386234da706e7c3175a7a2e43c2231040cc399488418eab9f6023a.jsonindex 78b3aa1bb0..88bcfc4608 100644--- a/rust/cloud-storage/.sqlx/query-31dbb9af47386234da706e7c3175a7a2e43c2231040cc399488418eab9f6023a.json+++ b/rust/cloud-storage/.sqlx/query-31dbb9af47386234da706e7c3175a7a2e43c2231040cc399488418eab9f6023a.json@@ -11,7 +11,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-41ef28446ebbd766c0778fd56fb8ee8094c2cb84ed3f4dab9e890d441611722b.json b/rust/cloud-storage/.sqlx/query-41ef28446ebbd766c0778fd56fb8ee8094c2cb84ed3f4dab9e890d441611722b.jsonindex c88fd987e6..4eaee7da4e 100644--- a/rust/cloud-storage/.sqlx/query-41ef28446ebbd766c0778fd56fb8ee8094c2cb84ed3f4dab9e890d441611722b.json+++ b/rust/cloud-storage/.sqlx/query-41ef28446ebbd766c0778fd56fb8ee8094c2cb84ed3f4dab9e890d441611722b.json@@ -81,7 +81,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-5293063d6203fdce622e3265581cb505e07534de33d0275ed860aea9f6614fc7.json b/rust/cloud-storage/.sqlx/query-5293063d6203fdce622e3265581cb505e07534de33d0275ed860aea9f6614fc7.jsonindex b434884797..b51c26591f 100644--- a/rust/cloud-storage/.sqlx/query-5293063d6203fdce622e3265581cb505e07534de33d0275ed860aea9f6614fc7.json+++ b/rust/cloud-storage/.sqlx/query-5293063d6203fdce622e3265581cb505e07534de33d0275ed860aea9f6614fc7.json@@ -81,7 +81,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-5959ff0d2410e3f2599a53bc1bf0de19c2d6e90cb030f64dccf965a0515b467e.json b/rust/cloud-storage/.sqlx/query-5959ff0d2410e3f2599a53bc1bf0de19c2d6e90cb030f64dccf965a0515b467e.jsonindex 334a1ac1ac..0d532ee4ad 100644--- a/rust/cloud-storage/.sqlx/query-5959ff0d2410e3f2599a53bc1bf0de19c2d6e90cb030f64dccf965a0515b467e.json+++ b/rust/cloud-storage/.sqlx/query-5959ff0d2410e3f2599a53bc1bf0de19c2d6e90cb030f64dccf965a0515b467e.json@@ -66,7 +66,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-6ea5fe0c08693b233361460d1a1b46168b4bf9848d252242a06569301144a4f6.json b/rust/cloud-storage/.sqlx/query-6ea5fe0c08693b233361460d1a1b46168b4bf9848d252242a06569301144a4f6.jsonindex 5d785a97ee..2f6283b3bf 100644--- a/rust/cloud-storage/.sqlx/query-6ea5fe0c08693b233361460d1a1b46168b4bf9848d252242a06569301144a4f6.json+++ b/rust/cloud-storage/.sqlx/query-6ea5fe0c08693b233361460d1a1b46168b4bf9848d252242a06569301144a4f6.json@@ -31,7 +31,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-7fc9da48b6c62ab0db6327e300eb80eafcff34b2d5d13621a688883acc3db154.json b/rust/cloud-storage/.sqlx/query-7fc9da48b6c62ab0db6327e300eb80eafcff34b2d5d13621a688883acc3db154.jsonindex b30cb13f0f..f8b30182d4 100644--- a/rust/cloud-storage/.sqlx/query-7fc9da48b6c62ab0db6327e300eb80eafcff34b2d5d13621a688883acc3db154.json+++ b/rust/cloud-storage/.sqlx/query-7fc9da48b6c62ab0db6327e300eb80eafcff34b2d5d13621a688883acc3db154.json@@ -86,7 +86,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-8b7e81c3b4f31c86100de517e1978a1879039b7230aa83df18f583106c97a18f.json b/rust/cloud-storage/.sqlx/query-8b7e81c3b4f31c86100de517e1978a1879039b7230aa83df18f583106c97a18f.jsonindex 06dcafa73e..cb673d055d 100644--- a/rust/cloud-storage/.sqlx/query-8b7e81c3b4f31c86100de517e1978a1879039b7230aa83df18f583106c97a18f.json+++ b/rust/cloud-storage/.sqlx/query-8b7e81c3b4f31c86100de517e1978a1879039b7230aa83df18f583106c97a18f.json@@ -86,7 +86,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-96a2c0a064e56b4fd812c2768403fc086f4518149772d661222d54592df920d3.json b/rust/cloud-storage/.sqlx/query-96a2c0a064e56b4fd812c2768403fc086f4518149772d661222d54592df920d3.jsonindex 44fbc49ef1..f884197d2e 100644--- a/rust/cloud-storage/.sqlx/query-96a2c0a064e56b4fd812c2768403fc086f4518149772d661222d54592df920d3.json+++ b/rust/cloud-storage/.sqlx/query-96a2c0a064e56b4fd812c2768403fc086f4518149772d661222d54592df920d3.json@@ -11,7 +11,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-a9fee4b6ef042c94f5dfc2ba668423e760ba3632bfae3aef9da1f146b7a9c638.json b/rust/cloud-storage/.sqlx/query-a9fee4b6ef042c94f5dfc2ba668423e760ba3632bfae3aef9da1f146b7a9c638.jsonindex aae5d98d86..3ee681677b 100644--- a/rust/cloud-storage/.sqlx/query-a9fee4b6ef042c94f5dfc2ba668423e760ba3632bfae3aef9da1f146b7a9c638.json+++ b/rust/cloud-storage/.sqlx/query-a9fee4b6ef042c94f5dfc2ba668423e760ba3632bfae3aef9da1f146b7a9c638.json@@ -46,7 +46,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-b509140ce307b4e440349fae476518b06d6247bf27821c9bea2f04c1eb999768.json b/rust/cloud-storage/.sqlx/query-b509140ce307b4e440349fae476518b06d6247bf27821c9bea2f04c1eb999768.jsonindex 8b8ac7b5ce..b0fb21d85c 100644--- a/rust/cloud-storage/.sqlx/query-b509140ce307b4e440349fae476518b06d6247bf27821c9bea2f04c1eb999768.json+++ b/rust/cloud-storage/.sqlx/query-b509140ce307b4e440349fae476518b06d6247bf27821c9bea2f04c1eb999768.json@@ -81,7 +81,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-c9fce1ac31e4e4f9992809c650e85fe45f4dc1e66d4b5a846c734b308c74fa70.json b/rust/cloud-storage/.sqlx/query-c9fce1ac31e4e4f9992809c650e85fe45f4dc1e66d4b5a846c734b308c74fa70.jsonindex 4c2fb23429..452e680e85 100644--- a/rust/cloud-storage/.sqlx/query-c9fce1ac31e4e4f9992809c650e85fe45f4dc1e66d4b5a846c734b308c74fa70.json+++ b/rust/cloud-storage/.sqlx/query-c9fce1ac31e4e4f9992809c650e85fe45f4dc1e66d4b5a846c734b308c74fa70.json@@ -86,7 +86,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-cc55e105bd5f6916a779d57ed7e4379c7fdaca83a33355842cf8b0b29d25a517.json b/rust/cloud-storage/.sqlx/query-cc55e105bd5f6916a779d57ed7e4379c7fdaca83a33355842cf8b0b29d25a517.jsonindex 6c7c3948d2..91afbc0b52 100644--- a/rust/cloud-storage/.sqlx/query-cc55e105bd5f6916a779d57ed7e4379c7fdaca83a33355842cf8b0b29d25a517.json+++ b/rust/cloud-storage/.sqlx/query-cc55e105bd5f6916a779d57ed7e4379c7fdaca83a33355842cf8b0b29d25a517.json@@ -86,7 +86,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-cfbec090ff3b62415ec0c215aa52bdafe162fb8c8fd217a8fcaf613e39525b0f.json b/rust/cloud-storage/.sqlx/query-cfbec090ff3b62415ec0c215aa52bdafe162fb8c8fd217a8fcaf613e39525b0f.jsonindex e17bd1ee56..358d08c4ed 100644--- a/rust/cloud-storage/.sqlx/query-cfbec090ff3b62415ec0c215aa52bdafe162fb8c8fd217a8fcaf613e39525b0f.json+++ b/rust/cloud-storage/.sqlx/query-cfbec090ff3b62415ec0c215aa52bdafe162fb8c8fd217a8fcaf613e39525b0f.json@@ -36,7 +36,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-d86be6e3a5bac69df99498b43dfc645a882c4f965226e71fc300d84a081ad30d.json b/rust/cloud-storage/.sqlx/query-d86be6e3a5bac69df99498b43dfc645a882c4f965226e71fc300d84a081ad30d.jsonindex 86f183fae7..d4ba5f46e7 100644--- a/rust/cloud-storage/.sqlx/query-d86be6e3a5bac69df99498b43dfc645a882c4f965226e71fc300d84a081ad30d.json+++ b/rust/cloud-storage/.sqlx/query-d86be6e3a5bac69df99498b43dfc645a882c4f965226e71fc300d84a081ad30d.json@@ -86,7 +86,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-da98ce3985fbf5eaed5300bb94b3354c7b4bd005b9e5657a702bd39846ff0917.json b/rust/cloud-storage/.sqlx/query-da98ce3985fbf5eaed5300bb94b3354c7b4bd005b9e5657a702bd39846ff0917.jsonindex 3c55abed30..5aa5cecd85 100644--- a/rust/cloud-storage/.sqlx/query-da98ce3985fbf5eaed5300bb94b3354c7b4bd005b9e5657a702bd39846ff0917.json+++ b/rust/cloud-storage/.sqlx/query-da98ce3985fbf5eaed5300bb94b3354c7b4bd005b9e5657a702bd39846ff0917.json@@ -11,7 +11,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-dd4f7c4b90b6340ea7f4a7d6eb16347612e9d197979f9d4a4df40314f22559f8.json b/rust/cloud-storage/.sqlx/query-dd4f7c4b90b6340ea7f4a7d6eb16347612e9d197979f9d4a4df40314f22559f8.jsonindex e4ffd6dc3c..6522361cd3 100644--- a/rust/cloud-storage/.sqlx/query-dd4f7c4b90b6340ea7f4a7d6eb16347612e9d197979f9d4a4df40314f22559f8.json+++ b/rust/cloud-storage/.sqlx/query-dd4f7c4b90b6340ea7f4a7d6eb16347612e9d197979f9d4a4df40314f22559f8.json@@ -81,7 +81,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-de888f70b426374eb436dfab5e58cab5a5d5423325a7834515c9c6a327f25f50.json b/rust/cloud-storage/.sqlx/query-de888f70b426374eb436dfab5e58cab5a5d5423325a7834515c9c6a327f25f50.jsonnew file mode 100644index 0000000000..4f08d6fc9f--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-de888f70b426374eb436dfab5e58cab5a5d5423325a7834515c9c6a327f25f50.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT tu.team_id\n FROM \"Document\" d\n JOIN team_user tu ON tu.user_id = d.owner\n WHERE d.id = $1\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "de888f70b426374eb436dfab5e58cab5a5d5423325a7834515c9c6a327f25f50"+}diff --git a/rust/cloud-storage/.sqlx/query-ecd59864bf9f241755a73ed370146370580a768c26a4c9f6b1fe9d8244abdb36.json b/rust/cloud-storage/.sqlx/query-ecd59864bf9f241755a73ed370146370580a768c26a4c9f6b1fe9d8244abdb36.jsonindex 8c528f8899..c1ea54d83e 100644--- a/rust/cloud-storage/.sqlx/query-ecd59864bf9f241755a73ed370146370580a768c26a4c9f6b1fe9d8244abdb36.json+++ b/rust/cloud-storage/.sqlx/query-ecd59864bf9f241755a73ed370146370580a768c26a4c9f6b1fe9d8244abdb36.json@@ -46,7 +46,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-f53db7386c5bcacad71c665b79d14921d77330e127ed9083235078bc0d8ee970.json b/rust/cloud-storage/.sqlx/query-f53db7386c5bcacad71c665b79d14921d77330e127ed9083235078bc0d8ee970.jsonnew file mode 100644index 0000000000..2dcc350139--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-f53db7386c5bcacad71c665b79d14921d77330e127ed9083235078bc0d8ee970.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = $2\n AND source_type = 'team'\n ) as \"exists!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "f53db7386c5bcacad71c665b79d14921d77330e127ed9083235078bc0d8ee970"+}diff --git a/rust/cloud-storage/.sqlx/query-f61fae90a53682f217091f1ecbdaa60d2eb5b7b0ff90863b0d0dc288779a5f7f.json b/rust/cloud-storage/.sqlx/query-f61fae90a53682f217091f1ecbdaa60d2eb5b7b0ff90863b0d0dc288779a5f7f.jsonindex 54d8bc401c..2333f15f8b 100644--- a/rust/cloud-storage/.sqlx/query-f61fae90a53682f217091f1ecbdaa60d2eb5b7b0ff90863b0d0dc288779a5f7f.json+++ b/rust/cloud-storage/.sqlx/query-f61fae90a53682f217091f1ecbdaa60d2eb5b7b0ff90863b0d0dc288779a5f7f.json@@ -56,7 +56,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-fab6b92c5781874261b3c3ca673d0bf0ad8155e25cf77aa57dafdcb133f30509.json b/rust/cloud-storage/.sqlx/query-fab6b92c5781874261b3c3ca673d0bf0ad8155e25cf77aa57dafdcb133f30509.jsonindex 1f209218c3..bbff4acae2 100644--- a/rust/cloud-storage/.sqlx/query-fab6b92c5781874261b3c3ca673d0bf0ad8155e25cf77aa57dafdcb133f30509.json+++ b/rust/cloud-storage/.sqlx/query-fab6b92c5781874261b3c3ca673d0bf0ad8155e25cf77aa57dafdcb133f30509.json@@ -11,7 +11,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/.sqlx/query-fcd4b67db8a3a8de51b0bb55880c5934f900adbadcc5549165e709cb1cd345b5.json b/rust/cloud-storage/.sqlx/query-fcd4b67db8a3a8de51b0bb55880c5934f900adbadcc5549165e709cb1cd345b5.jsonindex 51893d429f..671a73cb36 100644--- a/rust/cloud-storage/.sqlx/query-fcd4b67db8a3a8de51b0bb55880c5934f900adbadcc5549165e709cb1cd345b5.json+++ b/rust/cloud-storage/.sqlx/query-fcd4b67db8a3a8de51b0bb55880c5934f900adbadcc5549165e709cb1cd345b5.json@@ -91,7 +91,8 @@"name": "document_sub_type_value","kind": {"Enum": [- "task"+ "task",+ "snippet"]}}diff --git a/rust/cloud-storage/channels/src/outbound/notification_sender.rs b/rust/cloud-storage/channels/src/outbound/notification_sender.rsindex 6c3652dc4b..919bd8dc37 100644--- a/rust/cloud-storage/channels/src/outbound/notification_sender.rs+++ b/rust/cloud-storage/channels/src/outbound/notification_sender.rs@@ -169,6 +169,7 @@ wherefile_type: document.file_type,sub_type: match document.sub_type.as_deref() {Some("task") => Some(NotificationDocumentSubType::Task),+ Some("snippet") => Some(NotificationDocumentSubType::Snippet),_ => None,},channel: to_channel_mention_metadata(mention),diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rsindex 1ca6084646..87d8a86b32 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs@@ -139,9 +139,14 @@ pub async fn create_comment_handler(document_id: document_id.to_string(),owner: document_context.owner.clone(),file_type: document_context.file_type.clone(),- sub_type: document_context- .sub_type- .map(|_| NotificationDocumentSubType::Task),+ sub_type: document_context.sub_type.map(|sub_type| match sub_type {+ document_sub_type::DocumentSubType::Task => {+ NotificationDocumentSubType::Task+ }+ document_sub_type::DocumentSubType::Snippet => {+ NotificationDocumentSubType::Snippet+ }+ }),sender_id: sender_id.clone(),sender_profile_picture_url,};diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rsindex 53df6b3ed1..1f24fee246 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs@@ -77,7 +77,14 @@ pub async fn edit_comment_handler(document_id: res.document_id.to_string(),owner: res.document_owner.clone(),file_type: res.file_type.clone(),- sub_type: res.sub_type.map(|_| NotificationDocumentSubType::Task),+ sub_type: res.sub_type.map(|sub_type| match sub_type {+ document_sub_type::DocumentSubType::Task => {+ NotificationDocumentSubType::Task+ }+ document_sub_type::DocumentSubType::Snippet => {+ NotificationDocumentSubType::Snippet+ }+ }),sender_id: user_id.clone().try_into().ok(),sender_profile_picture_url,};diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 377515956a..f9e430d739 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -179,6 +179,9 @@ use utoipa::OpenApi;documents::revert_delete_document::handler,documents::export_document::handler,documents_hex::inbound::axum_router::create_task::create_task_handler,+ documents_hex::inbound::axum_router::create_snippet::create_snippet_handler,+ documents_hex::inbound::axum_router::team_share::get_team_share_handler,+ documents_hex::inbound::axum_router::team_share::set_team_share_handler,// instructionsinstructions::create_instructions::create_instructions_handler,@@ -332,6 +335,10 @@ use utoipa::OpenApi;documents_hex::domain::models::CreateMarkdownDocumentResponse,documents_hex::domain::models::CreateTaskRequest,documents_hex::domain::models::CreateTaskResponse,+ documents_hex::domain::models::CreateSnippetRequest,+ documents_hex::domain::models::CreateSnippetResponse,+ documents_hex::domain::models::DocumentTeamShareResponse,+ documents_hex::domain::models::SetDocumentTeamShareRequest,documents_hex::domain::models::PropertyInput,models_properties::api::requests::SetPropertyValue,models_properties::shared::EntityReference,diff --git a/rust/cloud-storage/document_sub_type/src/lib.rs b/rust/cloud-storage/document_sub_type/src/lib.rsindex 655cbc6ab6..4a5d8f05c9 100644--- a/rust/cloud-storage/document_sub_type/src/lib.rs+++ b/rust/cloud-storage/document_sub_type/src/lib.rs@@ -23,4 +23,7 @@ use schemars::JsonSchema;pub enum DocumentSubType {/// A task documentTask,+ /// A snippet document — a reusable block of markdown that can be inserted+ /// into any markdown area+ Snippet,}diff --git a/rust/cloud-storage/documents/fixtures/documents_test_data.sql b/rust/cloud-storage/documents/fixtures/documents_test_data.sqlindex ac5acfb645..f6ee8923b8 100644--- a/rust/cloud-storage/documents/fixtures/documents_test_data.sql+++ b/rust/cloud-storage/documents/fixtures/documents_test_data.sql@@ -81,6 +81,13 @@ INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId",INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")(SELECT 'macro|[email protected]', '[email protected]', 'stripe_id_t2', 1, 'a3333333-3333-3333-3333-333333333333');+-- A user that belongs to no team (team-share edge case tests)+INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id") VALUES+ ('a4444444-4444-4444-4444-444444444444', 'noteam', '[email protected]', 'stripe_id_nt');++INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")+ (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id_nt', 1, 'a4444444-4444-4444-4444-444444444444');+-- Team and team_user for sharing testsINSERT INTO public."team" ("id", "name", "owner_id")VALUES ('a0000000-0000-0000-0000-000000000001', 'test-team', 'macro|[email protected]');diff --git a/rust/cloud-storage/documents/src/domain/create/mod.rs b/rust/cloud-storage/documents/src/domain/create/mod.rsindex b1fc6e8d67..00bf975f3b 100644--- a/rust/cloud-storage/documents/src/domain/create/mod.rs+++ b/rust/cloud-storage/documents/src/domain/create/mod.rs@@ -67,7 +67,7 @@ impl NewDocumentMetadata {team_id: kind.team_id,email_attachment_id: self.email_attachment_id,created_at: self.created_at,- is_task: kind.subtype.is_task(),+ sub_type: kind.subtype.sub_type(),skip_history: self.skip_history,}}@@ -126,15 +126,23 @@ struct RepoDocumentKind {enum RepoDocumentSubtype {Regular,MarkdownTask,+ MarkdownSnippet,}impl RepoDocumentSubtype {- fn is_task(&self) -> bool {- matches!(self, RepoDocumentSubtype::MarkdownTask)+ fn sub_type(&self) -> Option<document_sub_type::DocumentSubType> {+ match self {+ RepoDocumentSubtype::Regular => None,+ RepoDocumentSubtype::MarkdownTask => Some(document_sub_type::DocumentSubType::Task),+ RepoDocumentSubtype::MarkdownSnippet => {+ Some(document_sub_type::DocumentSubType::Snippet)+ }+ }}}-/// Markdown-specific subtype. Task-ness only exists for markdown documents.+/// Markdown-specific subtype. Task-ness and snippet-ness only exist for+/// markdown documents.#[derive(Debug, Clone)]pub enum MarkdownSubtype {/// A regular markdown note.@@ -149,6 +157,9 @@ pub enum MarkdownSubtype {/// when the creator belongs to exactly one team.team_id: Option<uuid::Uuid>,},+ /// A snippet document — reusable markdown insertable in any markdown area.+ /// Snippets are created personal; team sharing is toggled separately.+ Snippet,}impl MarkdownSubtype {@@ -301,10 +312,18 @@ impl NewPlainTextDocumentBuilder<FileType, String> {let kind = if self.file_type == FileType::Md {PlainTextDocumentKind::Markdown(self.markdown_subtype)} else {- if matches!(self.markdown_subtype, MarkdownSubtype::Task { .. }) {- return Err(DocumentError::BadRequest(- "tasks must be markdown documents".to_string(),- ));+ match self.markdown_subtype {+ MarkdownSubtype::Task { .. } => {+ return Err(DocumentError::BadRequest(+ "tasks must be markdown documents".to_string(),+ ));+ }+ MarkdownSubtype::Snippet => {+ return Err(DocumentError::BadRequest(+ "snippets must be markdown documents".to_string(),+ ));+ }+ MarkdownSubtype::Note => {}}PlainTextDocumentKind::Text(NonMarkdownFileType::new(self.file_type)?)};@@ -493,7 +512,7 @@ wheresubtype,} = document;let task = match &subtype {- MarkdownSubtype::Note => None,+ MarkdownSubtype::Note | MarkdownSubtype::Snippet => None,MarkdownSubtype::Task {property_values,share_with_team,@@ -514,10 +533,10 @@ whereRepoDocumentKind {file_type: Some(FileType::Md),sha: EMPTY_SHA256.to_string(),- subtype: if task.is_some() {- RepoDocumentSubtype::MarkdownTask- } else {- RepoDocumentSubtype::Regular+ subtype: match &subtype {+ MarkdownSubtype::Note => RepoDocumentSubtype::Regular,+ MarkdownSubtype::Task { .. } => RepoDocumentSubtype::MarkdownTask,+ MarkdownSubtype::Snippet => RepoDocumentSubtype::MarkdownSnippet,},team_id,},diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rsindex 9b39e0cba4..a384ee9311 100644--- a/rust/cloud-storage/documents/src/domain/models.rs+++ b/rust/cloud-storage/documents/src/domain/models.rs@@ -294,8 +294,8 @@ pub struct CreateDocumentRepoArgs {pub email_attachment_id: Option<uuid::Uuid>,/// Custom creation timestamp.pub created_at: Option<chrono::DateTime<chrono::Utc>>,- /// Whether the document is a task (MD files only).- pub is_task: bool,+ /// Sub type of the document — task or snippet (MD files only).+ pub sub_type: Option<document_sub_type::DocumentSubType>,/// Whether to skip adding to user history.pub skip_history: bool,}@@ -444,6 +444,70 @@ pub struct CreateTaskResponse {pub team_task_id: Option<i32>,}+/// Request body for creating a snippet — a reusable markdown document that can+/// be inserted into any markdown area.+#[derive(serde::Serialize, serde::Deserialize, Debug)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct CreateSnippetRequest {+ /// The name of the snippet.+ pub snippet_name: String,+ /// Markdown source text. Defaults to an empty snippet document.+ pub markdown: Option<String>,+ /// Optional project ID to associate the snippet with.+ pub project_id: Option<uuid::Uuid>,+}++/// Response for creating a snippet.+#[derive(serde::Serialize, serde::Deserialize, Debug)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct CreateSnippetResponse {+ /// The document ID of the created snippet.+ pub document_id: String,+}++/// The team-share state of a document. The team is resolved from the document+/// owner's team membership.+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct DocumentTeamShareResponse {+ /// Whether the document is currently shared with the owner's team.+ pub shared_with_team: bool,+ /// The owner's team the document is (or would be) shared with. `None` when+ /// the owner does not belong to a team.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub team_id: Option<uuid::Uuid>,+}++/// Request body for setting a document's team-share state.+#[derive(serde::Serialize, serde::Deserialize, Debug)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct SetDocumentTeamShareRequest {+ /// Whether the document should be shared with the owner's team.+ pub share_with_team: bool,+}++/// Internal team-share state for a document, resolved against the owner's team.+#[derive(Debug, Clone, Copy)]+pub struct DocumentTeamShare {+ /// The owner's team, when the owner belongs to one.+ pub team_id: Option<uuid::Uuid>,+ /// Whether a team-source access row exists for the document.+ pub shared_with_team: bool,+}++impl From<DocumentTeamShare> for DocumentTeamShareResponse {+ fn from(value: DocumentTeamShare) -> Self {+ Self {+ shared_with_team: value.shared_with_team,+ team_id: value.team_id,+ }+ }+}+/// A comment thread attached to a document.#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone)]#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]diff --git a/rust/cloud-storage/documents/src/domain/ports/mod.rs b/rust/cloud-storage/documents/src/domain/ports/mod.rsindex 7da1f56069..6dddc97291 100644--- a/rust/cloud-storage/documents/src/domain/ports/mod.rs+++ b/rust/cloud-storage/documents/src/domain/ports/mod.rs@@ -25,8 +25,9 @@ use model_entity::Entity;use super::models::{BranchNameContext, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,- CreateTaskRequest, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,- GithubPullRequestsResponse, LocationQueryParams, TaskBranchName, TeamTaskMetadata,+ CreateTaskRequest, DocumentError, DocumentTeamShare, DocumentTeamShareResponse,+ EditDocumentRepoArgs, EditDocumentServiceArgs, GithubPullRequestsResponse, LocationQueryParams,+ TaskBranchName, TeamTaskMetadata,};/// Repository for accessing document data from the database.@@ -192,6 +193,19 @@ pub trait DocumentRepo: Send + Sync + 'static {document_id: &str,) -> impl Future<Output = Result<(), Self::Err>> + Send;+ /// Get the team-share state of a document, resolved against the owner's team.+ fn get_team_share(+ &self,+ document_id: &str,+ ) -> impl Future<Output = Result<DocumentTeamShare, Self::Err>> + Send;++ /// Grant or revoke the document owner's team's access on the document.+ fn set_team_share(+ &self,+ document_id: &str,+ share: bool,+ ) -> impl Future<Output = Result<DocumentTeamShare, Self::Err>> + Send;+/// Get document metadata at a specific version ID.fn get_document_metadata_at_version(&self,@@ -418,4 +432,17 @@ pub trait DocumentService: Send + Sync + 'static {document_id: &str,request: &CreateTaskRequest,) -> impl Future<Output = Result<(), DocumentError>> + Send;++ /// Get the team-share state of a document, resolved against the owner's team.+ fn get_team_share(+ &self,+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> impl Future<Output = Result<DocumentTeamShareResponse, DocumentError>> + Send;++ /// Grant or revoke the document owner's team's access on the document.+ fn set_team_share(+ &self,+ entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,+ share: bool,+ ) -> impl Future<Output = Result<DocumentTeamShareResponse, DocumentError>> + Send;}diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rsindex bc40ce8b62..6317875e03 100644--- a/rust/cloud-storage/documents/src/domain/service.rs+++ b/rust/cloud-storage/documents/src/domain/service.rs@@ -40,9 +40,9 @@ use super::branch_name::{build_task_branch_name, user_branch_prefix};use super::content::{DocumentContent, DocumentContentLocation, DocumentContentState};use super::models::{CloudFrontConfig, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,- CreateTaskRequest, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,- FileTypeUpdate, GithubPullRequest, GithubPullRequestsResponse, LocationQueryParams,- TaskBranchName, TeamTaskMetadata,+ CreateTaskRequest, DocumentError, DocumentTeamShareResponse, EditDocumentRepoArgs,+ EditDocumentServiceArgs, FileTypeUpdate, GithubPullRequest, GithubPullRequestsResponse,+ LocationQueryParams, TaskBranchName, TeamTaskMetadata,};#[cfg(feature = "document_create")]use super::ports::create::DocumentCreationService;@@ -1474,4 +1474,57 @@ impl<Ok(())}++ #[tracing::instrument(skip(self, entity_access_receipt))]+ async fn get_team_share(+ &self,+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<DocumentTeamShareResponse, DocumentError> {+ let document_id = &entity_access_receipt.entity().entity_id;++ let state = self+ .repo+ .get_team_share(document_id)+ .await+ .map_err(|e| DocumentError::Internal(e.into()))?;++ Ok(state.into())+ }++ #[tracing::instrument(skip(self, entity_access_receipt))]+ async fn set_team_share(+ &self,+ entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,+ share: bool,+ ) -> Result<DocumentTeamShareResponse, DocumentError> {+ let document_id = entity_access_receipt.entity().entity_id.clone();++ let state = self+ .repo+ .set_team_share(&document_id, share)+ .await+ .map_err(|e| DocumentError::Internal(e.into()))?;++ if share && state.team_id.is_none() {+ return Err(DocumentError::BadRequest(+ "document owner does not belong to a team".to_string(),+ ));+ }++ let _ = self+ .connection_service+ .send_invalidation_event(InvalidationEvent::<()> {+ invalidation_reason: InvalidationReason::Metadata,+ entity_id: Cow::Owned(document_id),+ entity_type: entity_access_receipt.entity().entity_type,+ invalidated_by: entity_access_receipt.auth().clone(),+ metadata: None,+ })+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, "failed to send invalidation event");+ });++ Ok(state.into())+ }}diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rsindex ad34be360a..1a37249f5c 100644--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs@@ -7,7 +7,9 @@//! - `GET /{document_id}/branch_name` — get short ID + task-aware git branch name (when the document is a task)//! - `GET /{document_id}/github_prs` — get GitHub pull requests associated with a task document//! - `GET /{document_id}/short_id` — get document short ID+//! - `GET`/`PUT /{document_id}/team_share` — get/set the document's team-share state//! - `POST /create_markdown` — create and initialize a markdown document+//! - `POST /create_snippet` — create and initialize a snippet document//! - `DELETE /{document_id}` — soft-delete a document#[cfg(test)]@@ -17,6 +19,8 @@ pub mod copy_document;pub mod create_document;#[cfg(feature = "document_create")]pub mod create_markdown;+#[cfg(feature = "document_create")]+pub mod create_snippet;pub mod create_task;pub mod delete_document;pub mod edit_document;@@ -26,6 +30,7 @@ pub mod get_github_pull_requests;pub mod get_location;pub mod get_short_id;pub mod task_duplicates;+pub mod team_share;use std::sync::Arc;@@ -45,6 +50,8 @@ use task_dedup::PgTaskDedupService;#[cfg(feature = "document_create")]use self::create_markdown::create_markdown_handler;+#[cfg(feature = "document_create")]+use self::create_snippet::create_snippet_handler;use self::{copy_document::copy_document_handler,create_document::create_document_handler,@@ -60,6 +67,7 @@ use self::{delete_this_duplicate_task_handler, dismiss_task_duplicates_handler,get_task_duplicates_handler, task_similarity_search_handler,},+ team_share::{get_team_share_handler, set_team_share_handler},};use crate::domain::models::DocumentError;@@ -188,6 +196,11 @@ where.route("/{document_id}/duplicates/{match_id}/delete_this",axum::routing::post(delete_this_duplicate_task_handler::<T, Svc>),+ )+ .route(+ "/{document_id}/team_share",+ axum::routing::get(get_team_share_handler::<T, Svc>)+ .put(set_team_share_handler::<T, Svc>),);let document_id_routes = document_id_routes.layer(middleware::from_fn_with_state(@@ -208,10 +221,15 @@ where);#[cfg(feature = "document_create")]- let router = router.route(- "/create_markdown",- axum::routing::post(create_markdown_handler::<T, Svc>),- );+ let router = router+ .route(+ "/create_markdown",+ axum::routing::post(create_markdown_handler::<T, Svc>),+ )+ .route(+ "/create_snippet",+ axum::routing::post(create_snippet_handler::<T, Svc>),+ );router.with_state(state)}diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rsindex aca1d38dbf..2a360656a1 100644--- a/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs@@ -90,7 +90,9 @@ pub async fn create_document_handler<T: DocumentService, Svc: EntityAccessServicteam_id,email_attachment_id: req.email_attachment_id,created_at: req.created_at,- is_task: req.is_task,+ sub_type: req+ .is_task+ .then_some(document_sub_type::DocumentSubType::Task),skip_history: req.skip_history,};diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_snippet.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_snippet.rsnew file mode 100644index 0000000000..6959234032--- /dev/null+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_snippet.rs@@ -0,0 +1,61 @@+//! Handler for `POST /documents/create_snippet`.++use axum::{Json, extract::State};+use entity_access::domain::ports::EntityAccessService;+use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractor;+use model_user::axum_extractor::MacroUserExtractor;+use models_permissions::share_permission::access_level::EditAccessLevel;++use super::DocumentRouterState;+use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument};+use crate::domain::models::{CreateSnippetRequest, CreateSnippetResponse, DocumentError};+use crate::domain::ports::DocumentService;+use crate::domain::ports::create::DocumentCreationService;++/// Creates a snippet document with initialized markdown content in one+/// backend-owned lifecycle. Snippets are created personal; team sharing is+/// toggled separately via `PUT /documents/{document_id}/team_share`.+#[utoipa::path(+ tag = "document",+ post,+ path = "/documents/create_snippet",+ request_body = CreateSnippetRequest,+ responses(+ (status = 200, body = inline(CreateSnippetResponse)),+ (status = 400, body = model_error_response::ErrorResponse),+ (status = 401, body = model_error_response::ErrorResponse),+ (status = 500, body = model_error_response::ErrorResponse),+ )+)]+#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.macro_user_id))]+pub async fn create_snippet_handler<+ T: DocumentService + DocumentCreationService,+ Svc: EntityAccessService,+>(+ State(state): State<DocumentRouterState<T, Svc>>,+ user_context: MacroUserExtractor,+ project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateSnippetRequest, Svc>,+) -> Result<Json<CreateSnippetResponse>, DocumentError> {+ let req = project.into_inner();++ let mut metadata = NewDocumentMetadata::builder(req.snippet_name);+ if let Some(project_id) = req.project_id {+ metadata = metadata.project_id(project_id);+ }++ let created = state+ .creator+ .create_markdown_text(+ user_context.macro_user_id,+ NewMarkdownTextDocument {+ metadata: metadata.build(),+ markdown: req.markdown.unwrap_or_default(),+ subtype: MarkdownSubtype::Snippet,+ },+ )+ .await?;++ Ok(Json(CreateSnippetResponse {+ document_id: created.document_id().to_string(),+ }))+}diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/get_branch_name.rs b/rust/cloud-storage/documents/src/inbound/axum_router/get_branch_name.rsindex 376f75b5ca..926564c53c 100644--- a/rust/cloud-storage/documents/src/inbound/axum_router/get_branch_name.rs+++ b/rust/cloud-storage/documents/src/inbound/axum_router/get_branch_name.rs@@ -67,7 +67,7 @@ pub async fn get_branch_name_handler<T: DocumentService, Svc: EntityAccessServicbranch_name: task_branch_name.branch_name,}))}- None => Err(DocumentError::BadRequest(format!(+ Some(DocumentSubType::Snippet) | None => Err(DocumentError::BadRequest(format!("document {document_id} is not a task"))),}diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/team_share.rs b/rust/cloud-storage/documents/src/inbound/axum_router/team_share.rsnew file mode 100644index 0000000000..c2b8e45c84--- /dev/null+++ b/rust/cloud-storage/documents/src/inbound/axum_router/team_share.rs@@ -0,0 +1,77 @@+//! Handlers for `GET`/`PUT /documents/{document_id}/team_share`.++use axum::{Json, extract::State};+use entity_access::domain::ports::EntityAccessService;+use entity_access::inbound::axum_extractors::DocumentAccessExtractor;+use models_permissions::share_permission::access_level::{EditAccessLevel, ViewAccessLevel};++use super::DocumentRouterState;+use crate::domain::models::{+ DocumentError, DocumentTeamShareResponse, SetDocumentTeamShareRequest,+};+use crate::domain::ports::DocumentService;++/// Gets the team-share state of a document. The team is resolved from the+/// document owner's team membership; `teamId` is omitted when the owner does+/// not belong to a team.+#[utoipa::path(+ tag = "document",+ get,+ path = "/documents/{document_id}/team_share",+ operation_id = "get_document_team_share",+ params(+ ("document_id" = String, Path, description = "Document ID")+ ),+ responses(+ (status = 200, body = DocumentTeamShareResponse),+ (status = 401, body = model_error_response::ErrorResponse),+ (status = 404, body = model_error_response::ErrorResponse),+ (status = 500, body = model_error_response::ErrorResponse),+ )+)]+#[tracing::instrument(skip(state, access), err)]+pub async fn get_team_share_handler<T: DocumentService, Svc: EntityAccessService>(+ State(state): State<DocumentRouterState<T, Svc>>,+ access: DocumentAccessExtractor<ViewAccessLevel, Svc>,+) -> Result<Json<DocumentTeamShareResponse>, DocumentError> {+ let response = state+ .service+ .get_team_share(access.entity_access_receipt)+ .await?;++ Ok(Json(response))+}++/// Sets the team-share state of a document. Sharing grants the document+/// owner's team Edit access; unsharing removes the team's access. Requires+/// Edit access on the document.+#[utoipa::path(+ tag = "document",+ put,+ path = "/documents/{document_id}/team_share",+ operation_id = "set_document_team_share",+ params(+ ("document_id" = String, Path, description = "Document ID")+ ),+ request_body = SetDocumentTeamShareRequest,+ responses(+ (status = 200, body = DocumentTeamShareResponse),+ (status = 400, body = model_error_response::ErrorResponse),+ (status = 401, body = model_error_response::ErrorResponse),+ (status = 404, body = model_error_response::ErrorResponse),+ (status = 500, body = model_error_response::ErrorResponse),+ )+)]+#[tracing::instrument(skip(state, access, request), err)]+pub async fn set_team_share_handler<T: DocumentService, Svc: EntityAccessService>(+ State(state): State<DocumentRouterState<T, Svc>>,+ access: DocumentAccessExtractor<EditAccessLevel, Svc>,+ Json(request): Json<SetDocumentTeamShareRequest>,+) -> Result<Json<DocumentTeamShareResponse>, DocumentError> {+ let response = state+ .service+ .set_team_share(access.entity_access_receipt, request.share_with_team)+ .await?;++ Ok(Json(response))+}diff --git a/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs b/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rsindex f481ecd6ff..932500008d 100644--- a/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs+++ b/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs@@ -99,6 +99,7 @@ whereSome(task_branch_name.branch_name)}+ document_sub_type::DocumentSubType::Snippet => None,}} else {Nonediff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rsindex 5c7c837e10..8dbfa5f1b7 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs@@ -22,7 +22,7 @@ use sqlx::Row;use crate::domain::content::{DocumentContent, DocumentContentState};use crate::domain::models::{BranchNameContext, Comment, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,- EditDocumentRepoArgs, TeamTaskMetadata, Thread,+ DocumentTeamShare, EditDocumentRepoArgs, TeamTaskMetadata, Thread,};use crate::domain::ports::DocumentRepo;@@ -403,7 +403,7 @@ impl DocumentRepo for PgDocumentRepo {team_id,email_attachment_id,created_at: provided_created_at,- is_task,+ sub_type: requested_sub_type,skip_history,} = args;@@ -437,9 +437,12 @@ impl DocumentRepo for PgDocumentRepo {// Insert document sub-typelet sub_type: Option<DocumentSubType> =- create::set_document_sub_type(&mut transaction, &document_id, is_task).await?;+ create::set_document_sub_type(&mut transaction, &document_id, requested_sub_type)+ .await?;- if is_task && let Some(team_id) = team_id.as_ref() {+ if sub_type == Some(DocumentSubType::Task)+ && let Some(team_id) = team_id.as_ref()+ {create::allocate_team_task_number(&mut transaction, team_id, &document_id).await?;}@@ -798,6 +801,20 @@ impl DocumentRepo for PgDocumentRepo {share::share_with_team(&self.pool, team_id, document_id).await}+ #[tracing::instrument(err, skip(self))]+ async fn get_team_share(&self, document_id: &str) -> Result<DocumentTeamShare, Self::Err> {+ share::get_team_share(&self.pool, document_id).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn set_team_share(+ &self,+ document_id: &str,+ share: bool,+ ) -> Result<DocumentTeamShare, Self::Err> {+ share::set_team_share(&self.pool, document_id, share).await+ }+#[tracing::instrument(err, skip(self))]async fn get_document_metadata_at_version(&self,diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/copy.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/copy.rsindex fa4f94e94d..630b554edb 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/copy.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/copy.rs@@ -1,4 +1,3 @@-use document_sub_type::DocumentSubType;use macro_user_id::user_id::MacroUserIdStr;use model::document::{BomPart, DocumentMetadata, IDWithTimeStamps, SaveBomPart, VersionIDWithTimeStamps,@@ -173,15 +172,15 @@ pub async fn copy_non_docx_document(None};- // Copy sub_type if the original is a task- if original_document.sub_type == Some(DocumentSubType::Task) {+ // Copy sub_type if the original has one (task, snippet, ...)+ if let Some(sub_type) = original_document.sub_type {sqlx::query!(r#"INSERT INTO document_sub_type (document_id, sub_type)VALUES ($1, $2)"#,document.id,- DocumentSubType::Task as _,+ sub_type as _,).execute(transaction.as_mut()).await?;diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rsindex caac82a4eb..5c0a5d1486 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs@@ -53,22 +53,22 @@ pub async fn insert_document_row<'a>(pub async fn set_document_sub_type(transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,document_id: &uuid::Uuid,- is_task: bool,+ sub_type: Option<DocumentSubType>,) -> Result<Option<DocumentSubType>, sqlx::Error> {- // Insert document sub-type (for tasks)- if is_task {+ // Insert document sub-type (for tasks and snippets)+ if let Some(sub_type) = sub_type {sqlx::query!(r#"INSERT INTO document_sub_type (document_id, sub_type)VALUES ($1, $2)"#,&document_id.to_string(),- DocumentSubType::Task as _+ sub_type as _).execute(transaction.as_mut()).await?;- Ok(Some(DocumentSubType::Task))+ Ok(Some(sub_type))} else {Ok(None)}diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rsindex 8169c7bb5e..4b3e2a0d52 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rs@@ -2,6 +2,8 @@ use entity_access_db_utils::AccessLevel;use sqlx::PgPool;use uuid::Uuid;+use crate::domain::models::DocumentTeamShare;+/// Share a document with the given team.#[tracing::instrument(err, skip(pool))]pub async fn share_with_team(@@ -27,3 +29,118 @@ pub async fn share_with_team(Ok(())}++/// Resolve the document owner's team. Returns `None` when the owner does not+/// belong to a team.+async fn owner_team_id(pool: &PgPool, document_id: &str) -> Result<Option<Uuid>, sqlx::Error> {+ sqlx::query_scalar!(+ r#"+ SELECT tu.team_id+ FROM "Document" d+ JOIN team_user tu ON tu.user_id = d.owner+ WHERE d.id = $1+ LIMIT 1+ "#,+ document_id,+ )+ .fetch_optional(pool)+ .await+}++/// Get the team-share state of a document, resolved against the owner's team.+#[tracing::instrument(err, skip(pool))]+pub async fn get_team_share(+ pool: &PgPool,+ document_id: &str,+) -> Result<DocumentTeamShare, sqlx::Error> {+ let document_uuid = macro_uuid::string_to_uuid(document_id)+ .map_err(|e| sqlx::Error::Protocol(e.to_string()))?;++ let Some(team_id) = owner_team_id(pool, document_id).await? else {+ return Ok(DocumentTeamShare {+ team_id: None,+ shared_with_team: false,+ });+ };++ let shared = sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1 FROM entity_access+ WHERE entity_id = $1+ AND entity_type = 'document'+ AND source_id = $2+ AND source_type = 'team'+ ) as "exists!"+ "#,+ &document_uuid,+ &team_id.to_string(),+ )+ .fetch_one(pool)+ .await?;++ Ok(DocumentTeamShare {+ team_id: Some(team_id),+ shared_with_team: shared,+ })+}++/// Grant or revoke the document owner's team's access on the document.+///+/// Granting gives the team Edit access so teammates can collaboratively+/// maintain team snippets; revoking removes the team-source access row+/// (project-granted rows are left untouched). Returns the new state, or the+/// unshared state when the owner has no team.+#[tracing::instrument(err, skip(pool))]+pub async fn set_team_share(+ pool: &PgPool,+ document_id: &str,+ share: bool,+) -> Result<DocumentTeamShare, sqlx::Error> {+ let document_uuid = macro_uuid::string_to_uuid(document_id)+ .map_err(|e| sqlx::Error::Protocol(e.to_string()))?;++ let Some(team_id) = owner_team_id(pool, document_id).await? else {+ return Ok(DocumentTeamShare {+ team_id: None,+ shared_with_team: false,+ });+ };++ if share {+ sqlx::query!(+ r#"+ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)+ VALUES ($1, 'document', $2, 'team', $3)+ ON CONFLICT (entity_id, entity_type, source_id, source_type)+ WHERE granted_from_project_id IS NULL+ DO UPDATE SET access_level = EXCLUDED.access_level, updated_at = NOW()+ "#,+ &document_uuid,+ &team_id.to_string(),+ AccessLevel::Edit as _,+ )+ .execute(pool)+ .await?;+ } else {+ sqlx::query!(+ r#"+ DELETE FROM entity_access+ WHERE entity_id = $1+ AND entity_type = 'document'+ AND source_id = $2+ AND source_type = 'team'+ AND granted_from_project_id IS NULL+ "#,+ &document_uuid,+ &team_id.to_string(),+ )+ .execute(pool)+ .await?;+ }++ Ok(DocumentTeamShare {+ team_id: Some(team_id),+ shared_with_team: share,+ })+}diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rsindex 81db5e7f87..bea723e7a8 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs@@ -39,7 +39,7 @@ fn create_document_args(team_id,email_attachment_id: None,created_at: None,- is_task,+ sub_type: is_task.then_some(document_sub_type::DocumentSubType::Task),skip_history: false,}}@@ -617,6 +617,120 @@ async fn test_share_with_team_idempotent(pool: Pool<Postgres>) {assert_eq!(count, 2); // owner + 1 team, no duplicates}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_team_share_roundtrip(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());+ let document_id = "d0000000-0000-0000-0000-000000000001";++ // Unshared by default, but the owner's team resolves+ let state = repo.get_team_share(document_id).await.unwrap();+ assert_eq!(state.team_id, Some(TEST_TEAM_ID));+ assert!(!state.shared_with_team);++ // Share grants the team Edit access+ let state = repo.set_team_share(document_id, true).await.unwrap();+ assert_eq!(state.team_id, Some(TEST_TEAM_ID));+ assert!(state.shared_with_team);++ let doc_uuid = macro_uuid::string_to_uuid(document_id).unwrap();+ let team_row = sqlx::query!(+ r#"+ SELECT access_level::text as "access_level"+ FROM entity_access+ WHERE entity_id = $1 AND entity_type = 'document'+ AND source_type = 'team'+ "#,+ doc_uuid,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(team_row.access_level, Some("edit".to_string()));++ let state = repo.get_team_share(document_id).await.unwrap();+ assert!(state.shared_with_team);++ // Unshare removes the team row+ let state = repo.set_team_share(document_id, false).await.unwrap();+ assert!(!state.shared_with_team);++ let count = sqlx::query_scalar!(+ r#"+ SELECT COUNT(*) as "count!"+ FROM entity_access+ WHERE entity_id = $1 AND entity_type = 'document'+ AND source_type = 'team'+ "#,+ doc_uuid,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(count, 0);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_set_team_share_upgrades_existing_team_grant(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());+ let document_id = "d0000000-0000-0000-0000-000000000001";++ // Existing Comment-level team grant (e.g. from task creation)+ repo.share_with_team(&TEST_TEAM_ID, document_id)+ .await+ .unwrap();++ // Toggling share on upgrades the team row to Edit+ repo.set_team_share(document_id, true).await.unwrap();++ let doc_uuid = macro_uuid::string_to_uuid(document_id).unwrap();+ let rows = sqlx::query!(+ r#"+ SELECT access_level::text as "access_level"+ FROM entity_access+ WHERE entity_id = $1 AND entity_type = 'document'+ AND source_type = 'team'+ "#,+ doc_uuid,+ )+ .fetch_all(&pool)+ .await+ .unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].access_level, Some("edit".to_string()));+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_team_share_no_team_owner(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());++ // Create a document owned by a user without a team+ let metadata = repo+ .create_document(create_document_args("macro|[email protected]", false, None))+ .await+ .unwrap();++ let state = repo.get_team_share(&metadata.document_id).await.unwrap();+ assert_eq!(state.team_id, None);+ assert!(!state.shared_with_team);++ // Sharing is a no-op when the owner has no team+ let state = repo+ .set_team_share(&metadata.document_id, true)+ .await+ .unwrap();+ assert_eq!(state.team_id, None);+ assert!(!state.shared_with_team);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data"))diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex 117470a197..5bbb8c00b4 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -221,6 +221,21 @@ impl DocumentService for StubDocumentService {Ok(())}+ async fn get_team_share(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<documents::domain::models::DocumentTeamShareResponse, DocumentError> {+ unimplemented!()+ }++ async fn set_team_share(+ &self,+ _receipt: EntityAccessReceipt<EditAccessLevel>,+ _share: bool,+ ) -> Result<documents::domain::models::DocumentTeamShareResponse, DocumentError> {+ unimplemented!()+ }+async fn edit_document(&self,_entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,diff --git a/rust/cloud-storage/macro_db_client/migrations/20260610162938_add_snippet_document_sub_type.sql b/rust/cloud-storage/macro_db_client/migrations/20260610162938_add_snippet_document_sub_type.sqlnew file mode 100644index 0000000000..2f522f8af3--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260610162938_add_snippet_document_sub_type.sql@@ -0,0 +1,4 @@+-- Add 'snippet' to the document sub type enum.+-- Snippets are reusable markdown documents that can be inserted into any+-- markdown area (`;` menu in the editor).+ALTER TYPE document_sub_type_value ADD VALUE IF NOT EXISTS 'snippet';diff --git a/rust/cloud-storage/model/src/document/mod.rs b/rust/cloud-storage/model/src/document/mod.rsindex e618b4375d..d583734355 100644--- a/rust/cloud-storage/model/src/document/mod.rs+++ b/rust/cloud-storage/model/src/document/mod.rs@@ -48,6 +48,8 @@ pub enum BasicDocumentSubType {/// True if the Status property is set to "Completed".is_completed: bool,},+ /// A snippet document — reusable markdown+ Snippet {},}impl BasicDocumentSubType {@@ -58,6 +60,7 @@ impl BasicDocumentSubType {DocumentSubType::Task => Some(Self::Task {is_completed: is_completed.unwrap_or_default(),}),+ DocumentSubType::Snippet => Some(Self::Snippet {}),}}}@@ -316,6 +319,8 @@ pub enum DocumentPreviewDataSubType {/// True if the Status property is set to "Completed".is_completed: bool,},+ /// A snippet document — reusable markdown+ Snippet {},}impl DocumentPreviewDataSubType {@@ -326,6 +331,7 @@ impl DocumentPreviewDataSubType {DocumentSubType::Task => Some(Self::Task {is_completed: is_completed.unwrap_or_default(),}),+ DocumentSubType::Snippet => Some(Self::Snippet {}),}}}diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rsindex 1f7c9d3d8f..29de0743d2 100644--- a/rust/cloud-storage/model_notifications/src/metadata.rs+++ b/rust/cloud-storage/model_notifications/src/metadata.rs@@ -304,6 +304,7 @@ pub struct ChannelReplyMetadata {#[serde(tag = "type", rename_all = "snake_case")]pub enum NotificationDocumentSubType {Task,+ Snippet,}/// Someone mentioned a document in a channeldiff --git a/rust/cloud-storage/models_soup/src/document.rs b/rust/cloud-storage/models_soup/src/document.rsindex 0131e11067..e9824fa7e4 100644--- a/rust/cloud-storage/models_soup/src/document.rs+++ b/rust/cloud-storage/models_soup/src/document.rs@@ -19,6 +19,8 @@ pub enum SoupDocumentSubType {/// True if the Status property is set to "Completed".is_completed: bool,},+ /// A snippet document — reusable markdown+ Snippet {},}impl SoupDocumentSubType {@@ -29,6 +31,7 @@ impl SoupDocumentSubType {DocumentSubType::Task => Some(Self::Task {is_completed: is_completed.unwrap_or_default(),}),+ DocumentSubType::Snippet => Some(Self::Snippet {}),}}@@ -36,6 +39,7 @@ impl SoupDocumentSubType {pub fn is_task_completed(&self) -> Option<bool> {match self {Self::Task { is_completed } => Some(*is_completed),+ Self::Snippet {} => None,}}}@@ -109,11 +113,13 @@ impl SoupDocument {/// Returns the entity type for this document.////// Documents with a `sub_type` of `Task` return `EntityType::Task`,- /// otherwise they return `EntityType::Document`.+ /// otherwise they return `EntityType::Document`. Snippets are documents+ /// as far as the entity system is concerned — their snippet-ness only+ /// lives in `sub_type`.pub fn entity_type(&self) -> EntityType {match &self.sub_type {Some(SoupDocumentSubType::Task { .. }) => EntityType::Task,- None => EntityType::Document,+ Some(SoupDocumentSubType::Snippet {}) | None => EntityType::Document,}}}