Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: shared documents get added to history on open (#1306)

gbirmanec720975a4bd
diff --git a/js/app/packages/block-channel/definition.ts b/js/app/packages/block-channel/definition.ts
index a0812de7f0..2a54b7f2e4 100644
--- a/js/app/packages/block-channel/definition.ts
+++ b/js/app/packages/block-channel/definition.ts
@@ -4,7 +4,6 @@ import {
fetchAndCacheChannel,
optimisticUpdateChannelViewedAt,
} from '@queries/channel/channel';
-import { optimisticUpdateViewedAt } from '@queries/history/history';
import ChannelBlock from './component/Block';
export const definition = defineBlock({
@@ -30,7 +29,6 @@ export const definition = defineBlock({
const [, channelData] = channel;
- optimisticUpdateViewedAt(source.id);
optimisticUpdateChannelViewedAt(source.id);
return ok({
diff --git a/js/app/packages/block-chat/definition.ts b/js/app/packages/block-chat/definition.ts
index 47a04068e1..1caa2d42bd 100644
--- a/js/app/packages/block-chat/definition.ts
+++ b/js/app/packages/block-chat/definition.ts
@@ -1,10 +1,8 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
import { isErr, ok } from '@core/util/maybeResult';
-import { optimisticUpdateViewedAt } from '@queries/history/history';
import { cognitionApiServiceClient } from '@service-cognition/client';
import { AllModels } from '@service-cognition/generated/schemas';
import type { ChatAttachmentWithName } from '@service-cognition/generated/schemas/chatAttachmentWithName';
-import { storageServiceClient } from '@service-storage/client';
import type { DocumentMetadata } from '@service-storage/generated/schemas/documentMetadata';
import BlockChat from './component/Block';
@@ -33,14 +31,6 @@ export const definition = defineBlock({
});
}
- optimisticUpdateViewedAt(source.id);
-
- storageServiceClient
- .trackOpenedChat({
- chatId: source.id,
- })
- .catch((err) => console.error(err));
-
return ok({
...chat,
allModels: AllModels, // TODO maybe limit people with something more swag based on acoun
diff --git a/js/app/packages/core/internal/BlockLoader.tsx b/js/app/packages/core/internal/BlockLoader.tsx
index 6e3db441e2..e4b115824d 100644
--- a/js/app/packages/core/internal/BlockLoader.tsx
+++ b/js/app/packages/core/internal/BlockLoader.tsx
@@ -9,7 +9,6 @@ import {
createBlockSignal,
type FileOrTextLike,
type LoadFunction,
- NonDocumentBlockTypes,
useIsNestedBlock,
} from '../block';
import {
@@ -26,6 +25,7 @@ import {
} from '../signal/load';
import type { Source, SourcePreload } from '../source';
import { err, isErr, type ObjectLike, ok } from '../util/maybeResult';
+import { useQueryClient } from '@queries/client';
export const blockDataSignal = createBlockSignal<unknown>();
export const blockLiveTrackingEnabledSignal = createBlockSignal<boolean>();
@@ -134,12 +134,10 @@ Check that the load function does not return a preload source when the intent is
});
if (!isNested && data) {
- // NOTE: refetch history causing full page reload so I am disabling it
- if (!NonDocumentBlockTypes.includes(data.__block)) {
- import('./trackAndReload').then(({ trackOpenAndRefetchHistory }) => {
- trackOpenAndRefetchHistory(props.id, false);
- });
- }
+ // we need to pass in a client accessor since the mutation is dynamically imported outside a query context provider
+ import('./trackBlockOpened').then(({ track }) => {
+ track(props.id, data.__block, useQueryClient);
+ });
// for analytics
const blockOpenEvent = blockOpenEvents[data.__block];
diff --git a/js/app/packages/core/internal/trackAndReload.tsx b/js/app/packages/core/internal/trackAndReload.tsx
deleted file mode 100644
index e4f9a1b988..0000000000
--- a/js/app/packages/core/internal/trackAndReload.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import {
- optimisticUpdateViewedAt,
- refetchHistory,
-} from '@queries/history/history';
-import { storageServiceClient } from '@service-storage/client';
-
-/**
- * Track the opening of a document and refetch the history
- * For the sidebar
- * @param documentId - The id of the document to track
- * @param refetch - Whether to refetch the history
- */
-export function trackOpenAndRefetchHistory(documentId: string, refetch = true) {
- optimisticUpdateViewedAt(documentId);
-
- storageServiceClient
- .trackOpenedDocument({
- documentId,
- })
- .then(() => {
- if (refetch) {
- refetchHistory();
- }
- })
- .catch((err) => console.error(err));
-}
diff --git a/js/app/packages/core/internal/trackBlockOpened.ts b/js/app/packages/core/internal/trackBlockOpened.ts
new file mode 100644
index 0000000000..d2c27bae5a
--- /dev/null
+++ b/js/app/packages/core/internal/trackBlockOpened.ts
@@ -0,0 +1,25 @@
+import type { BlockName } from '../block';
+import { useUpsertToHistoryMutation } from '@queries/history/history';
+import {
+ blockNameToItemType,
+ isCloudStorageItem,
+} from '@service-storage/client';
+import type { QueryClient } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+
+/**
+ * Tracks opening of a block and updates history accordingly.
+ * We have this in a separate file to prevent cyclic dependencies.
+ */
+export function track(
+ itemId: string,
+ blockName: BlockName,
+ client: Accessor<QueryClient>
+) {
+ const itemType = blockNameToItemType(blockName);
+
+ if (!isCloudStorageItem(itemType)) return;
+
+ const upsertToHistoryMutation = useUpsertToHistoryMutation(undefined, client);
+ upsertToHistoryMutation.mutate({ itemId, itemType });
+}
diff --git a/js/app/packages/core/util/freshSort.ts b/js/app/packages/core/util/freshSort.ts
index 36b4f0de17..729ec2dd35 100644
--- a/js/app/packages/core/util/freshSort.ts
+++ b/js/app/packages/core/util/freshSort.ts
@@ -30,6 +30,9 @@ export interface FreshSortConfig {
boostFn?: <T extends TimestampedItem>(item: T) => number;
}
+// TODO: fix this type since [key: string]: any is too loose
+// for example, CombinedEntity in mentions menu only includes timestamp info under the data field
+// but this assumed a flattened object so fresh search isn't working
export interface TimestampedItem {
updatedAt?: number | string;
updated_at?: number | string;
diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.ts
index dc0ad3512c..664c601a6c 100644
--- a/js/app/packages/queries/history/history.ts
+++ b/js/app/packages/queries/history/history.ts
@@ -7,6 +7,7 @@ import {
type UseQueryResult,
useMutation,
useQuery,
+ type QueryClient,
} from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
@@ -15,7 +16,7 @@ import {
type HistoryItem,
type HistoryQueryResponse,
transformHistoryResponse,
- updateItemViewedAt,
+ updateViewedAtAndMoveItemToFront,
} from './transforms';
export { historyKeys } from './keys';
@@ -24,7 +25,6 @@ export {
filterInstructionsMd,
transformHistoryItem,
transformHistoryResponse,
- updateItemViewedAt,
} from './transforms';
const HISTORY_STALE_TIME = 5 * 60 * 1000;
@@ -75,7 +75,9 @@ export function refetchHistory() {
});
}
-export function optimisticUpdateViewedAt(itemId: string) {
+// @ts-ignore
+// biome-ignore lint/correctness/noUnusedVariables: we may use this eventually
+function optimisticUpdateViewedAt(itemId: string) {
const now = Date.now();
queryClient.setQueryData<HistoryQueryResponse>(
@@ -83,105 +85,14 @@ export function optimisticUpdateViewedAt(itemId: string) {
(old) => {
if (!old) return old;
- // Find the item and move it to the front with updated viewedAt
- const itemIndex = old.data.findIndex((item) => item.id === itemId);
- if (itemIndex === -1) return old;
-
- const item = old.data[itemIndex];
- const updatedItem = { ...item, viewedAt: now };
- const newData = [
- updatedItem,
- ...old.data.slice(0, itemIndex),
- ...old.data.slice(itemIndex + 1),
- ];
-
return {
...old,
- data: newData,
+ data: updateViewedAtAndMoveItemToFront(old.data, itemId, now),
};
}
);
}
-type TrackViewedParams = {
- itemId: string;
- itemType: CloudStorageItemType;
-};
-
-type TrackViewedContext = {
- previousData: HistoryQueryResponse | undefined;
-};
-
-async function trackViewedOnServer(params: TrackViewedParams): Promise<void> {
- if (params.itemType === 'document') {
- await throwOnErr(
- async () =>
- await storageServiceClient.trackOpenedDocument({
- documentId: params.itemId,
- })
- );
- } else if (params.itemType === 'chat') {
- await throwOnErr(
- async () =>
- await storageServiceClient.trackOpenedChat({
- chatId: params.itemId,
- })
- );
- } else {
- await throwOnErr(
- async () =>
- await storageServiceClient.upsertItemToUserHistory({
- itemId: params.itemId,
- itemType: params.itemType,
- })
- );
- }
-}
-
-export function useTrackViewedMutation(
- callbacks?: MutationCallbacks<
- void,
- Error,
- TrackViewedParams,
- TrackViewedContext
- >
-) {
- return useMutation(() => ({
- mutationFn: trackViewedOnServer,
- ...withCallbacks<void, Error, TrackViewedParams, TrackViewedContext>(
- {
- onMutate: async (params) => {
- await queryClient.cancelQueries({
- queryKey: historyKeys.list.queryKey,
- });
-
- const previousData = queryClient.getQueryData<HistoryQueryResponse>(
- historyKeys.list.queryKey
- );
-
- optimisticUpdateViewedAt(params.itemId);
-
- return { previousData };
- },
- onError: (_err, _params, context) => {
- if (context?.previousData) {
- queryClient.setQueryData(
- historyKeys.list.queryKey,
- context.previousData
- );
- }
- },
- onSettled: () => {
- queryClient.invalidateQueries({
- queryKey: historyKeys.list.queryKey,
- });
- },
- },
- callbacks
- ),
- }));
-}
-
type UpsertToHistoryParams = {
itemId: string;
itemType: CloudStorageItemType;
@@ -197,77 +108,62 @@ export function useUpsertToHistoryMutation(
Error,
UpsertToHistoryParams,
UpsertToHistoryContext
- >
+ >,
+ client?: Accessor<QueryClient>
) {
- return useMutation(() => ({
- mutationFn: async (params: UpsertToHistoryParams) => {
- await throwOnErr(
- async () =>
- await storageServiceClient.upsertItemToUserHistory({
- itemId: params.itemId,
- itemType: params.itemType,
- })
- );
- },
- ...withCallbacks<
- void,
- Error,
- UpsertToHistoryParams,
- UpsertToHistoryContext
- >(
- {
- onMutate: async (params) => {
- await queryClient.cancelQueries({
- queryKey: historyKeys.list.queryKey,
- });
-
- const previousData = queryClient.getQueryData<HistoryQueryResponse>(
- historyKeys.list.queryKey
- );
-
- queryClient.setQueryData<HistoryQueryResponse>(
- historyKeys.list.queryKey,
- (old) => {
- if (!old) return old;
- const existsIndex = old.data.findIndex(
- (item) => item.id === params.itemId
+ return useMutation(
+ () => ({
+ mutationFn: async (params: UpsertToHistoryParams) => {
+ await throwOnErr(
+ async () =>
+ await storageServiceClient.upsertItemToUserHistory({
+ itemId: params.itemId,
+ itemType: params.itemType,
+ })
+ );
+ },
+ ...withCallbacks<
+ void,
+ Error,
+ UpsertToHistoryParams,
+ UpsertToHistoryContext
+ >(
+ {
+ onMutate: async (_params) => {
+ await queryClient.cancelQueries({
+ queryKey: historyKeys.list.queryKey,
+ });
+
+ const previousData = queryClient.getQueryData<HistoryQueryResponse>(
+ historyKeys.list.queryKey
+ );
+
+ // NOTE: doesn't make sense to do this if it gets invalidated on refetch anyways
+ // optimisticUpdateViewedAt(params.itemId);
+
+ return { previousData };
+ },
+ onError: (_err, _params, context) => {
+ if (context?.previousData) {
+ queryClient.setQueryData(
+ historyKeys.list.queryKey,
+ context.previousData
);
- if (existsIndex >= 0) {
- const updatedData = updateItemViewedAt(
- old.data,
- params.itemId,
- Date.now()
- );
- const [updatedItem] = updatedData.splice(existsIndex, 1);
- return {
- ...old,
- data: [updatedItem, ...updatedData],
- };
- } else {
- return old;
- }
}
- );
-
- return { previousData };
- },
- onError: (_err, _params, context) => {
- if (context?.previousData) {
- queryClient.setQueryData(
- historyKeys.list.queryKey,
- context.previousData
- );
- }
- },
- onSettled: () => {
- queryClient.invalidateQueries({
- queryKey: historyKeys.list.queryKey,
- });
+ },
+ onSettled: () => {
+ // NOTE: the history refetch will invalidate the optimistic update viewed at
+ // since only soup items have viewed at timestamp
+ queryClient.invalidateQueries({
+ queryKey: historyKeys.list.queryKey,
+ });
+ },
},
- },
- callbacks
- ),
- }));
+ callbacks
+ ),
+ }),
+ client
+ );
}
/**
diff --git a/js/app/packages/queries/history/tests/history.test.tsx b/js/app/packages/queries/history/tests/history.test.tsx
index 707f043f00..f034c5e6c4 100644
--- a/js/app/packages/queries/history/tests/history.test.tsx
+++ b/js/app/packages/queries/history/tests/history.test.tsx
@@ -5,7 +5,10 @@ vi.mock('@core/constant/allBlocks', () => ({
}));
import type { Item } from '@service-storage/generated/schemas/item';
-import { transformHistoryResponse, updateItemViewedAt } from '../transforms';
+import {
+ transformHistoryResponse,
+ updateViewedAtAndMoveItemToFront,
+} from '../transforms';
function createItem(overrides: Partial<Item> = {}): Item {
return {
@@ -35,12 +38,72 @@ describe('history transforms', () => {
expect(result[0].name).toBe('My Doc');
});
- it('updateItemViewedAt sets timestamp for optimistic updates', () => {
- const items = [createItem({ id: 'doc-1' }), createItem({ id: 'doc-2' })];
+ describe('updateViewedAtAndMoveItemToFront', () => {
+ it('moves item to front and updates viewedAt', () => {
+ const items: Item[] = [
+ createItem({ id: 'item-1' }),
+ createItem({ id: 'item-2' }),
+ createItem({ id: 'item-3' }),
+ ];
+ const timestamp = Date.now();
- const result = updateItemViewedAt(items, 'doc-1', 1704067200000);
+ const result = updateViewedAtAndMoveItemToFront(
+ items,
+ 'item-2',
+ timestamp
+ );
- expect(result[0]).toHaveProperty('viewedAt', 1704067200000);
- expect(items[0]).not.toHaveProperty('viewedAt'); // doesn't mutate
+ expect(result[0].id).toBe('item-2');
+ expect(result[0].viewedAt).toBe(timestamp);
+ expect(result[1].id).toBe('item-1');
+ expect(result[2].id).toBe('item-3');
+ });
+
+ it('returns original array if item not found', () => {
+ const items: Item[] = [
+ createItem({ id: 'item-1' }),
+ createItem({ id: 'item-2' }),
+ ];
+
+ const result = updateViewedAtAndMoveItemToFront(
+ items,
+ 'nonexistent',
+ Date.now()
+ );
+
+ expect(result).toBe(items);
+ expect(result.length).toBe(2);
+ });
+
+ it('keeps item at front if already first', () => {
+ const items: Item[] = [
+ createItem({ id: 'item-1' }),
+ createItem({ id: 'item-2' }),
+ ];
+ const timestamp = Date.now();
+
+ const result = updateViewedAtAndMoveItemToFront(
+ items,
+ 'item-1',
+ timestamp
+ );
+
+ expect(result[0].id).toBe('item-1');
+ expect(result[0].viewedAt).toBe(timestamp);
+ expect(result[1].id).toBe('item-2');
+ });
+
+ it('does not mutate original array', () => {
+ const items: Item[] = [
+ createItem({ id: 'item-1' }),
+ createItem({ id: 'item-2' }),
+ ];
+ const originalLength = items.length;
+
+ updateViewedAtAndMoveItemToFront(items, 'item-2', Date.now());
+
+ expect(items.length).toBe(originalLength);
+ expect(items[0].id).toBe('item-1');
+ });
});
});
diff --git a/js/app/packages/queries/history/transforms.ts b/js/app/packages/queries/history/transforms.ts
index 65a175eb03..339cb4b69c 100644
--- a/js/app/packages/queries/history/transforms.ts
+++ b/js/app/packages/queries/history/transforms.ts
@@ -37,12 +37,27 @@ export function transformHistoryResponse(
);
}
-export function updateItemViewedAt(
- items: Item[],
+/**
+ * Pure function: Updates an item's viewedAt timestamp and moves it to the front.
+ * Returns a new array without mutating the input.
+ */
+export function updateViewedAtAndMoveItemToFront(
+ items: ItemWithViewedAt[],
itemId: string,
timestamp: number
-): Item[] {
- return items.map((item) =>
- item.id === itemId ? { ...item, viewedAt: timestamp } : item
- );
+): ItemWithViewedAt[] {
+ const itemIndex = items.findIndex((item) => item.id === itemId);
+
+ // Item not found, return original array
+ if (itemIndex === -1) return items;
+
+ const item = items[itemIndex];
+ const updatedItem: ItemWithViewedAt = { ...item, viewedAt: timestamp };
+
+ // Return new array with updated item at front
+ return [
+ updatedItem,
+ ...items.slice(0, itemIndex),
+ ...items.slice(itemIndex + 1),
+ ];
}
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index be28a00ef9..39f08ffb09 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -350,27 +350,6 @@ export const storageServiceClient = {
);
},
- async trackOpenedDocument(params: { documentId: string }) {
- return mapOk(
- await dssFetch<SuccessResponse>(
- `/history/document/${params.documentId}`,
- {
- method: 'POST',
- }
- ),
- (result) => result.data
- );
- },
-
- async trackOpenedChat(params: { chatId: string }) {
- return mapOk(
- await dssFetch<SuccessResponse>(`/history/chat/${params.chatId}`, {
- method: 'POST',
- }),
- (result) => result.data
- );
- },
-
async getPins(params?: { limit?: number; offset?: number }) {
return mapOk(
await dssFetch<{ data: UserPins }>(
diff --git a/js/app/packages/service-clients/service-storage/service.ts b/js/app/packages/service-clients/service-storage/service.ts
index c1e77514cd..aef28ae8ab 100644
--- a/js/app/packages/service-clients/service-storage/service.ts
+++ b/js/app/packages/service-clients/service-storage/service.ts
@@ -356,24 +356,6 @@ export const StorageService = new Svc('Document++ Storage Service API')
access: { exclude: ['ai'] },
throws: withFetchErrors(),
})
- .fn('trackOpenedDocument', {
- description: schemas.upsertHistoryHandlerResponse.description!,
- args: {
- documentId: schemas.upsertHistoryHandlerParams.shape.item_id,
- },
- result: schemas.upsertHistoryHandlerResponse.shape.data.shape,
- modifies: true,
- throws: withFetchErrors(),
- })
- .fn('trackOpenedChat', {
- description: schemas.upsertHistoryHandlerResponse.description!,
- args: {
- chatId: schemas.upsertHistoryHandlerParams.shape.item_id,
- },
- result: schemas.upsertHistoryHandlerResponse.shape.data.shape,
- modifies: true,
- throws: withFetchErrors(),
- })
.fn('getPins', {
description: schemas.getPinsHandlerResponse.description!,
args: schemas.getRecentActivityHandlerQueryParams.shape,