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.

chore(service-clients): remove statefullness from service-clients (#1081)

teo43ca939ec51d
diff --git a/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx b/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx
index ec6a62cd1a..c3bd067d20 100644
--- a/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx
+++ b/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx
@@ -10,8 +10,8 @@ import Fragment from '@core/util/Fragment';
import { scrollToKeepGap } from '@core/util/scrollToKeepGap';
import CaretRight from '@icon/regular/caret-right.svg';
import ArrowRight from '@phosphor-icons/core/regular/arrow-right.svg?component-solid';
+import { useProjectsQuery } from '@queries/storage/projects';
import type { Project } from '@service-storage/generated/schemas';
-import { useProjects } from '@service-storage/projects';
import {
createEffect,
createMemo,
@@ -33,7 +33,8 @@ export const MoveToProjectView = (props: {
}) => {
let listRef!: HTMLDivElement;
const moveToProjectMutation = createMoveToProjectDssEntityMutation();
- const projects = useProjects();
+ const projectsQuery = useProjectsQuery();
+ const projects = () => projectsQuery.data ?? [];
const [searchQuery, setSearchQuery] = createSignal('');
const [selectedProject, setSelectedProject] = createSignal<Project | null>(
null
diff --git a/js/app/packages/app/component/GlobalHotkeys.tsx b/js/app/packages/app/component/GlobalHotkeys.tsx
index fd7bf52227..cc880cc532 100644
--- a/js/app/packages/app/component/GlobalHotkeys.tsx
+++ b/js/app/packages/app/component/GlobalHotkeys.tsx
@@ -3,7 +3,7 @@ import { useSettingsState } from '@core/constant/SettingsState';
import { TOKENS } from '@core/hotkey/tokens';
import type { ValidHotkey } from '@core/hotkey/types';
import { useBigChat } from '@core/signal/layout';
-import { AiInstructionsIcon } from '@service-storage/instructionsMd';
+import { AiInstructionsIcon } from '@queries/storage/instructions-md';
import { registerHotkey } from 'core/hotkey/hotkeys';
import { createMemo } from 'solid-js';
import {
diff --git a/js/app/packages/app/component/Launcher.tsx b/js/app/packages/app/component/Launcher.tsx
index 8b82dfc858..177b9c6d84 100644
--- a/js/app/packages/app/component/Launcher.tsx
+++ b/js/app/packages/app/component/Launcher.tsx
@@ -28,7 +28,7 @@ import WideFileMd from '@macro-icons/wide/file-md.svg';
import WideFolder from '@macro-icons/wide/folder.svg';
import WideStar from '@macro-icons/wide/star.svg';
import WideTask from '@macro-icons/wide/task.svg';
-import { useCreateProject } from '@service-storage/projects';
+import { createProject } from '@queries/storage/projects';
import { createEffect, createSignal, For, onMount, Show } from 'solid-js';
import { type FocusableElement, tabbable } from 'tabbable';
import { useSplitLayout } from './split-layout/layout';
@@ -239,10 +239,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
keyDownHandler: () => {
createBlock({
blockName: 'project',
- createFn: () => {
- const createProject = useCreateProject();
- return createProject({ name: 'New Folder' });
- },
+ createFn: () => createProject({ name: 'New Folder' }),
shouldInsert: !pressedKeys().has('opt'),
});
return true;
diff --git a/js/app/packages/app/component/NewRoute.tsx b/js/app/packages/app/component/NewRoute.tsx
index 241fe6c292..f702bd6fbb 100644
--- a/js/app/packages/app/component/NewRoute.tsx
+++ b/js/app/packages/app/component/NewRoute.tsx
@@ -5,7 +5,7 @@ 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 '@service-storage/history';
+import { postNewHistoryItem } from '@queries/history/history';
import { newBlankDocument } from '@service-storage/util/newBlankDocument';
import {
Navigate,
diff --git a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
index ca5dd8eff2..e35cd717b7 100644
--- a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
+++ b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
@@ -18,7 +18,7 @@ import {
} from '@macro-entity';
import XIcon from '@phosphor-icons/core/assets/regular/x.svg';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import { debounce } from '@solid-primitives/scheduled';
import type { Component } from 'solid-js';
import {
@@ -88,7 +88,7 @@ export const FilterValueEntity: Component<FilterValueEntityProps> = (props) => {
const contacts = useContacts();
const channelsContext = useChannelsContext();
const channels = channelsContext.channels;
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
// Email queries for THREAD type or generic ENTITY (no specific type)
const needsEmailSearch = () =>
@@ -133,7 +133,7 @@ export const FilterValueEntity: Component<FilterValueEntityProps> = (props) => {
if (!entityType) {
return [
...contacts().map(entityMapper('user')),
- ...history().map(entityMapper('item')),
+ ...(historyQuery.data ?? []).map(entityMapper('item')),
...channels().map(entityMapper('channel')),
...emails().map(threadMapper),
];
@@ -154,13 +154,13 @@ export const FilterValueEntity: Component<FilterValueEntityProps> = (props) => {
// Item-based types: DOCUMENT, PROJECT, CHAT
const itemTypes: EntityType[] = ['DOCUMENT', 'PROJECT', 'CHAT'];
if (itemTypes.includes(entityType)) {
- return history()
+ return (historyQuery.data ?? [])
.filter((item) => item.type.toUpperCase() === entityType)
.map(entityMapper('item'));
}
if (entityType === 'TASK') {
- return history()
+ return (historyQuery.data ?? [])
.filter(
(item) => item.type === 'document' && item.subType?.type === 'task'
)
diff --git a/js/app/packages/app/component/auth/Login.tsx b/js/app/packages/app/component/auth/Login.tsx
index b4723479e9..d8ce7c2aad 100644
--- a/js/app/packages/app/component/auth/Login.tsx
+++ b/js/app/packages/app/component/auth/Login.tsx
@@ -46,7 +46,6 @@ export function Login() {
const session_code = searchParams.session_code;
console.log({ session_code });
unsetTokenPromise();
- authServiceClient.getUserInfo.invalidate();
invalidateUserInfo();
authServiceClient.sessionLogin({ session_code }).then((res) => {
console.log({ res });
@@ -65,8 +64,6 @@ export function Login() {
setActiveModal();
unsetTokenPromise();
invalidateUserInfo();
- authServiceClient.getUserInfo.invalidate();
-
const userInfo = await fetchUserInfo();
if (
userInfo?.authenticated &&
diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx
index 46d722dd42..f3e064afbc 100644
--- a/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx
+++ b/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx
@@ -1,7 +1,7 @@
import { EntityIcon } from '@core/component/EntityIcon';
import { scrollToKeepGap } from '@core/util/scrollToKeepGap';
+import { useProjectsQuery } from '@queries/storage/projects';
import type { Project } from '@service-storage/generated/schemas';
-import { useProjects } from '@service-storage/projects';
import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
import { createMemo, createSignal, For, onMount, Show } from 'solid-js';
import { createBulkMoveToProjectDssEntityMutation } from '../../../macro-entity/src/queries/dss';
@@ -20,7 +20,8 @@ export const BulkMoveToProjectView = (props: {
}) => {
let listRef!: HTMLDivElement;
const bulkMoveToProjectMutation = createBulkMoveToProjectDssEntityMutation();
- const projects = useProjects();
+ const projectsQuery = useProjectsQuery();
+ const projects = () => projectsQuery.data ?? [];
const [searchQuery, setSearchQuery] = createSignal('');
const [selectedProject, setSelectedProject] =
createSignal<ProjectWithDepth | null>(null);
diff --git a/js/app/packages/app/component/command/KonsoleItem.tsx b/js/app/packages/app/component/command/KonsoleItem.tsx
index 148d5e358a..9cdfd242d3 100644
--- a/js/app/packages/app/component/command/KonsoleItem.tsx
+++ b/js/app/packages/app/component/command/KonsoleItem.tsx
@@ -22,7 +22,6 @@ import type { HotkeyCommand } from '@core/hotkey/types';
import { hasValidHotkey, runCommand } from '@core/hotkey/utils';
import type { BlockOrchestrator } from '@core/orchestrator';
import { type ChannelWithParticipants, idToDisplayName } from '@core/user';
-import PushPin from '@phosphor-icons/core/regular/push-pin.svg?component-solid';
import Terminal from '@phosphor-icons/core/regular/terminal.svg?component-solid';
import type { Channel } from '@service-comms/generated/models/channel';
import type { Attachment } from '@service-email/generated/schemas';
@@ -744,27 +743,3 @@ export function CommandItemCard(props: CommandItemProps) {
</CommandItemContainer>
);
}
-
-export function PinnedCommandItem(props: {
- item: CommandItemCard;
- itemAction: (item: CommandItemCard, action: ItemAction) => void;
-}) {
- const type = () => getCommandItemBlockName(props.item, true);
- const name = () => getCommandItemName(props.item);
-
- return (
- <div
- onMouseDown={() => props.itemAction(props.item, 'open')}
- class="flex items-center shrink-0 gap-1.5 px-2 py-1.5 rounded-md hover:bg-hover hover-transition-bg cursor-pointer w-[calc(25%-6px)]"
- title={name()}
- style={{
- 'padding-top': `${COMMAND_ITEM_PADDING}px`,
- 'padding-bottom': `${COMMAND_ITEM_PADDING}px`,
- }}
- >
- <EntityIcon targetType={type()} size="sm" />
- <span class="text-xs font-medium text-ink truncate">{name()}</span>
- <PushPin class="w-3.5 h-3.5 text-ink-extra-muted shrink-0" />
- </div>
- );
-}
diff --git a/js/app/packages/app/component/dock/BasicTierLimit.tsx b/js/app/packages/app/component/dock/BasicTierLimit.tsx
index ed98865780..a8669a7020 100644
--- a/js/app/packages/app/component/dock/BasicTierLimit.tsx
+++ b/js/app/packages/app/component/dock/BasicTierLimit.tsx
@@ -1,5 +1,5 @@
import { usePaywallState } from '@core/constant/PaywallState';
-import { useUserQuotaQuery } from '@service-auth/userQuota';
+import { useUserQuotaQuery } from '@queries/auth';
import { createMemo, Suspense } from 'solid-js';
const BasicTierLimitWrapper = () => {
diff --git a/js/app/packages/app/component/rightbar/Rightbar.tsx b/js/app/packages/app/component/rightbar/Rightbar.tsx
index e68a68a600..9075e56c70 100644
--- a/js/app/packages/app/component/rightbar/Rightbar.tsx
+++ b/js/app/packages/app/component/rightbar/Rightbar.tsx
@@ -45,13 +45,13 @@ import NotepadIcon from '@icon/regular/notepad.svg';
import PlusIcon from '@icon/regular/plus.svg';
import XIcon from '@icon/regular/x.svg';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
-import { invalidateUserQuota } from '@service-auth/userQuota';
+import { invalidateUserQuota } from '@queries/auth';
import {
cognitionApiServiceClient,
cognitionWebsocketServiceClient,
} from '@service-cognition/client';
import { createCognitionWebsocketEffect } from '@service-cognition/websocket';
-import { refetchHistory, useHistory } from '@service-storage/history';
+import { invalidateHistory, useHistoryQuery } from '@queries/history/history';
import { useOpenInstructionsMd } from 'core/component/AI/util/instructions';
import type { LexicalEditor } from 'lexical';
import {
@@ -112,9 +112,11 @@ const getChatData = async (chatId: string): Promise<ChatData> => {
};
const usePersistentChats = () => {
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
return createMemo(() =>
- history().filter((item) => item.type === 'chat' && item.isPersistent)
+ (historyQuery.data ?? []).filter(
+ (item) => item.type === 'chat' && item.isPersistent
+ )
);
};
@@ -541,9 +543,9 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {
// TODO: move this into a separate resource so we don't have to refetch history
// refetch history immediately to have the new chat id
// then rename again when the server provides a default name
- refetchHistory();
+ invalidateHistory();
waitChatRename(newChatId).then((_name) => {
- refetchHistory();
+ invalidateHistory();
});
return await onSend(response);
} else if (request.type === 'send') {
diff --git a/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx b/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx
index 1f2721b840..cc91a14a64 100644
--- a/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx
+++ b/js/app/packages/app/component/split-layout/components/SplitFileMenu.tsx
@@ -3,16 +3,13 @@ import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import { useItemOperations } from '@core/component/FileList/useItemOperations';
import { MenuItem } from '@core/component/Menu';
import { useIsDocumentOwner } from '@core/signal/permissions';
-import Unpin from '@icon/fill/push-pin-slash-fill.svg';
import ArrowRight from '@icon/regular/arrow-right.svg';
import Copy from '@icon/regular/copy.svg';
import ThreeDots from '@icon/regular/list.svg';
import Rename from '@icon/regular/pencil-line.svg';
-import Pin from '@icon/regular/push-pin.svg';
import Trash from '@icon/regular/trash-simple.svg';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import { blockNameToItemType, type ItemType } from '@service-storage/client';
-import { usePinnedIds } from '@service-storage/pins';
import {
type Component,
createMemo,
@@ -25,12 +22,7 @@ import { SplitPanelContext } from '../context';
import { useSplitLayout } from '../layout';
import { useSplitModal } from './SplitModalContext';
-export type FileOperationName =
- | 'pin'
- | 'delete'
- | 'rename'
- | 'copy'
- | 'moveToProject';
+export type FileOperationName = 'delete' | 'rename' | 'copy' | 'moveToProject';
export type DefaultFileOperation = {
op: FileOperationName;
@@ -71,9 +63,6 @@ export function SplitFileMenu(props: {
const [open, setOpen] = createSignal(false);
const itemOperations = useItemOperations();
- const pinnedIds = usePinnedIds();
- const isPinned = () => pinnedIds().includes(props.id);
-
const modal = useSplitModal();
const { replaceOrInsertSplit, resetSplit } = useSplitLayout();
@@ -83,18 +72,6 @@ export function SplitFileMenu(props: {
.map((op) => {
if (isDefaultFileOperation(op)) {
switch (op.op) {
- case 'pin':
- return {
- label: isPinned() ? 'Unpin' : 'Pin',
- action: () =>
- itemOperations.togglePin({
- itemType: props.itemType,
- id: props.id,
- }),
- icon: isPinned() ? Unpin : Pin,
- divideAbove: op.divideAbove || false,
- };
-
case 'delete':
if (!isOwner()) return null;
return {
diff --git a/js/app/packages/block-canvas/component/FileSelector.tsx b/js/app/packages/block-canvas/component/FileSelector.tsx
index 29ebf66701..d141baea45 100644
--- a/js/app/packages/block-canvas/component/FileSelector.tsx
+++ b/js/app/packages/block-canvas/component/FileSelector.tsx
@@ -7,7 +7,7 @@ import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import FileText from '@phosphor-icons/core/regular/file-text.svg?component-solid';
import type { ItemType } from '@service-storage/client';
import type { FileType } from '@service-storage/generated/schemas/fileType';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import { createEffect, createSignal, Show } from 'solid-js';
import { VList } from 'virtua/solid';
import { Tools } from '../constants';
@@ -59,14 +59,14 @@ export function FileSelector() {
const [userFiles, setUserFiles] = createSignal<
{ file: FileItem; type: string }[]
>([]);
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
const { focusCanvas } = useToolManager();
const [fileSelectorOpen, setFileSelectorOpen] = createSignal(false);
createEffect(async () => {
const files: { file: FileItem; type: string }[] = [];
- history().forEach((item) => {
+ (historyQuery.data ?? []).forEach((item) => {
if (
item.type === 'document' &&
item.fileType &&
diff --git a/js/app/packages/block-canvas/component/MediaSelector.tsx b/js/app/packages/block-canvas/component/MediaSelector.tsx
index 70e0ec239f..0cbfed5f04 100644
--- a/js/app/packages/block-canvas/component/MediaSelector.tsx
+++ b/js/app/packages/block-canvas/component/MediaSelector.tsx
@@ -25,7 +25,7 @@ import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import UploadSimple from '@phosphor-icons/core/bold/upload-simple-bold.svg?component-solid';
import Image from '@phosphor-icons/core/regular/image.svg?component-solid';
//import { copiedFile } from "@core/state/clipboard";
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import { createMemo, createSignal, Show } from 'solid-js';
import { VList } from 'virtua/solid';
import { Tools } from '../constants';
@@ -82,7 +82,7 @@ export function MediaSelector() {
const mediaTypes: MediaType[] = ENABLE_CANVAS_VIDEO
? ['image', 'video']
: ['image'];
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
//const copiedFileID = copiedFile();
const { track, TrackingEvents } = withAnalytics();
const select = useSelect();
@@ -117,7 +117,7 @@ export function MediaSelector() {
const userMediaFiles = createMemo(() => {
const mediaFiles: MediaItem[] = [];
- for (const item of history()) {
+ for (const item of historyQuery.data ?? []) {
for (const mediaType of mediaTypes) {
if (
item.type === 'document' &&
diff --git a/js/app/packages/block-canvas/component/TopBar.tsx b/js/app/packages/block-canvas/component/TopBar.tsx
index 2bc68df005..dc3fbbc55c 100644
--- a/js/app/packages/block-canvas/component/TopBar.tsx
+++ b/js/app/packages/block-canvas/component/TopBar.tsx
@@ -89,7 +89,6 @@ export function TopBar() {
};
const ops: FileOperation[] = [
- { op: 'pin' },
{ op: 'copy' },
{ op: 'rename' },
{ op: 'moveToProject' },
diff --git a/js/app/packages/block-channel/component/AttachMenu.tsx b/js/app/packages/block-channel/component/AttachMenu.tsx
index 40559dd9c8..fbf058098d 100644
--- a/js/app/packages/block-channel/component/AttachMenu.tsx
+++ b/js/app/packages/block-channel/component/AttachMenu.tsx
@@ -19,7 +19,7 @@ import {
import DeviceMobileIcon from '@icon/regular/device-mobile-speaker.svg';
import LaptopIcon from '@icon/regular/laptop.svg';
import SearchIcon from '@icon/regular/magnifying-glass.svg';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import {
createEffect,
createMemo,
@@ -55,7 +55,7 @@ function truncate(str: string, maxLength: number = 30) {
export function AttachMenu(props: AttachMenuProps) {
const [position, setPosition] = createSignal({ x: 0, y: 0 });
const [popupRef, setPopupRef] = createSignal<HTMLDivElement>();
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
const inputAttachments = () =>
props.inputAttachmentsStore.store[props.inputAttachmentsStore.key] ?? [];
@@ -83,7 +83,7 @@ export function AttachMenu(props: AttachMenuProps) {
};
const baseHistory = createMemo(() => {
- return [...history()].filter(
+ return [...(historyQuery.data ?? [])].filter(
(item) => !inputAttachments().find((a) => a.id === item.id)
);
});
diff --git a/js/app/packages/block-chat/client.ts b/js/app/packages/block-chat/client.ts
index a07fa119cc..c0f839491a 100644
--- a/js/app/packages/block-chat/client.ts
+++ b/js/app/packages/block-chat/client.ts
@@ -7,7 +7,7 @@ import { isPaymentError } from '@core/util/handlePaymentError';
import { isErr } from '@core/util/maybeResult';
import { propsToHref } from '@core/util/url';
import { cognitionApiServiceClient } from '@service-cognition/client';
-import { postNewHistoryItem } from '@service-storage/history';
+import { postNewHistoryItem } from '@queries/history/history';
const { track, TrackingEvents } = withAnalytics();
diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsx
index 0ae9fd597f..fcdfc783bb 100644
--- a/js/app/packages/block-chat/component/Chat.tsx
+++ b/js/app/packages/block-chat/component/Chat.tsx
@@ -29,7 +29,7 @@ import {
} from '@core/signal/blockElement';
import { blockHandleSignal } from '@core/signal/load';
import { useCanEdit } from '@core/signal/permissions';
-import { invalidateUserQuota } from '@service-auth/userQuota';
+import { invalidateUserQuota } from '@queries/auth';
import { cognitionWebsocketServiceClient } from '@service-cognition/client';
import { createCallback } from '@solid-primitives/rootless';
import type { LexicalEditor } from 'lexical';
diff --git a/js/app/packages/block-chat/component/NameMenu.tsx b/js/app/packages/block-chat/component/NameMenu.tsx
index 7ba93347d4..a6594c2337 100644
--- a/js/app/packages/block-chat/component/NameMenu.tsx
+++ b/js/app/packages/block-chat/component/NameMenu.tsx
@@ -17,10 +17,8 @@ import {
import { BarContext } from '@core/component/TopBar/Bar';
import { setCachedInputStore } from '@core/store/cacheChatInput';
import { isErr } from '@core/util/maybeResult';
-import Unpin from '@icon/fill/push-pin-slash-fill.svg';
import CopySimple from '@icon/regular/copy-simple.svg';
import PencilSimpleLine from '@icon/regular/pencil-simple-line.svg';
-import Pin from '@icon/regular/push-pin.svg';
import ShareFat from '@icon/regular/share-fat.svg';
import TrashSimple from '@icon/regular/trash-simple.svg';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
@@ -29,15 +27,8 @@ import { useEmail } from '@core/context/user';
import {
refetchHistory,
useUpdatedDssItemName,
-} from '@service-storage/history';
-import {
- pinItem,
- refetchPins,
- unpinItem,
- usePinnedIds,
-} from '@service-storage/pins';
+} from '@queries/history/history';
import { refetchResources } from '@service-storage/util/refetchResources';
-import { createCallback } from '@solid-primitives/rootless';
import { useNavigate } from '@solidjs/router';
import { useSplitPanelOrThrow } from 'app/component/split-layout/layoutUtils';
import { toast } from 'core/component/Toast/Toast';
@@ -50,22 +41,8 @@ type Props = { data: ChatData };
export function ChatNameMenu(props: Props) {
const [chatMenuOpen, setChatMenuOpen] = createSignal(false);
const isAuthenticated = useIsAuthenticated();
- const pinnedIds = usePinnedIds();
const panelContext = useSplitPanelOrThrow();
- const isPinned = createCallback(() => {
- return pinnedIds().includes(props.data.chat.id);
- });
-
- const mutatePin = (
- ...params: Parameters<typeof pinItem & typeof unpinItem>
- ) => {
- if (isPinned()) {
- return unpinItem(...params);
- }
-
- return pinItem(...params);
- };
const renameChat = async ({
chat_id,
new_name,
@@ -81,8 +58,6 @@ export function ChatNameMenu(props: Props) {
});
if (isErr(maybeRenameResult)) return;
- if (isPinned()) refetchPins();
-
refetchHistory();
};
const deleteChat = async (chat_id: string) => {
@@ -92,8 +67,6 @@ export function ChatNameMenu(props: Props) {
});
if (isErr(maybeDeletedChat)) return;
- if (isPinned()) refetchPins();
-
refetchResources();
panelContext?.handle.close();
};
@@ -153,16 +126,6 @@ export function ChatNameMenu(props: Props) {
<DropdownMenu.Portal>
<DropdownMenuContent>
- <Show when={isAuthenticated()}>
- <MenuItem
- text={isPinned() ? `Unpin` : 'Pin'}
- icon={isPinned() ? Unpin : Pin}
- onClick={() => {
- mutatePin('chat', props.data.chat.id);
- track(TrackingEvents.BLOCKCHAT.CHATMENU.FAVORITE);
- }}
- />
- </Show>
<MenuItem
text={'Make a Copy'}
icon={CopySimple}
diff --git a/js/app/packages/block-chat/component/TopBar.tsx b/js/app/packages/block-chat/component/TopBar.tsx
index 1f93ee3743..54573162a1 100644
--- a/js/app/packages/block-chat/component/TopBar.tsx
+++ b/js/app/packages/block-chat/component/TopBar.tsx
@@ -20,7 +20,7 @@ import { useGetPermissions } from '@core/signal/permissions';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import Notepad from '@icon/regular/notepad.svg';
import { createCognitionWebsocketEffect } from '@service-cognition/websocket';
-import { refetchHistory } from '@service-storage/history';
+import { refetchHistory } from '@queries/history/history';
import { useOpenInstructionsMd } from 'core/component/AI/util/instructions';
import { onCleanup, onMount } from 'solid-js';
@@ -49,7 +49,6 @@ export function TopBar() {
const openInstructions = useOpenInstructionsMd();
const ops: FileOperation[] = [
- { op: 'pin' },
{ op: 'rename' },
{ op: 'copy' },
{ op: 'moveToProject' },
diff --git a/js/app/packages/block-code/component/TopBar.tsx b/js/app/packages/block-code/component/TopBar.tsx
index b993059995..49ca405015 100644
--- a/js/app/packages/block-code/component/TopBar.tsx
+++ b/js/app/packages/block-code/component/TopBar.tsx
@@ -45,7 +45,6 @@ export const TopBar: Component = () => {
});
const ops: FileOperation[] = [
- { op: 'pin' },
{ op: 'rename' },
{ op: 'copy' },
{ op: 'moveToProject' },
diff --git a/js/app/packages/block-email/component/AttachMenu.tsx b/js/app/packages/block-email/component/AttachMenu.tsx
index 8ddd4c6f8e..d6a1054b62 100644
--- a/js/app/packages/block-email/component/AttachMenu.tsx
+++ b/js/app/packages/block-email/component/AttachMenu.tsx
@@ -10,7 +10,7 @@ import SearchIcon from '@icon/regular/magnifying-glass.svg';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import type { DocumentMentionInfo } from '@lexical-core';
import type { Item } from '@service-storage/generated/schemas/item';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import fuzzy from 'fuzzy';
import {
createMemo,
@@ -41,13 +41,13 @@ function truncate(str: string, maxLength: number = 30) {
}
export function AttachMenu(props: AttachMenuProps) {
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
const attachedItems = () => props.attachedItems?.() ?? [];
const [input, setInput] = createSignal('');
const baseHistory = createMemo(() => {
- return [...history()].filter(
+ return [...(historyQuery.data ?? [])].filter(
(item) => !attachedItems().find((a) => a.id === item.id)
);
});
diff --git a/js/app/packages/block-image/component/TopBar.tsx b/js/app/packages/block-image/component/TopBar.tsx
index de636166aa..465c3adf2d 100644
--- a/js/app/packages/block-image/component/TopBar.tsx
+++ b/js/app/packages/block-image/component/TopBar.tsx
@@ -38,7 +38,6 @@ export function TopBar() {
});
const ops: FileOperation[] = [
- { op: 'pin' },
{ op: 'rename' },
{ op: 'copy' },
{ op: 'moveToProject' },
diff --git a/js/app/packages/block-md/component/Block.tsx b/js/app/packages/block-md/component/Block.tsx
index fbc69847ad..b8b7dcb128 100644
--- a/js/app/packages/block-md/component/Block.tsx
+++ b/js/app/packages/block-md/component/Block.tsx
@@ -4,7 +4,7 @@ import { useBlockId } from '@core/block';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { DocumentDebouncedNotificationReadMarker } from '@notifications';
-import { useInstructionsMdIdQuery } from '@service-storage/instructionsMd';
+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import { createEffect, createSignal, onMount, Show, Suspense } from 'solid-js';
import { mdStore } from '../signal/markdownBlockData';
import { FindAndReplace } from './FindAndReplace';
diff --git a/js/app/packages/block-md/component/MediaSelector.tsx b/js/app/packages/block-md/component/MediaSelector.tsx
index 2a3f2369d6..f5d55a948d 100644
--- a/js/app/packages/block-md/component/MediaSelector.tsx
+++ b/js/app/packages/block-md/component/MediaSelector.tsx
@@ -12,7 +12,7 @@ import { fileSelector } from '@core/directive/fileSelector';
import ImageIcon from '@icon/regular/image.svg';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
import UploadSimple from '@phosphor-icons/core/bold/upload-simple-bold.svg?component-solid';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import type { LexicalEditor } from 'lexical';
import type { Accessor } from 'solid-js';
import { createMemo, createSignal, For, Show } from 'solid-js';
@@ -62,12 +62,12 @@ export function MediaSelector(props: MediaSelectorProps) {
const mdData = mdStore.get;
const editor = () => mdData.editor;
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
const [menuOpen, setMenuOpen] = createSignal(false);
const userMediaFiles = createMemo(() => {
let mediaFiles: MediaItem[] = [];
- for (const item of history()) {
+ for (const item of historyQuery.data ?? []) {
for (const mediaType of mediaTypes) {
if (
item.type === 'document' &&
@@ -115,8 +115,6 @@ export function MediaSelector(props: MediaSelectorProps) {
});
}
};
- console.log('acceptedFileExtensions', acceptedFileExtensions());
- console.log('acceptedMimeTypes', acceptedMimeTypes());
return (
// TODO bring up to menu best practices, ie. fully focusable menu items, etc.
diff --git a/js/app/packages/block-md/component/TopBar.tsx b/js/app/packages/block-md/component/TopBar.tsx
index 7088c207ee..6492e021bb 100644
--- a/js/app/packages/block-md/component/TopBar.tsx
+++ b/js/app/packages/block-md/component/TopBar.tsx
@@ -56,7 +56,6 @@ export function TopBar() {
const downloadAsMarkdownText = useDownloadDocumentAsMarkdownText();
const ops: FileOperation[] = [
- { op: 'pin' },
{ op: 'copy' },
{ op: 'rename' },
{ op: 'moveToProject' },
diff --git a/js/app/packages/block-md/signal/save.ts b/js/app/packages/block-md/signal/save.ts
index b6052e88ea..184cb9a574 100644
--- a/js/app/packages/block-md/signal/save.ts
+++ b/js/app/packages/block-md/signal/save.ts
@@ -8,7 +8,7 @@ import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import { isErr } from '@core/util/maybeResult';
import { utf8Encode } from '@core/util/string';
import { storageServiceClient } from '@service-storage/client';
-import { refetchHistory } from '@service-storage/history';
+import { refetchHistory } from '@queries/history/history';
import { refetchResources } from '@service-storage/util/refetchResources';
import { createCallback } from '@solid-primitives/rootless';
import { createMemo } from 'solid-js';
diff --git a/js/app/packages/block-pdf/component/TopBar.tsx b/js/app/packages/block-pdf/component/TopBar.tsx
index eabf7514f2..dbac2be837 100644
--- a/js/app/packages/block-pdf/component/TopBar.tsx
+++ b/js/app/packages/block-pdf/component/TopBar.tsx
@@ -140,7 +140,6 @@ export function TopBar() {
});
const ops: FileOperation[] = [
- { op: 'pin' },
{ op: 'rename' },
{ op: 'copy' },
{ op: 'moveToProject' },
diff --git a/js/app/packages/block-pdf/signal/save.ts b/js/app/packages/block-pdf/signal/save.ts
index 04e2527c14..0ee84a5d7f 100644
--- a/js/app/packages/block-pdf/signal/save.ts
+++ b/js/app/packages/block-pdf/signal/save.ts
@@ -3,7 +3,7 @@ import { createBlockSignal, useBlockId } from '@core/block';
import { ENABLE_PDF_MODIFICATION_DATA_AUTOSAVE } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import { storageServiceClient } from '@service-storage/client';
-import { refetchHistory } from '@service-storage/history';
+import { refetchHistory } from '@queries/history/history';
import { createMemo } from 'solid-js';
import { highlightStore } from '../store/highlight';
import { useTableOfContentsValue } from '../store/tableOfContents';
diff --git a/js/app/packages/block-project/component/ProjectCreateMenu.tsx b/js/app/packages/block-project/component/ProjectCreateMenu.tsx
index fb1aa2fa51..54cf9ce2f9 100644
--- a/js/app/packages/block-project/component/ProjectCreateMenu.tsx
+++ b/js/app/packages/block-project/component/ProjectCreateMenu.tsx
@@ -12,7 +12,7 @@ import {
createTask,
} from '@core/util/create';
import { DropdownMenu } from '@kobalte/core/dropdown-menu';
-import { useCreateProject } from '@service-storage/projects';
+import { createProject } from '@queries/storage/projects';
import { type Component, createSignal, For } from 'solid-js';
type MenuItemProps = {
@@ -201,7 +201,6 @@ function MenuContent(props: { projectId: string }) {
createBlock({
blockName: 'project',
createFn: async () => {
- const createProject = useCreateProject();
const result = await createProject({
name: 'New Project',
parentId: props.projectId,
diff --git a/js/app/packages/block-unknown/component/TopBar.tsx b/js/app/packages/block-unknown/component/TopBar.tsx
index b5bd342906..5bb1981749 100644
--- a/js/app/packages/block-unknown/component/TopBar.tsx
+++ b/js/app/packages/block-unknown/component/TopBar.tsx
@@ -44,7 +44,6 @@ export function TopBar() {
});
const ops: FileOperation[] = [
- { op: 'pin' },
{ op: 'rename' },
{ op: 'copy' },
{ op: 'moveToProject' },
diff --git a/js/app/packages/block-video/component/TopBar.tsx b/js/app/packages/block-video/component/TopBar.tsx
index ce94cb86be..79eb54f9cc 100644
--- a/js/app/packages/block-video/component/TopBar.tsx
+++ b/js/app/packages/block-video/component/TopBar.tsx
@@ -44,7 +44,6 @@ export function TopBar() {
});
const ops: FileOperation[] = [
- { op: 'pin' },
{ op: 'rename' },
{ op: 'copy' },
{ op: 'moveToProject' },
diff --git a/js/app/packages/core/component/AI/constant/prompts.ts b/js/app/packages/core/component/AI/constant/prompts.ts
index b4692b9d25..472574ae4a 100644
--- a/js/app/packages/core/component/AI/constant/prompts.ts
+++ b/js/app/packages/core/component/AI/constant/prompts.ts
@@ -1,5 +1,5 @@
import { useUserContext } from '@core/context/user';
-import { useInstructionsMdTextQuery } from '@service-storage/instructionsMd';
+import { useInstructionsMdTextQuery } from '@queries/storage/instructions-md';
import { createMemo } from 'solid-js';
const ABOUT_MACRO = `
diff --git a/js/app/packages/core/component/AI/signal/attachment.ts b/js/app/packages/core/component/AI/signal/attachment.ts
index 813d955f71..414d34a705 100644
--- a/js/app/packages/core/component/AI/signal/attachment.ts
+++ b/js/app/packages/core/component/AI/signal/attachment.ts
@@ -8,7 +8,7 @@ import { useChannelsContext } from '@core/context/channels';
import type { ItemMention } from '@core/component/LexicalMarkdown/plugins/mentions';
import { ENABLE_CHAT_CHANNEL_ATTACHMENT } from '@core/constant/featureFlags';
import { getItemBlockName } from '@core/util/getItemBlockName';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import { createMemo, createSignal } from 'solid-js';
export function useAttachments(initial?: Attachment[]): Attachments {
@@ -42,10 +42,10 @@ export function useAttachments(initial?: Attachment[]): Attachments {
}
export const useChatAttachableHistory = () => {
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
return createMemo(() => {
- return history().filter((item) => {
+ return (historyQuery.data ?? []).filter((item) => {
const blockName = getItemBlockName(item, true);
return SUPPORTED_CHAT_ATTACHMENT_BLOCKS.includes(blockName);
});
diff --git a/js/app/packages/core/component/AI/signal/tabAttachments.ts b/js/app/packages/core/component/AI/signal/tabAttachments.ts
index 5cd2873b8e..e1732c85f3 100644
--- a/js/app/packages/core/component/AI/signal/tabAttachments.ts
+++ b/js/app/packages/core/component/AI/signal/tabAttachments.ts
@@ -11,14 +11,16 @@ import type {
FileType,
} from '@service-cognition/generated/schemas';
import { emailClient } from '@service-email/client';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import { useQuery } from '@tanstack/solid-query';
import type { SplitContent } from 'app/component/split-layout/layoutManager';
import { globalSplitManager } from 'app/signal/splitLayout';
import type { Accessor } from 'solid-js';
import { createMemo } from 'solid-js';
-type Item = ReturnType<ReturnType<typeof useHistory>>[number] | null;
+import type { HistoryItem } from '@queries/history/history';
+
+type Item = HistoryItem | null;
function convertSplitToAttachment(
split: SplitContent,
@@ -92,7 +94,7 @@ function convertSplitToAttachment(
}
export function useTabAttachments(): Accessor<ChatAttachmentWithName[]> {
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
const channelsContext = useChannelsContext();
const channels = channelsContext.channels;
const emails = useEmails();
@@ -103,7 +105,7 @@ export function useTabAttachments(): Accessor<ChatAttachmentWithName[]> {
if (!splitManager) return [];
const splits = splitManager.splits();
- const historyItems = history();
+ const historyItems = historyQuery.data ?? [];
const channelList = channels();
const emailList = emails();
diff --git a/js/app/packages/core/component/AI/util/instructions.ts b/js/app/packages/core/component/AI/util/instructions.ts
index 5f880aee52..c0df5eca55 100644
--- a/js/app/packages/core/component/AI/util/instructions.ts
+++ b/js/app/packages/core/component/AI/util/instructions.ts
@@ -2,7 +2,7 @@ import { toast } from '@core/component/Toast/Toast';
import {
useCreateInstructionsMd,
useInstructionsMdIdQuery,
-} from '@service-storage/instructionsMd';
+} from '@queries/storage/instructions-md';
import { useSplitLayout } from 'app/component/split-layout/layout';
const showFailToast = () => {
diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.ts
index 605d92b525..fd465ab142 100644
--- a/js/app/packages/core/component/FileList/itemOperations.ts
+++ b/js/app/packages/core/component/FileList/itemOperations.ts
@@ -5,12 +5,11 @@ import { cognitionApiServiceClient } from '@service-cognition/client';
import { commsServiceClient } from '@service-comms/client';
import { type ItemType, storageServiceClient } from '@service-storage/client';
import {
+ getDeletedTree,
optimisticallyRemoveDeletedItem,
- useDeletedTree,
-} from '@service-storage/deleted';
+} from '@queries/storage/deleted';
import type { Item } from '@service-storage/generated/schemas/item';
-import { removeHistoryItem } from '@service-storage/history';
-import { pinItem, unpinItem, usePinnedIds } from '@service-storage/pins';
+import { removeHistoryItem } from '@queries/history/history';
import { refetchResources } from '@service-storage/util/refetchResources';
import {
getPermissions,
@@ -399,71 +398,6 @@ export async function bulkCopy(
};
}
-export async function togglePin(args: {
- itemType: ItemType;
- id: string;
-}): Promise<boolean> {
- const { itemType, id } = args;
- const pinnedIds = usePinnedIds();
- const pinned = pinnedIds().includes(id);
-
- if (pinned) {
- return unpinItem(itemType, id);
- } else {
- return pinItem(itemType, id);
- }
-}
-
-export async function bulkTogglePin(
- selectedItems: Item[],
- chunkSize: number = DEFAULT_CHUNK_SIZE
-): Promise<{ success: boolean; failedItems: Item[] }> {
- const pinnedIds = usePinnedIds();
- // Check if all items have the same pinned state
- const allItemsHaveSameState = selectedItems.every(
- (item) =>
- pinnedIds().includes(item.id) ===
- pinnedIds().includes(selectedItems[0].id)
- );
- if (!allItemsHaveSameState) {
- return {
- success: false,
- failedItems: selectedItems,
- };
- }
-
- const failedItems: Item[] = [];
-
- // Process items in chunks
- for (let i = 0; i < selectedItems.length; i += chunkSize) {
- const chunk = selectedItems.slice(i, i + chunkSize);
-
- const results = await Promise.allSettled(
- chunk.map((item) =>
- togglePin({
- itemType: item.type,
- id: item.id,
- })
- )
- );
-
- // Process results for this chunk
- results.forEach((result, index) => {
- if (
- result.status === 'rejected' ||
- (result.status === 'fulfilled' && !result.value)
- ) {
- failedItems.push(chunk[index]);
- }
- });
- }
-
- return {
- success: failedItems.length === 0,
- failedItems,
- };
-}
-
export async function revertDelete(args: {
itemType: ItemType;
id: string;
@@ -520,10 +454,10 @@ export async function permanentlyDelete(args: {
break;
}
case 'project': {
- const deleteTree = useDeletedTree();
+ const deleteTree = getDeletedTree();
const findAllDescendants = (projectId: string): string[] => {
const descendantIds: string[] = [];
- const node = deleteTree().itemMap[projectId];
+ const node = deleteTree.itemMap[projectId];
if (node && node.children) {
node.children.forEach((child) => {
descendantIds.push(child.id);
@@ -570,7 +504,7 @@ export async function bulkPermanentlyDelete(
const failedItems: Item[] = [];
const selectedItemIds = new Set(selectedItems.map((item) => item.id));
- const deleteTree = useDeletedTree();
+ const deleteTree = getDeletedTree();
const descendants: Item[] = [];
@@ -582,14 +516,14 @@ export async function bulkPermanentlyDelete(
let currentItem = item;
while (currentItem) {
const parentId = getParentId(currentItem);
- if (!parentId || !deleteTree().itemMap[parentId]?.item) break;
+ if (!parentId || !deleteTree.itemMap[parentId]?.item) break;
if (selectedItemIds.has(parentId)) {
descendants.push(item);
return false;
}
- currentItem = deleteTree().itemMap[parentId]?.item;
+ currentItem = deleteTree.itemMap[parentId]?.item;
if (!currentItem) break;
}
@@ -624,7 +558,7 @@ export async function bulkPermanentlyDelete(
const findChildren = (item: Item): Item[] => {
const children: Item[] = [];
- const node = deleteTree().itemMap[item.id];
+ const node = deleteTree.itemMap[item.id];
if (!node) return children;
node.children.forEach((child) => {
diff --git a/js/app/packages/core/component/FileList/useItemOperations.ts b/js/app/packages/core/component/FileList/useItemOperations.ts
index d56aed7413..b3025b486d 100644
--- a/js/app/packages/core/component/FileList/useItemOperations.ts
+++ b/js/app/packages/core/component/FileList/useItemOperations.ts
@@ -1,9 +1,11 @@
import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { ok } from '@core/util/maybeResult';
import type { ItemType } from '@service-storage/client';
-import { refetchDeletedItems, useDeletedItems } from '@service-storage/deleted';
+import {
+ getDeletedItems,
+ invalidateDeletedItems,
+ setDeletedItems,
+} from '@queries/storage/deleted';
import type { Item } from '@service-storage/generated/schemas/item';
-import { usePinnedIds } from '@service-storage/pins';
import {
createCallback,
createSingletonRoot,
@@ -16,7 +18,6 @@ import {
bulkPermanentlyDelete as bulkPermanentlyDeleteOp,
bulkRename as bulkRenameOp,
bulkRevertDelete as bulkRevertDeleteOp,
- bulkTogglePin as bulkTogglePinOp,
copyItem as copyItemOp,
deleteItem as deleteItemOp,
getItemAccessLevel as getItemAccessLevelOp,
@@ -24,7 +25,6 @@ import {
permanentlyDelete as permanentlyDeleteOp,
renameItem as renameItemOp,
revertDelete as revertDeleteOp,
- togglePin as togglePinOp,
} from './itemOperations';
export const useItemOperations = createSingletonRoot(() => {
@@ -116,34 +116,6 @@ export const useItemOperations = createSingletonRoot(() => {
return id;
}
);
- const togglePin = createCallback(
- (args: { itemType: ItemType; id: string }) => {
- if (!args.id) return toast.failure('Unable to pin item');
- return togglePinOp(args);
- }
- );
-
- const bulkTogglePin = createCallback(async (items: Item[]) => {
- const pinnedIds = usePinnedIds();
- const wasPinned = pinnedIds().includes(items[0].id);
- const action = wasPinned ? 'unpin' : 'pin';
-
- const result = await toast.promise(bulkTogglePinOp(items), {
- loading: `${wasPinned ? 'Unpinning' : 'Pinning'} ${items.length} ${items.length === 1 ? 'item' : 'items'}...`,
- success: ({ failedItems }) => {
- if (failedItems.length > 0) {
- return `Failed to ${action} ${failedItems.length} ${failedItems.length === 1 ? 'item' : 'items'}`;
- }
- return `Successfully ${action}ned ${items.length} ${items.length === 1 ? 'item' : 'items'}`;
- },
- error: (error) =>
- `Failed to ${action} items: ${error.message || 'Unknown error'}`,
- toastTypeDeterminer: (result) =>
- result.failedItems.length > 0 ? ToastType.FAILURE : ToastType.SUCCESS,
- });
- return result;
- });
-
const bulkDelete = createCallback(async (items: Item[]) => {
const result = await toast.promise(bulkDeleteOp(items), {
loading: `Deleting ${items.length} ${items.length === 1 ? 'item' : 'items'}...`,
@@ -220,20 +192,17 @@ export const useItemOperations = createSingletonRoot(() => {
// If items have failed to permanently delete, we can't just refetch resources, because items delete so slowly everything that had been successfully deleted will reappear.
// So we need to undo our optimistic removal here.
if (result.failedItems.length > 0) {
- await refetchDeletedItems();
- const { deletedItems, mutate } = useDeletedItems();
- mutate(
- ok({
- items:
- deletedItems()?.filter((item) => {
- return (
- result.failedItems.some(
- (failedItem) => failedItem.id === item.id
- ) || !items.some((argItem) => argItem.id === item.id)
- );
- }) ?? [],
- })
- );
+ await invalidateDeletedItems();
+ const deletedItems = getDeletedItems();
+ setDeletedItems(() => ({
+ items: deletedItems.filter((item) => {
+ return (
+ result.failedItems.some(
+ (failedItem) => failedItem.id === item.id
+ ) || !items.some((argItem) => argItem.id === item.id)
+ );
+ }),
+ }));
}
return result;
@@ -281,8 +250,6 @@ export const useItemOperations = createSingletonRoot(() => {
deleteItem,
moveToFolder,
copyItem,
- togglePin,
- bulkTogglePin,
bulkDelete,
bulkCopy,
bulkMoveToFolder,
diff --git a/js/app/packages/core/component/ItemPreview.tsx b/js/app/packages/core/component/ItemPreview.tsx
index 1c5a762053..00edd6d142 100644
--- a/js/app/packages/core/component/ItemPreview.tsx
+++ b/js/app/packages/core/component/ItemPreview.tsx
@@ -20,7 +20,7 @@ import type { FileType } from '@service-storage/generated/schemas/fileType';
import {
insertProjectIntoHistory,
postNewHistoryItem,
-} from '@service-storage/history';
+} from '@queries/history/history';
import { Match, Switch } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { useSplitLayout } from '../../app/component/split-layout/layout';
diff --git a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
index a8fdd9443d..7bda248863 100644
--- a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
@@ -4,7 +4,7 @@ import { useChannelsContext } from '@core/context/channels';
import { itemToBlockName } from '@core/constant/allBlocks';
import { isOk } from '@core/util/maybeResult';
import { cognitionApiServiceClient } from '@service-cognition/client';
-import { useHistory } from '@service-storage/history';
+import { getHistoryItems } from '@queries/history/history';
import { validate as uuidValidate } from 'uuid';
export const jsonToXML = (tag: string, data: object) => {
@@ -12,8 +12,8 @@ export const jsonToXML = (tag: string, data: object) => {
};
const createDocumentMentionXML = (documentId: string) => {
- const history = useHistory();
- const item = history().find((item) => item.id === documentId);
+ const history = getHistoryItems();
+ const item = history.find((item) => item.id === documentId);
if (!item) {
if (import.meta.env.DEV) {
console.error('Could not find item', documentId);
@@ -34,8 +34,8 @@ const createDocumentMentionXML = (documentId: string) => {
};
const createChatMentionXML = (chatId: string) => {
- const chats = useHistory();
- const chat = chats().find((c) => c.id === chatId);
+ const chats = getHistoryItems();
+ const chat = chats.find((c) => c.id === chatId);
if (!chat) {
if (import.meta.env.DEV) {
console.error('Could not find chat', chatId);
@@ -78,8 +78,8 @@ const createChannelMentionXML = (channelId: string) => {
};
const createProjectMentionXML = (projectId: string) => {
- const projects = useHistory();
- const project = projects().find((p) => p.id === projectId);
+ const projects = getHistoryItems();
+ const project = projects.find((p) => p.id === projectId);
if (!project) {
if (import.meta.env.DEV) {
console.error('Could not find project', projectId);
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/userPrompt/userPromptPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/userPrompt/userPromptPlugin.ts
index 4b5237259c..26d0a45441 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/userPrompt/userPromptPlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/userPrompt/userPromptPlugin.ts
@@ -1,6 +1,6 @@
import { $convertToMarkdownString } from '@lexical/markdown';
import { ALL_TRANSFORMERS } from '@lexical-core';
-import { useUpdateInstructionsMdTextCache } from '@service-storage/instructionsMd';
+import { useUpdateInstructionsMdTextCache } from '@queries/storage/instructions-md';
import { debounce } from '@solid-primitives/scheduled';
import { $getRoot, type LexicalEditor, type UpdateListener } from 'lexical';
diff --git a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
index 37a0bb777d..7b59cf98b8 100644
--- a/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
+++ b/js/app/packages/core/component/Properties/component/modal/shared/PropertyEntitySelector.tsx
@@ -21,7 +21,7 @@ import {
} from '@macro-entity';
import { useUserId } from '@core/context/user';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import { debounce } from '@solid-primitives/scheduled';
import {
createEffect,
@@ -152,7 +152,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
const blockId = useMaybeBlockId();
const { entityType: currentEntityType } = usePropertiesContext();
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
const contacts = useContacts();
const channelsContext = useChannelsContext();
const channels = channelsContext.channels;
@@ -241,7 +241,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
if (!specificEntityType) {
return [
...contactsWithCurrentUser().map(entityMapper('user')),
- ...history().map(entityMapper('item')),
+ ...(historyQuery.data ?? []).map(entityMapper('item')),
...channels().map(entityMapper('channel')),
...emails().map(threadMapper),
];
@@ -265,7 +265,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
}
if (specificEntityType === 'TASK') {
- return history()
+ return (historyQuery.data ?? [])
.filter(
(item) =>
item.type === 'document' &&
@@ -278,7 +278,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
const itemTypes: EntityType[] = ['DOCUMENT', 'PROJECT', 'CHAT'];
if (itemTypes.includes(specificEntityType)) {
- return history()
+ return (historyQuery.data ?? [])
.filter(
(item) =>
item.type.toUpperCase() === specificEntityType &&
diff --git a/js/app/packages/core/internal/DataDebug.tsx b/js/app/packages/core/internal/DataDebug.tsx
index 517214af65..a1ce49d234 100644
--- a/js/app/packages/core/internal/DataDebug.tsx
+++ b/js/app/packages/core/internal/DataDebug.tsx
@@ -3,7 +3,7 @@ import { Bar } from '@core/component/TopBar/Bar';
import { useContacts } from '@core/user';
import Refresh from '@phosphor-icons/core/regular/arrow-clockwise.svg?component-solid';
import Copy from '@phosphor-icons/core/regular/copy.svg?component-solid';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import { type Component, createSignal, For, type JSX, Show } from 'solid-js';
interface SignalDebugCardProps {
@@ -71,7 +71,7 @@ function SignalDebugCard(props: SignalDebugCardProps) {
const DataDebug: Component = () => {
const contacts = useContacts();
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
const [_, setRefreshKey] = createSignal(0);
@@ -110,8 +110,8 @@ const DataDebug: Component = () => {
/>
<SignalDebugCard
- title="useHistory()"
- data={history()}
+ title="useHistoryQuery()"
+ data={historyQuery.data ?? []}
renderItem={(item) => (
<div class="bg-surface-secondary p-2 rounded text-sm">
<div class="font-medium">{item.name}</div>
diff --git a/js/app/packages/core/util/create.ts b/js/app/packages/core/util/create.ts
index 70c642bceb..385ca48966 100644
--- a/js/app/packages/core/util/create.ts
+++ b/js/app/packages/core/util/create.ts
@@ -3,13 +3,13 @@ import { MARKDOWN_LORO_SCHEMA } from '@block-md/definition';
import { rawStateToLoroSnapshot } from '@core/collab/utils';
import { createMarkdownStateFromContent } from '@core/component/LexicalMarkdown/collaboration/utils';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
-import { invalidateUserQuota } from '@service-auth/userQuota';
+import { invalidateUserQuota } from '@queries/auth';
import { cognitionApiServiceClient } from '@service-cognition/client';
import type { CreateChatRequest } from '@service-cognition/generated/schemas';
import { staticFileClient } from '@service-static-files/client';
import { storageServiceClient } from '@service-storage/client';
import type { PropertyInput } from '@service-storage/generated/schemas/propertyInput';
-import { postNewHistoryItem } from '@service-storage/history';
+import { postNewHistoryItem } from '@queries/history/history';
import { uploadToPresignedUrl } from '@service-storage/util/uploadToPresignedUrl';
import { syncServiceClient } from '@service-sync/client';
import { contentHash } from './hash';
diff --git a/js/app/packages/core/util/currentBlockDocumentName.ts b/js/app/packages/core/util/currentBlockDocumentName.ts
index f4729f4fb2..b9916fdd21 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 '@service-storage/history';
+import { useUpdatedDssItemName } from '@queries/history/history';
import { formatDocumentName } from '@service-storage/util/filename';
import { createMemo } from 'solid-js';
diff --git a/js/app/packages/core/util/md.ts b/js/app/packages/core/util/md.ts
index 6678198b12..3d60395d9e 100644
--- a/js/app/packages/core/util/md.ts
+++ b/js/app/packages/core/util/md.ts
@@ -1,7 +1,7 @@
import { createLexicalWrapper } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
import { setEditorStateFromMarkdown } from '@core/component/LexicalMarkdown/utils';
import { storageServiceClient } from '@service-storage/client';
-import { postNewHistoryItem } from '@service-storage/history';
+import { postNewHistoryItem } from '@queries/history/history';
import { uploadToPresignedUrl } from '@service-storage/util/uploadToPresignedUrl';
import { contentHash } from './hash';
import { isErr } from './maybeResult';
diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.ts
index 295938d16f..4ac7a5230e 100644
--- a/js/app/packages/macro-entity/src/queries/dss.ts
+++ b/js/app/packages/macro-entity/src/queries/dss.ts
@@ -18,7 +18,7 @@ import type {
} from '@service-storage/generated/schemas';
import type { GetItemsSoupParams } from '@service-storage/generated/schemas/getItemsSoupParams';
import type { SoupPage } from '@service-storage/generated/schemas/soupPage';
-import { useInstructionsMdIdQuery } from '@service-storage/instructionsMd';
+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import {
hashKey,
type InfiniteData,
diff --git a/js/app/packages/macro-entity/src/queries/search.ts b/js/app/packages/macro-entity/src/queries/search.ts
index 4ebc8a8ae0..df5a5fe52d 100644
--- a/js/app/packages/macro-entity/src/queries/search.ts
+++ b/js/app/packages/macro-entity/src/queries/search.ts
@@ -19,7 +19,7 @@ import type {
ProjectSearchResult,
UnifiedSearchResponseItem,
} from '@service-search/generated/models';
-import { useHistory } from '@service-storage/history';
+import { useHistoryQuery } from '@queries/history/history';
import { useInfiniteQuery } from '@tanstack/solid-query';
import { type Accessor, createMemo } from 'solid-js';
import type { EntityData } from '../types/entity';
@@ -164,7 +164,7 @@ const useMapSearchResponseItem = () => {
const channelsContext = useChannelsContext();
const channels = channelsContext.channels;
- const history = useHistory();
+ const historyQuery = useHistoryQuery();
return (
result: UnifiedSearchResponseItem,
@@ -266,7 +266,9 @@ const useMapSearchResponseItem = () => {
});
let name = result.name;
if (!name || name === blockNameToDefaultFile('chat')) {
- const chat = history().find((item) => item.id === result.chat_id);
+ const chat = (historyQuery.data ?? []).find(
+ (item) => item.id === result.chat_id
+ );
if (chat) {
name = chat.name;
}
diff --git a/js/app/packages/queries/auth/index.ts b/js/app/packages/queries/auth/index.ts
index 0e2b2f508c..f977842435 100644
--- a/js/app/packages/queries/auth/index.ts
+++ b/js/app/packages/queries/auth/index.ts
@@ -30,3 +30,9 @@ export {
useCompleteOnboardingMutation,
useSetGroupMutation,
} from './mutations';
+export {
+ useUserQuotaQuery,
+ invalidateUserQuota,
+ useInvalidateUserQuota,
+ useUpdateUserQuotaCache,
+} from './user-quota';
diff --git a/js/app/packages/queries/auth/keys.ts b/js/app/packages/queries/auth/keys.ts
index 8e6e262358..718d38bf9c 100644
--- a/js/app/packages/queries/auth/keys.ts
+++ b/js/app/packages/queries/auth/keys.ts
@@ -3,4 +3,5 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';
export const authKeys = createQueryKeys('auth', {
userInfo: null,
organization: null,
+ userQuota: null,
});
diff --git a/js/app/packages/service-clients/service-auth/userQuota.ts b/js/app/packages/queries/auth/user-quota.ts
similarity index 65%
rename from js/app/packages/service-clients/service-auth/userQuota.ts
rename to js/app/packages/queries/auth/user-quota.ts
index 0a38fe6226..028ead7f4d 100644
--- a/js/app/packages/service-clients/service-auth/userQuota.ts
+++ b/js/app/packages/queries/auth/user-quota.ts
@@ -1,9 +1,11 @@
import { isOk } from '@core/util/maybeResult';
-import { QueryClient, useQuery } from '@tanstack/solid-query';
-import { authServiceClient } from './client';
-import type { UserQuota } from './generated/schemas';
+import { authServiceClient } from '@service-auth/client';
+import type { UserQuota } from '@service-auth/generated/schemas';
+import { useQuery } from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { authKeys } from './keys';
-const queryClient = new QueryClient();
+const USER_QUOTA_STALE_TIME = 1000 * 60 * 5; // 5 minutes
/**
* Fetches the user's quota information.
@@ -23,23 +25,23 @@ const getUserQuota = async (): Promise<UserQuota> => {
throw new Error(`Failed to get user quota: ${code} - ${message}`);
};
+function userQuotaQueryOptions() {
+ return {
+ queryKey: authKeys.userQuota.queryKey,
+ queryFn: getUserQuota,
+ staleTime: USER_QUOTA_STALE_TIME,
+ throwOnError: false,
+ retry: 1,
+ retryOnMount: false,
+ };
+}
+
/**
* useQuery hook for retrieving the user's quota information.
* Returns the current quota including documents, AI chat messages, and their limits.
*/
export function useUserQuotaQuery() {
- const query = useQuery(
- () => ({
- queryKey: ['userQuota'],
- queryFn: getUserQuota,
- staleTime: 1000 * 60 * 5, // 5 minutes
- throwOnError: false,
- retry: 1,
- retryOnMount: false,
- }),
- () => queryClient
- );
- return query;
+ return useQuery(() => userQuotaQueryOptions());
}
/**
@@ -47,7 +49,9 @@ export function useUserQuotaQuery() {
* Useful for refreshing quota data after mutations that might affect it (e.g., sending AI chat messages).
*/
export function invalidateUserQuota() {
- queryClient.invalidateQueries({ queryKey: ['userQuota'] });
+ return queryClient.invalidateQueries({
+ queryKey: authKeys.userQuota.queryKey,
+ });
}
/**
@@ -64,6 +68,6 @@ export function useInvalidateUserQuota() {
*/
export function useUpdateUserQuotaCache() {
return (quota: UserQuota) => {
- queryClient.setQueryData(['userQuota'], quota);
+ queryClient.setQueryData(authKeys.userQuota.queryKey, quota);
};
}
diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.ts
index e2e04b9e6f..4460e7609b 100644
--- a/js/app/packages/queries/history/history.ts
+++ b/js/app/packages/queries/history/history.ts
@@ -1,13 +1,14 @@
-import { throwOnErr, catchToResult } from '@core/util/maybeResult';
+import { isOk, throwOnErr, catchToResult } 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 { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import {
type UseQueryResult,
useMutation,
useQuery,
} from '@tanstack/solid-query';
+import { type Accessor, createMemo } from 'solid-js';
import { queryClient } from '../client';
import { historyKeys } from './keys';
import {
@@ -81,9 +82,22 @@ export function optimisticUpdateViewedAt(itemId: string) {
historyKeys.list.queryKey,
(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: updateItemViewedAt(old.data, itemId, now),
+ data: newData,
};
}
);
@@ -255,3 +269,146 @@ export function useUpsertToHistoryMutation(
),
}));
}
+
+/**
+ * Standalone function to add an item to history.
+ * Prefer `useUpsertToHistoryMutation` when inside a component.
+ */
+export async function postNewHistoryItem(
+ itemType: CloudStorageItemType,
+ itemId: string
+): Promise<boolean> {
+ const maybeAdded = await storageServiceClient.upsertItemToUserHistory({
+ itemId,
+ itemType,
+ });
+
+ await refetchHistory();
+
+ return isOk(maybeAdded) && !!maybeAdded[1].success;
+}
+
+/**
+ * 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),
+ };
+ }
+ );
+
+ const maybeRemoved = await storageServiceClient.removeItemFromUserHistory({
+ itemId,
+ itemType,
+ });
+
+ await refetchHistory();
+
+ return isOk(maybeRemoved) && !!maybeRemoved[1].success;
+}
+
+/**
+ * Hook to get the updated name of a DSS item from history.
+ */
+export function useUpdatedDssItemName(itemId: string | Accessor<string>) {
+ const historyQuery = useHistoryQuery();
+
+ return createMemo(() => {
+ 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;
+ });
+}
+
+/**
+ * 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
+ );
+ if (!data) return [];
+ return transformHistoryResponse(data, null);
+}
+
+/**
+ * Alias for refetchHistory for backward compatibility.
+ */
+export const invalidateHistory = refetchHistory;
+
+/**
+ * Inserts a project and its nested items into history.
+ * 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 ids = [projectId];
+
+ storageServiceClient.upsertItemToUserHistory({
+ itemId: projectId,
+ itemType: 'project',
+ });
+
+ while (ids.length > 0) {
+ const id = ids.shift();
+ if (!id) continue;
+
+ const projectContent = await storageServiceClient.projects.getContent({
+ id,
+ });
+ if (isOk(projectContent)) {
+ ids.push(
+ ...projectContent[1].data.reduce<string[]>((acc, { item }) => {
+ if (
+ item.type === 'project' &&
+ !prevData.some(({ id }) => id === item.id)
+ ) {
+ acc.push(item.id);
+ }
+ return acc;
+ }, [])
+ );
+ newData.push(...projectContent[1].data.map(({ item }) => item));
+ }
+ }
+
+ queryClient.setQueryData<HistoryQueryResponse>(
+ historyKeys.list.queryKey,
+ (old) => {
+ if (!old) return old;
+ return {
+ ...old,
+ data: [...old.data, ...newData],
+ };
+ }
+ );
+
+ const upsertResults = newData
+ .filter((item) => !prevData.some(({ id }) => id === item.id))
+ .map(({ id, type }) =>
+ storageServiceClient.upsertItemToUserHistory({
+ itemId: id,
+ itemType: type,
+ })
+ );
+ await Promise.all(upsertResults);
+ await refetchHistory();
+}
diff --git a/js/app/packages/queries/storage/deleted.ts b/js/app/packages/queries/storage/deleted.ts
new file mode 100644
index 0000000000..800813246d
--- /dev/null
+++ b/js/app/packages/queries/storage/deleted.ts
@@ -0,0 +1,120 @@
+import { buildFileTree } from '@core/component/FileList/buildFileTree';
+import { itemToSafeName } from '@core/constant/allBlocks';
+import { isOk } from '@core/util/maybeResult';
+import { storageServiceClient } from '@service-storage/client';
+import type { Item } from '@service-storage/generated/schemas/item';
+import { useQuery } from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { storageKeys } from './keys';
+
+const DELETED_STALE_TIME = 5 * 60 * 1000;
+const DELETED_GC_TIME = 10 * 60 * 1000;
+
+type DeletedItemsQueryResponse = {
+ items: Item[];
+};
+
+async function fetchDeletedItems(): Promise<DeletedItemsQueryResponse> {
+ const result = await storageServiceClient.getDeletedItems();
+ if (isOk(result)) {
+ return result[1];
+ }
+ return { items: [] };
+}
+
+function deletedItemsQueryOptions() {
+ return {
+ queryKey: storageKeys.deleted.list.queryKey,
+ queryFn: fetchDeletedItems,
+ staleTime: DELETED_STALE_TIME,
+ gcTime: DELETED_GC_TIME,
+ };
+}
+
+function transformItems(items: Item[]): Item[] {
+ return items.map((item) => ({ ...item, name: itemToSafeName(item) }));
+}
+
+export function useDeletedItemsQuery() {
+ return useQuery(() => ({
+ ...deletedItemsQueryOptions(),
+ placeholderData: (prev) => prev,
+ select: (data: DeletedItemsQueryResponse): Item[] =>
+ transformItems(data.items),
+ }));
+}
+
+type FileTree = ReturnType<typeof buildFileTree>;
+
+export function useDeletedTreeQuery() {
+ return useQuery(() => ({
+ ...deletedItemsQueryOptions(),
+ placeholderData: (prev) => prev,
+ select: (data: DeletedItemsQueryResponse): FileTree =>
+ buildFileTree(transformItems(data.items)),
+ }));
+}
+
+export function invalidateDeletedItems() {
+ return queryClient.invalidateQueries({
+ queryKey: storageKeys.deleted.list.queryKey,
+ });
+}
+
+/**
+ * Get the current deleted items from the query cache.
+ * For use in standalone functions outside component context.
+ */
+export function getDeletedItems(): Item[] {
+ const data = queryClient.getQueryData<DeletedItemsQueryResponse>(
+ storageKeys.deleted.list.queryKey
+ );
+ return data ? transformItems(data.items) : [];
+}
+
+/**
+ * Get the deleted tree from the query cache.
+ * For use in standalone functions outside component context.
+ */
+export function getDeletedTree(): FileTree {
+ const data = queryClient.getQueryData<DeletedItemsQueryResponse>(
+ storageKeys.deleted.list.queryKey
+ );
+ return data
+ ? buildFileTree(transformItems(data.items))
+ : { rootItems: [], itemMap: {} };
+}
+
+/**
+ * Optimistically remove an item from the deleted items cache.
+ */
+export function optimisticallyRemoveDeletedItem(itemId: string): boolean {
+ const data = queryClient.getQueryData<DeletedItemsQueryResponse>(
+ storageKeys.deleted.list.queryKey
+ );
+ if (!data) return false;
+
+ queryClient.setQueryData<DeletedItemsQueryResponse>(
+ storageKeys.deleted.list.queryKey,
+ {
+ items: data.items.filter((item) => item.id !== itemId),
+ }
+ );
+
+ return true;
+}
+
+/**
+ * Set the deleted items in the cache.
+ * Used for optimistic updates.
+ */
+export function setDeletedItems(
+ updater: (
+ old: DeletedItemsQueryResponse | undefined
+ ) => DeletedItemsQueryResponse
+) {
+ queryClient.setQueryData<DeletedItemsQueryResponse>(
+ storageKeys.deleted.list.queryKey,
+ updater
+ );
+}
diff --git a/js/app/packages/service-clients/service-storage/instructionsMd.ts b/js/app/packages/queries/storage/instructions-md.ts
similarity index 65%
rename from js/app/packages/service-clients/service-storage/instructionsMd.ts
rename to js/app/packages/queries/storage/instructions-md.ts
index a69d5b4ff3..430f159223 100644
--- a/js/app/packages/service-clients/service-storage/instructionsMd.ts
+++ b/js/app/packages/queries/storage/instructions-md.ts
@@ -7,17 +7,17 @@ import {
initializeEditorWithState,
} from '@core/component/LexicalMarkdown/utils';
import { isOk } from '@core/util/maybeResult';
-import { QueryClient, useQuery } from '@tanstack/solid-query';
-import { syncServiceClient } from '../service-sync/client';
-import { storageServiceClient } from './client';
+import { storageServiceClient } from '@service-storage/client';
+import { syncServiceClient } from '@service-sync/client';
+import { useQuery } from '@tanstack/solid-query';
+import { queryClient } from '../client';
+import { instructionsMdKeys } from './keys';
export { default as AiInstructionsIcon } from '@icon/regular/notepad.svg';
-const queryClient = new QueryClient();
-
/**
- * Returns the instructions md document id for the current user.
- * Returns null if not yet created, throws otherwise.
+ * Returns the instructions md document id for the current user.
+ * Returns null if not yet created, throws otherwise.
*/
const getInstructionsMdId = async (): Promise<string | null | undefined> => {
const getResult = await storageServiceClient.instructions.get();
@@ -37,33 +37,24 @@ const getInstructionsMdId = async (): Promise<string | null | undefined> => {
throw new Error('Error getting instructionsMdId');
};
-/** Creates the instructions md document. Backend prevents duplicates */
-export const useCreateInstructionsMd = () => {
- return async () => {
- const emptyMarkdownState = await createMarkdownStateFromContent(undefined);
- const snapshot = await rawStateToLoroSnapshot(
- MARKDOWN_LORO_SCHEMA,
- emptyMarkdownState as any
- );
- if (!snapshot) return;
- const createResult = await storageServiceClient.instructions.create();
- if (isOk(createResult)) {
- const [, { documentId }] = createResult;
- let res = await syncServiceClient.initializeFromSnapshot({
- snapshot,
- documentId: documentId,
- });
- if (!isOk(res)) {
- console.error(
- 'Failed to initialize instructions document from snapshot'
- );
- return;
- }
- queryClient.setQueryData(['instructionsMdId'], documentId);
- return documentId;
- }
+function instructionsMdIdQueryOptions() {
+ return {
+ queryKey: instructionsMdKeys.id.queryKey,
+ queryFn: getInstructionsMdId,
+ staleTime: Infinity,
+ throwOnError: false,
+ retry: false,
+ retryOnMount: false,
};
-};
+}
+
+/**
+ * useQuery hook for retrieving the instructions md document id.
+ * Returns null if not yet created, throws otherwise.
+ */
+export function useInstructionsMdIdQuery() {
+ return useQuery(() => instructionsMdIdQueryOptions());
+}
const getInstructionsMdText = async (id: string | null | undefined) => {
if (!id) {
@@ -74,9 +65,7 @@ const getInstructionsMdText = async (id: string | null | undefined) => {
documentId: id,
});
- // Create lexical editor with raw JSON state
const { editor } = createLexicalWrapper({
- // this should be plain-text but there might be edge cases so we don't want to throw
type: 'markdown',
namespace: 'instructions-md-text-extractor',
isInteractable: () => false,
@@ -89,42 +78,54 @@ const getInstructionsMdText = async (id: string | null | undefined) => {
return plaintext;
};
-/** useQuery hook for retrieving the instructions md document id
- * returns null if not yet created, throws otherwise.
- */
-export function useInstructionsMdIdQuery() {
- const query = useQuery(
- () => ({
- queryKey: ['instructionsMdId'],
- queryFn: getInstructionsMdId,
- staleTime: Infinity,
- throwOnError: false,
- retry: false,
- retryOnMount: false,
- }),
- () => queryClient
- );
- return query;
-}
-
/** useQuery hook for retrieving the instructions md document text content */
export function useInstructionsMdTextQuery() {
const idQuery = useInstructionsMdIdQuery();
- const query = useQuery(
- () => ({
- queryKey: ['instructionsMdText', idQuery.data],
- queryFn: () => getInstructionsMdText(idQuery.data),
- enabled: idQuery.isSuccess && !!idQuery.data,
+ return useQuery(() => {
+ const id = idQuery.data;
+ return {
+ // Use a placeholder key when id is null/undefined - query is disabled anyway
+ queryKey: id
+ ? instructionsMdKeys.text(id).queryKey
+ : ['instructionsMd', 'text', null],
+ queryFn: () => getInstructionsMdText(id),
+ enabled: idQuery.isSuccess && !!id,
staleTime: Infinity,
throwOnError: false,
retry: false,
retryOnMount: false,
- }),
- () => queryClient
- );
+ };
+ });
+}
- return query;
+/** Creates the instructions md document. Backend prevents duplicates */
+export function useCreateInstructionsMd() {
+ return async () => {
+ const emptyMarkdownState = await createMarkdownStateFromContent(undefined);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const snapshot = await rawStateToLoroSnapshot(
+ MARKDOWN_LORO_SCHEMA,
+ emptyMarkdownState as any
+ );
+ if (!snapshot) return;
+ const createResult = await storageServiceClient.instructions.create();
+ if (isOk(createResult)) {
+ const [, { documentId }] = createResult;
+ const res = await syncServiceClient.initializeFromSnapshot({
+ snapshot,
+ documentId: documentId,
+ });
+ if (!isOk(res)) {
+ console.error(
+ 'Failed to initialize instructions document from snapshot'
+ );
+ return;
+ }
+ queryClient.setQueryData(instructionsMdKeys.id.queryKey, documentId);
+ return documentId;
+ }
+ };
}
/** Hook to get a function that updates the instructions text in the query cache */
@@ -134,7 +135,7 @@ export function useUpdateInstructionsMdTextCache() {
return (text: string) => {
const id = idQuery.data;
if (id) {
- queryClient.setQueryData(['instructionsMdText', id], text);
+ queryClient.setQueryData(instructionsMdKeys.text(id).queryKey, text);
}
};
}
diff --git a/js/app/packages/queries/storage/keys.ts b/js/app/packages/queries/storage/keys.ts
new file mode 100644
index 0000000000..54fb63f145
--- /dev/null
+++ b/js/app/packages/queries/storage/keys.ts
@@ -0,0 +1,24 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const projectsKeys = createQueryKeys('projects', {
+ list: null,
+});
+
+export const deletedKeys = createQueryKeys('deleted', {
+ list: null,
+});
+
+export const instructionsMdKeys = createQueryKeys('instructionsMd', {
+ id: null,
+ text: (id: string) => ({
+ queryKey: [id],
+ }),
+});
+
+/**
+ * @deprecated Use `projectsKeys` or `deletedKeys` directly
+ */
+export const storageKeys = {
+ projects: projectsKeys,
+ deleted: deletedKeys,
+};
diff --git a/js/app/packages/queries/storage/projects.ts b/js/app/packages/queries/storage/projects.ts
new file mode 100644
index 0000000000..a5fd2be917
--- /dev/null
+++ b/js/app/packages/queries/storage/projects.ts
@@ -0,0 +1,213 @@
+import { ENABLE_PROJECT_SHARING } from '@core/constant/featureFlags';
+import { useUserId } from '@core/context/user';
+import { isOk } from '@core/util/maybeResult';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import { storageServiceClient } from '@service-storage/client';
+import type { Project } from '@service-storage/generated/schemas/project';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import { v4 as uuidv4 } from 'uuid';
+import { queryClient } from '../client';
+import { storageKeys } from './keys';
+import {
+ useUpsertToHistoryMutation,
+ refetchHistory,
+} from '@queries/history/history';
+
+const PROJECTS_STALE_TIME = 5 * 60 * 1000;
+const PROJECTS_GC_TIME = 10 * 60 * 1000;
+
+type ProjectsQueryResponse = {
+ projects: Project[];
+ pending: Project[];
+};
+
+async function fetchProjects(): Promise<ProjectsQueryResponse> {
+ const [projectsResult, pendingResult] = await Promise.all([
+ storageServiceClient.projects.getAll(),
+ storageServiceClient.projects.getPending(),
+ ]);
+
+ const projects = isOk(projectsResult) ? projectsResult[1].data : [];
+ const pending = isOk(pendingResult) ? pendingResult[1].data : [];
+
+ return { projects, pending };
+}
+
+function projectsQueryOptions() {
+ return {
+ queryKey: storageKeys.projects.list.queryKey,
+ queryFn: fetchProjects,
+ staleTime: PROJECTS_STALE_TIME,
+ gcTime: PROJECTS_GC_TIME,
+ };
+}
+
+function sortProjects(projects: Project[]): Project[] {
+ return [...projects].sort((a, b) => b.createdAt - a.createdAt);
+}
+
+function filterByUserId(
+ projects: Project[],
+ userId: string | undefined
+): Project[] {
+ if (!userId) return projects;
+ return projects.filter((project) => project.userId === userId);
+}
+
+export function useProjectsQuery() {
+ const userId = useUserId();
+
+ return useQuery(() => ({
+ ...projectsQueryOptions(),
+ placeholderData: (prev) => prev,
+ select: (data: ProjectsQueryResponse): Project[] => {
+ const allProjects = [...data.projects, ...data.pending];
+ const sorted = sortProjects(allProjects);
+
+ if (!ENABLE_PROJECT_SHARING) {
+ return filterByUserId(sorted, userId());
+ }
+
+ return sorted;
+ },
+ }));
+}
+
+export function invalidateProjects() {
+ return queryClient.invalidateQueries({
+ queryKey: storageKeys.projects.list.queryKey,
+ });
+}
+
+/**
+ * Standalone function for creating projects that can be used outside of component context.
+ * Prefer `useCreateProjectMutation` when inside a component.
+ */
+export async function createProject(params: {
+ name: string;
+ parentId?: string;
+ sharePermission?: null;
+}): Promise<string | undefined> {
+ const maybeResult = await storageServiceClient.projects.create({
+ name: params.name,
+ projectParentId: params.parentId,
+ sharePermission: params.sharePermission,
+ });
+
+ if (isOk(maybeResult)) {
+ const projectId = maybeResult[1].id;
+ await storageServiceClient.upsertItemToUserHistory({
+ itemId: projectId,
+ itemType: 'project',
+ });
+ await Promise.all([invalidateProjects(), refetchHistory()]);
+ return projectId;
+ }
+
+ return undefined;
+}
+
+type CreateProjectParams = {
+ name: string;
+ parentId?: string;
+ sharePermission?: null;
+};
+
+type CreateProjectContext = {
+ previousData: ProjectsQueryResponse | undefined;
+ tempProjectId: string;
+};
+
+export function useCreateProjectMutation(
+ callbacks?: MutationCallbacks<
+ string | undefined,
+ Error,
+ CreateProjectParams,
+ CreateProjectContext
+ >
+) {
+ const upsertToHistoryMutation = useUpsertToHistoryMutation();
+
+ return useMutation(() => ({
+ mutationFn: async (
+ params: CreateProjectParams
+ ): Promise<string | undefined> => {
+ const maybeResult = await storageServiceClient.projects.create({
+ name: params.name,
+ projectParentId: params.parentId,
+ sharePermission: params.sharePermission,
+ });
+
+ if (isOk(maybeResult)) {
+ return maybeResult[1].id;
+ }
+ return undefined;
+ },
+ ...withCallbacks<
+ string | undefined,
+ Error,
+ CreateProjectParams,
+ CreateProjectContext
+ >(
+ {
+ onMutate: async (params) => {
+ await queryClient.cancelQueries({
+ queryKey: storageKeys.projects.list.queryKey,
+ });
+
+ const previousData = queryClient.getQueryData<ProjectsQueryResponse>(
+ storageKeys.projects.list.queryKey
+ );
+
+ const tempProjectId = uuidv4();
+ const tempProject: Project = {
+ createdAt: Date.now(),
+ id: tempProjectId,
+ name: params.name,
+ parentId: params.parentId,
+ type: 'project',
+ userId: '',
+ updatedAt: Date.now(),
+ deletedAt: null,
+ };
+
+ queryClient.setQueryData<ProjectsQueryResponse>(
+ storageKeys.projects.list.queryKey,
+ (old) => {
+ if (!old) return { projects: [tempProject], pending: [] };
+ return {
+ ...old,
+ projects: [tempProject, ...old.projects],
+ };
+ }
+ );
+
+ return { previousData, tempProjectId };
+ },
+ onSuccess: (projectId, _params, _context) => {
+ if (projectId) {
+ upsertToHistoryMutation.mutate({
+ itemId: projectId,
+ itemType: 'project',
+ });
+ }
+ },
+ onError: (_err, _params, context) => {
+ if (context?.previousData) {
+ queryClient.setQueryData(
+ storageKeys.projects.list.queryKey,
+ context.previousData
+ );
+ }
+ },
+ onSettled: () => {
+ queryClient.invalidateQueries({
+ queryKey: storageKeys.projects.list.queryKey,
+ });
+ refetchHistory();
+ },
+ },
+ callbacks
+ ),
+ }));
+}
diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.ts
index 8e1cb528fe..604ede0448 100644
--- a/js/app/packages/service-clients/service-auth/client.ts
+++ b/js/app/packages/service-clients/service-auth/client.ts
@@ -1,6 +1,5 @@
import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';
import { SERVER_HOSTS } from '@core/constant/servers';
-import { cache } from '@core/util/cache';
import { fetchWithToken } from '@core/util/fetchWithToken';
import {
isOk,
@@ -132,24 +131,19 @@ export const authServiceClient = {
(result) => result
);
},
- getUserInfo: cache(
- async function getUserInfo() {
- return mapOk(
- await fetchWithAuth<Partial<GetUserInfo>>(`${authHost}/user/me`, {
- method: 'GET',
- }),
- (data) => ({
- authenticated: !!data.user_id,
- permissions: data.permissions || [],
- userId: data.user_id,
- organizationId: data.organization_id ?? undefined,
- })
- );
- },
- {
- minutes: 15,
- }
- ),
+ async getUserInfo() {
+ return mapOk(
+ await fetchWithAuth<Partial<GetUserInfo>>(`${authHost}/user/me`, {
+ method: 'GET',
+ }),
+ (data) => ({
+ authenticated: !!data.user_id,
+ permissions: data.permissions || [],
+ userId: data.user_id,
+ organizationId: data.organization_id ?? undefined,
+ })
+ );
+ },
async sessionLogin(args: { session_code: string }) {
const maybeResult = await authApiFetch<UserTokensResponse>(
`/session/login/${args.session_code}`
diff --git a/js/app/packages/service-clients/service-notification/unsubscribe.ts b/js/app/packages/service-clients/service-notification/unsubscribe.ts
deleted file mode 100644
index 91c94e5279..0000000000
--- a/js/app/packages/service-clients/service-notification/unsubscribe.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { ok } from '@core/util/maybeResult';
-import { createSingletonRoot } from '@solid-primitives/rootless';
-import { createResource } from 'solid-js';
-import { notificationServiceClient } from './client';
-
-const _unsubscribeResource = createSingletonRoot(() =>
- createResource(notificationServiceClient.getUnsubscribes, {
- initialValue: ok({ data: [] }),
- })
-);
diff --git a/js/app/packages/service-clients/service-storage/deleted.ts b/js/app/packages/service-clients/service-storage/deleted.ts
deleted file mode 100644
index d1977eb581..0000000000
--- a/js/app/packages/service-clients/service-storage/deleted.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { buildFileTree } from '@core/component/FileList/buildFileTree';
-import { itemToSafeName } from '@core/constant/allBlocks';
-import { isErr, isOk, ok } from '@core/util/maybeResult';
-import { createSingletonRoot } from '@solid-primitives/rootless';
-import { createMemo, createResource } from 'solid-js';
-import { storageServiceClient } from './client';
-import type { Item } from './generated/schemas/item';
-
-const deletedResource = createSingletonRoot(() =>
- createResource(storageServiceClient.getDeletedItems, {
- initialValue: ok({ items: [] }),
- })
-);
-
-export async function refetchDeletedItems(force = false) {
- const [resource, { refetch }] = deletedResource();
- if (force) return refetch();
- if (resource.loading) return resource.latest;
-
- return refetch();
-}
-
-export const useDeletedItems = createSingletonRoot(() => {
- const [resource, { mutate }] = deletedResource();
- const deletedItems = createMemo(() => {
- const result = resource.latest;
- if (isOk(result)) {
- return result[1].items.map((item) => ({
- ...item,
- name: itemToSafeName(item),
- })) as Item[];
- }
- });
-
- return {
- deletedItems,
- mutate,
- };
-});
-
-export const useDeletedTree = createSingletonRoot(() => {
- const [resource] = deletedResource();
- return createMemo(() => {
- const result = resource.latest;
-
- if (isOk(result)) {
- const items = result[1].items.map((item) => ({
- ...item,
- name: itemToSafeName(item),
- }));
- return buildFileTree(items);
- }
-
- return {
- rootItems: [],
- itemMap: {},
- };
- });
-});
-
-export async function optimisticallyRemoveDeletedItem(itemId: string) {
- const [resource, { mutate }] = deletedResource();
- const result = resource.latest;
- if (resource.error || isErr(result)) return false;
-
- // Optimistically remove the item
- mutate(
- ok({
- items: result[1].items.filter((item) => item.id !== itemId),
- })
- );
- return true;
-}
diff --git a/js/app/packages/service-clients/service-storage/history.ts b/js/app/packages/service-clients/service-storage/history.ts
deleted file mode 100644
index bbde737ffa..0000000000
--- a/js/app/packages/service-clients/service-storage/history.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-import { itemToSafeName } from '@core/constant/allBlocks';
-import { isErr, isOk, ok } from '@core/util/maybeResult';
-import type { HistoryItem } from '@queries/history/transforms';
-import { createSingletonRoot } from '@solid-primitives/rootless';
-import { buildFileTree } from 'core/component/FileList/buildFileTree';
-import { type Accessor, createMemo, createResource } from 'solid-js';
-import { storageServiceClient } from './client';
-import type { CloudStorageItemType } from './generated/schemas/cloudStorageItemType';
-import type { Item } from './generated/schemas/item';
-import { useInstructionsMdIdQuery } from './instructionsMd';
-import { refetchResources } from './util/refetchResources';
-
-const historyResource = createSingletonRoot(() => {
- return createResource(storageServiceClient.getUsersHistory, {
- initialValue: ok({ data: [] }),
- });
-});
-
-// this is a helper to filter out the instructions document from the history
-const useFilteredHistory = createSingletonRoot(() => {
- const [resource] = historyResource();
- const instructionsMdIdQuery = useInstructionsMdIdQuery();
-
- return createMemo(() => {
- const result = resource();
-
- if (isOk(result)) {
- const [, history] = result;
- const data = history.data.filter(
- (item) => item.id !== instructionsMdIdQuery.data
- );
- return ok({ data });
- }
-
- return result;
- });
-});
-
-export const useHistoryTree = createSingletonRoot(() => {
- const history = useFilteredHistory();
-
- return createMemo(() => {
- const result = history();
-
- if (isOk(result)) {
- const items = result[1].data.map((item) => ({
- ...item,
- name: itemToSafeName(item),
- }));
- return buildFileTree(items);
- }
-
- return {
- rootItems: [],
- itemMap: {},
- };
- });
-});
-
-export const useHistory = createSingletonRoot(() => {
- const history = useFilteredHistory();
-
- return createMemo((): HistoryItem[] => {
- const result = history();
-
- if (isOk(result))
- return result[1].data.map((item) => {
- return {
- ...item,
- name: itemToSafeName(item),
- };
- });
-
- return [];
- });
-});
-
-export function useOptimisticMarkAsUpdated() {
- const [resource, { mutate }] = historyResource();
- const data = createMemo(() => {
- const result = resource.latest;
- if (!result) return [];
- const [, activity] = result;
- if (!activity) return [];
- return activity.data;
- });
-
- return (itemId: string) => {
- const now = Date.now() / 1000;
- mutate(
- ok({
- data: data().map((item) => {
- if (item.id === itemId) {
- return {
- ...item,
- updatedAt: now,
- };
- }
- return item;
- }),
- })
- );
- };
-}
-
-export const insertProjectIntoHistory = async (projectId: string) => {
- const [resource, { mutate }] = historyResource();
- const prevData = resource.latest[1]?.data ?? [];
- const newData: Item[] = [];
- const ids = [projectId];
- storageServiceClient.upsertItemToUserHistory({
- itemId: projectId,
- itemType: 'project',
- });
-
- while (ids.length > 0) {
- const id = ids.shift();
- if (!id) continue;
-
- const projectContent = await storageServiceClient.projects.getContent({
- id,
- });
- if (isOk(projectContent)) {
- ids.push(
- ...projectContent[1].data.reduce<string[]>((acc, { item }) => {
- if (
- item.type === 'project' &&
- !prevData.some(({ id }) => id === item.id)
- ) {
- acc.push(item.id);
- }
- return acc;
- }, [])
- );
- newData.push(...projectContent[1].data.map(({ item }) => item));
- }
- }
- mutate(
- ok({
- data: [...prevData, ...newData],
- })
- );
- const upsertResults = newData
- .filter((item) => !prevData.some(({ id }) => id === item.id))
- .map(({ id, type }) =>
- storageServiceClient.upsertItemToUserHistory({
- itemId: id,
- itemType: type,
- })
- );
- await Promise.all(upsertResults);
- refetchResources();
-};
-
-export async function refetchHistory(force = false) {
- const [resource, { refetch }] = historyResource();
- if (force) return refetch();
- if (resource.loading) return resource.latest;
-
- return refetch();
-}
-
-export async function removeHistoryItem(
- itemType: CloudStorageItemType,
- itemId: string
-) {
- const [resource, { mutate, refetch }] = historyResource();
- const result = resource.latest;
- if (resource.error || isErr(result)) return false;
-
- mutate(
- ok({
- data: result[1].data.filter((item) => item.id !== itemId),
- })
- );
- const maybeRemoved = await storageServiceClient.removeItemFromUserHistory({
- itemId,
- itemType,
- });
- refetch();
-
- if (isOk(maybeRemoved) && maybeRemoved[1].success) return true;
-
- return false;
-}
-
-export async function postNewHistoryItem(
- itemType: CloudStorageItemType,
- itemId: string
-) {
- const [resource, { mutate }] = historyResource();
-
- const result = resource.latest;
- if (resource.error || isErr(result)) return false;
-
- const history = result[1].data;
-
- const recentItemIndex = history.findIndex((item) => item.id === itemId);
-
- if (recentItemIndex > 0) {
- mutate(
- ok({
- data: [
- ...history.slice(0, recentItemIndex),
- history[recentItemIndex],
- ...history.slice(recentItemIndex + 1),
- ],
- })
- );
- }
-
- const maybeAdded = await storageServiceClient.upsertItemToUserHistory({
- itemId,
- itemType,
- });
-
- await refetchHistory();
-
- if (isOk(maybeAdded) && maybeAdded[1].success) return true;
-
- return false;
-}
-
-export function useUpdatedDssItemName(itemId: string | Accessor<string>) {
- const [resource] = historyResource();
-
- return createMemo(() => {
- const maybeResult = resource.latest;
- if (isErr(maybeResult)) return;
-
- const itemIdValue = typeof itemId === 'function' ? itemId() : itemId;
- if (!itemIdValue) return;
-
- const dssItem = maybeResult[1].data.find((item) => item.id === itemIdValue);
- if (!dssItem) return;
-
- return dssItem.name;
- });
-}
diff --git a/js/app/packages/service-clients/service-storage/pins.ts b/js/app/packages/service-clients/service-storage/pins.ts
deleted file mode 100644
index f350e00d7f..0000000000
--- a/js/app/packages/service-clients/service-storage/pins.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { itemToSafeName } from '@core/constant/allBlocks';
-import { isErr, isOk, ok } from '@core/util/maybeResult';
-import { createSingletonRoot } from '@solid-primitives/rootless';
-import { createMemo, createResource } from 'solid-js';
-import { type ItemType, storageServiceClient } from './client';
-import type { FileType } from './generated/schemas/fileType';
-import type { Item } from './generated/schemas/item';
-import { useHistory } from './history';
-
-const pinsResource = createSingletonRoot(() =>
- createResource(() => storageServiceClient.getPins(), {
- initialValue: ok({ recent: [] }),
- })
-);
-
-export function usePins() {
- const [resource] = pinsResource();
- return createMemo(() => {
- const result = resource.latest;
-
- if (isOk(result))
- return result[1].recent.map((pinnedItem) => ({
- ...pinnedItem,
- item: {
- ...pinnedItem.item,
- name: itemToSafeName(pinnedItem.item),
- },
- }));
-
- return [];
- });
-}
-
-export function usePinnedIds() {
- const pins = usePins();
- return createMemo(() => pins().map(({ item }) => item.id), [], {
- equals: (a, b) => a.length === b.length && a.every((v) => b.includes(v)),
- });
-}
-
-export async function refetchPins(force = false) {
- const [resource, { refetch }] = pinsResource();
- if (force) return refetch();
- if (resource.loading) return resource.latest;
-
- return refetch();
-}
-
-export async function pinItem(pinType: ItemType, id: string, index?: number) {
- const [resource, { mutate, refetch }] = pinsResource();
- const result = resource.latest;
- if (resource.error || isErr(result)) return false;
-
- const pinnedItems = result[1].recent;
- const pinIndex = index ?? pinnedItems.length;
-
- const history = useHistory();
- const item = history().find((item) => item.id === id);
-
- if (item) {
- pinnedItems.push({ activity: item, item, pinIndex });
- mutate(
- ok({
- recent: pinnedItems,
- })
- );
- }
-
- const maybeAdded = await storageServiceClient.pinItem({
- id,
- pinType,
- pinIndex,
- });
-
- if (maybeAdded[1]?.success) {
- await storageServiceClient.reorderPins({
- pins: pinnedItems.map(({ item }, index) => ({
- pinIndex: index,
- pinnedItemType: item.type,
- pinnedItemId: item.id,
- })),
- });
-
- refetch();
- return true;
- }
-
- return false;
-}
-
-export async function unpinItem(pinType: ItemType, id: string) {
- const [resource, { mutate, refetch }] = pinsResource();
- const result = resource.latest;
- if (resource.error || isErr(result)) return false;
-
- const pinnedItems = result[1].recent;
-
- mutate(ok({ recent: pinnedItems.filter(({ item }) => item.id !== id) }));
-
- const maybeRemoved = await storageServiceClient.removePin({
- id,
- pinType,
- });
- refetch();
-
- return !!maybeRemoved[1]?.success;
-}
-
-type UnwrappedItemType = 'chat' | 'project' | 'rss' | FileType;
-
-export function getUnwrappedType(item: Item): UnwrappedItemType {
- if (item.type === 'document') return item.fileType as FileType;
- return item.type;
-}
diff --git a/js/app/packages/service-clients/service-storage/projects.ts b/js/app/packages/service-clients/service-storage/projects.ts
deleted file mode 100644
index 17492c9426..0000000000
--- a/js/app/packages/service-clients/service-storage/projects.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-import { ENABLE_PROJECT_SHARING } from '@core/constant/featureFlags';
-import { useUserId } from '@core/context/user';
-import { isOk, ok } from '@core/util/maybeResult';
-import { createSingletonRoot } from '@solid-primitives/rootless';
-import { createMemo, createResource } from 'solid-js';
-import { v4 as uuidv4 } from 'uuid';
-import { storageServiceClient } from './client';
-import type { Project } from './generated/schemas/project';
-import { UploadDocumentStatus } from './generated/schemas/uploadDocumentStatus';
-import { postNewHistoryItem } from './history';
-
-/**
- * @internal Don't use this directly
- */
-const projectsResource = createSingletonRoot(() =>
- createResource(storageServiceClient.projects.getAll, {
- initialValue: ok({ data: [] }),
- })
-);
-
-const pendingProjectsResource = createSingletonRoot(() =>
- createResource(storageServiceClient.projects.getPending, {
- initialValue: ok({ data: [] }),
- })
-);
-
-const projectContentResource = createSingletonRoot(
- () => new Map<string, ReturnType<typeof createProjectContentResource>>()
-);
-
-export function useIsPendingProject() {
- const [resource] = pendingProjectsResource();
-
- const pendingProjectIdSet = createMemo((): Set<string> => {
- const [err, result] = resource.latest;
- if (err || resource.error) return new Set();
-
- const data = result.data;
- let pendingProjectIds: string[] = [];
- for (const project of data) {
- const projectId = project.id;
- // NOTE: there can be a race condition where the documents are marked
- // as completed before the project is marked as pending so we handle here
- const hasPendingDocument = project.documentStatuses.some(
- (status) => status.status !== UploadDocumentStatus.completed
- );
- if (hasPendingDocument) {
- pendingProjectIds.push(projectId);
- }
- }
-
- return new Set(pendingProjectIds);
- });
-
- return (projectId: string) => {
- return pendingProjectIdSet().has(projectId);
- };
-}
-
-export function useIsPendingDocument() {
- const [resource] = pendingProjectsResource();
-
- const pendingDocumentIdSet = createMemo((): Set<string> => {
- const [err, result] = resource.latest;
- if (err || resource.error) return new Set();
-
- const data = result.data;
- return new Set(
- data.flatMap((project) =>
- project.documentStatuses
- .filter((s) => s.status !== UploadDocumentStatus.pending)
- .map((s) => s.documentId)
- )
- );
- });
-
- return (documentId: string) => {
- return pendingDocumentIdSet().has(documentId);
- };
-}
-
-export function useProjects() {
- const [resource] = projectsResource();
- const [pendingResource] = pendingProjectsResource();
- const userId = useUserId();
- return createMemo((prev: Project[]) => {
- const [err, projectResult] = resource.latest;
- const projectData = err || resource.error ? [] : projectResult.data;
-
- const [pendingErr, pendingResult] = pendingResource.latest;
- const pendingData =
- pendingErr || pendingResource.error ? [] : pendingResult.data;
-
- const allProjects: Project[] = [...projectData, ...pendingData];
-
- const sortedByCreatedAt = allProjects.sort(
- (a, b) => b.createdAt - a.createdAt
- );
-
- if (!ENABLE_PROJECT_SHARING) {
- const _userId = userId();
- return sortedByCreatedAt.filter((project) => project.userId === _userId);
- }
-
- if (prev.length !== sortedByCreatedAt.length) return sortedByCreatedAt;
-
- /*
- * This is naive looking however other methods were freezing the server on
- * reloads
- */
- const validateSameData = (a: Project, b: Project) => {
- if (a.id !== b.id) return false;
- if (a.name !== b.name) return false;
- if (a.parentId !== b.parentId) return false;
- if (a.type !== b.type) return false;
- if (a.userId !== b.userId) return false;
- if (a.createdAt !== b.createdAt) return false;
- if (a.updatedAt !== b.updatedAt) return false;
- return true;
- };
-
- const noDiff = sortedByCreatedAt.every((project) =>
- prev.some((prevProject) => validateSameData(project, prevProject))
- );
-
- if (noDiff) return prev;
-
- return sortedByCreatedAt;
- }, []);
-}
-
-export async function refetchProjects(force = false) {
- const [resource, { refetch }] = projectsResource();
- const [pendingResource, { refetch: pendingRefetch }] =
- pendingProjectsResource();
-
- if (force || (!resource.loading && !pendingResource.loading)) {
- await Promise.allSettled([refetch(), pendingRefetch()]);
- return;
- }
-
- if (resource.loading) {
- await pendingRefetch();
- } else if (pendingResource.loading) {
- await refetch();
- }
-}
-
-export function useCreateProject() {
- const [resource, { mutate }] = projectsResource();
- return async ({
- name,
- parentId,
- sharePermission,
- }: {
- name: string;
- parentId?: string;
- sharePermission?: null;
- }) => {
- const [err, result] = resource.latest;
- if (err) return;
-
- // Create temporary project for optimistic update
- // TODO: this should optimistically update the file tree, not the projectsResource
- const tempProject: Project = {
- createdAt: Date.now(),
- id: uuidv4(), // temporary ID
- name: name,
- parentId: parentId ?? undefined,
- type: 'project',
- userId: '',
- updatedAt: Date.now(),
- deletedAt: null,
- };
-
- // Optimistic update
- mutate(
- ok({
- data: [tempProject, ...result.data],
- })
- );
-
- const maybeResult = await storageServiceClient.projects.create({
- name,
- projectParentId: parentId,
- sharePermission,
- });
-
- if (isOk(maybeResult)) {
- postNewHistoryItem('project', maybeResult[1].id);
- return maybeResult[1].id;
- }
- };
-}
-
-const createProjectContentResource = (projectId: string) => {
- return createResource(
- () => {
- if (!projectId) return;
- return { id: projectId };
- },
- storageServiceClient.projects.getContent,
- { initialValue: ok({ data: [], error: false }) }
- );
-};
-
-export function refetchAllProjectContent(force = false) {
- const resources = projectContentResource();
- for (const [, resource] of resources) {
- const [, { refetch }] = resource;
- if (force) {
- refetch();
- continue;
- }
- if (!resource[0].loading) {
- refetch();
- }
- }
-}
-
-// Utility functions for gathering project children ids
-export const getAllChildProjectIds = (
- projectId: string,
- projects?: Project[]
-): string[] => {
- if (!projects) projects = useProjects()();
-
- const directChildren = projects.filter(
- (project) => project.parentId === projectId
- );
-
- if (!directChildren) {
- return [];
- }
-
- const directChildrenIds = directChildren.map((project) => project.id);
-
- const allChildIds = directChildrenIds.flatMap((projectId) =>
- getAllChildProjectIds(projectId)
- );
-
- return [...directChildrenIds, ...allChildIds];
-};
-
-// Utility functions for gathering non-child project ids
-export const getAllParentSiblingProjectIds = (
- projecId: string,
- projects?: Project[]
-) => {
- if (!projects) projects = useProjects()();
- const childrenIds = getAllChildProjectIds(projecId);
- const excludeIds = [projecId, ...childrenIds];
-
- return projects
- .filter((project) => !excludeIds.includes(project.id))
- .map((project) => project.id);
-};
diff --git a/js/app/packages/service-clients/service-storage/util/refetchResources.ts b/js/app/packages/service-clients/service-storage/util/refetchResources.ts
index e4a1e4ebbc..1f6142efc1 100644
--- a/js/app/packages/service-clients/service-storage/util/refetchResources.ts
+++ b/js/app/packages/service-clients/service-storage/util/refetchResources.ts
@@ -1,11 +1,10 @@
import { refetchDocumentShareButtonResource } from '@core/component/TopBar/ShareButton';
-import { invalidateUserQuota } from '@service-auth/userQuota';
-import { refetchDeletedItems } from '@service-storage/deleted';
-import { refetchHistory } from '@service-storage/history';
-import { refetchPins } from '@service-storage/pins';
-import { refetchProjects } from '@service-storage/projects';
+import { invalidateDeletedItems } from '@queries/storage/deleted';
+import { invalidateProjects } from '@queries/storage/projects';
+import { invalidateUserQuota } from '@queries/auth';
+import { refetchHistory } from '@queries/history/history';
-type StorageServiceResource = 'documents' | 'history' | 'pins' | 'projects';
+type StorageServiceResource = 'documents' | 'history' | 'projects';
type RefetchResourcesOptions = {
[key in StorageServiceResource]: {
force?: boolean;
@@ -17,15 +16,14 @@ export function refetchResources(options?: RefetchResourcesOptions) {
// refetchDocuments();
invalidateUserQuota();
refetchHistory();
- refetchPins();
refetchProjectResources();
- refetchDeletedItems();
+ invalidateDeletedItems();
return;
}
}
-export async function refetchProjectResources(force = false) {
- await refetchProjects(force);
+export async function refetchProjectResources(_force = false) {
+ await invalidateProjects();
refetchDocumentShareButtonResource();
}