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(kommand): kommand menu ordering improvements, history live updates (#816)

teo732249f2defa
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index cf70a99cc5..2738a32498 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -29,6 +29,7 @@ import {
} from '@notifications';
import { maybeHandlePlatformNotification } from '@notifications/notification-platform';
import { setUser, useObserveRouting } from '@observability';
+import { fetchAndCacheHistory } from '@queries/history/history';
import { ws as connectionGatewayWebsocket } from '@service-connection/websocket';
import { gqlServiceClient } from '@service-gql/client';
import { MetaProvider, Title } from '@solidjs/meta';
@@ -135,6 +136,10 @@ const rootPreload: RoutePreloadFunc = async (args) => {
if (PROD_MODE_ENV) {
identify(id, { email, os, hasChromeExt });
}
+
+ fetchAndCacheHistory().catch(() => {
+ // Non-blocking - command menu will still work without prefetch
+ });
}
};
diff --git a/js/app/packages/app/component/command/Konsole.tsx b/js/app/packages/app/component/command/Konsole.tsx
index 7ea4eb0279..c1976cc464 100644
--- a/js/app/packages/app/component/command/Konsole.tsx
+++ b/js/app/packages/app/component/command/Konsole.tsx
@@ -126,11 +126,23 @@ export function KommandMenuInner(props: {
});
const channelsContext = useChannelsContext();
- const freshSearch = createFreshSearch<CommandItemCard>({}, (item) => {
- return item.data.name;
+ const freshSearchConfig = createMemo(() => {
+ const query = debouncedLocalQuery();
+ const hasQuery = query && query.trim().length > 0;
+ return {
+ useViewedAt: true,
+ channelBoost: hasQuery ? 1.5 : 1.0,
+ fuzzyWeight: hasQuery ? 0.7 : 0.1,
+ timeWeight: hasQuery ? 0.3 : 0.9,
+ minFuzzyThreshold: hasQuery ? 0.1 : 0,
+ };
});
const searchItems = createMemo(() => {
+ const freshSearch = createFreshSearch<CommandItemCard>(
+ freshSearchConfig(),
+ (item) => item.data.name
+ );
return freshSearch(allItems(), debouncedLocalQuery()).map(
(result) => result.item
);
diff --git a/js/app/packages/app/component/command/KonsoleItem.tsx b/js/app/packages/app/component/command/KonsoleItem.tsx
index 5a02df2e22..502f723308 100644
--- a/js/app/packages/app/component/command/KonsoleItem.tsx
+++ b/js/app/packages/app/component/command/KonsoleItem.tsx
@@ -221,6 +221,7 @@ type CommandItemBase = {
height?: number;
// Add an optional timestamp to pass to fresh search/sort
updatedAt?: number | string;
+ viewedAt?: number | string;
};
type SimpleText = {
diff --git a/js/app/packages/app/component/command/useCommandItems.ts b/js/app/packages/app/component/command/useCommandItems.ts
index 860c1866e9..8562ce81cf 100644
--- a/js/app/packages/app/component/command/useCommandItems.ts
+++ b/js/app/packages/app/component/command/useCommandItems.ts
@@ -2,12 +2,14 @@ import { useChannelsContext } from '@core/component/ChannelsProvider';
import { getActiveCommandsFromScope } from '@core/hotkey/getCommands';
import { activeScope } from '@core/hotkey/state';
import { mapFromListsByKey } from '@core/util/compareUtils';
+import { useHistoryQuery } from '@queries/history/history';
import type { Channel } from '@service-comms/generated/models/channel';
import type { ChannelType } from '@service-comms/generated/models/channelType';
-import { useHistory } from '@service-storage/history';
import { createMemo } from 'solid-js';
import type { CommandItemCard } from './KonsoleItem';
+type ChannelWithViewedAt = Channel & { viewed_at?: number };
+
const FILTER_PERSISTENT_CHATS = false;
function channelsIntoCategories(channels: Channel[]) {
@@ -26,7 +28,7 @@ function channelsIntoCategories(channels: Channel[]) {
}
export function useCommandItems() {
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
const channelsContext = useChannelsContext();
const channels = () => channelsContext.channels();
const activeCommands = getActiveCommandsFromScope(activeScope(), {
@@ -52,7 +54,8 @@ export function useCommandItems() {
};
});
- const items: CommandItemCard[] = history()
+ const historyData = historyQuery.data ?? [];
+ const items: CommandItemCard[] = historyData
.filter((item) => {
// Remove the persistent sidebar chats. Those are all called "New Chat"
// and searching against the name is completely useless.
@@ -75,6 +78,7 @@ export function useCommandItems() {
subType: item.type === 'document' ? item.subType : undefined,
},
updatedAt: item.updatedAt,
+ viewedAt: item.viewedAt,
}));
const bins = channelsIntoCategories(channels());
const channels_: CommandItemCard[] = [
@@ -94,6 +98,7 @@ export function useCommandItems() {
: undefined,
},
updatedAt: channel.updated_at,
+ viewedAt: (channel as ChannelWithViewedAt).viewed_at,
}));
return mapFromListsByKey<CommandItemCard>(
diff --git a/js/app/packages/block-channel/definition.ts b/js/app/packages/block-channel/definition.ts
index 31259637ce..a0812de7f0 100644
--- a/js/app/packages/block-channel/definition.ts
+++ b/js/app/packages/block-channel/definition.ts
@@ -1,6 +1,10 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
import { isErr, ok } from '@core/util/maybeResult';
-import { fetchAndCacheChannel } from '@queries/channel/channel';
+import {
+ fetchAndCacheChannel,
+ optimisticUpdateChannelViewedAt,
+} from '@queries/channel/channel';
+import { optimisticUpdateViewedAt } from '@queries/history/history';
import ChannelBlock from './component/Block';
export const definition = defineBlock({
@@ -26,6 +30,9 @@ export const definition = defineBlock({
const [, channelData] = channel;
+ optimisticUpdateViewedAt(source.id);
+ optimisticUpdateChannelViewedAt(source.id);
+
return ok({
...channelData.channel,
});
diff --git a/js/app/packages/block-chat/definition.ts b/js/app/packages/block-chat/definition.ts
index 8a34069716..00b0227a08 100644
--- a/js/app/packages/block-chat/definition.ts
+++ b/js/app/packages/block-chat/definition.ts
@@ -1,5 +1,6 @@
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';
@@ -32,6 +33,8 @@ export const definition = defineBlock({
});
}
+ optimisticUpdateViewedAt(source.id);
+
storageServiceClient
.trackOpenedChat({
chatId: source.id,
diff --git a/js/app/packages/core/internal/trackAndReload.tsx b/js/app/packages/core/internal/trackAndReload.tsx
index e766e13634..e4f9a1b988 100644
--- a/js/app/packages/core/internal/trackAndReload.tsx
+++ b/js/app/packages/core/internal/trackAndReload.tsx
@@ -1,5 +1,8 @@
+import {
+ optimisticUpdateViewedAt,
+ refetchHistory,
+} from '@queries/history/history';
import { storageServiceClient } from '@service-storage/client';
-import { refetchHistory } from '@service-storage/history';
/**
* Track the opening of a document and refetch the history
@@ -8,6 +11,8 @@ import { refetchHistory } from '@service-storage/history';
* @param refetch - Whether to refetch the history
*/
export function trackOpenAndRefetchHistory(documentId: string, refetch = true) {
+ optimisticUpdateViewedAt(documentId);
+
storageServiceClient
.trackOpenedDocument({
documentId,
diff --git a/js/app/packages/core/util/freshSort.test.ts b/js/app/packages/core/util/freshSort.test.ts
new file mode 100644
index 0000000000..35cc7c3dda
--- /dev/null
+++ b/js/app/packages/core/util/freshSort.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest';
+import { createFreshSearch } from './freshSort';
+
+interface MockItem {
+ id: string;
+ name: string;
+ type: 'item' | 'channel';
+ viewedAt?: number;
+ updatedAt?: number;
+}
+
+function createSearch(opts: { useViewedAt?: boolean; channelBoost?: number }) {
+ return createFreshSearch<MockItem>(
+ {
+ useViewedAt: opts.useViewedAt,
+ channelBoost: opts.channelBoost,
+ timeWeight: 0.9,
+ fuzzyWeight: 0.1,
+ },
+ (item) => item.name
+ );
+}
+
+describe('freshSort ordering', () => {
+ it('orders by viewedAt - most recent first', () => {
+ const now = Date.now();
+ 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
+ ];
+
+ const search = createSearch({ useViewedAt: true });
+ const results = search(items, '');
+
+ expect(results.map((r) => r.item.id)).toEqual(['2', '1', '3']);
+ });
+
+ it('boosts channels above documents when searching', () => {
+ const now = Date.now();
+ const items: MockItem[] = [
+ { id: '1', name: 'Design Doc', type: 'item', viewedAt: now - 1000 },
+ {
+ id: '2',
+ name: 'Design Channel',
+ type: 'channel',
+ viewedAt: now - 5000,
+ },
+ ];
+
+ const search = createSearch({ useViewedAt: true, channelBoost: 2.0 });
+ const results = search(items, 'Design');
+
+ expect(results[0].item.type).toBe('channel');
+ });
+
+ it('mixes documents and channels by recency without boost', () => {
+ const now = Date.now();
+ 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
+ ];
+
+ const search = createSearch({ useViewedAt: true, channelBoost: 1.0 });
+ const results = search(items, '');
+
+ expect(results.map((r) => r.item.id)).toEqual(['2', '1', '3']);
+ });
+});
diff --git a/js/app/packages/core/util/freshSort.ts b/js/app/packages/core/util/freshSort.ts
index 94cdc13924..085c9ad1f8 100644
--- a/js/app/packages/core/util/freshSort.ts
+++ b/js/app/packages/core/util/freshSort.ts
@@ -18,13 +18,20 @@ export interface FreshSortConfig {
maxAgeMs?: number;
/** Minimum fuzzy score threshold (0-1). Items below this are heavily penalized. Default: 0.1 */
minFuzzyThreshold?: number;
+ /** Use viewedAt instead of updatedAt for time scoring. Default: false */
+ useViewedAt?: boolean;
+ /** Boost multiplier for channel items when query is present. Default: 1.0 (no boost) */
+ channelBoost?: number;
}
export interface TimestampedItem {
updatedAt?: number | string;
updated_at?: number | string;
+ viewedAt?: number | string;
+ viewed_at?: number | string;
lastInteraction?: number | string;
last_interaction?: number | string;
+ type?: string;
[key: string]: any;
}
@@ -44,14 +51,32 @@ const DEFAULT_CONFIG: Required<FreshSortConfig> = {
timeDecayFactor: 0.5,
maxAgeMs: 30 * 24 * 60 * 60 * 1000, // 30 days
minFuzzyThreshold: 0.1,
+ useViewedAt: false,
+ channelBoost: 1.0,
};
-function extractTimestamp(item: TimestampedItem): number {
- const timestamp =
- item.updatedAt ??
- item.updated_at ??
- item.lastInteraction ??
- item.last_interaction;
+function extractTimestamp(
+ item: TimestampedItem,
+ useViewedAt: boolean = false
+): number {
+ let timestamp: number | string | undefined;
+
+ if (useViewedAt) {
+ timestamp =
+ item.viewedAt ??
+ item.viewed_at ??
+ item.updatedAt ??
+ item.updated_at ??
+ item.lastInteraction ??
+ item.last_interaction;
+ } else {
+ timestamp =
+ item.updatedAt ??
+ item.updated_at ??
+ item.lastInteraction ??
+ item.last_interaction;
+ }
+
if (timestamp === undefined || timestamp === null) return 0;
if (typeof timestamp === 'number') {
@@ -73,6 +98,10 @@ function extractTimestamp(item: TimestampedItem): number {
return 0;
}
+function isChannelItem(item: TimestampedItem): boolean {
+ return item.type === 'channel';
+}
+
function calculateTimeScore(
timestamp: number,
config: Required<FreshSortConfig>
@@ -124,7 +153,7 @@ export function freshSort<T extends TimestampedItem>(
? 0
: normalizeFuzzyScore(result.score, maxFuzzyScore);
const timeScore = calculateTimeScore(
- extractTimestamp(result.original),
+ extractTimestamp(result.original, finalConfig.useViewedAt),
finalConfig
);
@@ -134,11 +163,16 @@ export function freshSort<T extends TimestampedItem>(
// Apply fuzzy threshold penalty
const fuzzyPenalty = fuzzyScore < finalConfig.minFuzzyThreshold ? 0.1 : 1;
+ const channelMultiplier = isChannelItem(result.original)
+ ? finalConfig.channelBoost
+ : 1.0;
+
const combinedScore =
(normalizedFuzzyWeight * fuzzyScore +
normalizedTimeWeight * timeScore +
normalizedBrevityWeight * brevityScore) *
- fuzzyPenalty;
+ fuzzyPenalty *
+ channelMultiplier;
return {
item: result.original,
diff --git a/js/app/packages/queries/channel/channel.ts b/js/app/packages/queries/channel/channel.ts
index 1fb5fa1eaa..8da726f5cb 100644
--- a/js/app/packages/queries/channel/channel.ts
+++ b/js/app/packages/queries/channel/channel.ts
@@ -5,9 +5,13 @@ import {
ok,
throwOnErr,
} from '@core/util/maybeResult';
+import { queryKeys } from '@macro-entity';
import { commsServiceClient } from '@service-comms/client';
import type { getChannelResponseError } from '@service-comms/generated/client';
-import type { GetChannelResponse } from '@service-comms/generated/models';
+import type {
+ ApiChannelWithLatest,
+ GetChannelResponse,
+} from '@service-comms/generated/models';
import {
type QueryClient,
type UseBaseQueryOptions,
@@ -22,9 +26,6 @@ type ChannelQueryOptions = UseBaseQueryOptions<
getChannelResponseError
>;
-/**
- * Shared query options for getting a channel with an ID
- */
function channelQueryOptions(channelId: string): ChannelQueryOptions {
return {
queryKey: channelKeys.withID(channelId).queryKey,
@@ -42,12 +43,6 @@ function channelQueryOptions(channelId: string): ChannelQueryOptions {
};
}
-/**
- * Imperatively fetch a channel (for use outside of components).
- * Returns cached data if fresh, otherwise fetches from server.
- * Ensures the query data will be available for the next time the query is
- * accessed if it's before the stale time period.
- */
export async function fetchAndCacheChannel(
channelId: string
): Promise<MaybeResult<string, { channel: GetChannelResponse }>> {
@@ -63,9 +58,6 @@ export async function fetchAndCacheChannel(
return ok({ channel: result[1] });
}
-/**
- * Query hook for fetching a channel
- */
export function useChannelQuery(
channelId: Accessor<string>,
options?: Accessor<Omit<ChannelQueryOptions, 'queryKey' | 'queryFn'>>,
@@ -111,3 +103,17 @@ export function invalidateChannelWithID(channelID: string) {
queryKey: channelKeys.withID(channelID).queryKey,
});
}
+
+export function optimisticUpdateChannelViewedAt(channelId: string) {
+ const now = new Date().toISOString();
+
+ queryClient.setQueryData<ApiChannelWithLatest[]>(
+ queryKeys.all.channel,
+ (old) => {
+ if (!old) return old;
+ return old.map((channel) =>
+ channel.id === channelId ? { ...channel, viewed_at: now } : channel
+ );
+ }
+ );
+}
diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.ts
new file mode 100644
index 0000000000..aeed47c84f
--- /dev/null
+++ b/js/app/packages/queries/history/history.ts
@@ -0,0 +1,166 @@
+import { throwOnErr } from '@core/util/maybeResult';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import { storageServiceClient } from '@service-storage/client';
+import type { CloudStorageItemType } from '@service-storage/generated/schemas/cloudStorageItemType';
+import { useInstructionsMdIdQuery } from '@service-storage/instructionsMd';
+import {
+ type UseQueryResult,
+ useMutation,
+ useQuery,
+} from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { historyKeys } from './keys';
+import {
+ type HistoryItem,
+ type HistoryQueryResponse,
+ transformHistoryResponse,
+ updateItemViewedAt,
+} from './transforms';
+
+export { historyKeys } from './keys';
+export type { HistoryItem, HistoryQueryResponse } from './transforms';
+export {
+ filterInstructionsMd,
+ transformHistoryItem,
+ transformHistoryResponse,
+ updateItemViewedAt,
+} from './transforms';
+
+const HISTORY_STALE_TIME = 5 * 60 * 1000;
+const HISTORY_GC_TIME = 10 * 60 * 1000;
+
+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,
+ };
+}
+
+export function useHistoryQuery(options?: {
+ instructionsMdIdQuery?: UseQueryResult<string | null | undefined, Error>;
+}) {
+ const instructionsMdIdQueryInternal = useInstructionsMdIdQuery();
+ const instructionsIdQuery =
+ options?.instructionsMdIdQuery ?? instructionsMdIdQueryInternal;
+
+ return useQuery(() => ({
+ ...historyQueryOptions(),
+ select: (data: HistoryQueryResponse): HistoryItem[] => {
+ const instructionsId = instructionsIdQuery.isSuccess
+ ? instructionsIdQuery.data
+ : null;
+ return transformHistoryResponse(data, instructionsId);
+ },
+ }));
+}
+
+export async function fetchAndCacheHistory(): Promise<HistoryQueryResponse> {
+ return queryClient.fetchQuery(historyQueryOptions());
+}
+
+export function refetchHistory() {
+ return queryClient.invalidateQueries({
+ queryKey: historyKeys.list.queryKey,
+ });
+}
+
+export function optimisticUpdateViewedAt(itemId: string) {
+ const now = Date.now();
+
+ queryClient.setQueryData<HistoryQueryResponse>(
+ historyKeys.list.queryKey,
+ (old) => {
+ if (!old) return old;
+ return {
+ ...old,
+ data: updateItemViewedAt(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
+ ),
+ }));
+}
diff --git a/js/app/packages/queries/history/keys.ts b/js/app/packages/queries/history/keys.ts
new file mode 100644
index 0000000000..951d65c57a
--- /dev/null
+++ b/js/app/packages/queries/history/keys.ts
@@ -0,0 +1,6 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const historyKeys = createQueryKeys('history', {
+ all: null,
+ list: null,
+});
diff --git a/js/app/packages/queries/history/tests/history.test.tsx b/js/app/packages/queries/history/tests/history.test.tsx
new file mode 100644
index 0000000000..707f043f00
--- /dev/null
+++ b/js/app/packages/queries/history/tests/history.test.tsx
@@ -0,0 +1,46 @@
+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, updateItemViewedAt } from '../transforms';
+
+function createItem(overrides: Partial<Item> = {}): Item {
+ return {
+ id: `item-${Math.random().toString(36).slice(2)}`,
+ name: 'Test Item',
+ type: 'document',
+ userId: 'user-1',
+ createdAt: Date.now() / 1000,
+ updatedAt: Date.now() / 1000,
+ ...overrides,
+ } as Item;
+}
+
+describe('history transforms', () => {
+ it('transforms response and filters instructions.md', () => {
+ 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');
+
+ expect(result.map((i) => i.id)).toEqual(['doc-1', 'doc-2']);
+ expect(result[0].name).toBe('My Doc');
+ });
+
+ it('updateItemViewedAt sets timestamp for optimistic updates', () => {
+ const items = [createItem({ id: 'doc-1' }), createItem({ id: 'doc-2' })];
+
+ const result = updateItemViewedAt(items, 'doc-1', 1704067200000);
+
+ expect(result[0]).toHaveProperty('viewedAt', 1704067200000);
+ expect(items[0]).not.toHaveProperty('viewedAt'); // doesn't mutate
+ });
+});
diff --git a/js/app/packages/queries/history/transforms.ts b/js/app/packages/queries/history/transforms.ts
new file mode 100644
index 0000000000..65a175eb03
--- /dev/null
+++ b/js/app/packages/queries/history/transforms.ts
@@ -0,0 +1,48 @@
+import { itemToSafeName } from '@core/constant/allBlocks';
+import type { Item } from '@service-storage/generated/schemas/item';
+
+type ItemWithViewedAt = Item & { viewedAt?: number };
+
+export type HistoryItem = Item & {
+ name: string;
+ viewedAt?: number;
+};
+
+export type HistoryQueryResponse = {
+ data: Item[];
+};
+
+export function transformHistoryItem(item: Item): HistoryItem {
+ return {
+ ...item,
+ name: itemToSafeName(item),
+ viewedAt: (item as ItemWithViewedAt).viewedAt,
+ };
+}
+
+export function filterInstructionsMd(
+ items: Item[],
+ instructionsId: string | null | undefined
+): Item[] {
+ if (!instructionsId) return items;
+ return items.filter((item) => item.id !== instructionsId);
+}
+
+export function transformHistoryResponse(
+ data: HistoryQueryResponse,
+ instructionsId: string | null | undefined
+): HistoryItem[] {
+ return filterInstructionsMd(data.data, instructionsId).map(
+ transformHistoryItem
+ );
+}
+
+export function updateItemViewedAt(
+ items: Item[],
+ itemId: string,
+ timestamp: number
+): Item[] {
+ return items.map((item) =>
+ item.id === itemId ? { ...item, viewedAt: timestamp } : item
+ );
+}
diff --git a/js/app/packages/service-clients/service-storage/history.ts b/js/app/packages/service-clients/service-storage/history.ts
index b6bea474b7..e5903faf6c 100644
--- a/js/app/packages/service-clients/service-storage/history.ts
+++ b/js/app/packages/service-clients/service-storage/history.ts
@@ -1,5 +1,6 @@
import { itemToSafeName } from '@core/constant/allBlocks';
import { isErr, isOk, ok } from '@core/util/maybeResult';
+import type { HistoryItem } from '@queries/history/transforms';
import { cognitionApiServiceClient } from '@service-cognition/client';
import { createSingletonRoot } from '@solid-primitives/rootless';
import { buildFileTree } from 'core/component/FileList/buildFileTree';
@@ -60,7 +61,7 @@ export const useHistoryTree = createSingletonRoot(() => {
export const useHistory = createSingletonRoot(() => {
const history = useFilteredHistory();
- return createMemo(() => {
+ return createMemo((): HistoryItem[] => {
const result = history();
if (isOk(result))