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
fix: new soup item on create (#1372)
gbirmanc54333cd88a8
diff --git a/js/app/packages/app/component/NewRoute.tsx b/js/app/packages/app/component/NewRoute.tsxdeleted file mode 100644index f702bd6fbb..0000000000--- a/js/app/packages/app/component/NewRoute.tsx+++ /dev/null@@ -1,109 +0,0 @@-import { useIsAuthenticated } from '@core/auth';-import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';-import { createCodeFileFromText } from '@core/util/create';-import { isPaymentError } from '@core/util/handlePaymentError';-import { isErr } from '@core/util/maybeResult';-import { uploadFile } from '@core/util/upload';-import { cognitionApiServiceClient } from '@service-cognition/client';-import { postNewHistoryItem } from '@queries/history/history';-import { newBlankDocument } from '@service-storage/util/newBlankDocument';-import {- Navigate,- type RouteSectionProps,- useNavigate,- useSearchParams,-} from '@solidjs/router';-import { createResource, Show } from 'solid-js';--export default function NewBlockRoute(props: RouteSectionProps) {- const authenticated = useIsAuthenticated();- const { showPaywall } = usePaywallState();- const navigate = useNavigate();-- const upload = async (file: File, type: 'md' | 'canvas') => {- const uploadResult = await uploadFile(file, 'dss', {- skipAnalytics: true,- fileType: type,- });- if (uploadResult.failed || uploadResult.type !== 'document') {- console.error(- 'Invalid upload result. Expected DSS document',- uploadResult- );- return navigate('/');- }- const documentId = uploadResult.documentId;- postNewHistoryItem('document', documentId);- return documentId;- };-- const [newBlockId] = createResource(async () => {- switch (props.params.block) {- case 'chat': {- const maybeChat = await cognitionApiServiceClient.createChat({});- if (isPaymentError(maybeChat)) {- showPaywall();- return navigate('/');- }- if (isErr(maybeChat)) {- return navigate('/');- }- const [, chat] = maybeChat;- postNewHistoryItem('chat', chat.id);- return chat.id;- }- case 'rss':- return navigate('/');- case 'pdf':- // noop, can't create new pdf- return navigate('/');- case 'md': {- const emptyMdFile = newBlankDocument('md');- if (!emptyMdFile) return navigate('/');- return upload(emptyMdFile, 'md');- }- case 'code': {- const maybeDoc = await createCodeFileFromText({- code: 'print("Hello, World!")',- extension: 'py',- });- if (isErr(maybeDoc, 'UNAUTHORIZED')) {- showPaywall(PaywallKey.FILE_LIMIT);- }- const [, result] = maybeDoc;- if (!result?.documentId) {- return navigate('/');- }- postNewHistoryItem('document', result.documentId);- return result.documentId;- }- case 'canvas': {- const emptyCanvasFile = newBlankDocument('canvas');- if (!emptyCanvasFile) return navigate('/');- return upload(emptyCanvasFile, 'canvas');- }- case 'start':- return 'block';- }- });-- // If we have a prompt in the search params,- // we should pass it to the new chat block- const [searchParams] = useSearchParams();- const prompt = searchParams.prompt;- const chatPrompt =- props.params.block === 'chat' && prompt ? `?prompt=${prompt}` : '';-- // If the user is not authenticated, redirect to login- if (!authenticated()) {- return <Navigate href="/login" />;- }-- return (- <Show when={newBlockId()}>- {(id) => (- <Navigate href={`/${props.params.block}/${id()}${chatPrompt}`} />- )}- </Show>- );-}diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsxindex e7d8418424..0921004096 100644--- a/js/app/packages/app/component/Root.tsx+++ b/js/app/packages/app/component/Root.tsx@@ -50,7 +50,6 @@ import { detect } from 'detect-browser';import {createEffect,type JSX,- lazy,Match,onCleanup,onMount,@@ -258,10 +257,6 @@ const ROUTES: RouteDefinition[] = [</div>),},- {- path: '/new/:block',- component: lazy(() => import('./NewRoute')),- },{// This splat route must be last to catch all unmatched routespath: '*404',diff --git a/js/app/packages/block-md/component/MarkdownPopup.tsx b/js/app/packages/block-md/component/MarkdownPopup.tsxindex 196eaa4a97..1372a0dd32 100644--- a/js/app/packages/block-md/component/MarkdownPopup.tsx+++ b/js/app/packages/block-md/component/MarkdownPopup.tsx@@ -35,10 +35,9 @@ import {import { toast } from '@core/component/Toast/Toast';import { ScopedPortal } from '@core/component/ScopedPortal';import { blockElementSignal } from '@core/signal/blockElement';-import { blockMetadataSignal } from '@core/signal/load';import { useCanComment, useCanEdit } from '@core/signal/permissions';import { debouncedDependent } from '@core/util/debounce';-import { createFromMarkdownText } from '@core/util/md';+import { createMarkdownFile } from '@core/util/create';import { getScrollParentElement } from '@core/util/scrollParent';import type { NodeIdMappings } from '@lexical-core';import { useUserId } from '@core/context/user';@@ -72,6 +71,7 @@ import {} from 'solid-js';import { FormatTools } from './FormatTools';import { isMobile } from '@core/mobile/isMobile';+import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';const MENU_ID = 'markdown-popup';@@ -302,6 +302,7 @@ export function MarkdownPopup(props: {setPopupVisible(false);});+ const name = useBlockDocumentName();const handleEditInMarkdown = createCallback(async () => {setIsLoading(true);const content = completion()?.content;@@ -310,21 +311,13 @@ export function MarkdownPopup(props: {}const title: string | undefined = await generateTitleForMarkdown(content);- const maybeDoc = await createFromMarkdownText({- markdown: content,- title:- title ?? `${blockMetadataSignal()?.documentName} - AI Explanation`,- preserveNewLines: false,+ const documentId = await createMarkdownFile({+ content,+ title: title ?? `${name()} - AI Explanation`,});- if ('error' in maybeDoc) {- console.error('Error opening AI message in Notes', maybeDoc.error);- setIsLoading(false);- return;- }-- const documentId = maybeDoc.documentId;if (!documentId) {+ console.error('Error opening AI message in Notes');setIsLoading(false);return;}diff --git a/js/app/packages/block-pdf/component/PDFPopup.tsx b/js/app/packages/block-pdf/component/PDFPopup.tsxindex a76e5cd584..c01cdf5435 100644--- a/js/app/packages/block-pdf/component/PDFPopup.tsx+++ b/js/app/packages/block-pdf/component/PDFPopup.tsx@@ -9,8 +9,7 @@ import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';import { AskAi } from '@core/component/GeneralizedPopup/AskAI';import { GeneralizedPopup } from '@core/component/GeneralizedPopup/Popup';import { blockElementSignal } from '@core/signal/blockElement';-import { blockMetadataSignal } from '@core/signal/load';-import { createFromMarkdownText } from '@core/util/md';+import { createMarkdownFile } from '@core/util/create';import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';import NotesIcon from '@phosphor-icons/core/bold/file-md-bold.svg?component-solid';@@ -36,6 +35,7 @@ import {PDFPopupCompletionSignal,PDFPopupSelectedTextSignal,} from './PageOverlay';+import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';const { track, TrackingEvents } = withAnalytics();@@ -197,6 +197,7 @@ export function PDFPopup(props: PDFPopupProps) {return undefined;}+ const name = useBlockDocumentName();const handleEditInMarkdown = createCallback(async () => {setIsLoading(true);const content = completion()?.content;@@ -205,20 +206,13 @@ export function PDFPopup(props: PDFPopupProps) {}const title: string | undefined = await generateTitleForMarkdown(content);- const maybeDoc = await createFromMarkdownText({- markdown: content,- title: title ?? `${blockMetadataSignal()?.documentName} - AI Explanation`,- preserveNewLines: false,+ const documentId = await createMarkdownFile({+ content,+ title: title ?? `${name()} - AI Explanation`,});- if ('error' in maybeDoc) {- console.error('Error opening AI message in Notes', maybeDoc.error);- setIsLoading(false);- return;- }-- const documentId = maybeDoc.documentId;if (!documentId) {+ console.error('Error opening AI message in Notes');setIsLoading(false);return;}diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsxindex 395e91dfe9..f58e54e69a 100644--- a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx+++ b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx@@ -4,7 +4,7 @@ import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMeimport { RenderTool } from '@core/component/AI/component/tool/handler';import { replaceCitations } from '@core/component/LexicalMarkdown/citationsUtils';import { ENABLE_TTFT } from '@core/constant/featureFlags';-import { createFromMarkdownText } from '@core/util/md';+import { createMarkdownFile } from '@core/util/create';import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';import NotesIcon from '@phosphor-icons/core/bold/file-md-bold.svg?component-solid';@@ -184,20 +184,13 @@ export function AssistantMessage(props: {content.replace(/\[\[.*?\]\]/g, ''));- const maybeDoc = await createFromMarkdownText({- markdown: content,+ const documentId = await createMarkdownFile({+ content,title: title ?? `AI Message`,- preserveNewLines: false,});- if ('error' in maybeDoc) {- console.error('Error opening AI message in Notes', maybeDoc.error);- setIsLoading(false);- return;- }-- const documentId = maybeDoc.documentId;if (!documentId) {+ console.error('Error opening AI message in Notes');setIsLoading(false);return;}diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessageActionMenu.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessageActionMenu.tsxindex c969eaa860..ee1cf2b6b2 100644--- a/js/app/packages/core/component/AI/component/message/AssistantMessageActionMenu.tsx+++ b/js/app/packages/core/component/AI/component/message/AssistantMessageActionMenu.tsx@@ -5,7 +5,7 @@ import {MODEL_PROVIDER_ICON,} from '@core/component/AI/constant/model';import { replaceCitations } from '@core/component/LexicalMarkdown/citationsUtils';-import { createFromMarkdownText } from '@core/util/md';+import { createMarkdownFile } from '@core/util/create';import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';import NotesIcon from '@phosphor-icons/core/bold/file-md-bold.svg?component-solid';@@ -97,20 +97,13 @@ export function AssistantMessageActionAndMetadata(props: AssistantActionProps) {content.replace(/\[\[.*?\]\]/g, ''));- const maybeDoc = await createFromMarkdownText({- markdown: content,+ const documentId = await createMarkdownFile({+ content,title: title ?? `AI Message`,- preserveNewLines: false,});- if ('error' in maybeDoc) {- console.error('Error opening AI message in Notes', maybeDoc.error);- setIsLoading(false);- return;- }-- const documentId = maybeDoc.documentId;if (!documentId) {+ console.error('Error opening AI message in Notes');setIsLoading(false);return;}diff --git a/js/app/packages/core/component/ItemPreview.tsx b/js/app/packages/core/component/ItemPreview.tsxindex d58a2c145a..9cc49eee20 100644--- a/js/app/packages/core/component/ItemPreview.tsx+++ b/js/app/packages/core/component/ItemPreview.tsx@@ -18,10 +18,6 @@ import type { NamedSubType } from '@macro-entity';import type { ChannelType } from '@service-cognition/generated/schemas/channelType';import type { ItemType } from '@service-storage/client';import type { FileType } from '@service-storage/generated/schemas/fileType';-import {- insertProjectIntoHistory,- postNewHistoryItem,-} from '@queries/history/history';import { Match, Switch, Suspense } from 'solid-js';import { Dynamic } from 'solid-js/web';import { PopupPreview } from './DocumentPreview';@@ -78,10 +74,6 @@ function useItemPreviewData(props: ItemPreviewProps) {subType?: NamedSubType,altKey?: boolean) {- if (type === 'project') {- insertProjectIntoHistory(id);- await postNewHistoryItem('project', id);- }const _type = subType ?? fileType ?? type;if (!_type) return;openItem(_type, id, openInNewSplitForMention(altKey, true));diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts b/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.tsindex 48ca07ccbd..38dc096eaf 100644--- a/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts+++ b/js/app/packages/core/component/LexicalMarkdown/utils/snapshotMention.ts@@ -3,7 +3,7 @@ import { entityPropertyFromApi } from '@core/component/Properties/api/convertersimport type { Property } from '@core/component/Properties/types';import { trackMention } from '@core/signal/mention';import { isErr, isOk } from '@core/util/maybeResult';-import { fetchDocumentAsMarkdown } from '@queries/storage/markdownText';+import { fetchDocumentAsMarkdown } from '@queries/sync/markdownText';import { propertiesServiceClient } from '@service-properties/client';import { EntityType } from '@service-properties/generated/schemas/entityType';import { storageServiceClient } from '@service-storage/client';diff --git a/js/app/packages/core/context/channels.ts b/js/app/packages/core/context/channels.tsindex 78dee24d91..07d57507bc 100644--- a/js/app/packages/core/context/channels.ts+++ b/js/app/packages/core/context/channels.ts@@ -8,6 +8,7 @@ import { useChannelsActivityQuery } from '@queries/channel/activity';import { queryReadyGate } from '@queries/gate';import { createAssertedContextProvider } from './createContext';import { useUserId } from './user';+import type { LastInteractionTimestamp } from '@core/user/types';type ChannelsContextValue = {channels: Accessor<ApiChannelWithLatest[]>;@@ -81,10 +82,10 @@ export function useDmActivityByUserId(): Accessor<Map<string, number>> {return createMemo(() => {const currentUser = currentUserId();- if (!currentUser) return new Map<string, number>();+ if (!currentUser) return new Map<string, LastInteractionTimestamp>();const allChannels = channels();- const map = new Map<string, number>();+ const map = new Map<string, LastInteractionTimestamp>();for (const channel of allChannels) {if (channel.channel_type !== 'direct_message') continue;@@ -97,7 +98,7 @@ export function useDmActivityByUserId(): Accessor<Map<string, number>> {const timestamp = channel.updated_at;if (timestamp) {const date = new Date(timestamp);- const unixTimestamp = Math.floor(date.getTime() / 1000);+ const unixTimestamp = date.getTime();map.set(otherParticipant.user_id, unixTimestamp);}}diff --git a/js/app/packages/core/internal/trackBlockOpened.ts b/js/app/packages/core/internal/trackBlockOpened.tsindex 458002fe40..285270e9c5 100644--- a/js/app/packages/core/internal/trackBlockOpened.ts+++ b/js/app/packages/core/internal/trackBlockOpened.ts@@ -1,6 +1,10 @@import type { BlockName } from '../block';import { useUpsertToHistoryMutation } from '@queries/history/history';-import { optimisticUpdateDssItemViewedAt } from '@macro-entity';+import {+ optimisticUpdateDssItemViewedAt,+ hasSoupItem,+ invalidateSoup,+} from '@macro-entity';import {blockNameToItemType,isCloudStorageItem,@@ -19,7 +23,12 @@ export function track() {const itemType = blockNameToItemType(blockName);- optimisticUpdateDssItemViewedAt(itemId);+ const inSoup = hasSoupItem(itemId);+ if (inSoup) {+ optimisticUpdateDssItemViewedAt(itemId);+ } else {+ invalidateSoup();+ }if (!isCloudStorageItem(itemType)) return;diff --git a/js/app/packages/core/user/types.ts b/js/app/packages/core/user/types.tsindex b12b50e4da..ef88d77b3c 100644--- a/js/app/packages/core/user/types.ts+++ b/js/app/packages/core/user/types.ts@@ -9,11 +9,15 @@ export interface IOrganizationUser {is_it_admin: boolean;}+/** Timestamp of last interaction with the user (in milliseconds to match server timestamps) */+export type LastInteractionTimestamp = number;+export type IUser = {id: string;email: string;name: string;- lastInteraction?: number;+ /** timestamp of last interaction with the user (in milliseconds to match server timestamps) */+ lastInteraction?: LastInteractionTimestamp;};type BaseUserName = {diff --git a/js/app/packages/core/util/create.ts b/js/app/packages/core/util/create.tsindex 385ca48966..4f0eb71517 100644--- a/js/app/packages/core/util/create.ts+++ b/js/app/packages/core/util/create.ts@@ -36,11 +36,11 @@ type CreateMarkdownFileArgs = {title?: string;content?: string;projectId?: string;- isTask?: boolean;};/**- * Initializes a new markdown file in dss & sync_service given a content string+ * Initializes a new markdown file in dss & sync_service given a content string.+ * Use createTask for the task subtype.*/export async function createMarkdownFile(args?: CreateMarkdownFileArgs@@ -58,7 +58,7 @@ export async function createMarkdownFile(fileType: 'md',sha: fakeSha,projectId: args?.projectId,- isTask: args?.isTask ?? false,+ isTask: false,});invalidateUserQuota();@@ -134,79 +134,47 @@ export async function createTask(export async function createCodeFileFromText({code,extension,+ language,title,}: {code: string;title?: string;- extension: CodeFileExtension;+ extension?: CodeFileExtension;+ language?: string;}) {const encoder = new TextEncoder();const buffer = encoder.encode(code);const sha = await contentHash(buffer);- if (!isCodeEditorExtensionSupported(extension))- return err(- 'UNSUPPORTED_EXTENSION',- `${extension} is not supported by the code block`- );- // mime types for code blocks are all text, and the backend doesn't care- const mimeType = 'text/plain';-- const maybeCode = await storageServiceClient.createDocument({- documentName: title ?? 'New Code File',- fileType: extension,- sha: sha,- });-- invalidateUserQuota();- // TODO: this is kind of odd, since there's an actual code we could use for the paywall, 402 Payment Required- if (isErr(maybeCode) && maybeCode[0][0].message.includes('403')) {- return err('UNAUTHORIZED', maybeCode[0][0].message);+ let finalExtension: string | undefined = extension;++ if (language && !extension) {+ if (!isCodeEditorLanguageSupported(language))+ return err(+ 'UNSUPPORTED_LANGUAGE',+ `${language} is not supported by the code block`+ );++ finalExtension = getExtensionForLanguage(language) ?? undefined;+ if (!finalExtension) {+ return err(+ 'UNSUPPORTED_LANGUAGE',+ `Could not find file extension for language: ${language}`+ );+ }}- if (isErr(maybeCode)) return err('SERVER_ERROR', maybeCode[0][0].message);- const [, document] = maybeCode;- const uploadResult = await uploadToPresignedUrl({- presignedUrl: document.presignedUrl,- buffer,- sha,- type: mimeType,- });- if (isErr(uploadResult)) return err('SERVER_ERROR', 'Failed to upload file');- postNewHistoryItem('document', document.metadata.documentId);- return ok({ documentId: document.metadata.documentId });-}-export async function createCodeFileFromTextWithLanguage({- code,- language,- title,-}: {- code: string;- title?: string;- language: string;-}) {- const encoder = new TextEncoder();- const buffer = encoder.encode(code);- const sha = await contentHash(buffer);- if (!isCodeEditorLanguageSupported(language))+ if (!finalExtension || !isCodeEditorExtensionSupported(finalExtension))return err(- 'UNSUPPORTED_LANGUAGE',- `${language} is not supported by the code block`+ 'UNSUPPORTED_EXTENSION',+ `${finalExtension ?? 'undefined'} is not supported by the code block`);- // mime types for code blocks are all text, and the backend doesn't care- const mimeType = 'text/plain';- const extension = getExtensionForLanguage(language);- if (!extension) {- return err(- 'UNSUPPORTED_LANGUAGE',- `Could not find file extension for language: ${language}`- );- }+ const mimeType = 'text/plain';const maybeCode = await storageServiceClient.createDocument({documentName: title ?? 'New Code File',- fileType: extension,+ fileType: finalExtension,sha: sha,});@@ -288,7 +256,7 @@ export async function createStaticFile(file: File): Promise<string> {if (isErr(result)) throw new Error('Failed to upload file');const { upload_url, id } = result[1];- const uploadResult = await staticFileClient.uploadToPresignedUlr({+ const uploadResult = await staticFileClient.uploadToPresignedUrl({url: upload_url,blob: file,});diff --git a/js/app/packages/core/util/dateSearch/dateParser.test.ts b/js/app/packages/core/util/dateSearch/dateParser.test.tsindex cf202cf187..8a95226777 100644--- a/js/app/packages/core/util/dateSearch/dateParser.test.ts+++ b/js/app/packages/core/util/dateSearch/dateParser.test.ts@@ -4,6 +4,7 @@ import {addHours,addMinutes,addMonths,+ addSeconds,addWeeks,addYears,} from 'date-fns';@@ -55,6 +56,13 @@ describe('parseDurationString', () => {expect(parseDurationString('90min')).toEqual({ value: 90, unit: 'min' });});+ it('should parse seconds correctly', () => {+ expect(parseDurationString('1s')).toEqual({ value: 1, unit: 's' });+ expect(parseDurationString('30s')).toEqual({ value: 30, unit: 's' });+ expect(parseDurationString('90s')).toEqual({ value: 90, unit: 's' });+ expect(parseDurationString('0.5s')).toEqual({ value: 0.5, unit: 's' });+ });+it('should handle whitespace', () => {expect(parseDurationString(' 3d ')).toEqual({ value: 3, unit: 'd' });expect(parseDurationString('3 d')).toEqual({ value: 3, unit: 'd' });@@ -66,6 +74,7 @@ describe('parseDurationString', () => {expect(parseDurationString('1W')).toEqual({ value: 1, unit: 'w' });expect(parseDurationString('2H')).toEqual({ value: 2, unit: 'h' });expect(parseDurationString('30MIN')).toEqual({ value: 30, unit: 'min' });+ expect(parseDurationString('30S')).toEqual({ value: 30, unit: 's' });});it('should return null for invalid input', () => {@@ -118,6 +127,12 @@ describe('applyDurationToDate', () => {expect(result).toEqual(addMinutes(baseDate, 45));});+ it('should add seconds correctly', () => {+ const duration: ParsedDuration = { value: 30, unit: 's' };+ const result = applyDurationToDate(baseDate, duration);+ expect(result).toEqual(addSeconds(baseDate, 30));+ });+it('should round decimal values', () => {const duration: ParsedDuration = { value: 1.7, unit: 'h' };const result = applyDurationToDate(baseDate, duration);@@ -203,6 +218,7 @@ describe('formatDuration', () => {expect(formatDuration({ value: 1, unit: 'm' })).toBe('1 month');expect(formatDuration({ value: 1, unit: 'y' })).toBe('1 year');expect(formatDuration({ value: 1, unit: 'min' })).toBe('1 minute');+ expect(formatDuration({ value: 1, unit: 's' })).toBe('1 second');});it('should format plural units correctly', () => {@@ -212,6 +228,7 @@ describe('formatDuration', () => {expect(formatDuration({ value: 5, unit: 'm' })).toBe('5 months');expect(formatDuration({ value: 2, unit: 'y' })).toBe('2 years');expect(formatDuration({ value: 30, unit: 'min' })).toBe('30 minutes');+ expect(formatDuration({ value: 30, unit: 's' })).toBe('30 seconds');});it('should handle decimal values', () => {diff --git a/js/app/packages/core/util/dateSearch/dateParser.ts b/js/app/packages/core/util/dateSearch/dateParser.tsindex 86fb36d159..b62a72a354 100644--- a/js/app/packages/core/util/dateSearch/dateParser.ts+++ b/js/app/packages/core/util/dateSearch/dateParser.ts@@ -5,17 +5,18 @@ import {addMonths,addWeeks,addYears,+ addSeconds,} from 'date-fns';import { match } from 'ts-pattern';-export type TimeUnit = 'h' | 'd' | 'w' | 'm' | 'y' | 'min';+export type TimeUnit = 'h' | 'd' | 'w' | 'm' | 'y' | 'min' | 's';export interface ParsedDuration {value: number;unit: TimeUnit;}-const UNITS = new Set<TimeUnit>(['h', 'd', 'w', 'm', 'y', 'min']);+const UNITS = new Set<TimeUnit>(['h', 'd', 'w', 'm', 'y', 'min', 's']);/*** Parses a duration string like "3d", "1w", "36h", "2m", "1y", "30min"@@ -50,6 +51,7 @@ export function applyDurationToDate(const unit = duration.unit;return match(unit)+ .with('s', () => addSeconds(baseDate, value)).with('min', () => addMinutes(baseDate, value)).with('h', () => addHours(baseDate, value)).with('d', () => addDays(baseDate, value))@@ -101,6 +103,7 @@ export function formatDuration(duration: ParsedDuration): string {const { value, unit } = duration;const unitLabels: Record<TimeUnit, string> = {+ s: value === 1 ? 'second' : 'seconds',min: value === 1 ? 'minute' : 'minutes',h: value === 1 ? 'hour' : 'hours',d: value === 1 ? 'day' : 'days',diff --git a/js/app/packages/core/util/freshSort.test.ts b/js/app/packages/core/util/freshSort.test.tsindex cac8e9bc74..878afba656 100644--- a/js/app/packages/core/util/freshSort.test.ts+++ b/js/app/packages/core/util/freshSort.test.ts@@ -1,5 +1,7 @@import { describe, expect, it } from 'vitest';import { createFreshSearch, normalizeFuzzyScore } from './freshSort';+import type { LastInteractionTimestamp } from '@core/user/types';+import { applyDurationToDate } from './dateSearch/dateParser';interface MockItem {id: string;@@ -7,6 +9,11 @@ interface MockItem {type: 'item' | 'channel';viewedAt?: number;updatedAt?: number;+ lastInteraction?: LastInteractionTimestamp;+}++interface User extends MockItem {+ email: string;}function createSearch(opts: { useViewedAt?: boolean; channelBoost?: number }) {@@ -25,11 +32,29 @@ function createSearch(opts: { useViewedAt?: boolean; channelBoost?: number }) {describe('freshSort ordering', () => {it('orders by viewedAt - most recent first', () => {- const now = Date.now();+ const now = new Date();const items: MockItem[] = [- { id: '1', name: 'Meeting Notes', type: 'item', viewedAt: now - 3600000 }, // 1hr ago- { id: '2', name: 'Project Plan', type: 'item', viewedAt: now - 60000 }, // 1min ago- { id: '3', name: 'Old Draft', type: 'item', viewedAt: now - 86400000 }, // 1day ago+ {+ id: '1',+ name: 'Meeting Notes',+ type: 'item',+ viewedAt: applyDurationToDate(now, { value: -1, unit: 'h' }).getTime(),+ },+ {+ id: '2',+ name: 'Project Plan',+ type: 'item',+ viewedAt: applyDurationToDate(now, {+ value: -1,+ unit: 'min',+ }).getTime(),+ },+ {+ id: '3',+ name: 'Old Draft',+ type: 'item',+ viewedAt: applyDurationToDate(now, { value: -1, unit: 'd' }).getTime(),+ },];const search = createSearch({ useViewedAt: true });@@ -39,14 +64,25 @@ describe('freshSort ordering', () => {});it('boosts channels above documents when searching', () => {- const now = Date.now();+ const now = new Date();const items: MockItem[] = [- { id: '1', name: 'Design Doc', type: 'item', viewedAt: now - 1000 },+ {+ id: '1',+ name: 'Design Doc',+ type: 'item',+ viewedAt: applyDurationToDate(now, {+ value: -1,+ unit: 'min',+ }).getTime(),+ },{id: '2',name: 'Design Channel',type: 'channel',- viewedAt: now - 5000,+ viewedAt: applyDurationToDate(now, {+ value: -5,+ unit: 'min',+ }).getTime(),},];@@ -57,11 +93,29 @@ describe('freshSort ordering', () => {});it('mixes documents and channels by recency without boost', () => {- const now = Date.now();+ const now = new Date();const items: MockItem[] = [- { id: '1', name: 'Doc A', type: 'item', viewedAt: now - 3600000 }, // 1hr ago- { id: '2', name: 'Channel B', type: 'channel', viewedAt: now - 60000 }, // 1min ago- { id: '3', name: 'Doc C', type: 'item', viewedAt: now - 86400000 }, // 1day ago+ {+ id: '1',+ name: 'Doc A',+ type: 'item',+ viewedAt: applyDurationToDate(now, { value: -1, unit: 'h' }).getTime(),+ },+ {+ id: '2',+ name: 'Channel B',+ type: 'channel',+ viewedAt: applyDurationToDate(now, {+ value: -1,+ unit: 'min',+ }).getTime(),+ },+ {+ id: '3',+ name: 'Doc C',+ type: 'item',+ viewedAt: applyDurationToDate(now, { value: -1, unit: 'd' }).getTime(),+ },];const search = createSearch({ useViewedAt: true, channelBoost: 1.0 });@@ -207,12 +261,30 @@ describe('normalizeFuzzyScore', () => {describe('freshSort with all exact matches', () => {it('sorts by recency when all items are exact matches (Infinity scores)', () => {- const now = Date.now();+ const now = new Date();const items: MockItem[] = [- { id: '1', name: 'Design', type: 'item', viewedAt: now - 3600000 }, // 1hr ago- { id: '2', name: 'Design', type: 'item', viewedAt: now - 60000 }, // 1min ago- { id: '3', name: 'Design', type: 'item', viewedAt: now - 86400000 }, // 1day ago- { id: '4', name: 'Design', type: 'item', viewedAt: now - 1000 }, // 1sec ago+ {+ id: '1',+ name: 'Design',+ type: 'item',+ viewedAt: applyDurationToDate(now, { value: -1, unit: 'h' }).getTime(),+ },+ {+ id: '2',+ name: 'Design',+ type: 'item',+ viewedAt: applyDurationToDate(now, {+ value: -1,+ unit: 'min',+ }).getTime(),+ },+ {+ id: '3',+ name: 'Design',+ type: 'item',+ viewedAt: applyDurationToDate(now, { value: -1, unit: 'd' }).getTime(),+ },+ { id: '4', name: 'Design', type: 'item', viewedAt: now.getTime() },];const search = createFreshSearch<MockItem>(@@ -241,10 +313,20 @@ describe('freshSort with all exact matches', () => {});it('channel boost works correctly with all exact matches', () => {- const now = Date.now();+ const now = new Date();const items: MockItem[] = [- { id: '1', name: 'Design', type: 'item', viewedAt: now - 1000 },- { id: '2', name: 'Design', type: 'channel', viewedAt: now - 5000 },+ {+ id: '1',+ name: 'Design',+ type: 'item',+ viewedAt: applyDurationToDate(now, { value: -1, unit: 's' }).getTime(),+ },+ {+ id: '2',+ name: 'Design',+ type: 'channel',+ viewedAt: applyDurationToDate(now, { value: -5, unit: 's' }).getTime(),+ },];const search = createFreshSearch<MockItem>(@@ -272,28 +354,28 @@ describe('boostFn functionality', () => {}it('applies per-item boost correctly', () => {- const now = Date.now();+ const now = new Date();const items: MockItemWithEmail[] = [{id: '1',name: 'Alice Johnson',type: 'item',email: '[email protected]',- viewedAt: now - 1000,+ viewedAt: applyDurationToDate(now, { value: -1, unit: 's' }).getTime(),},{id: '2',name: 'Bob Smith',type: 'item',email: '[email protected]',- viewedAt: now - 5000, // Older than Alice+ viewedAt: applyDurationToDate(now, { value: -5, unit: 's' }).getTime(),},{id: '3',name: 'Charlie Brown',type: 'item',email: '[email protected]',- viewedAt: now - 3000,+ viewedAt: applyDurationToDate(now, { value: -3, unit: 's' }).getTime(),},];@@ -319,21 +401,21 @@ describe('boostFn functionality', () => {});it('boostFn works with search query', () => {- const now = Date.now();+ const now = new Date();const items: MockItemWithEmail[] = [{id: '1',name: 'Alice Johnson',type: 'item',email: '[email protected]',- viewedAt: now - 1000,+ viewedAt: applyDurationToDate(now, { value: -1, unit: 's' }).getTime(),},{id: '2',name: 'Alicia Smith',type: 'item',email: '[email protected]',- viewedAt: now - 1000,+ viewedAt: applyDurationToDate(now, { value: -1, unit: 's' }).getTime(),},];@@ -360,10 +442,26 @@ describe('boostFn functionality', () => {});it('handles boostFn returning 0 for no boost', () => {- const now = Date.now();+ const now = new Date();const items: MockItemWithEmail[] = [- { id: '1', name: 'Alice', type: 'item', viewedAt: now - 1000 },- { id: '2', name: 'Bob', type: 'item', viewedAt: now - 2000 },+ {+ id: '1',+ name: 'Alice',+ type: 'item',+ viewedAt: applyDurationToDate(now, {+ value: -1,+ unit: 'min',+ }).getTime(),+ },+ {+ id: '2',+ name: 'Bob',+ type: 'item',+ viewedAt: applyDurationToDate(now, {+ value: -2,+ unit: 'min',+ }).getTime(),+ },];const search = createFreshSearch<MockItemWithEmail>(@@ -384,21 +482,21 @@ describe('boostFn functionality', () => {});it('combines boostFn with channelBoost', () => {- const now = Date.now();+ const now = new Date();const items: MockItemWithEmail[] = [{id: '1',name: 'Design Doc',type: 'item',email: '[email protected]',- viewedAt: now - 1000,+ viewedAt: applyDurationToDate(now, { value: -1, unit: 's' }).getTime(),},{id: '2',name: 'Design Channel',type: 'channel',email: '[email protected]',- viewedAt: now - 1000,+ viewedAt: applyDurationToDate(now, { value: -1, unit: 's' }).getTime(),},];@@ -424,10 +522,26 @@ describe('boostFn functionality', () => {});it('works without boostFn (undefined)', () => {- const now = Date.now();+ const now = new Date();const items: MockItemWithEmail[] = [- { id: '1', name: 'Alice', type: 'item', viewedAt: now - 1000 },- { id: '2', name: 'Bob', type: 'item', viewedAt: now - 2000 },+ {+ id: '1',+ name: 'Alice',+ type: 'item',+ viewedAt: applyDurationToDate(now, {+ value: -1,+ unit: 'min',+ }).getTime(),+ },+ {+ id: '2',+ name: 'Bob',+ type: 'item',+ viewedAt: applyDurationToDate(now, {+ value: -2,+ unit: 'min',+ }).getTime(),+ },];const search = createFreshSearch<MockItemWithEmail>(@@ -449,27 +563,28 @@ describe('boostFn functionality', () => {});describe('DM activity timestamps for user ranking', () => {- interface UserWithInteraction extends MockItem {- email: string;- lastInteraction?: number;- }-it('ranks users with recent DM activity higher', () => {- const now = Date.now();- const users: UserWithInteraction[] = [+ const now = new Date();+ const users: User[] = [{id: '1',name: 'Alice Johnson',type: 'item',email: '[email protected]',- lastInteraction: now / 1000 - 86400, // 1 day ago (unix timestamp in seconds)+ lastInteraction: applyDurationToDate(now, {+ value: -1,+ unit: 'd',+ }).getTime(),},{id: '2',name: 'Bob Smith',type: 'item',email: '[email protected]',- lastInteraction: now / 1000 - 3600, // 1 hour ago+ lastInteraction: applyDurationToDate(now, {+ value: -1,+ unit: 'h',+ }).getTime(),},{id: '3',@@ -480,7 +595,7 @@ describe('DM activity timestamps for user ranking', () => {},];- const search = createFreshSearch<UserWithInteraction>(+ const search = createFreshSearch<User>({fuzzyWeight: 0.6,timeWeight: 0.3,@@ -502,32 +617,41 @@ describe('DM activity timestamps for user ranking', () => {});it('combines DM activity with fuzzy search', () => {- const now = Date.now();- const users: UserWithInteraction[] = [+ const now = new Date();+ const users: User[] = [{id: '1',name: 'Alice Anderson',type: 'item',email: '[email protected]',- lastInteraction: now / 1000 - 86400, // 1 day ago+ lastInteraction: applyDurationToDate(now, {+ value: -1,+ unit: 'd',+ }).getTime(),},{id: '2',name: 'Alicia Martinez',type: 'item',email: '[email protected]',- lastInteraction: now / 1000 - 3600, // 1 hour ago+ lastInteraction: applyDurationToDate(now, {+ value: -1,+ unit: 'h',+ }).getTime(),},{id: '3',name: 'Bob Wilson',type: 'item',email: '[email protected]',- lastInteraction: now / 1000 - 60, // 1 minute ago+ lastInteraction: applyDurationToDate(now, {+ value: -1,+ unit: 'min',+ }).getTime(),},];- const search = createFreshSearch<UserWithInteraction>(+ const search = createFreshSearch<User>({fuzzyWeight: 0.6,timeWeight: 0.3,@@ -547,7 +671,7 @@ describe('DM activity timestamps for user ranking', () => {});it('handles users without lastInteraction gracefully', () => {- const users: UserWithInteraction[] = [+ const users: User[] = [{id: '1',name: 'Alice',@@ -564,7 +688,7 @@ describe('DM activity timestamps for user ranking', () => {},];- const search = createFreshSearch<UserWithInteraction>(+ const search = createFreshSearch<User>({fuzzyWeight: 0.6,timeWeight: 0.3,diff --git a/js/app/packages/core/util/freshSort.ts b/js/app/packages/core/util/freshSort.tsindex 644f250684..93ea1396a9 100644--- a/js/app/packages/core/util/freshSort.ts+++ b/js/app/packages/core/util/freshSort.ts@@ -6,6 +6,7 @@ import type { Accessor } from 'solid-js';import type { FilterResult } from 'fuzzy';import fuzzy from 'fuzzy';import { fuzzyScoreCommaSpaceSeparated } from './fuzzy';+import type { LastInteractionTimestamp } from '@core/user';type BoostFn<T> = (item: T) => number;@@ -45,7 +46,7 @@ type FreshSortConfigWithDefaults = Required<FreshSortConfig<unknown>>;export interface TimestampedItem {updatedAt?: number | string;viewedAt?: number | string;- lastInteraction?: number | string;+ lastInteraction?: LastInteractionTimestamp | string;}export interface FreshSortResult<T> {@@ -85,18 +86,19 @@ function extractTimestamp(if (timestamp === undefined || timestamp === null) return 0;if (typeof timestamp === 'number') {- return timestamp > 1e10 ? Math.floor(timestamp / 1000) : timestamp;+ return timestamp;}if (typeof timestamp === 'string') {const isoDate = new Date(timestamp);- if (!isNaN(isoDate.getTime())) {- return Math.floor(isoDate.getTime() / 1000);+ const isoDateTime = isoDate.getTime();+ if (!isNaN(isoDateTime)) {+ return isoDateTime;}const parsed = parseInt(timestamp, 10);if (!isNaN(parsed)) {- return parsed > 1e10 ? Math.floor(parsed / 1000) : parsed;+ return parsed;}}@@ -108,7 +110,7 @@ function calculateTimeScore(config: FreshSortConfigWithDefaults): number {const now = Date.now();- const itemTime = timestamp * 1000;+ const itemTime = timestamp;const age = Math.max(0, now - itemTime);if (age >= config.maxAgeMs) {return 0;diff --git a/js/app/packages/core/util/md.ts b/js/app/packages/core/util/md.tsdeleted file mode 100644index 3d60395d9e..0000000000--- a/js/app/packages/core/util/md.ts+++ /dev/null@@ -1,70 +0,0 @@-import { createLexicalWrapper } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';-import { setEditorStateFromMarkdown } from '@core/component/LexicalMarkdown/utils';-import { storageServiceClient } from '@service-storage/client';-import { postNewHistoryItem } from '@queries/history/history';-import { uploadToPresignedUrl } from '@service-storage/util/uploadToPresignedUrl';-import { contentHash } from './hash';-import { isErr } from './maybeResult';--export async function createFromMarkdownText(args: {- markdown: string;- title?: string;- preserveNewLines?: boolean;-}): Promise<{ documentId: string } | { error: string }> {- const { markdown, title, preserveNewLines } = args;- const { editor, cleanup } = createLexicalWrapper({- type: 'markdown',- namespace: 'block-md-disposable',- isInteractable: () => true,- });- setEditorStateFromMarkdown(- editor,- markdown,- 'external',- preserveNewLines ?? true- );- const state = JSON.stringify(editor.getEditorState().toJSON());- cleanup();-- const encoder = new TextEncoder();- const buffer = encoder.encode(state);-- const sha = await contentHash(buffer);-- const maybeMd = await storageServiceClient.createDocument({- documentName: title ?? 'New Notebook',- fileType: 'md',- sha: sha,- });-- if (isErr(maybeMd)) return { error: 'Document creation failed.' };-- const [, md] = maybeMd;-- const uploadResult = await uploadToPresignedUrl({- presignedUrl: md.presignedUrl,- buffer,- sha,- type: 'text/markdown',- });-- if (isErr(uploadResult)) return { error: 'Failed to upload file.' };-- postNewHistoryItem('document', md.metadata.documentId);- return { documentId: md.metadata.documentId };-}--export async function transformMarkdownText(args: {- markdown: string;-}): Promise<{ json: string } | { error: string }> {- const { markdown } = args;- const { editor, cleanup } = createLexicalWrapper({- type: 'markdown',- namespace: 'block-md-disposable',- isInteractable: () => false,- });- setEditorStateFromMarkdown(editor, markdown, 'external');- const state = JSON.stringify(editor.getEditorState().toJSON());- cleanup();- return { json: state };-}diff --git a/js/app/packages/macro-entity/src/index.tsx b/js/app/packages/macro-entity/src/index.tsxindex d31986bb9d..67917c2c33 100644--- a/js/app/packages/macro-entity/src/index.tsx+++ b/js/app/packages/macro-entity/src/index.tsx@@ -19,6 +19,8 @@ export {createMoveToProjectDssEntityMutation,createCopyDssEntityMutation,optimisticUpdateDssItemViewedAt,+ hasSoupItem,+ invalidateSoup,} from './queries/dss';export { createEmailsInfiniteQuery } from './queries/email';export type { EntityInfiniteQuery, EntityQuery } from './queries/entity';diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.tsindex ae686ad0fb..a5361a9493 100644--- a/js/app/packages/macro-entity/src/queries/dss.ts+++ b/js/app/packages/macro-entity/src/queries/dss.ts@@ -205,6 +205,7 @@ export function createDssInfiniteQuery(};});}+const selectData: (data: InfiniteData<SoupPage,@@ -793,39 +794,39 @@ export function createBulkMoveToProjectDssEntityMutation() {/*** Optimistically update the viewedAt timestamp for a DSS item.- * Updates the item across all DSS queries.+ * Updates the item across all DSS queries if it exists.*/-export function optimisticUpdateDssItemViewedAt(itemId: string): void {- const now = new Date().toISOString();+export function optimisticUpdateDssItemViewedAt(itemId: string) {+ const now = new Date();queryClient.setQueriesData({ queryKey: queryKeys.all.dss },(prev: InfiniteData<SoupPage, unknown> | undefined) => {if (!prev) return prev;- const pages = prev.pages.map((page) => ({- ...page,- items: page.items.map((item): SoupApiItem => {- // Get the item ID based on its type- const currentItemId = getSoupItemId(item);-- if (currentItemId !== itemId) return item;-- switch (item.tag) {- case 'document':- case 'chat':- case 'project':- case 'emailThread':- item.data.viewedAt = Date.parse(now);- break;- case 'channel':- item.data.viewed_at = now;- break;- }-- return item;- }),- }));+ const pages = prev.pages.map((page) => {+ return {+ ...page,+ items: page.items.map((item): SoupApiItem => {+ const currentItemId = getSoupItemId(item);+ if (currentItemId !== itemId) return item;++ switch (item.tag) {+ case 'document':+ case 'chat':+ case 'project':+ case 'emailThread':+ item.data.viewedAt = now.getTime();+ break;+ case 'channel':+ item.data.viewed_at = now.toISOString();+ break;+ }++ return item;+ }),+ };+ });return {...prev,@@ -834,3 +835,34 @@ export function optimisticUpdateDssItemViewedAt(itemId: string): void {});}++/** Finds a soup item in the cache and returns its location. */+export function hasSoupItem(itemId: string) {+ const queries = queryClient.getQueriesData<InfiniteData<SoupPage, unknown>>({+ queryKey: queryKeys.all.dss,+ });++ for (const [, data] of queries) {+ if (!data) continue;++ for (let pageIndex = 0; pageIndex < data.pages.length; pageIndex++) {+ const page = data.pages[pageIndex];+ const itemIndex = page.items.findIndex(+ (item) => getSoupItemId(item) === itemId+ );+ if (itemIndex >= 0) return true;+ }+ }++ return false;+}++/**+ * Invalidates all DSS soup queries, marking them as stale.+ * If the query is currently being rendered, it will also be refetched in the background+ */+export function invalidateSoup() {+ queryClient.invalidateQueries({+ queryKey: queryKeys.all.dss,+ });+}diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.tsindex f90baecf37..72a272fedc 100644--- a/js/app/packages/queries/history/history.ts+++ b/js/app/packages/queries/history/history.ts@@ -254,6 +254,7 @@ export function getHistoryItems() {/*** Inserts a project and its nested items into history.* Recursively fetches project content and adds all items to history.+ * NOTE: this is currently not used since the block loader only calls upsertItemToUserHistory*/export async function insertProjectIntoHistory(projectId: string) {const prevData = getHistoryItems();diff --git a/js/app/packages/queries/storage/markdownText.ts b/js/app/packages/queries/sync/markdownText.tssimilarity index 100%rename from js/app/packages/queries/storage/markdownText.tsrename to js/app/packages/queries/sync/markdownText.tsdiff --git a/js/app/packages/service-clients/service-static-files/client.ts b/js/app/packages/service-clients/service-static-files/client.tsindex 8ac49ba0f3..e34d93e9e9 100644--- a/js/app/packages/service-clients/service-static-files/client.ts+++ b/js/app/packages/service-clients/service-static-files/client.ts@@ -65,7 +65,7 @@ export const staticFileClient = {return await staticFetch(`/file/${args.file_id}`, { method: 'GET' });},- async uploadToPresignedUlr(args: { url: string; blob: Blob | File }) {+ async uploadToPresignedUrl(args: { url: string; blob: Blob | File }) {const result = await platformFetch(args.url, {method: 'PUT',body: args.blob,diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex 58b331b7d4..1a634fd105 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -16,7 +16,6 @@ import {type FetchWithTokenErrorCode,fetchWithToken,} from '@core/util/fetchWithToken';-import { contentHash } from '@core/util/hash';import {err,isErr,@@ -28,7 +27,6 @@ import {} from '@core/util/maybeResult';import { registerClient } from '@core/util/mockClient';import type { SafeFetchInit } from '@core/util/safeFetch';-import { utf8Encode } from '@core/util/string';import type { IDocumentStorageServiceFile } from '@filesystem/file';import { platformFetch } from 'core/util/platformFetch';import type { AccessLevel, View, ViewsResponse } from './generated/schemas';@@ -87,7 +85,6 @@ import {type GetDocxFileResponse,getDocxExpandedParts,} from './util/getDocxFile';-import { uploadToPresignedUrl } from './util/uploadToPresignedUrl';// the server is set to expire at 15 minutes, so expire just before thatconst MINUTES_BEFORE_PRESIGNED_EXPIRES = 14;@@ -462,51 +459,6 @@ export const storageServiceClient = {return ok({ documentId: response.documentId });},- async createTextDocument({ text, ...docArgs }) {- const buffer = utf8Encode(text);- const sha = await contentHash(buffer);- // INFO: Typescript trips up on resolving storageServiceClient.createDocument, not sure why- const maybeDoc = await dssFetch<CreateDocumentResponse>(`/documents`, {- method: 'POST',- body: JSON.stringify({ sha, ...docArgs }),- });- if (isErr(maybeDoc)) {- const err = maybeDoc[0];-- if (err[0].message.includes('403')) {- showPaywall(PaywallKey.FILE_LIMIT);- }- return maybeDoc;- }-- const [- ,- {- data: { documentMetadata, presignedUrl },- },- ] = maybeDoc;-- if (!presignedUrl) {- console.error('no presigned url found for upload');- return err('SERVER_ERROR', 'Failed to upload file');- }-- const maybeUpload = await uploadToPresignedUrl({- presignedUrl,- buffer,- sha,- type: 'text/plain',- });-- if (isErr(maybeUpload)) {- return err('SERVER_ERROR', 'Failed to upload file');- }-- return ok({- metadata: documentMetadata,- });- },-async copyDocument(params: {documentId: string;documentVersionId?: number;diff --git a/js/app/packages/service-clients/service-storage/service.ts b/js/app/packages/service-clients/service-storage/service.tsindex aef28ae8ab..ad5acdfddd 100644--- a/js/app/packages/service-clients/service-storage/service.ts+++ b/js/app/packages/service-clients/service-storage/service.ts@@ -422,22 +422,6 @@ export const StorageService = new Svc('Document++ Storage Service API')modifies: true,throws: withFetchErrors('INVALID_RESPONSE'),})- .fn('createTextDocument', {- description: 'Creates a new text document',- args: {- ...schemas.createDocumentHandlerBody.omit({- sha: true,- }).shape,- text: z.string().describe('The text content of the document'),- },- result: {- metadata:- schemas.createDocumentHandlerResponse.shape.data._def.left.shape- .documentMetadata,- },- modifies: true,- throws: withFetchErrors('INVALID_RESPONSE'),- }).fn('copyDocument', {description: schemas.copyDocumentHandlerResponse.description!,args: {