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.

feat: command k viewed at (#2313)

gbirmana85cf8a1e7eb
diff --git a/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx
index 0ff9fe5052..e0616bb1e7 100644
--- a/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx
+++ b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx
@@ -10,6 +10,7 @@ import {
import type { ApiChannelWithLatest } from '@service-comms/generated/models';
import type { ChannelEntity } from '@entity';
import { useHistoryQuery, type HistoryItem } from '@queries/history/history';
+import { useRecentlyViewedSoupQuery } from '@queries/soup/recently-viewed';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import { queryReadyGate } from '@queries/gate';
import type { DateValue } from '@core/util/date';
@@ -48,7 +49,6 @@ function historyItemToEntity(item: HistoryItem): QuickAccessEntity {
name: item.name,
createdAt: item.createdAt,
updatedAt: item.updatedAt,
- viewedAt: item.viewedAt,
ownerId: item.ownerId,
};
@@ -139,17 +139,17 @@ function toTimestamp(value: DateValue | null | undefined): number {
return toDate(value).getTime();
}
-/** dumb history item hash */
-function getHistoryItemVersion(item: HistoryItem): string {
- return `${item.name}|${item.updatedAt}|${item.viewedAt}|${item.deletedAt}`;
+function getHistoryItemVersion(item: HistoryItem, viewedAt?: string): string {
+ return `${item.name}|${item.updatedAt}|${viewedAt}|${item.deletedAt}`;
}
-/** dumb channel hash */
-function getChannelVersion(channel: ApiChannelWithLatest): string {
- return `${channel.name}|${channel.updated_at}|${channel.viewed_at}`;
+function getChannelVersion(
+ channel: ApiChannelWithLatest,
+ viewedAt?: string
+): string {
+ return `${channel.name}|${channel.updated_at}|${viewedAt}`;
}
-/** dumb use hash */
function getUserVersion(user: IUser): string {
return `${user.name}|${user.email}|${user.lastInteraction}`;
}
@@ -227,11 +227,24 @@ export const [QuickAccessProvider, useQuickAccess] =
// stable cache for transformed items
const itemCache = new Map<string, CacheEntry>();
- /**
- * Process all data sources and update the cache incrementally.
- * Returns the sorted index entries (lightweight id+timestamp arrays).
- */
+ const recentlyViewedQuery = useRecentlyViewedSoupQuery();
+
+ const soupViewedAtMap = createLazyMemo(() => {
+ const map = new Map<string, string>();
+ const data = recentlyViewedQuery.data;
+ if (!data) return map;
+ for (const item of data.items) {
+ const id =
+ item.tag === 'channel' ? item.data.channel.id : item.data.id;
+ const viewedAt =
+ item.tag === 'channel' ? item.data.viewed_at : item.data.viewedAt;
+ if (viewedAt) map.set(id, viewedAt);
+ }
+ return map;
+ });
+
const processedData = createLazyMemo(() => {
+ const viewedAtMap = soupViewedAtMap();
const seenIds = new Set<string>();
const allEntries: IndexEntry[] = [];
@@ -250,10 +263,11 @@ export const [QuickAccessProvider, useQuickAccess] =
if (hidden.has(item.id)) continue;
seenIds.add(item.id);
- const version = getHistoryItemVersion(item);
+ const viewedAt = viewedAtMap.get(item.id);
+
+ const version = getHistoryItemVersion(item, viewedAt);
const cached = itemCache.get(item.id);
- // Only transform if not cached or version changed
if (!cached || cached.version !== version) {
const reason = !cached
? 'new'
@@ -265,8 +279,11 @@ export const [QuickAccessProvider, useQuickAccess] =
reason,
});
const bucket = getBucketForHistoryItem(item);
- const entity = historyItemToEntity(item);
- const viewedAtMs = toTimestamp(item.viewedAt);
+ const entity = {
+ ...historyItemToEntity(item),
+ viewedAt,
+ };
+ const viewedAtMs = toTimestamp(viewedAt);
const updatedAtMs = toTimestamp(item.updatedAt);
const sortTimestamp = viewedAtMs || updatedAtMs;
@@ -277,7 +294,7 @@ export const [QuickAccessProvider, useQuickAccess] =
searchText: getEntitySearchText(entity),
sortTimestamp,
timestamps: {
- viewedAt: item.viewedAt,
+ viewedAt,
updatedAt: item.updatedAt,
createdAt: item.createdAt,
},
@@ -300,7 +317,10 @@ export const [QuickAccessProvider, useQuickAccess] =
for (const channel of channelData) {
seenIds.add(channel.id);
- const version = getChannelVersion(channel);
+ const viewedAt =
+ viewedAtMap.get(channel.id) ?? channel.viewed_at ?? undefined;
+
+ const version = getChannelVersion(channel, viewedAt);
const cached = itemCache.get(channel.id);
if (!cached || cached.version !== version) {
@@ -315,8 +335,13 @@ export const [QuickAccessProvider, useQuickAccess] =
});
const isDm = channel.channel_type === 'direct_message';
const bucket: Bucket = isDm ? 'dm' : 'channel';
- const entity = channelToEntity(channel);
- const sortTimestamp = toTimestamp(channel.updated_at);
+ const entity = {
+ ...channelToEntity(channel),
+ viewedAt,
+ };
+ const viewedAtMs = toTimestamp(viewedAt);
+ const updatedAtMs = toTimestamp(channel.updated_at);
+ const sortTimestamp = viewedAtMs || updatedAtMs;
const quickAccessItem: QuickAccessItem = {
kind: 'entity',
@@ -325,7 +350,7 @@ export const [QuickAccessProvider, useQuickAccess] =
searchText: channel.name ?? '',
sortTimestamp,
timestamps: {
- viewedAt: channel.viewed_at,
+ viewedAt,
updatedAt: channel.updated_at,
createdAt: channel.created_at,
},
diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.ts
index 46da6271eb..05e761440a 100644
--- a/js/app/packages/queries/history/history.ts
+++ b/js/app/packages/queries/history/history.ts
@@ -12,11 +12,7 @@ import {
import type { Accessor, Setter } from 'solid-js';
import { queryClient } from '../client';
import { historyKeys } from './keys';
-import {
- transformHistoryItem,
- transformHistoryResponse,
- updateViewedAtAndMoveItemToFront,
-} from './transforms';
+import { transformHistoryItem, transformHistoryResponse } from './transforms';
import type { HistoryItem } from './types';
// re-export history item type from this file
@@ -91,16 +87,6 @@ export function refetchHistory() {
});
}
-// @ts-ignore
-// biome-ignore lint/correctness/noUnusedVariables: we may use this eventually
-function optimisticUpdateViewedAt(itemId: string) {
- const now = new Date();
-
- setHistoryData((old) => {
- return updateViewedAtAndMoveItemToFront(old, itemId, now);
- });
-}
-
type UpsertToHistoryParams = {
itemId: string;
itemType: CloudStorageItemType;
@@ -137,16 +123,13 @@ export function useUpsertToHistoryMutation(
UpsertToHistoryContext
>(
{
- onMutate: async (_params) => {
+ onMutate: async () => {
await queryClient.cancelQueries({
queryKey: historyQueryOptions.queryKey,
});
const previousData = getHistoryItems();
- // NOTE: doesn't make sense to do this if it gets invalidated on refetch anyways
- // optimisticUpdateViewedAt(params.itemId);
-
return { previousData };
},
onError: (_err, _params, context) => {
@@ -155,8 +138,6 @@ export function useUpsertToHistoryMutation(
}
},
onSettled: () => {
- // NOTE: the history refetch will invalidate the optimistic update viewed at
- // since only soup items have viewed at timestamp
queryClient.invalidateQueries({
queryKey: historyQueryOptions.queryKey,
});
diff --git a/js/app/packages/queries/history/tests/history.test.tsx b/js/app/packages/queries/history/tests/history.test.tsx
index 50cfdab650..20eee46a23 100644
--- a/js/app/packages/queries/history/tests/history.test.tsx
+++ b/js/app/packages/queries/history/tests/history.test.tsx
@@ -1,10 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import type { Item } from '@service-storage/generated/schemas/item';
-import {
- transformHistoryItem,
- transformHistoryResponse,
- updateViewedAtAndMoveItemToFront,
-} from '../transforms';
+import { transformHistoryResponse } from '../transforms';
vi.mock('@core/constant/allBlocks', () => ({
itemToSafeName: (item: { name?: string }) => item.name || 'Untitled',
@@ -22,10 +18,6 @@ function createItem(overrides: Partial<Item> = {}): Item {
} as Item;
}
-function createHistoryItem(overrides: Partial<Item> = {}) {
- return transformHistoryItem(createItem(overrides));
-}
-
describe('history transforms', () => {
it('transforms response', () => {
const data = {
@@ -53,73 +45,4 @@ describe('history transforms', () => {
expect(result[0].name).toBe('Untitled');
expect(result[0].rawName).toBe('');
});
-
- describe('updateViewedAtAndMoveItemToFront', () => {
- it('moves item to front and updates viewedAt', () => {
- const items = [
- createHistoryItem({ id: 'item-1' }),
- createHistoryItem({ id: 'item-2' }),
- createHistoryItem({ id: 'item-3' }),
- ];
- const timestamp = new Date();
-
- const result = updateViewedAtAndMoveItemToFront(
- items,
- 'item-2',
- timestamp
- );
-
- 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 = [
- createHistoryItem({ id: 'item-1' }),
- createHistoryItem({ id: 'item-2' }),
- ];
-
- const result = updateViewedAtAndMoveItemToFront(
- items,
- 'nonexistent',
- new Date()
- );
-
- expect(result).toBe(items);
- expect(result.length).toBe(2);
- });
-
- it('keeps item at front if already first', () => {
- const items = [
- createHistoryItem({ id: 'item-1' }),
- createHistoryItem({ id: 'item-2' }),
- ];
- const timestamp = new Date();
-
- 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 = [
- createHistoryItem({ id: 'item-1' }),
- createHistoryItem({ id: 'item-2' }),
- ];
- const originalLength = items.length;
-
- updateViewedAtAndMoveItemToFront(items, 'item-2', new Date());
-
- 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 1a61e81892..392184a4a2 100644
--- a/js/app/packages/queries/history/transforms.ts
+++ b/js/app/packages/queries/history/transforms.ts
@@ -1,5 +1,4 @@
import { itemToSafeName } from '@core/constant/allBlocks';
-import type { DateValue } from '@core/util/date';
import type { Item } from '@service-storage/generated/schemas/item';
import type { HistoryItem, HistoryQueryResponse } from './types';
@@ -45,28 +44,3 @@ export function transformHistoryResponse(
): HistoryItem[] {
return response.data.map(transformHistoryItem);
}
-
-/**
- * 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: HistoryItem[],
- itemId: string,
- timestamp: DateValue
-): HistoryItem[] {
- 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: HistoryItem = { ...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/queries/history/types.ts b/js/app/packages/queries/history/types.ts
index 8ba9b505a5..979900e785 100644
--- a/js/app/packages/queries/history/types.ts
+++ b/js/app/packages/queries/history/types.ts
@@ -5,9 +5,6 @@ type BaseHistoryItem = Pick<Item, 'id' | 'name'> & {
createdAt?: DateValue | null;
updatedAt?: DateValue | null;
deletedAt?: DateValue | null;
- // NOTE: the history endpoint does not return this field so this
- // is a placeholder for now
- viewedAt?: DateValue;
// TODO: item name without safe name transform
rawName?: string;
// Normalized owner field: BasicDocument.owner, Chat.userId, Project.userId
diff --git a/js/app/packages/queries/soup/recently-viewed.ts b/js/app/packages/queries/soup/recently-viewed.ts
new file mode 100644
index 0000000000..2fbcdd7193
--- /dev/null
+++ b/js/app/packages/queries/soup/recently-viewed.ts
@@ -0,0 +1,39 @@
+import { throwOnErr } from '@core/util/maybeResult';
+import { storageServiceClient } from '@service-storage/client';
+import { useQuery } from '@tanstack/solid-query';
+import { soupKeys } from './keys';
+import type { SoupItemsQueryArgs } from './items';
+
+const RECENTLY_VIEWED_LIMIT = 50;
+const RECENTLY_VIEWED_STALE_TIME = 5 * 60 * 1000; // 5 minutes
+const RECENTLY_VIEWED_GC_TIME = 10 * 60 * 1000; // 10 minutes
+
+const recentlyViewedArgs: SoupItemsQueryArgs = {
+ params: { sort_method: 'viewed_at', limit: RECENTLY_VIEWED_LIMIT },
+ body: {},
+};
+
+export const recentlyViewedQueryKey =
+ soupKeys.items(recentlyViewedArgs).queryKey;
+
+export function useRecentlyViewedSoupQuery() {
+ return useQuery(() => ({
+ queryKey: recentlyViewedQueryKey,
+ queryFn: async () => {
+ return throwOnErr(
+ async () =>
+ await storageServiceClient.getSoupItems({
+ params: {},
+ body: {
+ ...recentlyViewedArgs.body,
+ ...recentlyViewedArgs.params,
+ },
+ })
+ );
+ },
+ staleTime: RECENTLY_VIEWED_STALE_TIME,
+ gcTime: RECENTLY_VIEWED_GC_TIME,
+ placeholderData: (prev: any) => prev,
+ meta: { normalize: true },
+ }));
+}