Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat: update previews on rename (#1164)

gbirman3ac43d13faaf
diff --git a/js/app/packages/app/component/EntityModal/RenameView.tsx b/js/app/packages/app/component/EntityModal/RenameView.tsx
index 90208e4553..46706c72cd 100644
--- a/js/app/packages/app/component/EntityModal/RenameView.tsx
+++ b/js/app/packages/app/component/EntityModal/RenameView.tsx
@@ -40,10 +40,11 @@ export const RenameView = (props: {
() => onMutateResult.previousData
);
},
- onSettled(_, __, variables) {
- queryClient.invalidateQueries({
- queryKey: channelKeys.withID(variables.entity.id).queryKey,
- });
+ onSettled(_, __, _variables) {
+ // TODO: fix the backend so that the /channels/{id} endpoint returns the updated name
+ // queryClient.invalidateQueries({
+ // queryKey: channelKeys.withID(variables.entity.id).queryKey,
+ // });
},
});
let inputRef: HTMLInputElement | undefined;
diff --git a/js/app/packages/app/component/rightbar/Rightbar.tsx b/js/app/packages/app/component/rightbar/Rightbar.tsx
index 89133b0e67..b9116648d6 100644
--- a/js/app/packages/app/component/rightbar/Rightbar.tsx
+++ b/js/app/packages/app/component/rightbar/Rightbar.tsx
@@ -52,7 +52,7 @@ import {
cognitionWebsocketServiceClient,
} from '@service-cognition/client';
import { createCognitionWebsocketEffect } from '@service-cognition/websocket';
-import { invalidateHistory, useHistoryQuery } from '@queries/history/history';
+import { refetchHistory, useHistoryQuery } from '@queries/history/history';
import { useOpenInstructionsMd } from 'core/component/AI/util/instructions';
import type { LexicalEditor } from 'lexical';
import {
@@ -70,6 +70,7 @@ import {
import { SplitlikeContainer } from '../split-layout/components/SplitContainer';
import { Button } from '@ui/components/Button';
import { Hotkey } from '@core/component/Hotkey';
+import { setPreviewData } from '@queries/preview';
type ChatData = {
messages: ChatMessageWithAttachments[];
@@ -553,9 +554,15 @@ 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
- invalidateHistory();
- waitChatRename(newChatId).then((_name) => {
- invalidateHistory();
+ refetchHistory();
+ waitChatRename(newChatId).then((name) => {
+ refetchHistory();
+ if (name) {
+ setPreviewData(newChatId, (prev) => ({
+ ...prev,
+ name,
+ }));
+ }
});
return await onSend(response);
} else if (request.type === 'send') {
diff --git a/js/app/packages/block-chat/component/NameMenu.tsx b/js/app/packages/block-chat/component/NameMenu.tsx
deleted file mode 100644
index a6594c2337..0000000000
--- a/js/app/packages/block-chat/component/NameMenu.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-import { copyChat } from '@block-chat/client';
-import type { ChatData } from '@block-chat/definition';
-import { LocationType, useCreateShareUrl } from '@block-pdf/signal/location';
-import { withAnalytics } from '@coparse/analytics';
-import { useIsAuthenticated } from '@core/auth';
-import {
- DeprecatedEditingTextButton,
- DeprecatedTextButton,
-} from '@core/component/DeprecatedTextButton';
-import { EditableProvider } from '@core/component/Editable';
-import {
- DropdownMenuContent,
- MenuItem,
- MenuItemRenameTrigger,
- MenuSeparator,
-} from '@core/component/Menu';
-import { BarContext } from '@core/component/TopBar/Bar';
-import { setCachedInputStore } from '@core/store/cacheChatInput';
-import { isErr } from '@core/util/maybeResult';
-import CopySimple from '@icon/regular/copy-simple.svg';
-import PencilSimpleLine from '@icon/regular/pencil-simple-line.svg';
-import ShareFat from '@icon/regular/share-fat.svg';
-import TrashSimple from '@icon/regular/trash-simple.svg';
-import { DropdownMenu } from '@kobalte/core/dropdown-menu';
-import { cognitionApiServiceClient } from '@service-cognition/client';
-import { useEmail } from '@core/context/user';
-import {
- refetchHistory,
- useUpdatedDssItemName,
-} from '@queries/history/history';
-import { refetchResources } from '@service-storage/util/refetchResources';
-import { useNavigate } from '@solidjs/router';
-import { useSplitPanelOrThrow } from 'app/component/split-layout/layoutUtils';
-import { toast } from 'core/component/Toast/Toast';
-import { createMemo, createSignal, Show, useContext } from 'solid-js';
-
-const { track, TrackingEvents } = withAnalytics();
-
-type Props = { data: ChatData };
-
-export function ChatNameMenu(props: Props) {
- const [chatMenuOpen, setChatMenuOpen] = createSignal(false);
- const isAuthenticated = useIsAuthenticated();
- const panelContext = useSplitPanelOrThrow();
-
- const renameChat = async ({
- chat_id,
- new_name,
- }: {
- chat_id: string;
- new_name: string;
- }) => {
- if (!new_name.trim()) return toast.alert('Chat name cannot be empty');
-
- const maybeRenameResult = await cognitionApiServiceClient.renameChat({
- chat_id,
- new_name,
- });
- if (isErr(maybeRenameResult)) return;
-
- refetchHistory();
- };
- const deleteChat = async (chat_id: string) => {
- setCachedInputStore(chat_id, undefined);
- const maybeDeletedChat = await cognitionApiServiceClient.deleteChat({
- chat_id,
- });
- if (isErr(maybeDeletedChat)) return;
-
- refetchResources();
- panelContext?.handle.close();
- };
- const navigate = useNavigate();
-
- const updatedDssItemName = useUpdatedDssItemName(props.data.chat.id);
-
- const chatName = createMemo(() => {
- const updatedDssName = updatedDssItemName();
- const fallbackName = props.data.chat.name ?? 'Untitled Chat';
-
- if (updatedDssName) return updatedDssName;
-
- return fallbackName;
- });
-
- const context = useContext(BarContext);
- if (!context) throw new Error('ChatNameMenu must be used within a Bar');
- const truncation = context.truncation;
-
- const truncatedName = () => {
- const name = chatName();
- if (!name) return 'Untitled Chat';
- const maxLength = truncation().stage.fileNameLength;
- return name.length > maxLength
- ? `${name.slice(0, maxLength - 3)}...`
- : name;
- };
- const email = useEmail();
- const isChatOwner = () => email() === props.data.chat.userId;
- const createShareUrl = useCreateShareUrl();
-
- return (
- <EditableProvider
- editingComponent={
- <DeprecatedEditingTextButton
- handleSubmitEdit={(new_name) => {
- renameChat({ chat_id: props.data.chat.id, new_name });
- }}
- labelText={chatName() ?? ''}
- theme="clear"
- dynamicSizing
- showChevron
- />
- }
- >
- <DropdownMenu
- open={chatMenuOpen()}
- onOpenChange={setChatMenuOpen}
- sameWidth
- >
- <DropdownMenu.Trigger>
- <DeprecatedTextButton theme="clear" showChevron tabIndex={-1}>
- {truncatedName()}
- </DeprecatedTextButton>
- </DropdownMenu.Trigger>
-
- <DropdownMenu.Portal>
- <DropdownMenuContent>
- <MenuItem
- text={'Make a Copy'}
- icon={CopySimple}
- onClick={async () => {
- const result = await copyChat({
- id: props.data.chat.id,
- name: props.data.chat.name + ' Copy',
- }).catch((_) => {});
- if (result?.href) navigate(result.href);
- }}
- />
- <Show when={isAuthenticated() && isChatOwner()}>
- <MenuItemRenameTrigger
- text="Rename"
- icon={PencilSimpleLine}
- sideEffect={() => setChatMenuOpen(false)}
- />
- </Show>
- <MenuSeparator />
- <MenuItem
- text={'Share'}
- icon={ShareFat}
- onClick={async () => {
- createShareUrl(LocationType.General);
- track(TrackingEvents.BLOCKCHAT.CHATMENU.SHARE);
- toast.success('Link copied to clipboard');
- }}
- />
- <Show when={isAuthenticated() && isChatOwner()}>
- <MenuSeparator />
- <MenuItem
- text={'Delete'}
- icon={TrashSimple}
- onClick={async () => {
- deleteChat(props.data.chat.id);
- track(TrackingEvents.BLOCKCHAT.CHATMENU.DELETE);
- }}
- />
- </Show>
- </DropdownMenuContent>
- </DropdownMenu.Portal>
- </DropdownMenu>
- </EditableProvider>
- );
-}
diff --git a/js/app/packages/block-chat/component/TopBar.tsx b/js/app/packages/block-chat/component/TopBar.tsx
index 54573162a1..2d42861099 100644
--- a/js/app/packages/block-chat/component/TopBar.tsx
+++ b/js/app/packages/block-chat/component/TopBar.tsx
@@ -23,6 +23,7 @@ import { createCognitionWebsocketEffect } from '@service-cognition/websocket';
import { refetchHistory } from '@queries/history/history';
import { useOpenInstructionsMd } from 'core/component/AI/util/instructions';
import { onCleanup, onMount } from 'solid-js';
+import { setPreviewData } from '@queries/preview';
export function TopBar() {
const blockId = useBlockId();
@@ -35,6 +36,10 @@ export function TopBar() {
const dispose = createCognitionWebsocketEffect('chat_renamed', (data) => {
if (data.chat_id === blockId) {
refetchHistory();
+ setPreviewData(data.chat_id, (prev) => ({
+ ...prev,
+ name: data.name,
+ }));
dispose();
}
});
diff --git a/js/app/packages/block-md/signal/save.ts b/js/app/packages/block-md/signal/save.ts
index 184cb9a574..fd6060b1a8 100644
--- a/js/app/packages/block-md/signal/save.ts
+++ b/js/app/packages/block-md/signal/save.ts
@@ -4,12 +4,12 @@ import {
editorStateAsMarkdown,
getSaveState,
} from '@core/component/LexicalMarkdown/utils';
+import { renameItem } from '@core/component/FileList/itemOperations';
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 '@queries/history/history';
-import { refetchResources } from '@service-storage/util/refetchResources';
import { createCallback } from '@solid-primitives/rootless';
import { createMemo } from 'solid-js';
import { mdStore } from './markdownBlockData';
@@ -47,13 +47,11 @@ export function useRenameMarkdownDocument() {
const documentId = useBlockId();
return createCallback(async (documentName: string) => {
- const result = await storageServiceClient.editDocument({
- documentId,
- documentName,
+ await renameItem({
+ itemType: 'document',
+ id: documentId,
+ newName: documentName,
});
- if (isErr(result)) return;
-
- refetchResources();
});
}
diff --git a/js/app/packages/block-project/component/TopBar.tsx b/js/app/packages/block-project/component/TopBar.tsx
index e70ef99878..1a65a1b1de 100644
--- a/js/app/packages/block-project/component/TopBar.tsx
+++ b/js/app/packages/block-project/component/TopBar.tsx
@@ -42,8 +42,12 @@ export function TopBar() {
const permissions = useGetPermissions();
const isOwner = useIsDocumentOwner();
const canEdit = useCanEdit();
- const name = () => projectBlockDataSignal()?.projectMetadata.name ?? '';
- const owner = () => projectBlockDataSignal()?.projectMetadata.userId;
+ const name = createMemo(
+ () => projectBlockDataSignal()?.projectMetadata.name ?? ''
+ );
+ const owner = createMemo(
+ () => projectBlockDataSignal()?.projectMetadata.userId
+ );
function handleCopyLink() {
navigator.clipboard.writeText(
diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.ts
index fd465ab142..28c9ec8570 100644
--- a/js/app/packages/core/component/FileList/itemOperations.ts
+++ b/js/app/packages/core/component/FileList/itemOperations.ts
@@ -109,7 +109,7 @@ export async function renameItem(args: {
}
if (!skipRefetch) {
- refetchResources();
+ refetchResources({ id });
}
return true;
}
diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.ts
index 4ac7a5230e..86ca4dbc47 100644
--- a/js/app/packages/macro-entity/src/queries/dss.ts
+++ b/js/app/packages/macro-entity/src/queries/dss.ts
@@ -558,7 +558,7 @@ const isEntityRenameSupported = (entity: EntityData) => {
};
/**
- * Mutation to mark a thread as seen.
+ * Mutation to rename a DSS entity.
*/
export function createRenameDssEntityMutation(
callbacks?: MutationCallbacks<
diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.ts
index 4460e7609b..79d3268fcb 100644
--- a/js/app/packages/queries/history/history.ts
+++ b/js/app/packages/queries/history/history.ts
@@ -346,11 +346,6 @@ export function getHistoryItems(): HistoryItem[] {
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.
diff --git a/js/app/packages/queries/preview/index.ts b/js/app/packages/queries/preview/index.ts
index 5f981aa5ba..97184c670c 100644
--- a/js/app/packages/queries/preview/index.ts
+++ b/js/app/packages/queries/preview/index.ts
@@ -1,5 +1,9 @@
export { previewKeys } from './keys';
-export { useItemPreview } from './preview';
+export {
+ useItemPreview,
+ invalidatePreview,
+ setPreviewData,
+} from './preview';
export type {
PreviewItem,
PreviewItemNoAccess,
diff --git a/js/app/packages/queries/preview/preview.ts b/js/app/packages/queries/preview/preview.ts
index e3f93b2f91..d887f77638 100644
--- a/js/app/packages/queries/preview/preview.ts
+++ b/js/app/packages/queries/preview/preview.ts
@@ -1,7 +1,8 @@
import { DEFAULT_ITEM_TYPE } from '@service-storage/client';
import { useQuery } from '@tanstack/solid-query';
-import type { Accessor } from 'solid-js';
+import type { Accessor, Setter } from 'solid-js';
import { createMemo } from 'solid-js';
+import { queryClient } from '../client';
import { previewDataLoader } from './dataloader';
import { defaultNameTransform } from './fetchers';
import { previewKeys } from './keys';
@@ -12,9 +13,7 @@ export function useItemPreview(item: Accessor<ItemEntity>) {
const query = useQuery(() => ({
queryKey: previewKeys.item(item().id).queryKey,
queryFn: () => previewDataLoader.load(item()),
- // TODO: we need to invalidate the cache when the item changes
- // for now let's lower the stale time
- staleTime: 60 * 1000 * 10, // 10 minutes
+ staleTime: 60 * 1000 * 60 * 24, // 24 hours
}));
const preview = createMemo(() => {
@@ -32,3 +31,22 @@ export function useItemPreview(item: Accessor<ItemEntity>) {
return [preview] as const;
}
+
+/** Invalidate preview for the given item id. if no id is provided, invalidates all previews */
+export function invalidatePreview(itemId?: string) {
+ if (!itemId)
+ return queryClient.invalidateQueries({
+ queryKey: previewKeys._def,
+ });
+ return queryClient.invalidateQueries({
+ queryKey: previewKeys.item(itemId).queryKey,
+ });
+}
+
+/** Directly update preview data in the cache without refetching */
+export function setPreviewData(itemId: string, updater: Setter<PreviewItem>) {
+ return queryClient.setQueryData<PreviewItem>(
+ previewKeys.item(itemId).queryKey,
+ updater
+ );
+}
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 1f6142efc1..f1421bef04 100644
--- a/js/app/packages/service-clients/service-storage/util/refetchResources.ts
+++ b/js/app/packages/service-clients/service-storage/util/refetchResources.ts
@@ -3,23 +3,22 @@ import { invalidateDeletedItems } from '@queries/storage/deleted';
import { invalidateProjects } from '@queries/storage/projects';
import { invalidateUserQuota } from '@queries/auth';
import { refetchHistory } from '@queries/history/history';
+import { invalidatePreview } from '@queries/preview';
-type StorageServiceResource = 'documents' | 'history' | 'projects';
type RefetchResourcesOptions = {
- [key in StorageServiceResource]: {
- force?: boolean;
- };
+ id?: string;
};
+
export function refetchResources(options?: RefetchResourcesOptions) {
- if (!options) {
- // TODO: fetch documents
- // refetchDocuments();
- invalidateUserQuota();
- refetchHistory();
- refetchProjectResources();
- invalidateDeletedItems();
- return;
- }
+ // TODO: fetch documents
+ // refetchDocuments();
+ invalidateUserQuota();
+ refetchHistory();
+ refetchProjectResources();
+ invalidateDeletedItems();
+ // TODO: consolidate where we rename items
+ // and optimistically set the data using setPreviewData
+ invalidatePreview(options?.id);
}
export async function refetchProjectResources(_force = false) {