Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: clean up history work being done on front end (#1355)
gbirmanedfdf8df5a0e
diff --git a/js/app/packages/core/util/currentBlockDocumentName.ts b/js/app/packages/core/util/currentBlockDocumentName.tsindex acbcba6658..b405c2e820 100644--- a/js/app/packages/core/util/currentBlockDocumentName.ts+++ b/js/app/packages/core/util/currentBlockDocumentName.ts@@ -6,7 +6,7 @@ import {} from '@core/block';import { blockNameToDefaultFile } from '@core/constant/allBlocks';import { blockMetadataSignal } from '@core/signal/load';-import { useUpdatedDssItemName } from '@queries/history/history';+import { useHistoryItemRawName } from '@queries/history/history';import { formatDocumentName } from '@service-storage/util/filename';export const useBlockDocumentName = (defaultName?: string) => {@@ -15,10 +15,11 @@ export const useBlockDocumentName = (defaultName?: string) => {}// TODO: find new solution once block sigal is deprecated for good.const [metadata] = blockMetadataSignal;+ const blockId = useBlockId();const blockName = useBlockAliasedName();const isFileBlock = !NonDocumentBlockTypes.includes(blockName);- const updatedName = useUpdatedDssItemName(useBlockId());+ const updatedName = useHistoryItemRawName(blockId);return () => {const current = updatedName();diff --git a/js/app/packages/macro-entity/src/components/Provider.tsx b/js/app/packages/macro-entity/src/components/Provider.tsxindex cd61d31ccd..fc4248f2de 100644--- a/js/app/packages/macro-entity/src/components/Provider.tsx+++ b/js/app/packages/macro-entity/src/components/Provider.tsx@@ -5,6 +5,7 @@ import { Show, type ParentProps } from 'solid-js';import { fetchApiToken } from '../queries/auth';import { queryClient } from '../queries/client';import { queryKeys } from '../queries/key';+import { RemoveInstructionsMdFromHistorySideEffect } from '@queries/history/history';export function Provider(props: ParentProps) {queryClient.setQueryDefaults(queryKeys.all.auth, {@@ -18,6 +19,7 @@ export function Provider(props: ParentProps) {return (<QueryClientProvider client={queryClient}>+ <RemoveInstructionsMdFromHistorySideEffect />{props.children}<Show when={LOCAL_ONLY}><SolidQueryDevtools initialIsOpen={false} />diff --git a/js/app/packages/macro-entity/src/queries/rename.ts b/js/app/packages/macro-entity/src/queries/rename.tsindex d93fba2501..1cabe8a674 100644--- a/js/app/packages/macro-entity/src/queries/rename.ts+++ b/js/app/packages/macro-entity/src/queries/rename.ts@@ -13,7 +13,7 @@ import { type InfiniteData, useMutation } from '@tanstack/solid-query';import { toast } from '@core/component/Toast/Toast';import type { SoupPage } from '@service-storage/generated/schemas';import { setPreviewData } from '@queries/preview';-import { setHistoryItemData } from '@queries/history/history';+import { setHistoryItemName } from '@queries/history/history';type RenamableEntity = Pick<EntityData, 'id' | 'type' | 'name'> &Partial<EntityData>;@@ -177,10 +177,7 @@ const renamePreviewSetData = (entities: EntityRenameData[]) => {const renameHistorySetData = (entities: EntityRenameData[]) => {entities.forEach(({ id, newName }) => {- setHistoryItemData(id, (prev) => ({- ...prev,- name: newName,- }));+ setHistoryItemName(id, newName);});};diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.tsindex 3a8fd0b4f1..f90baecf37 100644--- a/js/app/packages/queries/history/history.ts+++ b/js/app/packages/queries/history/history.ts@@ -4,96 +4,111 @@ import { storageServiceClient } from '@service-storage/client';import type { CloudStorageItemType } from '@service-storage/generated/schemas/cloudStorageItemType';import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';import {- type UseQueryResult,useMutation,useQuery,+ queryOptions,type QueryClient,+ type Updater,} from '@tanstack/solid-query';-import type { Accessor, Setter } from 'solid-js';+import { createEffect, type Accessor, type Setter } from 'solid-js';import { queryClient } from '../client';import { historyKeys } from './keys';import {- type HistoryItem,- type HistoryQueryResponse,transformHistoryResponse,updateViewedAtAndMoveItemToFront,} from './transforms';+import { queryReadyGate } from '@queries/gate';+import type { HistoryItem } from './types';-export { historyKeys } from './keys';-export type { HistoryItem, HistoryQueryResponse } from './transforms';-export {- filterInstructionsMd,- transformHistoryItem,- transformHistoryResponse,-} from './transforms';+// re-export history item type from this file+export type { HistoryItem } from './types';const HISTORY_STALE_TIME = 5 * 60 * 1000;const HISTORY_GC_TIME = 10 * 60 * 1000;-export function setHistoryItemData(- itemId: string,- updater: Setter<HistoryItem>+type HistoryQueryFnResult = HistoryItem[];++/** Sets the history data on the query cache directly. Updater fn already handles undefined. */+function setHistoryData(+ updater: Updater<HistoryQueryFnResult, HistoryQueryFnResult>) {- return queryClient.setQueryData<HistoryQueryResponse>(- historyKeys.list.queryKey,- (prev) => {- if (!prev) return prev;- const items = prev.data.map((item) => {- if (item.id === itemId) {- return updater(item);- }- return item;- });- return {- ...prev,- data: items,- };- }- );+ return queryClient.setQueryData(historyQueryOptions.queryKey, (prev) => {+ if (!prev) return prev;+ return typeof updater === 'function' ? updater(prev) : updater;+ });}-function historyQueryOptions() {- return {- queryKey: historyKeys.list.queryKey,- queryFn: async (): Promise<HistoryQueryResponse> => {- const result = await throwOnErr(- async () => await storageServiceClient.getUsersHistory()- );- return result;- },- staleTime: HISTORY_STALE_TIME,- gcTime: HISTORY_GC_TIME,- };+/** Sets the history data on the query cache directly for a single item */+function setHistoryItemData(itemId: string, updater: Setter<HistoryItem>) {+ return setHistoryData((prev) => {+ return prev.map((item) => {+ if (item.id === itemId) {+ return updater(item);+ }+ return item;+ });+ });}-export function useHistoryQuery(options?: {- instructionsMdIdQuery?: UseQueryResult<string | null | undefined, Error>;-}) {- const instructionsMdIdQueryInternal = useInstructionsMdIdQuery();- const instructionsIdQuery =- options?.instructionsMdIdQuery ?? instructionsMdIdQueryInternal;+export function setHistoryItemName(itemId: string, name: string) {+ return setHistoryItemData(itemId, (prev) => ({+ ...prev,+ name,+ rawName: name,+ }));+}- return useQuery(() => ({- ...historyQueryOptions(),+const historyQueryOptions = queryOptions({+ queryKey: historyKeys.list.queryKey,+ queryFn: async (): Promise<HistoryQueryFnResult> => {+ const result = await throwOnErr(+ async () => await storageServiceClient.getUsersHistory()+ );+ return transformHistoryResponse(result);+ },+ staleTime: HISTORY_STALE_TIME,+ gcTime: HISTORY_GC_TIME,+});++export function useHistoryQuery() {+ const baseQuery = useQuery(() => ({+ ...historyQueryOptions,placeholderData: (prev) => prev,- select: (data: HistoryQueryResponse): HistoryItem[] => {- const instructionsId = instructionsIdQuery.isSuccess- ? instructionsIdQuery.data- : null;- return transformHistoryResponse(data, instructionsId);- },+ reconcile: 'id',}));++ return baseQuery;+}++// TODO: this is a temporary side effect to remove the instructions item from history+// load this at the app root level to prevent duplicate work+// this will be removed from the backend+export function RemoveInstructionsMdFromHistorySideEffect() {+ const instructionsIdQuery = useInstructionsMdIdQuery();+ const historyQuery = useHistoryQuery();+ createEffect(() => {+ const instructionsReady = queryReadyGate(instructionsIdQuery);+ if (!instructionsReady) return;+ const instructionsId = instructionsIdQuery.data;+ const history = historyQuery.data;+ if (!instructionsId || !history || !history.length) return;+ if (!history.some((item) => item.id === instructionsId)) return;+ return setHistoryData((prev) => {+ return prev.filter((item) => item.id !== instructionsId);+ });+ });+ return null;}export async function prefetchHistory() {void (await catchToResult(- async () => await queryClient.prefetchQuery(historyQueryOptions())+ async () => await queryClient.prefetchQuery(historyQueryOptions)));}export function refetchHistory() {return queryClient.invalidateQueries({- queryKey: historyKeys.list.queryKey,+ queryKey: historyQueryOptions.queryKey,});}@@ -102,17 +117,9 @@ export function refetchHistory() {function optimisticUpdateViewedAt(itemId: string) {const now = Date.now();- queryClient.setQueryData<HistoryQueryResponse>(- historyKeys.list.queryKey,- (old) => {- if (!old) return old;-- return {- ...old,- data: updateViewedAtAndMoveItemToFront(old.data, itemId, now),- };- }- );+ setHistoryData((old) => {+ return updateViewedAtAndMoveItemToFront(old, itemId, now);+ });}type UpsertToHistoryParams = {@@ -121,7 +128,7 @@ type UpsertToHistoryParams = {};type UpsertToHistoryContext = {- previousData: HistoryQueryResponse | undefined;+ previousData: HistoryQueryFnResult | undefined;};export function useUpsertToHistoryMutation(@@ -153,12 +160,10 @@ export function useUpsertToHistoryMutation({onMutate: async (_params) => {await queryClient.cancelQueries({- queryKey: historyKeys.list.queryKey,+ queryKey: historyQueryOptions.queryKey,});- const previousData = queryClient.getQueryData<HistoryQueryResponse>(- historyKeys.list.queryKey- );+ const previousData = getHistoryItems();// NOTE: doesn't make sense to do this if it gets invalidated on refetch anyways// optimisticUpdateViewedAt(params.itemId);@@ -167,17 +172,14 @@ export function useUpsertToHistoryMutation(},onError: (_err, _params, context) => {if (context?.previousData) {- queryClient.setQueryData(- historyKeys.list.queryKey,- context.previousData- );+ setHistoryData(context.previousData);}},onSettled: () => {// NOTE: the history refetch will invalidate the optimistic update viewed at// since only soup items have viewed at timestampqueryClient.invalidateQueries({- queryKey: historyKeys.list.queryKey,+ queryKey: historyQueryOptions.queryKey,});},},@@ -206,23 +208,14 @@ export async function postNewHistoryItem(return isOk(maybeAdded) && !!maybeAdded[1].success;}-/**- * Standalone function to remove an item from history.- */+/** Standalone function to remove an item from history. */export async function removeHistoryItem(itemType: CloudStorageItemType,itemId: string): Promise<boolean> {- queryClient.setQueryData<HistoryQueryResponse>(- historyKeys.list.queryKey,- (old) => {- if (!old) return old;- return {- ...old,- data: old.data.filter((item) => item.id !== itemId),- };- }- );+ setHistoryData((old) => {+ return old.filter((item) => item.id !== itemId);+ });const maybeRemoved = await storageServiceClient.removeItemFromUserHistory({itemId,@@ -234,36 +227,17 @@ export async function removeHistoryItem(return isOk(maybeRemoved) && !!maybeRemoved[1].success;}-/**- * Hook to get the updated name of a DSS item from history.- * Returns the raw name without transform (preserves empty strings).- */-export function useUpdatedDssItemName(itemId: string | Accessor<string>) {- const instructionsMdIdQuery = useInstructionsMdIdQuery();-- const rawHistoryQuery = useQuery(() => {- const instructionsId = instructionsMdIdQuery.isSuccess- ? instructionsMdIdQuery.data- : null;-- return {- ...historyQueryOptions(),- select: (data: HistoryQueryResponse): HistoryItem[] => {- return transformHistoryResponse(data, instructionsId, true);- },- };- });+/** Hook to get the updated raw name (no transform) of a HistoryItem */+export function useHistoryItemRawName(itemId: string) {+ const historyQuery = useHistoryQuery();return () => {- if (rawHistoryQuery.isLoading) return undefined;- const history = rawHistoryQuery.data;+ if (historyQuery.isLoading) return undefined;+ const history = historyQuery.data;if (!history) return undefined;- const itemIdValue = typeof itemId === 'function' ? itemId() : itemId;- if (!itemIdValue) return undefined;-- const item = history.find((item) => item.id === itemIdValue);- return item?.name;+ const item = history.find((item) => item.id === itemId);+ return item?.rawName;};}@@ -271,12 +245,10 @@ export function useUpdatedDssItemName(itemId: string | Accessor<string>) {* Get history items from cache.* For use in standalone functions outside component context.*/-export function getHistoryItems(): HistoryItem[] {- const data = queryClient.getQueryData<HistoryQueryResponse>(- historyKeys.list.queryKey- );+export function getHistoryItems() {+ const data = queryClient.getQueryData(historyQueryOptions.queryKey);if (!data) return [];- return transformHistoryResponse(data, null);+ return data;}/**@@ -284,10 +256,8 @@ export function getHistoryItems(): HistoryItem[] {* Recursively fetches project content and adds all items to history.*/export async function insertProjectIntoHistory(projectId: string) {- const prevData =- queryClient.getQueryData<HistoryQueryResponse>(historyKeys.list.queryKey)- ?.data ?? [];- const newData: HistoryQueryResponse['data'] = [];+ const prevData = getHistoryItems();+ const newData: HistoryItem[] = [];const ids = [projectId];storageServiceClient.upsertItemToUserHistory({@@ -318,16 +288,9 @@ export async function insertProjectIntoHistory(projectId: string) {}}- queryClient.setQueryData<HistoryQueryResponse>(- historyKeys.list.queryKey,- (old) => {- if (!old) return old;- return {- ...old,- data: [...old.data, ...newData],- };- }- );+ setHistoryData((old) => {+ return [...old, ...newData];+ });const upsertResults = newData.filter((item) => !prevData.some(({ id }) => id === item.id))diff --git a/js/app/packages/queries/history/tests/history.test.tsx b/js/app/packages/queries/history/tests/history.test.tsxindex f034c5e6c4..bb0c06096e 100644--- a/js/app/packages/queries/history/tests/history.test.tsx+++ b/js/app/packages/queries/history/tests/history.test.tsx@@ -1,15 +1,14 @@import { describe, expect, it, vi } from 'vitest';--vi.mock('@core/constant/allBlocks', () => ({- itemToSafeName: (item: { name?: string }) => item.name ?? 'Untitled',-}));-import type { Item } from '@service-storage/generated/schemas/item';import {transformHistoryResponse,updateViewedAtAndMoveItemToFront,} from '../transforms';+vi.mock('@core/constant/allBlocks', () => ({+ itemToSafeName: (item: { name?: string }) => item.name || 'Untitled',+}));+function createItem(overrides: Partial<Item> = {}): Item {return {id: `item-${Math.random().toString(36).slice(2)}`,@@ -23,21 +22,33 @@ function createItem(overrides: Partial<Item> = {}): Item {}describe('history transforms', () => {- it('transforms response and filters instructions.md', () => {+ it('transforms response', () => {const data = {data: [createItem({ id: 'doc-1', name: 'My Doc' }),- createItem({ id: 'instructions-md', name: 'Instructions' }),createItem({ id: 'doc-2', name: 'Other Doc' }),],};- const result = transformHistoryResponse(data, 'instructions-md');+ const result = transformHistoryResponse(data);expect(result.map((i) => i.id)).toEqual(['doc-1', 'doc-2']);expect(result[0].name).toBe('My Doc');});+ it('keeps raw name for md documents', () => {+ const data = {+ data: [createItem({ id: 'doc-1', name: '', fileType: 'md' })],+ };++ console.log('data', data);++ const result = transformHistoryResponse(data);++ expect(result[0].name).toBe('Untitled');+ expect(result[0].rawName).toBe('');+ });+describe('updateViewedAtAndMoveItemToFront', () => {it('moves item to front and updates viewedAt', () => {const items: Item[] = [diff --git a/js/app/packages/queries/history/transforms.ts b/js/app/packages/queries/history/transforms.tsindex 384caa1599..9c11a596d4 100644--- a/js/app/packages/queries/history/transforms.ts+++ b/js/app/packages/queries/history/transforms.ts@@ -1,43 +1,15 @@import { itemToSafeName } from '@core/constant/allBlocks';-import type { Item } from '@service-storage/generated/schemas/item';+import type { HistoryItem, HistoryQueryResponse } from './types';-type BaseHistoryItem = Pick<- Item,- 'id' | 'name' | 'createdAt' | 'updatedAt' | 'deletedAt'-> & {- viewedAt?: number;-};--export type DocumentHistoryItem = BaseHistoryItem &- Pick<Extract<Item, { type: 'document' }>, 'type' | 'fileType' | 'subType'>;--export type ChatHistoryItem = BaseHistoryItem &- Pick<Extract<Item, { type: 'chat' }>, 'type' | 'isPersistent'>;--export type ProjectHistoryItem = BaseHistoryItem &- Pick<Extract<Item, { type: 'project' }>, 'type'>;--/** Minimal history item types containing only the properties actually used */-export type HistoryItem =- | DocumentHistoryItem- | ChatHistoryItem- | ProjectHistoryItem;--export type HistoryQueryResponse = {- data: HistoryItem[];-};--export function transformHistoryItem(- item: HistoryItem,- rawName?: boolean-): HistoryItem {+export function transformHistoryItem(item: HistoryItem): HistoryItem {const base = {id: item.id,- name: rawName ? item.name : itemToSafeName(item),+ name: itemToSafeName(item),createdAt: item.createdAt,updatedAt: item.updatedAt,deletedAt: item.deletedAt,viewedAt: item.viewedAt,+ rawName: item.name,};switch (item.type) {@@ -64,22 +36,10 @@ export function transformHistoryItem(}}-export function filterInstructionsMd(- items: HistoryItem[],- instructionsId: string | null | undefined-): HistoryItem[] {- if (!instructionsId) return items;- return items.filter((item) => item.id !== instructionsId);-}-export function transformHistoryResponse(- data: HistoryQueryResponse,- instructionsId: string | null | undefined,- rawName?: boolean+ response: HistoryQueryResponse): HistoryItem[] {- return filterInstructionsMd(data.data, instructionsId).map((item) =>- transformHistoryItem(item, rawName)- );+ return response.data.map(transformHistoryItem);}/**diff --git a/js/app/packages/queries/history/types.ts b/js/app/packages/queries/history/types.tsnew file mode 100644index 0000000000..8e8093fc33--- /dev/null+++ b/js/app/packages/queries/history/types.ts@@ -0,0 +1,31 @@+import type { Item } from '@service-storage/generated/schemas/item';++type BaseHistoryItem = Pick<+ Item,+ 'id' | 'name' | 'createdAt' | 'updatedAt' | 'deletedAt'+> & {+ // NOTE: the history endpoint does not return this field so this+ // is a placeholder for now+ viewedAt?: number;+ // TODO: item name without safe name transform+ rawName?: string;+};++export type DocumentHistoryItem = BaseHistoryItem &+ Pick<Extract<Item, { type: 'document' }>, 'type' | 'fileType' | 'subType'>;++export type ChatHistoryItem = BaseHistoryItem &+ Pick<Extract<Item, { type: 'chat' }>, 'type' | 'isPersistent'>;++export type ProjectHistoryItem = BaseHistoryItem &+ Pick<Extract<Item, { type: 'project' }>, 'type'>;++/** Minimal history item types containing only the properties actually used */+export type HistoryItem =+ | DocumentHistoryItem+ | ChatHistoryItem+ | ProjectHistoryItem;++export type HistoryQueryResponse = {+ data: HistoryItem[];+};